{"version":3,"sources":["src/main.ts","src/app/app.config.ts","node_modules/@angular/common/locales/it.mjs","node_modules/@angular/platform-browser/fesm2022/animations.mjs","node_modules/@angular/animations/fesm2022/browser.mjs","node_modules/ngx-editor/fesm2022/ngx-editor.mjs","node_modules/ngx-editor/fesm2022/ngx-editor-utils.mjs","node_modules/prosemirror-state/dist/index.js","node_modules/prosemirror-model/dist/index.js","node_modules/prosemirror-transform/dist/index.js","node_modules/prosemirror-schema-list/dist/index.js","node_modules/prosemirror-commands/dist/index.js","node_modules/ngx-editor/fesm2022/ngx-editor-commands.mjs","node_modules/ngx-editor/fesm2022/ngx-editor-helpers.mjs","node_modules/prosemirror-history/dist/index.js","node_modules/rope-sequence/dist/index.js","src/app/app.routes.ts","src/app/auth.guard.ts","src/app/pages/ui-kit-page/ui-kit-production.routes.ts","src/app/graphql.provider.ts","node_modules/apollo-angular/fesm2022/ngApolloLinkHttp.mjs","node_modules/extract-files/extractFiles.mjs","node_modules/is-plain-obj/index.js","node_modules/extract-files/isExtractableFile.mjs","src/app/i18n/dynamic-import-loader.ts","src/app/svg/account-circle.ts","src/app/svg/account-pin.ts","src/app/svg/add-line.ts","src/app/svg/application.ts","src/app/svg/archive.ts","src/app/svg/arrow.ts","src/app/svg/arrow-back.ts","src/app/svg/arrow-left.ts","src/app/svg/arrow-up.ts","src/app/svg/arrow-up-down-fill.ts","src/app/svg/cake-line.ts","src/app/svg/calendar-event.ts","src/app/svg/call.ts","src/app/svg/chat-smile.ts","src/app/svg/check.ts","src/app/svg/check-outline.ts","src/app/svg/chevron-down.ts","src/app/svg/circle.ts","src/app/svg/close.ts","src/app/svg/close-circle.ts","src/app/svg/communication.ts","src/app/svg/copy.ts","src/app/svg/dashboard-line.ts","src/app/svg/dataset.ts","src/app/svg/delete-back.ts","src/app/svg/delete-bin-line.ts","src/app/svg/download.ts","src/app/svg/drag-handle.ts","src/app/svg/edit.ts","src/app/svg/email.ts","src/app/svg/expand.ts","src/app/svg/eye-line.ts","src/app/svg/eye-off-line.ts","src/app/svg/feedback-line.ts","src/app/svg/file.ts","src/app/svg/filter.ts","src/app/svg/flag.ts","src/app/svg/fresh-man.ts","src/app/svg/global.ts","src/app/svg/group-line.ts","src/app/svg/home-line.ts","src/app/svg/home-not.ts","src/app/svg/inbox-unarchive.ts","src/app/svg/info.ts","src/app/svg/intercultura.ts","src/app/svg/kanban-view.ts","src/app/svg/lead.ts","src/app/svg/links-fill.ts","src/app/svg/loading.ts","src/app/svg/log-out.ts","src/app/svg/mail-line.ts","src/app/svg/mail-open.ts","src/app/svg/mail-unread.ts","src/app/svg/map-pin-line.ts","src/app/svg/map-pin-range-line.ts","src/app/svg/more-fill.ts","src/app/svg/more-fill-orizzontal.ts","src/app/svg/note-line.ts","src/app/svg/notification.ts","src/app/svg/parent.ts","src/app/svg/passport-line.ts","src/app/svg/person.ts","src/app/svg/phone-line.ts","src/app/svg/pin-drop.ts","src/app/svg/play-circle.ts","src/app/svg/play-mini.ts","src/app/svg/price-tag.ts","src/app/svg/private.ts","src/app/svg/program.ts","src/app/svg/progress.ts","src/app/svg/remove-labels.ts","src/app/svg/school-line.ts","src/app/svg/search.ts","src/app/svg/search-eye.ts","src/app/svg/search-shortcut.ts","src/app/svg/setting.ts","src/app/svg/sort-alphabet.ts","src/app/svg/stack-line.ts","src/app/svg/star.ts","src/app/svg/star-smile.ts","src/app/svg/sticky-note.ts","src/app/svg/stop-circle.ts","src/app/svg/student.ts","src/app/svg/subtract-line.ts","src/app/svg/sun.ts","src/app/svg/task.ts","src/app/svg/text.ts","src/app/svg/text-field.ts","src/app/svg/unknown.ts","src/app/svg/upload.ts","src/app/svg/user-add-line.ts","src/app/svg/whatsapp.ts"],"sourcesContent":["import { bootstrapApplication } from '@angular/platform-browser';\n\nimport { appConfig } from './app/app.config';\nimport { RootComponent } from './app/root/root.component';\n\nbootstrapApplication(RootComponent, appConfig).catch((err) => console.error(err));\n","import { registerLocaleData } from '@angular/common';\nimport { HttpClientModule, provideHttpClient } from '@angular/common/http';\nimport localeIt from '@angular/common/locales/it';\nimport { ApplicationConfig, LOCALE_ID, importProvidersFrom } from '@angular/core';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { provideRouter, withComponentInputBinding } from '@angular/router';\nimport { provideSvgIconsConfig } from '@ngneat/svg-icon';\nimport { TranslateLoader, TranslateModule } from '@ngx-translate/core';\nimport { GoogleChartsModule } from 'angular-google-charts';\nimport { NgxEditorModule } from 'ngx-editor';\n\nimport { routes } from './app.routes';\nimport { graphqlProvider } from './graphql.provider';\nimport { DynamicImportLoader } from './i18n/dynamic-import-loader';\nimport { accountCircleIcon } from './svg/account-circle';\nimport { accountPinIcon } from './svg/account-pin';\nimport { addLineIcon } from './svg/add-line';\nimport { applicationIcon } from './svg/application';\nimport { archiveIcon } from './svg/archive';\nimport { arrowIcon } from './svg/arrow';\nimport { arrowBackIcon } from './svg/arrow-back';\nimport { arrowLeftIcon } from './svg/arrow-left';\nimport { arrowUpIcon } from './svg/arrow-up';\nimport { arrowUpDownFillIcon } from './svg/arrow-up-down-fill';\nimport { cakeLineIcon } from './svg/cake-line';\nimport { calendarEventIcon } from './svg/calendar-event';\nimport { callIcon } from './svg/call';\nimport { chatSmileIcon } from './svg/chat-smile';\nimport { checkIcon } from './svg/check';\nimport { checkOutlineIcon } from './svg/check-outline';\nimport { chevronDownIcon } from './svg/chevron-down';\nimport { circleIcon } from './svg/circle';\nimport { closeIcon } from './svg/close';\nimport { closeCircleIcon } from './svg/close-circle';\nimport { communicationIcon } from './svg/communication';\nimport { copyIcon } from './svg/copy';\nimport { dashboardLineIcon } from './svg/dashboard-line';\nimport { datasetIcon } from './svg/dataset';\nimport { deleteBackIcon } from './svg/delete-back';\nimport { deleteBinLineIcon } from './svg/delete-bin-line';\nimport { downloadIcon } from './svg/download';\nimport { dragHandleIcon } from './svg/drag-handle';\nimport { editIcon } from './svg/edit';\nimport { emailIcon } from './svg/email';\nimport { expandIcon } from './svg/expand';\nimport { eyeLineIcon } from './svg/eye-line';\nimport { eyeOffLineIcon } from './svg/eye-off-line';\nimport { feedbackLineIcon } from './svg/feedback-line';\nimport { fileIcon } from './svg/file';\nimport { filterIcon } from './svg/filter';\nimport { flagIcon } from './svg/flag';\nimport { freshManIcon } from './svg/fresh-man';\nimport { globalIcon } from './svg/global';\nimport { groupLineIcon } from './svg/group-line';\nimport { homeLineIcon } from './svg/home-line';\nimport { homeNotIcon } from './svg/home-not';\nimport { inboxUnarchiveIcon } from './svg/inbox-unarchive';\nimport { infoIcon } from './svg/info';\nimport { interculturaIcon } from './svg/intercultura';\nimport { kanbanViewIcon } from './svg/kanban-view';\nimport { leadIcon } from './svg/lead';\nimport { linksFillIcon } from './svg/links-fill';\nimport { loadingIcon } from './svg/loading';\nimport { logOutIcon } from './svg/log-out';\nimport { mailLineIcon } from './svg/mail-line';\nimport { mailOpenIcon } from './svg/mail-open';\nimport { mailUnreadIcon } from './svg/mail-unread';\nimport { mapPinLineIcon } from './svg/map-pin-line';\nimport { mapPinRangeLineIcon } from './svg/map-pin-range-line';\nimport { moreFillIcon } from './svg/more-fill';\nimport { moreFillOrizzontalIcon } from './svg/more-fill-orizzontal';\nimport { noteLineIcon } from './svg/note-line';\nimport { notificationIcon } from './svg/notification';\nimport { parentIcon } from './svg/parent';\nimport { passportLineIcon } from './svg/passport-line';\nimport { personIcon } from './svg/person';\nimport { phoneLineIcon } from './svg/phone-line';\nimport { pinDropIcon } from './svg/pin-drop';\nimport { playCircleIcon } from './svg/play-circle';\nimport { playMiniIcon } from './svg/play-mini';\nimport { priceTagIcon } from './svg/price-tag';\nimport { privateIcon } from './svg/private';\nimport { programIcon } from './svg/program';\nimport { progressIcon } from './svg/progress';\nimport { removeLabelsIcon } from './svg/remove-labels';\nimport { schoolLineIcon } from './svg/school-line';\nimport { searchIcon } from './svg/search';\nimport { searchEyeIcon } from './svg/search-eye';\nimport { searchShortcutIcon } from './svg/search-shortcut';\nimport { settingIcon } from './svg/setting';\nimport { sortAlphabetIcon } from './svg/sort-alphabet';\nimport { stackLineIcon } from './svg/stack-line';\nimport { starIcon } from './svg/star';\nimport { starSmileIcon } from './svg/star-smile';\nimport { stickyNoteIcon } from './svg/sticky-note';\nimport { stopCircleIcon } from './svg/stop-circle';\nimport { studentIcon } from './svg/student';\nimport { subtractLineIcon } from './svg/subtract-line';\nimport { sunIcon } from './svg/sun';\nimport { taskIcon } from './svg/task';\nimport { textIcon } from './svg/text';\nimport { textFieldIcon } from './svg/text-field';\nimport { unknownIcon } from './svg/unknown';\nimport { uploadIcon } from './svg/upload';\nimport { userAddLineIcon } from './svg/user-add-line';\nimport { whatsappIcon } from './svg/whatsapp';\nimport { environment } from '../environments/environment';\n\nexport const svgIcons = [\n accountCircleIcon,\n accountPinIcon,\n accountPinIcon,\n addLineIcon,\n applicationIcon,\n archiveIcon,\n arrowBackIcon,\n arrowIcon,\n arrowLeftIcon,\n arrowUpDownFillIcon,\n arrowUpIcon,\n cakeLineIcon,\n calendarEventIcon,\n callIcon,\n chatSmileIcon,\n checkIcon,\n checkOutlineIcon,\n checkOutlineIcon,\n chevronDownIcon,\n circleIcon,\n circleIcon,\n closeCircleIcon,\n closeIcon,\n closeIcon,\n communicationIcon,\n communicationIcon,\n copyIcon,\n copyIcon,\n dashboardLineIcon,\n dashboardLineIcon,\n datasetIcon,\n deleteBackIcon,\n deleteBinLineIcon,\n deleteBinLineIcon,\n downloadIcon,\n dragHandleIcon,\n editIcon,\n emailIcon,\n expandIcon,\n eyeLineIcon,\n eyeOffLineIcon,\n fileIcon,\n filterIcon,\n filterIcon,\n flagIcon,\n flagIcon,\n feedbackLineIcon,\n freshManIcon,\n globalIcon,\n groupLineIcon,\n homeLineIcon,\n homeNotIcon,\n inboxUnarchiveIcon,\n infoIcon,\n interculturaIcon,\n kanbanViewIcon,\n leadIcon,\n linksFillIcon,\n loadingIcon,\n logOutIcon,\n mailLineIcon,\n mailOpenIcon,\n mailUnreadIcon,\n mapPinLineIcon,\n mapPinRangeLineIcon,\n moreFillIcon,\n moreFillIcon,\n moreFillOrizzontalIcon,\n noteLineIcon,\n notificationIcon,\n parentIcon,\n passportLineIcon,\n personIcon,\n phoneLineIcon,\n pinDropIcon,\n playCircleIcon,\n playMiniIcon,\n priceTagIcon,\n privateIcon,\n programIcon,\n progressIcon,\n removeLabelsIcon,\n schoolLineIcon,\n searchEyeIcon,\n searchIcon,\n searchShortcutIcon,\n settingIcon,\n sortAlphabetIcon,\n stackLineIcon,\n starIcon,\n starSmileIcon,\n stickyNoteIcon,\n stopCircleIcon,\n studentIcon,\n subtractLineIcon,\n sunIcon,\n taskIcon,\n textFieldIcon,\n textIcon,\n unknownIcon,\n uploadIcon,\n userAddLineIcon,\n whatsappIcon,\n];\n\nexport type SvgName = (typeof svgIcons)[number]['name'];\n\nexport interface RouteLink {\n routerLink?: string;\n routerParams?: { [key: string]: string | number };\n label: string;\n icon?: SvgName;\n disable?: boolean;\n}\n\nregisterLocaleData(localeIt);\n\nexport const appConfig: ApplicationConfig = {\n providers: [\n { provide: LOCALE_ID, useValue: 'it-IT' },\n provideRouter(routes, withComponentInputBinding()),\n provideSvgIconsConfig({\n icons: svgIcons,\n missingIconFallback: unknownIcon,\n }),\n importProvidersFrom(\n BrowserAnimationsModule,\n HttpClientModule,\n NgxEditorModule.forRoot({\n locals: {\n bold: 'Bold',\n italic: 'Italic',\n blockquote: 'Blockquote',\n underline: 'Underline',\n strike: 'Strike',\n text_color: 'Text Color',\n bullet_list: 'Bullet List',\n ordered_list: 'Ordered List',\n align_left: 'Left Align',\n align_center: 'Center Align',\n align_right: 'Right Align',\n align_justify: 'Justify',\n background_color: 'Background Color',\n },\n }),\n TranslateModule.forRoot({\n defaultLanguage: environment.defaultLang,\n loader: {\n provide: TranslateLoader,\n useClass: DynamicImportLoader,\n },\n }),\n GoogleChartsModule.forRoot({ version: 'current' }),\n ),\n provideHttpClient(),\n graphqlProvider,\n ],\n};\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n// THIS CODE IS GENERATED - DO NOT MODIFY.\nconst u = undefined;\nfunction plural(val) {\n const n = val,\n i = Math.floor(Math.abs(val)),\n v = val.toString().replace(/^[^.]*\\.?/, '').length,\n e = parseInt(val.toString().replace(/^[^e]*(e([-+]?\\d+))?/, '$2')) || 0;\n if (i === 1 && v === 0) return 1;\n if (e === 0 && !(i === 0) && i % 1000000 === 0 && v === 0 || !(e >= 0 && e <= 5)) return 4;\n return 5;\n}\nexport default [\"it\", [[\"m.\", \"p.\"], [\"AM\", \"PM\"], u], u, [[\"D\", \"L\", \"M\", \"M\", \"G\", \"V\", \"S\"], [\"dom\", \"lun\", \"mar\", \"mer\", \"gio\", \"ven\", \"sab\"], [\"domenica\", \"lunedì\", \"martedì\", \"mercoledì\", \"giovedì\", \"venerdì\", \"sabato\"], [\"dom\", \"lun\", \"mar\", \"mer\", \"gio\", \"ven\", \"sab\"]], u, [[\"G\", \"F\", \"M\", \"A\", \"M\", \"G\", \"L\", \"A\", \"S\", \"O\", \"N\", \"D\"], [\"gen\", \"feb\", \"mar\", \"apr\", \"mag\", \"giu\", \"lug\", \"ago\", \"set\", \"ott\", \"nov\", \"dic\"], [\"gennaio\", \"febbraio\", \"marzo\", \"aprile\", \"maggio\", \"giugno\", \"luglio\", \"agosto\", \"settembre\", \"ottobre\", \"novembre\", \"dicembre\"]], u, [[\"aC\", \"dC\"], [\"a.C.\", \"d.C.\"], [\"avanti Cristo\", \"dopo Cristo\"]], 1, [6, 0], [\"dd/MM/yy\", \"d MMM y\", \"d MMMM y\", \"EEEE d MMMM y\"], [\"HH:mm\", \"HH:mm:ss\", \"HH:mm:ss z\", \"HH:mm:ss zzzz\"], [\"{1}, {0}\", u, \"{1} {0}\", u], [\",\", \".\", \";\", \"%\", \"+\", \"-\", \"E\", \"×\", \"‰\", \"∞\", \"NaN\", \":\"], [\"#,##0.###\", \"#,##0%\", \"#,##0.00 ¤\", \"#E0\"], \"EUR\", \"€\", \"euro\", {\n \"BRL\": [u, \"R$\"],\n \"BYN\": [u, \"Br\"],\n \"EGP\": [u, \"£E\"],\n \"HKD\": [u, \"$\"],\n \"INR\": [u, \"₹\"],\n \"JPY\": [u, \"¥\"],\n \"KRW\": [u, \"₩\"],\n \"MXN\": [u, \"$\"],\n \"NOK\": [u, \"NKr\"],\n \"THB\": [\"฿\"],\n \"TWD\": [u, \"NT$\"],\n \"USD\": [u, \"$\"],\n \"VND\": [u, \"₫\"]\n}, \"ltr\", plural];\n","/**\n * @license Angular v17.3.3\n * (c) 2010-2022 Google LLC. https://angular.io/\n * License: MIT\n */\n\nimport * as i0 from '@angular/core';\nimport { inject, ɵChangeDetectionScheduler, Injectable, Inject, RendererFactory2, NgZone, ANIMATION_MODULE_TYPE, NgModule, ɵperformanceMarkFeature } from '@angular/core';\nexport { ANIMATION_MODULE_TYPE } from '@angular/core';\nimport { ɵDomRendererFactory2, BrowserModule } from '@angular/platform-browser';\nimport * as i1 from '@angular/animations/browser';\nimport { ɵAnimationEngine, ɵWebAnimationsStyleNormalizer, ɵAnimationRendererFactory, ɵAnimationStyleNormalizer, AnimationDriver, ɵWebAnimationsDriver, NoopAnimationDriver } from '@angular/animations/browser';\nimport { DOCUMENT } from '@angular/common';\nlet InjectableAnimationEngine = /*#__PURE__*/(() => {\n class InjectableAnimationEngine extends ɵAnimationEngine {\n // The `ApplicationRef` is injected here explicitly to force the dependency ordering.\n // Since the `ApplicationRef` should be created earlier before the `AnimationEngine`, they\n // both have `ngOnDestroy` hooks and `flush()` must be called after all views are destroyed.\n constructor(doc, driver, normalizer) {\n super(doc, driver, normalizer, inject(ɵChangeDetectionScheduler, {\n optional: true\n }));\n }\n ngOnDestroy() {\n this.flush();\n }\n static {\n this.ɵfac = function InjectableAnimationEngine_Factory(t) {\n return new (t || InjectableAnimationEngine)(i0.ɵɵinject(DOCUMENT), i0.ɵɵinject(i1.AnimationDriver), i0.ɵɵinject(i1.ɵAnimationStyleNormalizer));\n };\n }\n static {\n this.ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: InjectableAnimationEngine,\n factory: InjectableAnimationEngine.ɵfac\n });\n }\n }\n return InjectableAnimationEngine;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nfunction instantiateDefaultStyleNormalizer() {\n return new ɵWebAnimationsStyleNormalizer();\n}\nfunction instantiateRendererFactory(renderer, engine, zone) {\n return new ɵAnimationRendererFactory(renderer, engine, zone);\n}\nconst SHARED_ANIMATION_PROVIDERS = [{\n provide: ɵAnimationStyleNormalizer,\n useFactory: instantiateDefaultStyleNormalizer\n}, {\n provide: ɵAnimationEngine,\n useClass: InjectableAnimationEngine\n}, {\n provide: RendererFactory2,\n useFactory: instantiateRendererFactory,\n deps: [ɵDomRendererFactory2, ɵAnimationEngine, NgZone]\n}];\n/**\n * Separate providers from the actual module so that we can do a local modification in Google3 to\n * include them in the BrowserModule.\n */\nconst BROWSER_ANIMATIONS_PROVIDERS = [{\n provide: AnimationDriver,\n useFactory: () => new ɵWebAnimationsDriver()\n}, {\n provide: ANIMATION_MODULE_TYPE,\n useValue: 'BrowserAnimations'\n}, ...SHARED_ANIMATION_PROVIDERS];\n/**\n * Separate providers from the actual module so that we can do a local modification in Google3 to\n * include them in the BrowserTestingModule.\n */\nconst BROWSER_NOOP_ANIMATIONS_PROVIDERS = [{\n provide: AnimationDriver,\n useClass: NoopAnimationDriver\n}, {\n provide: ANIMATION_MODULE_TYPE,\n useValue: 'NoopAnimations'\n}, ...SHARED_ANIMATION_PROVIDERS];\n\n/**\n * Exports `BrowserModule` with additional [dependency-injection providers](guide/glossary#provider)\n * for use with animations. See [Animations](guide/animations).\n * @publicApi\n */\nlet BrowserAnimationsModule = /*#__PURE__*/(() => {\n class BrowserAnimationsModule {\n /**\n * Configures the module based on the specified object.\n *\n * @param config Object used to configure the behavior of the `BrowserAnimationsModule`.\n * @see {@link BrowserAnimationsModuleConfig}\n *\n * @usageNotes\n * When registering the `BrowserAnimationsModule`, you can use the `withConfig`\n * function as follows:\n * ```\n * @NgModule({\n * imports: [BrowserAnimationsModule.withConfig(config)]\n * })\n * class MyNgModule {}\n * ```\n */\n static withConfig(config) {\n return {\n ngModule: BrowserAnimationsModule,\n providers: config.disableAnimations ? BROWSER_NOOP_ANIMATIONS_PROVIDERS : BROWSER_ANIMATIONS_PROVIDERS\n };\n }\n static {\n this.ɵfac = function BrowserAnimationsModule_Factory(t) {\n return new (t || BrowserAnimationsModule)();\n };\n }\n static {\n this.ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: BrowserAnimationsModule\n });\n }\n static {\n this.ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({\n providers: BROWSER_ANIMATIONS_PROVIDERS,\n imports: [BrowserModule]\n });\n }\n }\n return BrowserAnimationsModule;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * Returns the set of [dependency-injection providers](guide/glossary#provider)\n * to enable animations in an application. See [animations guide](guide/animations)\n * to learn more about animations in Angular.\n *\n * @usageNotes\n *\n * The function is useful when you want to enable animations in an application\n * bootstrapped using the `bootstrapApplication` function. In this scenario there\n * is no need to import the `BrowserAnimationsModule` NgModule at all, just add\n * providers returned by this function to the `providers` list as show below.\n *\n * ```typescript\n * bootstrapApplication(RootComponent, {\n * providers: [\n * provideAnimations()\n * ]\n * });\n * ```\n *\n * @publicApi\n */\nfunction provideAnimations() {\n ɵperformanceMarkFeature('NgEagerAnimations');\n // Return a copy to prevent changes to the original array in case any in-place\n // alterations are performed to the `provideAnimations` call results in app code.\n return [...BROWSER_ANIMATIONS_PROVIDERS];\n}\n/**\n * A null player that must be imported to allow disabling of animations.\n * @publicApi\n */\nlet NoopAnimationsModule = /*#__PURE__*/(() => {\n class NoopAnimationsModule {\n static {\n this.ɵfac = function NoopAnimationsModule_Factory(t) {\n return new (t || NoopAnimationsModule)();\n };\n }\n static {\n this.ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: NoopAnimationsModule\n });\n }\n static {\n this.ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({\n providers: BROWSER_NOOP_ANIMATIONS_PROVIDERS,\n imports: [BrowserModule]\n });\n }\n }\n return NoopAnimationsModule;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * Returns the set of [dependency-injection providers](guide/glossary#provider)\n * to disable animations in an application. See [animations guide](guide/animations)\n * to learn more about animations in Angular.\n *\n * @usageNotes\n *\n * The function is useful when you want to bootstrap an application using\n * the `bootstrapApplication` function, but you need to disable animations\n * (for example, when running tests).\n *\n * ```typescript\n * bootstrapApplication(RootComponent, {\n * providers: [\n * provideNoopAnimations()\n * ]\n * });\n * ```\n *\n * @publicApi\n */\nfunction provideNoopAnimations() {\n // Return a copy to prevent changes to the original array in case any in-place\n // alterations are performed to the `provideNoopAnimations` call results in app code.\n return [...BROWSER_NOOP_ANIMATIONS_PROVIDERS];\n}\n\n/**\n * @module\n * @description\n * Entry point for all animation APIs of the animation browser package.\n */\n\n/**\n * @module\n * @description\n * Entry point for all public APIs of this package.\n */\n\n// This file is not used to build this module. It is only used during editing\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { BrowserAnimationsModule, NoopAnimationsModule, provideAnimations, provideNoopAnimations, InjectableAnimationEngine as ɵInjectableAnimationEngine };\n","/**\n * @license Angular v17.3.3\n * (c) 2010-2022 Google LLC. https://angular.io/\n * License: MIT\n */\n\nimport { ɵAnimationGroupPlayer, NoopAnimationPlayer, AUTO_STYLE, ɵPRE_STYLE, sequence, AnimationMetadataType, style } from '@angular/animations';\nimport * as i0 from '@angular/core';\nimport { ɵRuntimeError, Injectable } from '@angular/core';\nconst LINE_START = '\\n - ';\nfunction invalidTimingValue(exp) {\n return new ɵRuntimeError(3000 /* RuntimeErrorCode.INVALID_TIMING_VALUE */, ngDevMode && `The provided timing value \"${exp}\" is invalid.`);\n}\nfunction negativeStepValue() {\n return new ɵRuntimeError(3100 /* RuntimeErrorCode.NEGATIVE_STEP_VALUE */, ngDevMode && 'Duration values below 0 are not allowed for this animation step.');\n}\nfunction negativeDelayValue() {\n return new ɵRuntimeError(3101 /* RuntimeErrorCode.NEGATIVE_DELAY_VALUE */, ngDevMode && 'Delay values below 0 are not allowed for this animation step.');\n}\nfunction invalidStyleParams(varName) {\n return new ɵRuntimeError(3001 /* RuntimeErrorCode.INVALID_STYLE_PARAMS */, ngDevMode && `Unable to resolve the local animation param ${varName} in the given list of values`);\n}\nfunction invalidParamValue(varName) {\n return new ɵRuntimeError(3003 /* RuntimeErrorCode.INVALID_PARAM_VALUE */, ngDevMode && `Please provide a value for the animation param ${varName}`);\n}\nfunction invalidNodeType(nodeType) {\n return new ɵRuntimeError(3004 /* RuntimeErrorCode.INVALID_NODE_TYPE */, ngDevMode && `Unable to resolve animation metadata node #${nodeType}`);\n}\nfunction invalidCssUnitValue(userProvidedProperty, value) {\n return new ɵRuntimeError(3005 /* RuntimeErrorCode.INVALID_CSS_UNIT_VALUE */, ngDevMode && `Please provide a CSS unit value for ${userProvidedProperty}:${value}`);\n}\nfunction invalidTrigger() {\n return new ɵRuntimeError(3006 /* RuntimeErrorCode.INVALID_TRIGGER */, ngDevMode && \"animation triggers cannot be prefixed with an `@` sign (e.g. trigger('@foo', [...]))\");\n}\nfunction invalidDefinition() {\n return new ɵRuntimeError(3007 /* RuntimeErrorCode.INVALID_DEFINITION */, ngDevMode && 'only state() and transition() definitions can sit inside of a trigger()');\n}\nfunction invalidState(metadataName, missingSubs) {\n return new ɵRuntimeError(3008 /* RuntimeErrorCode.INVALID_STATE */, ngDevMode && `state(\"${metadataName}\", ...) must define default values for all the following style substitutions: ${missingSubs.join(', ')}`);\n}\nfunction invalidStyleValue(value) {\n return new ɵRuntimeError(3002 /* RuntimeErrorCode.INVALID_STYLE_VALUE */, ngDevMode && `The provided style string value ${value} is not allowed.`);\n}\nfunction invalidProperty(prop) {\n return new ɵRuntimeError(3009 /* RuntimeErrorCode.INVALID_PROPERTY */, ngDevMode && `The provided animation property \"${prop}\" is not a supported CSS property for animations`);\n}\nfunction invalidParallelAnimation(prop, firstStart, firstEnd, secondStart, secondEnd) {\n return new ɵRuntimeError(3010 /* RuntimeErrorCode.INVALID_PARALLEL_ANIMATION */, ngDevMode && `The CSS property \"${prop}\" that exists between the times of \"${firstStart}ms\" and \"${firstEnd}ms\" is also being animated in a parallel animation between the times of \"${secondStart}ms\" and \"${secondEnd}ms\"`);\n}\nfunction invalidKeyframes() {\n return new ɵRuntimeError(3011 /* RuntimeErrorCode.INVALID_KEYFRAMES */, ngDevMode && `keyframes() must be placed inside of a call to animate()`);\n}\nfunction invalidOffset() {\n return new ɵRuntimeError(3012 /* RuntimeErrorCode.INVALID_OFFSET */, ngDevMode && `Please ensure that all keyframe offsets are between 0 and 1`);\n}\nfunction keyframeOffsetsOutOfOrder() {\n return new ɵRuntimeError(3200 /* RuntimeErrorCode.KEYFRAME_OFFSETS_OUT_OF_ORDER */, ngDevMode && `Please ensure that all keyframe offsets are in order`);\n}\nfunction keyframesMissingOffsets() {\n return new ɵRuntimeError(3202 /* RuntimeErrorCode.KEYFRAMES_MISSING_OFFSETS */, ngDevMode && `Not all style() steps within the declared keyframes() contain offsets`);\n}\nfunction invalidStagger() {\n return new ɵRuntimeError(3013 /* RuntimeErrorCode.INVALID_STAGGER */, ngDevMode && `stagger() can only be used inside of query()`);\n}\nfunction invalidQuery(selector) {\n return new ɵRuntimeError(3014 /* RuntimeErrorCode.INVALID_QUERY */, ngDevMode && `\\`query(\"${selector}\")\\` returned zero elements. (Use \\`query(\"${selector}\", { optional: true })\\` if you wish to allow this.)`);\n}\nfunction invalidExpression(expr) {\n return new ɵRuntimeError(3015 /* RuntimeErrorCode.INVALID_EXPRESSION */, ngDevMode && `The provided transition expression \"${expr}\" is not supported`);\n}\nfunction invalidTransitionAlias(alias) {\n return new ɵRuntimeError(3016 /* RuntimeErrorCode.INVALID_TRANSITION_ALIAS */, ngDevMode && `The transition alias value \"${alias}\" is not supported`);\n}\nfunction validationFailed(errors) {\n return new ɵRuntimeError(3500 /* RuntimeErrorCode.VALIDATION_FAILED */, ngDevMode && `animation validation failed:\\n${errors.map(err => err.message).join('\\n')}`);\n}\nfunction buildingFailed(errors) {\n return new ɵRuntimeError(3501 /* RuntimeErrorCode.BUILDING_FAILED */, ngDevMode && `animation building failed:\\n${errors.map(err => err.message).join('\\n')}`);\n}\nfunction triggerBuildFailed(name, errors) {\n return new ɵRuntimeError(3404 /* RuntimeErrorCode.TRIGGER_BUILD_FAILED */, ngDevMode && `The animation trigger \"${name}\" has failed to build due to the following errors:\\n - ${errors.map(err => err.message).join('\\n - ')}`);\n}\nfunction animationFailed(errors) {\n return new ɵRuntimeError(3502 /* RuntimeErrorCode.ANIMATION_FAILED */, ngDevMode && `Unable to animate due to the following errors:${LINE_START}${errors.map(err => err.message).join(LINE_START)}`);\n}\nfunction registerFailed(errors) {\n return new ɵRuntimeError(3503 /* RuntimeErrorCode.REGISTRATION_FAILED */, ngDevMode && `Unable to build the animation due to the following errors: ${errors.map(err => err.message).join('\\n')}`);\n}\nfunction missingOrDestroyedAnimation() {\n return new ɵRuntimeError(3300 /* RuntimeErrorCode.MISSING_OR_DESTROYED_ANIMATION */, ngDevMode && \"The requested animation doesn't exist or has already been destroyed\");\n}\nfunction createAnimationFailed(errors) {\n return new ɵRuntimeError(3504 /* RuntimeErrorCode.CREATE_ANIMATION_FAILED */, ngDevMode && `Unable to create the animation due to the following errors:${errors.map(err => err.message).join('\\n')}`);\n}\nfunction missingPlayer(id) {\n return new ɵRuntimeError(3301 /* RuntimeErrorCode.MISSING_PLAYER */, ngDevMode && `Unable to find the timeline player referenced by ${id}`);\n}\nfunction missingTrigger(phase, name) {\n return new ɵRuntimeError(3302 /* RuntimeErrorCode.MISSING_TRIGGER */, ngDevMode && `Unable to listen on the animation trigger event \"${phase}\" because the animation trigger \"${name}\" doesn\\'t exist!`);\n}\nfunction missingEvent(name) {\n return new ɵRuntimeError(3303 /* RuntimeErrorCode.MISSING_EVENT */, ngDevMode && `Unable to listen on the animation trigger \"${name}\" because the provided event is undefined!`);\n}\nfunction unsupportedTriggerEvent(phase, name) {\n return new ɵRuntimeError(3400 /* RuntimeErrorCode.UNSUPPORTED_TRIGGER_EVENT */, ngDevMode && `The provided animation trigger event \"${phase}\" for the animation trigger \"${name}\" is not supported!`);\n}\nfunction unregisteredTrigger(name) {\n return new ɵRuntimeError(3401 /* RuntimeErrorCode.UNREGISTERED_TRIGGER */, ngDevMode && `The provided animation trigger \"${name}\" has not been registered!`);\n}\nfunction triggerTransitionsFailed(errors) {\n return new ɵRuntimeError(3402 /* RuntimeErrorCode.TRIGGER_TRANSITIONS_FAILED */, ngDevMode && `Unable to process animations due to the following failed trigger transitions\\n ${errors.map(err => err.message).join('\\n')}`);\n}\nfunction triggerParsingFailed(name, errors) {\n return new ɵRuntimeError(3403 /* RuntimeErrorCode.TRIGGER_PARSING_FAILED */, ngDevMode && `Animation parsing for the ${name} trigger have failed:${LINE_START}${errors.map(err => err.message).join(LINE_START)}`);\n}\nfunction transitionFailed(name, errors) {\n return new ɵRuntimeError(3505 /* RuntimeErrorCode.TRANSITION_FAILED */, ngDevMode && `@${name} has failed due to:\\n ${errors.map(err => err.message).join('\\n- ')}`);\n}\n\n/**\n * Set of all animatable CSS properties\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties\n */\nconst ANIMATABLE_PROP_SET = /*#__PURE__*/new Set(['-moz-outline-radius', '-moz-outline-radius-bottomleft', '-moz-outline-radius-bottomright', '-moz-outline-radius-topleft', '-moz-outline-radius-topright', '-ms-grid-columns', '-ms-grid-rows', '-webkit-line-clamp', '-webkit-text-fill-color', '-webkit-text-stroke', '-webkit-text-stroke-color', 'accent-color', 'all', 'backdrop-filter', 'background', 'background-color', 'background-position', 'background-size', 'block-size', 'border', 'border-block-end', 'border-block-end-color', 'border-block-end-width', 'border-block-start', 'border-block-start-color', 'border-block-start-width', 'border-bottom', 'border-bottom-color', 'border-bottom-left-radius', 'border-bottom-right-radius', 'border-bottom-width', 'border-color', 'border-end-end-radius', 'border-end-start-radius', 'border-image-outset', 'border-image-slice', 'border-image-width', 'border-inline-end', 'border-inline-end-color', 'border-inline-end-width', 'border-inline-start', 'border-inline-start-color', 'border-inline-start-width', 'border-left', 'border-left-color', 'border-left-width', 'border-radius', 'border-right', 'border-right-color', 'border-right-width', 'border-start-end-radius', 'border-start-start-radius', 'border-top', 'border-top-color', 'border-top-left-radius', 'border-top-right-radius', 'border-top-width', 'border-width', 'bottom', 'box-shadow', 'caret-color', 'clip', 'clip-path', 'color', 'column-count', 'column-gap', 'column-rule', 'column-rule-color', 'column-rule-width', 'column-width', 'columns', 'filter', 'flex', 'flex-basis', 'flex-grow', 'flex-shrink', 'font', 'font-size', 'font-size-adjust', 'font-stretch', 'font-variation-settings', 'font-weight', 'gap', 'grid-column-gap', 'grid-gap', 'grid-row-gap', 'grid-template-columns', 'grid-template-rows', 'height', 'inline-size', 'input-security', 'inset', 'inset-block', 'inset-block-end', 'inset-block-start', 'inset-inline', 'inset-inline-end', 'inset-inline-start', 'left', 'letter-spacing', 'line-clamp', 'line-height', 'margin', 'margin-block-end', 'margin-block-start', 'margin-bottom', 'margin-inline-end', 'margin-inline-start', 'margin-left', 'margin-right', 'margin-top', 'mask', 'mask-border', 'mask-position', 'mask-size', 'max-block-size', 'max-height', 'max-inline-size', 'max-lines', 'max-width', 'min-block-size', 'min-height', 'min-inline-size', 'min-width', 'object-position', 'offset', 'offset-anchor', 'offset-distance', 'offset-path', 'offset-position', 'offset-rotate', 'opacity', 'order', 'outline', 'outline-color', 'outline-offset', 'outline-width', 'padding', 'padding-block-end', 'padding-block-start', 'padding-bottom', 'padding-inline-end', 'padding-inline-start', 'padding-left', 'padding-right', 'padding-top', 'perspective', 'perspective-origin', 'right', 'rotate', 'row-gap', 'scale', 'scroll-margin', 'scroll-margin-block', 'scroll-margin-block-end', 'scroll-margin-block-start', 'scroll-margin-bottom', 'scroll-margin-inline', 'scroll-margin-inline-end', 'scroll-margin-inline-start', 'scroll-margin-left', 'scroll-margin-right', 'scroll-margin-top', 'scroll-padding', 'scroll-padding-block', 'scroll-padding-block-end', 'scroll-padding-block-start', 'scroll-padding-bottom', 'scroll-padding-inline', 'scroll-padding-inline-end', 'scroll-padding-inline-start', 'scroll-padding-left', 'scroll-padding-right', 'scroll-padding-top', 'scroll-snap-coordinate', 'scroll-snap-destination', 'scrollbar-color', 'shape-image-threshold', 'shape-margin', 'shape-outside', 'tab-size', 'text-decoration', 'text-decoration-color', 'text-decoration-thickness', 'text-emphasis', 'text-emphasis-color', 'text-indent', 'text-shadow', 'text-underline-offset', 'top', 'transform', 'transform-origin', 'translate', 'vertical-align', 'visibility', 'width', 'word-spacing', 'z-index', 'zoom']);\nfunction optimizeGroupPlayer(players) {\n switch (players.length) {\n case 0:\n return new NoopAnimationPlayer();\n case 1:\n return players[0];\n default:\n return new ɵAnimationGroupPlayer(players);\n }\n}\nfunction normalizeKeyframes$1(normalizer, keyframes, preStyles = new Map(), postStyles = new Map()) {\n const errors = [];\n const normalizedKeyframes = [];\n let previousOffset = -1;\n let previousKeyframe = null;\n keyframes.forEach(kf => {\n const offset = kf.get('offset');\n const isSameOffset = offset == previousOffset;\n const normalizedKeyframe = isSameOffset && previousKeyframe || new Map();\n kf.forEach((val, prop) => {\n let normalizedProp = prop;\n let normalizedValue = val;\n if (prop !== 'offset') {\n normalizedProp = normalizer.normalizePropertyName(normalizedProp, errors);\n switch (normalizedValue) {\n case ɵPRE_STYLE:\n normalizedValue = preStyles.get(prop);\n break;\n case AUTO_STYLE:\n normalizedValue = postStyles.get(prop);\n break;\n default:\n normalizedValue = normalizer.normalizeStyleValue(prop, normalizedProp, normalizedValue, errors);\n break;\n }\n }\n normalizedKeyframe.set(normalizedProp, normalizedValue);\n });\n if (!isSameOffset) {\n normalizedKeyframes.push(normalizedKeyframe);\n }\n previousKeyframe = normalizedKeyframe;\n previousOffset = offset;\n });\n if (errors.length) {\n throw animationFailed(errors);\n }\n return normalizedKeyframes;\n}\nfunction listenOnPlayer(player, eventName, event, callback) {\n switch (eventName) {\n case 'start':\n player.onStart(() => callback(event && copyAnimationEvent(event, 'start', player)));\n break;\n case 'done':\n player.onDone(() => callback(event && copyAnimationEvent(event, 'done', player)));\n break;\n case 'destroy':\n player.onDestroy(() => callback(event && copyAnimationEvent(event, 'destroy', player)));\n break;\n }\n}\nfunction copyAnimationEvent(e, phaseName, player) {\n const totalTime = player.totalTime;\n const disabled = player.disabled ? true : false;\n const event = makeAnimationEvent(e.element, e.triggerName, e.fromState, e.toState, phaseName || e.phaseName, totalTime == undefined ? e.totalTime : totalTime, disabled);\n const data = e['_data'];\n if (data != null) {\n event['_data'] = data;\n }\n return event;\n}\nfunction makeAnimationEvent(element, triggerName, fromState, toState, phaseName = '', totalTime = 0, disabled) {\n return {\n element,\n triggerName,\n fromState,\n toState,\n phaseName,\n totalTime,\n disabled: !!disabled\n };\n}\nfunction getOrSetDefaultValue(map, key, defaultValue) {\n let value = map.get(key);\n if (!value) {\n map.set(key, value = defaultValue);\n }\n return value;\n}\nfunction parseTimelineCommand(command) {\n const separatorPos = command.indexOf(':');\n const id = command.substring(1, separatorPos);\n const action = command.slice(separatorPos + 1);\n return [id, action];\n}\nconst documentElement = /* @__PURE__ */(() => typeof document === 'undefined' ? null : document.documentElement)();\nfunction getParentElement(element) {\n const parent = element.parentNode || element.host || null; // consider host to support shadow DOM\n if (parent === documentElement) {\n return null;\n }\n return parent;\n}\nfunction containsVendorPrefix(prop) {\n // Webkit is the only real popular vendor prefix nowadays\n // cc: http://shouldiprefix.com/\n return prop.substring(1, 6) == 'ebkit'; // webkit or Webkit\n}\nlet _CACHED_BODY = null;\nlet _IS_WEBKIT = false;\nfunction validateStyleProperty(prop) {\n if (!_CACHED_BODY) {\n _CACHED_BODY = getBodyNode() || {};\n _IS_WEBKIT = _CACHED_BODY.style ? 'WebkitAppearance' in _CACHED_BODY.style : false;\n }\n let result = true;\n if (_CACHED_BODY.style && !containsVendorPrefix(prop)) {\n result = prop in _CACHED_BODY.style;\n if (!result && _IS_WEBKIT) {\n const camelProp = 'Webkit' + prop.charAt(0).toUpperCase() + prop.slice(1);\n result = camelProp in _CACHED_BODY.style;\n }\n }\n return result;\n}\nfunction validateWebAnimatableStyleProperty(prop) {\n return ANIMATABLE_PROP_SET.has(prop);\n}\nfunction getBodyNode() {\n if (typeof document != 'undefined') {\n return document.body;\n }\n return null;\n}\nfunction containsElement(elm1, elm2) {\n while (elm2) {\n if (elm2 === elm1) {\n return true;\n }\n elm2 = getParentElement(elm2);\n }\n return false;\n}\nfunction invokeQuery(element, selector, multi) {\n if (multi) {\n return Array.from(element.querySelectorAll(selector));\n }\n const elem = element.querySelector(selector);\n return elem ? [elem] : [];\n}\nfunction hypenatePropsKeys(original) {\n const newMap = new Map();\n original.forEach((val, prop) => {\n const newProp = prop.replace(/([a-z])([A-Z])/g, '$1-$2');\n newMap.set(newProp, val);\n });\n return newMap;\n}\n\n/**\n * @publicApi\n *\n * `AnimationDriver` implentation for Noop animations\n */\nlet NoopAnimationDriver = /*#__PURE__*/(() => {\n class NoopAnimationDriver {\n /**\n * @returns Whether `prop` is a valid CSS property\n */\n validateStyleProperty(prop) {\n return validateStyleProperty(prop);\n }\n /**\n * @deprecated unused\n */\n matchesElement(_element, _selector) {\n // This method is deprecated and no longer in use so we return false.\n return false;\n }\n /**\n *\n * @returns Whether elm1 contains elm2.\n */\n containsElement(elm1, elm2) {\n return containsElement(elm1, elm2);\n }\n /**\n * @returns Rhe parent of the given element or `null` if the element is the `document`\n */\n getParentElement(element) {\n return getParentElement(element);\n }\n /**\n * @returns The result of the query selector on the element. The array will contain up to 1 item\n * if `multi` is `false`.\n */\n query(element, selector, multi) {\n return invokeQuery(element, selector, multi);\n }\n /**\n * @returns The `defaultValue` or empty string\n */\n computeStyle(element, prop, defaultValue) {\n return defaultValue || '';\n }\n /**\n * @returns An `NoopAnimationPlayer`\n */\n animate(element, keyframes, duration, delay, easing, previousPlayers = [], scrubberAccessRequested) {\n return new NoopAnimationPlayer(duration, delay);\n }\n static {\n this.ɵfac = function NoopAnimationDriver_Factory(t) {\n return new (t || NoopAnimationDriver)();\n };\n }\n static {\n this.ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: NoopAnimationDriver,\n factory: NoopAnimationDriver.ɵfac\n });\n }\n }\n return NoopAnimationDriver;\n})();\n/*#__PURE__*/(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n/**\n * @publicApi\n */\nclass AnimationDriver {\n /**\n * @deprecated Use the NoopAnimationDriver class.\n */\n static {\n this.NOOP = /*#__PURE__*/new NoopAnimationDriver();\n }\n}\nclass AnimationStyleNormalizer {}\nclass NoopAnimationStyleNormalizer {\n normalizePropertyName(propertyName, errors) {\n return propertyName;\n }\n normalizeStyleValue(userProvidedProperty, normalizedProperty, value, errors) {\n return value;\n }\n}\nconst ONE_SECOND = 1000;\nconst SUBSTITUTION_EXPR_START = '{{';\nconst SUBSTITUTION_EXPR_END = '}}';\nconst ENTER_CLASSNAME = 'ng-enter';\nconst LEAVE_CLASSNAME = 'ng-leave';\nconst NG_TRIGGER_CLASSNAME = 'ng-trigger';\nconst NG_TRIGGER_SELECTOR = '.ng-trigger';\nconst NG_ANIMATING_CLASSNAME = 'ng-animating';\nconst NG_ANIMATING_SELECTOR = '.ng-animating';\nfunction resolveTimingValue(value) {\n if (typeof value == 'number') return value;\n const matches = value.match(/^(-?[\\.\\d]+)(m?s)/);\n if (!matches || matches.length < 2) return 0;\n return _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);\n}\nfunction _convertTimeValueToMS(value, unit) {\n switch (unit) {\n case 's':\n return value * ONE_SECOND;\n default:\n // ms or something else\n return value;\n }\n}\nfunction resolveTiming(timings, errors, allowNegativeValues) {\n return timings.hasOwnProperty('duration') ? timings : parseTimeExpression(timings, errors, allowNegativeValues);\n}\nfunction parseTimeExpression(exp, errors, allowNegativeValues) {\n const regex = /^(-?[\\.\\d]+)(m?s)(?:\\s+(-?[\\.\\d]+)(m?s))?(?:\\s+([-a-z]+(?:\\(.+?\\))?))?$/i;\n let duration;\n let delay = 0;\n let easing = '';\n if (typeof exp === 'string') {\n const matches = exp.match(regex);\n if (matches === null) {\n errors.push(invalidTimingValue(exp));\n return {\n duration: 0,\n delay: 0,\n easing: ''\n };\n }\n duration = _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);\n const delayMatch = matches[3];\n if (delayMatch != null) {\n delay = _convertTimeValueToMS(parseFloat(delayMatch), matches[4]);\n }\n const easingVal = matches[5];\n if (easingVal) {\n easing = easingVal;\n }\n } else {\n duration = exp;\n }\n if (!allowNegativeValues) {\n let containsErrors = false;\n let startIndex = errors.length;\n if (duration < 0) {\n errors.push(negativeStepValue());\n containsErrors = true;\n }\n if (delay < 0) {\n errors.push(negativeDelayValue());\n containsErrors = true;\n }\n if (containsErrors) {\n errors.splice(startIndex, 0, invalidTimingValue(exp));\n }\n }\n return {\n duration,\n delay,\n easing\n };\n}\nfunction normalizeKeyframes(keyframes) {\n if (!keyframes.length) {\n return [];\n }\n if (keyframes[0] instanceof Map) {\n return keyframes;\n }\n return keyframes.map(kf => new Map(Object.entries(kf)));\n}\nfunction normalizeStyles(styles) {\n return Array.isArray(styles) ? new Map(...styles) : new Map(styles);\n}\nfunction setStyles(element, styles, formerStyles) {\n styles.forEach((val, prop) => {\n const camelProp = dashCaseToCamelCase(prop);\n if (formerStyles && !formerStyles.has(prop)) {\n formerStyles.set(prop, element.style[camelProp]);\n }\n element.style[camelProp] = val;\n });\n}\nfunction eraseStyles(element, styles) {\n styles.forEach((_, prop) => {\n const camelProp = dashCaseToCamelCase(prop);\n element.style[camelProp] = '';\n });\n}\nfunction normalizeAnimationEntry(steps) {\n if (Array.isArray(steps)) {\n if (steps.length == 1) return steps[0];\n return sequence(steps);\n }\n return steps;\n}\nfunction validateStyleParams(value, options, errors) {\n const params = options.params || {};\n const matches = extractStyleParams(value);\n if (matches.length) {\n matches.forEach(varName => {\n if (!params.hasOwnProperty(varName)) {\n errors.push(invalidStyleParams(varName));\n }\n });\n }\n}\nconst PARAM_REGEX = /*#__PURE__*/new RegExp(`${SUBSTITUTION_EXPR_START}\\\\s*(.+?)\\\\s*${SUBSTITUTION_EXPR_END}`, 'g');\nfunction extractStyleParams(value) {\n let params = [];\n if (typeof value === 'string') {\n let match;\n while (match = PARAM_REGEX.exec(value)) {\n params.push(match[1]);\n }\n PARAM_REGEX.lastIndex = 0;\n }\n return params;\n}\nfunction interpolateParams(value, params, errors) {\n const original = `${value}`;\n const str = original.replace(PARAM_REGEX, (_, varName) => {\n let localVal = params[varName];\n // this means that the value was never overridden by the data passed in by the user\n if (localVal == null) {\n errors.push(invalidParamValue(varName));\n localVal = '';\n }\n return localVal.toString();\n });\n // we do this to assert that numeric values stay as they are\n return str == original ? value : str;\n}\nconst DASH_CASE_REGEXP = /-+([a-z0-9])/g;\nfunction dashCaseToCamelCase(input) {\n return input.replace(DASH_CASE_REGEXP, (...m) => m[1].toUpperCase());\n}\nfunction camelCaseToDashCase(input) {\n return input.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n}\nfunction allowPreviousPlayerStylesMerge(duration, delay) {\n return duration === 0 || delay === 0;\n}\nfunction balancePreviousStylesIntoKeyframes(element, keyframes, previousStyles) {\n if (previousStyles.size && keyframes.length) {\n let startingKeyframe = keyframes[0];\n let missingStyleProps = [];\n previousStyles.forEach((val, prop) => {\n if (!startingKeyframe.has(prop)) {\n missingStyleProps.push(prop);\n }\n startingKeyframe.set(prop, val);\n });\n if (missingStyleProps.length) {\n for (let i = 1; i < keyframes.length; i++) {\n let kf = keyframes[i];\n missingStyleProps.forEach(prop => kf.set(prop, computeStyle(element, prop)));\n }\n }\n }\n return keyframes;\n}\nfunction visitDslNode(visitor, node, context) {\n switch (node.type) {\n case AnimationMetadataType.Trigger:\n return visitor.visitTrigger(node, context);\n case AnimationMetadataType.State:\n return visitor.visitState(node, context);\n case AnimationMetadataType.Transition:\n return visitor.visitTransition(node, context);\n case AnimationMetadataType.Sequence:\n return visitor.visitSequence(node, context);\n case AnimationMetadataType.Group:\n return visitor.visitGroup(node, context);\n case AnimationMetadataType.Animate:\n return visitor.visitAnimate(node, context);\n case AnimationMetadataType.Keyframes:\n return visitor.visitKeyframes(node, context);\n case AnimationMetadataType.Style:\n return visitor.visitStyle(node, context);\n case AnimationMetadataType.Reference:\n return visitor.visitReference(node, context);\n case AnimationMetadataType.AnimateChild:\n return visitor.visitAnimateChild(node, context);\n case AnimationMetadataType.AnimateRef:\n return visitor.visitAnimateRef(node, context);\n case AnimationMetadataType.Query:\n return visitor.visitQuery(node, context);\n case AnimationMetadataType.Stagger:\n return visitor.visitStagger(node, context);\n default:\n throw invalidNodeType(node.type);\n }\n}\nfunction computeStyle(element, prop) {\n return window.getComputedStyle(element)[prop];\n}\nconst DIMENSIONAL_PROP_SET = /*#__PURE__*/new Set(['width', 'height', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'left', 'top', 'bottom', 'right', 'fontSize', 'outlineWidth', 'outlineOffset', 'paddingTop', 'paddingLeft', 'paddingBottom', 'paddingRight', 'marginTop', 'marginLeft', 'marginBottom', 'marginRight', 'borderRadius', 'borderWidth', 'borderTopWidth', 'borderLeftWidth', 'borderRightWidth', 'borderBottomWidth', 'textIndent', 'perspective']);\nclass WebAnimationsStyleNormalizer extends AnimationStyleNormalizer {\n normalizePropertyName(propertyName, errors) {\n return dashCaseToCamelCase(propertyName);\n }\n normalizeStyleValue(userProvidedProperty, normalizedProperty, value, errors) {\n let unit = '';\n const strVal = value.toString().trim();\n if (DIMENSIONAL_PROP_SET.has(normalizedProperty) && value !== 0 && value !== '0') {\n if (typeof value === 'number') {\n unit = 'px';\n } else {\n const valAndSuffixMatch = value.match(/^[+-]?[\\d\\.]+([a-z]*)$/);\n if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {\n errors.push(invalidCssUnitValue(userProvidedProperty, value));\n }\n }\n }\n return strVal + unit;\n }\n}\nfunction createListOfWarnings(warnings) {\n const LINE_START = '\\n - ';\n return `${LINE_START}${warnings.filter(Boolean).map(warning => warning).join(LINE_START)}`;\n}\nfunction warnValidation(warnings) {\n (typeof ngDevMode === 'undefined' || ngDevMode) && console.warn(`animation validation warnings:${createListOfWarnings(warnings)}`);\n}\nfunction warnTriggerBuild(name, warnings) {\n (typeof ngDevMode === 'undefined' || ngDevMode) && console.warn(`The animation trigger \"${name}\" has built with the following warnings:${createListOfWarnings(warnings)}`);\n}\nfunction warnRegister(warnings) {\n (typeof ngDevMode === 'undefined' || ngDevMode) && console.warn(`Animation built with the following warnings:${createListOfWarnings(warnings)}`);\n}\nfunction triggerParsingWarnings(name, warnings) {\n (typeof ngDevMode === 'undefined' || ngDevMode) && console.warn(`Animation parsing for the ${name} trigger presents the following warnings:${createListOfWarnings(warnings)}`);\n}\nfunction pushUnrecognizedPropertiesWarning(warnings, props) {\n if (props.length) {\n warnings.push(`The following provided properties are not recognized: ${props.join(', ')}`);\n }\n}\nconst ANY_STATE = '*';\nfunction parseTransitionExpr(transitionValue, errors) {\n const expressions = [];\n if (typeof transitionValue == 'string') {\n transitionValue.split(/\\s*,\\s*/).forEach(str => parseInnerTransitionStr(str, expressions, errors));\n } else {\n expressions.push(transitionValue);\n }\n return expressions;\n}\nfunction parseInnerTransitionStr(eventStr, expressions, errors) {\n if (eventStr[0] == ':') {\n const result = parseAnimationAlias(eventStr, errors);\n if (typeof result == 'function') {\n expressions.push(result);\n return;\n }\n eventStr = result;\n }\n const match = eventStr.match(/^(\\*|[-\\w]+)\\s*()\\s*(\\*|[-\\w]+)$/);\n if (match == null || match.length < 4) {\n errors.push(invalidExpression(eventStr));\n return expressions;\n }\n const fromState = match[1];\n const separator = match[2];\n const toState = match[3];\n expressions.push(makeLambdaFromStates(fromState, toState));\n const isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE;\n if (separator[0] == '<' && !isFullAnyStateExpr) {\n expressions.push(makeLambdaFromStates(toState, fromState));\n }\n return;\n}\nfunction parseAnimationAlias(alias, errors) {\n switch (alias) {\n case ':enter':\n return 'void => *';\n case ':leave':\n return '* => void';\n case ':increment':\n return (fromState, toState) => parseFloat(toState) > parseFloat(fromState);\n case ':decrement':\n return (fromState, toState) => parseFloat(toState) < parseFloat(fromState);\n default:\n errors.push(invalidTransitionAlias(alias));\n return '* => *';\n }\n}\n// DO NOT REFACTOR ... keep the follow set instantiations\n// with the values intact (closure compiler for some reason\n// removes follow-up lines that add the values outside of\n// the constructor...\nconst TRUE_BOOLEAN_VALUES = /*#__PURE__*/new Set(['true', '1']);\nconst FALSE_BOOLEAN_VALUES = /*#__PURE__*/new Set(['false', '0']);\nfunction makeLambdaFromStates(lhs, rhs) {\n const LHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(lhs) || FALSE_BOOLEAN_VALUES.has(lhs);\n const RHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(rhs) || FALSE_BOOLEAN_VALUES.has(rhs);\n return (fromState, toState) => {\n let lhsMatch = lhs == ANY_STATE || lhs == fromState;\n let rhsMatch = rhs == ANY_STATE || rhs == toState;\n if (!lhsMatch && LHS_MATCH_BOOLEAN && typeof fromState === 'boolean') {\n lhsMatch = fromState ? TRUE_BOOLEAN_VALUES.has(lhs) : FALSE_BOOLEAN_VALUES.has(lhs);\n }\n if (!rhsMatch && RHS_MATCH_BOOLEAN && typeof toState === 'boolean') {\n rhsMatch = toState ? TRUE_BOOLEAN_VALUES.has(rhs) : FALSE_BOOLEAN_VALUES.has(rhs);\n }\n return lhsMatch && rhsMatch;\n };\n}\nconst SELF_TOKEN = ':self';\nconst SELF_TOKEN_REGEX = /*#__PURE__*/new RegExp(`s*${SELF_TOKEN}s*,?`, 'g');\n/*\n * [Validation]\n * The visitor code below will traverse the animation AST generated by the animation verb functions\n * (the output is a tree of objects) and attempt to perform a series of validations on the data. The\n * following corner-cases will be validated:\n *\n * 1. Overlap of animations\n * Given that a CSS property cannot be animated in more than one place at the same time, it's\n * important that this behavior is detected and validated. The way in which this occurs is that\n * each time a style property is examined, a string-map containing the property will be updated with\n * the start and end times for when the property is used within an animation step.\n *\n * If there are two or more parallel animations that are currently running (these are invoked by the\n * group()) on the same element then the validator will throw an error. Since the start/end timing\n * values are collected for each property then if the current animation step is animating the same\n * property and its timing values fall anywhere into the window of time that the property is\n * currently being animated within then this is what causes an error.\n *\n * 2. Timing values\n * The validator will validate to see if a timing value of `duration delay easing` or\n * `durationNumber` is valid or not.\n *\n * (note that upon validation the code below will replace the timing data with an object containing\n * {duration,delay,easing}.\n *\n * 3. Offset Validation\n * Each of the style() calls are allowed to have an offset value when placed inside of keyframes().\n * Offsets within keyframes() are considered valid when:\n *\n * - No offsets are used at all\n * - Each style() entry contains an offset value\n * - Each offset is between 0 and 1\n * - Each offset is greater to or equal than the previous one\n *\n * Otherwise an error will be thrown.\n */\nfunction buildAnimationAst(driver, metadata, errors, warnings) {\n return new AnimationAstBuilderVisitor(driver).build(metadata, errors, warnings);\n}\nconst ROOT_SELECTOR = '';\nclass AnimationAstBuilderVisitor {\n constructor(_driver) {\n this._driver = _driver;\n }\n build(metadata, errors, warnings) {\n const context = new AnimationAstBuilderContext(errors);\n this._resetContextStyleTimingState(context);\n const ast = visitDslNode(this, normalizeAnimationEntry(metadata), context);\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n if (context.unsupportedCSSPropertiesFound.size) {\n pushUnrecognizedPropertiesWarning(warnings, [...context.unsupportedCSSPropertiesFound.keys()]);\n }\n }\n return ast;\n }\n _resetContextStyleTimingState(context) {\n context.currentQuerySelector = ROOT_SELECTOR;\n context.collectedStyles = new Map();\n context.collectedStyles.set(ROOT_SELECTOR, new Map());\n context.currentTime = 0;\n }\n visitTrigger(metadata, context) {\n let queryCount = context.queryCount = 0;\n let depCount = context.depCount = 0;\n const states = [];\n const transitions = [];\n if (metadata.name.charAt(0) == '@') {\n context.errors.push(invalidTrigger());\n }\n metadata.definitions.forEach(def => {\n this._resetContextStyleTimingState(context);\n if (def.type == AnimationMetadataType.State) {\n const stateDef = def;\n const name = stateDef.name;\n name.toString().split(/\\s*,\\s*/).forEach(n => {\n stateDef.name = n;\n states.push(this.visitState(stateDef, context));\n });\n stateDef.name = name;\n } else if (def.type == AnimationMetadataType.Transition) {\n const transition = this.visitTransition(def, context);\n queryCount += transition.queryCount;\n depCount += transition.depCount;\n transitions.push(transition);\n } else {\n context.errors.push(invalidDefinition());\n }\n });\n return {\n type: AnimationMetadataType.Trigger,\n name: metadata.name,\n states,\n transitions,\n queryCount,\n depCount,\n options: null\n };\n }\n visitState(metadata, context) {\n const styleAst = this.visitStyle(metadata.styles, context);\n const astParams = metadata.options && metadata.options.params || null;\n if (styleAst.containsDynamicStyles) {\n const missingSubs = new Set();\n const params = astParams || {};\n styleAst.styles.forEach(style => {\n if (style instanceof Map) {\n style.forEach(value => {\n extractStyleParams(value).forEach(sub => {\n if (!params.hasOwnProperty(sub)) {\n missingSubs.add(sub);\n }\n });\n });\n }\n });\n if (missingSubs.size) {\n context.errors.push(invalidState(metadata.name, [...missingSubs.values()]));\n }\n }\n return {\n type: AnimationMetadataType.State,\n name: metadata.name,\n style: styleAst,\n options: astParams ? {\n params: astParams\n } : null\n };\n }\n visitTransition(metadata, context) {\n context.queryCount = 0;\n context.depCount = 0;\n const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);\n const matchers = parseTransitionExpr(metadata.expr, context.errors);\n return {\n type: AnimationMetadataType.Transition,\n matchers,\n animation,\n queryCount: context.queryCount,\n depCount: context.depCount,\n options: normalizeAnimationOptions(metadata.options)\n };\n }\n visitSequence(metadata, context) {\n return {\n type: AnimationMetadataType.Sequence,\n steps: metadata.steps.map(s => visitDslNode(this, s, context)),\n options: normalizeAnimationOptions(metadata.options)\n };\n }\n visitGroup(metadata, context) {\n const currentTime = context.currentTime;\n let furthestTime = 0;\n const steps = metadata.steps.map(step => {\n context.currentTime = currentTime;\n const innerAst = visitDslNode(this, step, context);\n furthestTime = Math.max(furthestTime, context.currentTime);\n return innerAst;\n });\n context.currentTime = furthestTime;\n return {\n type: AnimationMetadataType.Group,\n steps,\n options: normalizeAnimationOptions(metadata.options)\n };\n }\n visitAnimate(metadata, context) {\n const timingAst = constructTimingAst(metadata.timings, context.errors);\n context.currentAnimateTimings = timingAst;\n let styleAst;\n let styleMetadata = metadata.styles ? metadata.styles : style({});\n if (styleMetadata.type == AnimationMetadataType.Keyframes) {\n styleAst = this.visitKeyframes(styleMetadata, context);\n } else {\n let styleMetadata = metadata.styles;\n let isEmpty = false;\n if (!styleMetadata) {\n isEmpty = true;\n const newStyleData = {};\n if (timingAst.easing) {\n newStyleData['easing'] = timingAst.easing;\n }\n styleMetadata = style(newStyleData);\n }\n context.currentTime += timingAst.duration + timingAst.delay;\n const _styleAst = this.visitStyle(styleMetadata, context);\n _styleAst.isEmptyStep = isEmpty;\n styleAst = _styleAst;\n }\n context.currentAnimateTimings = null;\n return {\n type: AnimationMetadataType.Animate,\n timings: timingAst,\n style: styleAst,\n options: null\n };\n }\n visitStyle(metadata, context) {\n const ast = this._makeStyleAst(metadata, context);\n this._validateStyleAst(ast, context);\n return ast;\n }\n _makeStyleAst(metadata, context) {\n const styles = [];\n const metadataStyles = Array.isArray(metadata.styles) ? metadata.styles : [metadata.styles];\n for (let styleTuple of metadataStyles) {\n if (typeof styleTuple === 'string') {\n if (styleTuple === AUTO_STYLE) {\n styles.push(styleTuple);\n } else {\n context.errors.push(invalidStyleValue(styleTuple));\n }\n } else {\n styles.push(new Map(Object.entries(styleTuple)));\n }\n }\n let containsDynamicStyles = false;\n let collectedEasing = null;\n styles.forEach(styleData => {\n if (styleData instanceof Map) {\n if (styleData.has('easing')) {\n collectedEasing = styleData.get('easing');\n styleData.delete('easing');\n }\n if (!containsDynamicStyles) {\n for (let value of styleData.values()) {\n if (value.toString().indexOf(SUBSTITUTION_EXPR_START) >= 0) {\n containsDynamicStyles = true;\n break;\n }\n }\n }\n }\n });\n return {\n type: AnimationMetadataType.Style,\n styles,\n easing: collectedEasing,\n offset: metadata.offset,\n containsDynamicStyles,\n options: null\n };\n }\n _validateStyleAst(ast, context) {\n const timings = context.currentAnimateTimings;\n let endTime = context.currentTime;\n let startTime = context.currentTime;\n if (timings && startTime > 0) {\n startTime -= timings.duration + timings.delay;\n }\n ast.styles.forEach(tuple => {\n if (typeof tuple === 'string') return;\n tuple.forEach((value, prop) => {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n if (!this._driver.validateStyleProperty(prop)) {\n tuple.delete(prop);\n context.unsupportedCSSPropertiesFound.add(prop);\n return;\n }\n }\n // This is guaranteed to have a defined Map at this querySelector location making it\n // safe to add the assertion here. It is set as a default empty map in prior methods.\n const collectedStyles = context.collectedStyles.get(context.currentQuerySelector);\n const collectedEntry = collectedStyles.get(prop);\n let updateCollectedStyle = true;\n if (collectedEntry) {\n if (startTime != endTime && startTime >= collectedEntry.startTime && endTime <= collectedEntry.endTime) {\n context.errors.push(invalidParallelAnimation(prop, collectedEntry.startTime, collectedEntry.endTime, startTime, endTime));\n updateCollectedStyle = false;\n }\n // we always choose the smaller start time value since we\n // want to have a record of the entire animation window where\n // the style property is being animated in between\n startTime = collectedEntry.startTime;\n }\n if (updateCollectedStyle) {\n collectedStyles.set(prop, {\n startTime,\n endTime\n });\n }\n if (context.options) {\n validateStyleParams(value, context.options, context.errors);\n }\n });\n });\n }\n visitKeyframes(metadata, context) {\n const ast = {\n type: AnimationMetadataType.Keyframes,\n styles: [],\n options: null\n };\n if (!context.currentAnimateTimings) {\n context.errors.push(invalidKeyframes());\n return ast;\n }\n const MAX_KEYFRAME_OFFSET = 1;\n let totalKeyframesWithOffsets = 0;\n const offsets = [];\n let offsetsOutOfOrder = false;\n let keyframesOutOfRange = false;\n let previousOffset = 0;\n const keyframes = metadata.steps.map(styles => {\n const style = this._makeStyleAst(styles, context);\n let offsetVal = style.offset != null ? style.offset : consumeOffset(style.styles);\n let offset = 0;\n if (offsetVal != null) {\n totalKeyframesWithOffsets++;\n offset = style.offset = offsetVal;\n }\n keyframesOutOfRange = keyframesOutOfRange || offset < 0 || offset > 1;\n offsetsOutOfOrder = offsetsOutOfOrder || offset < previousOffset;\n previousOffset = offset;\n offsets.push(offset);\n return style;\n });\n if (keyframesOutOfRange) {\n context.errors.push(invalidOffset());\n }\n if (offsetsOutOfOrder) {\n context.errors.push(keyframeOffsetsOutOfOrder());\n }\n const length = metadata.steps.length;\n let generatedOffset = 0;\n if (totalKeyframesWithOffsets > 0 && totalKeyframesWithOffsets < length) {\n context.errors.push(keyframesMissingOffsets());\n } else if (totalKeyframesWithOffsets == 0) {\n generatedOffset = MAX_KEYFRAME_OFFSET / (length - 1);\n }\n const limit = length - 1;\n const currentTime = context.currentTime;\n const currentAnimateTimings = context.currentAnimateTimings;\n const animateDuration = currentAnimateTimings.duration;\n keyframes.forEach((kf, i) => {\n const offset = generatedOffset > 0 ? i == limit ? 1 : generatedOffset * i : offsets[i];\n const durationUpToThisFrame = offset * animateDuration;\n context.currentTime = currentTime + currentAnimateTimings.delay + durationUpToThisFrame;\n currentAnimateTimings.duration = durationUpToThisFrame;\n this._validateStyleAst(kf, context);\n kf.offset = offset;\n ast.styles.push(kf);\n });\n return ast;\n }\n visitReference(metadata, context) {\n return {\n type: AnimationMetadataType.Reference,\n animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),\n options: normalizeAnimationOptions(metadata.options)\n };\n }\n visitAnimateChild(metadata, context) {\n context.depCount++;\n return {\n type: AnimationMetadataType.AnimateChild,\n options: normalizeAnimationOptions(metadata.options)\n };\n }\n visitAnimateRef(metadata, context) {\n return {\n type: AnimationMetadataType.AnimateRef,\n animation: this.visitReference(metadata.animation, context),\n options: normalizeAnimationOptions(metadata.options)\n };\n }\n visitQuery(metadata, context) {\n const parentSelector = context.currentQuerySelector;\n const options = metadata.options || {};\n context.queryCount++;\n context.currentQuery = metadata;\n const [selector, includeSelf] = normalizeSelector(metadata.selector);\n context.currentQuerySelector = parentSelector.length ? parentSelector + ' ' + selector : selector;\n getOrSetDefaultValue(context.collectedStyles, context.currentQuerySelector, new Map());\n const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);\n context.currentQuery = null;\n context.currentQuerySelector = parentSelector;\n return {\n type: AnimationMetadataType.Query,\n selector,\n limit: options.limit || 0,\n optional: !!options.optional,\n includeSelf,\n animation,\n originalSelector: metadata.selector,\n options: normalizeAnimationOptions(metadata.options)\n };\n }\n visitStagger(metadata, context) {\n if (!context.currentQuery) {\n context.errors.push(invalidStagger());\n }\n const timings = metadata.timings === 'full' ? {\n duration: 0,\n delay: 0,\n easing: 'full'\n } : resolveTiming(metadata.timings, context.errors, true);\n return {\n type: AnimationMetadataType.Stagger,\n animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),\n timings,\n options: null\n };\n }\n}\nfunction normalizeSelector(selector) {\n const hasAmpersand = selector.split(/\\s*,\\s*/).find(token => token == SELF_TOKEN) ? true : false;\n if (hasAmpersand) {\n selector = selector.replace(SELF_TOKEN_REGEX, '');\n }\n // Note: the :enter and :leave aren't normalized here since those\n // selectors are filled in at runtime during timeline building\n selector = selector.replace(/@\\*/g, NG_TRIGGER_SELECTOR).replace(/@\\w+/g, match => NG_TRIGGER_SELECTOR + '-' + match.slice(1)).replace(/:animating/g, NG_ANIMATING_SELECTOR);\n return [selector, hasAmpersand];\n}\nfunction normalizeParams(obj) {\n return obj ? {\n ...obj\n } : null;\n}\nclass AnimationAstBuilderContext {\n constructor(errors) {\n this.errors = errors;\n this.queryCount = 0;\n this.depCount = 0;\n this.currentTransition = null;\n this.currentQuery = null;\n this.currentQuerySelector = null;\n this.currentAnimateTimings = null;\n this.currentTime = 0;\n this.collectedStyles = new Map();\n this.options = null;\n this.unsupportedCSSPropertiesFound = new Set();\n }\n}\nfunction consumeOffset(styles) {\n if (typeof styles == 'string') return null;\n let offset = null;\n if (Array.isArray(styles)) {\n styles.forEach(styleTuple => {\n if (styleTuple instanceof Map && styleTuple.has('offset')) {\n const obj = styleTuple;\n offset = parseFloat(obj.get('offset'));\n obj.delete('offset');\n }\n });\n } else if (styles instanceof Map && styles.has('offset')) {\n const obj = styles;\n offset = parseFloat(obj.get('offset'));\n obj.delete('offset');\n }\n return offset;\n}\nfunction constructTimingAst(value, errors) {\n if (value.hasOwnProperty('duration')) {\n return value;\n }\n if (typeof value == 'number') {\n const duration = resolveTiming(value, errors).duration;\n return makeTimingAst(duration, 0, '');\n }\n const strValue = value;\n const isDynamic = strValue.split(/\\s+/).some(v => v.charAt(0) == '{' && v.charAt(1) == '{');\n if (isDynamic) {\n const ast = makeTimingAst(0, 0, '');\n ast.dynamic = true;\n ast.strValue = strValue;\n return ast;\n }\n const timings = resolveTiming(strValue, errors);\n return makeTimingAst(timings.duration, timings.delay, timings.easing);\n}\nfunction normalizeAnimationOptions(options) {\n if (options) {\n options = {\n ...options\n };\n if (options['params']) {\n options['params'] = normalizeParams(options['params']);\n }\n } else {\n options = {};\n }\n return options;\n}\nfunction makeTimingAst(duration, delay, easing) {\n return {\n duration,\n delay,\n easing\n };\n}\nfunction createTimelineInstruction(element, keyframes, preStyleProps, postStyleProps, duration, delay, easing = null, subTimeline = false) {\n return {\n type: 1 /* AnimationTransitionInstructionType.TimelineAnimation */,\n element,\n keyframes,\n preStyleProps,\n postStyleProps,\n duration,\n delay,\n totalTime: duration + delay,\n easing,\n subTimeline\n };\n}\nclass ElementInstructionMap {\n constructor() {\n this._map = new Map();\n }\n get(element) {\n return this._map.get(element) || [];\n }\n append(element, instructions) {\n let existingInstructions = this._map.get(element);\n if (!existingInstructions) {\n this._map.set(element, existingInstructions = []);\n }\n existingInstructions.push(...instructions);\n }\n has(element) {\n return this._map.has(element);\n }\n clear() {\n this._map.clear();\n }\n}\nconst ONE_FRAME_IN_MILLISECONDS = 1;\nconst ENTER_TOKEN = ':enter';\nconst ENTER_TOKEN_REGEX = /*#__PURE__*/new RegExp(ENTER_TOKEN, 'g');\nconst LEAVE_TOKEN = ':leave';\nconst LEAVE_TOKEN_REGEX = /*#__PURE__*/new RegExp(LEAVE_TOKEN, 'g');\n/*\n * The code within this file aims to generate web-animations-compatible keyframes from Angular's\n * animation DSL code.\n *\n * The code below will be converted from:\n *\n * ```\n * sequence([\n * style({ opacity: 0 }),\n * animate(1000, style({ opacity: 0 }))\n * ])\n * ```\n *\n * To:\n * ```\n * keyframes = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: 1 }]\n * duration = 1000\n * delay = 0\n * easing = ''\n * ```\n *\n * For this operation to cover the combination of animation verbs (style, animate, group, etc...) a\n * combination of AST traversal and merge-sort-like algorithms are used.\n *\n * [AST Traversal]\n * Each of the animation verbs, when executed, will return an string-map object representing what\n * type of action it is (style, animate, group, etc...) and the data associated with it. This means\n * that when functional composition mix of these functions is evaluated (like in the example above)\n * then it will end up producing a tree of objects representing the animation itself.\n *\n * When this animation object tree is processed by the visitor code below it will visit each of the\n * verb statements within the visitor. And during each visit it will build the context of the\n * animation keyframes by interacting with the `TimelineBuilder`.\n *\n * [TimelineBuilder]\n * This class is responsible for tracking the styles and building a series of keyframe objects for a\n * timeline between a start and end time. The builder starts off with an initial timeline and each\n * time the AST comes across a `group()`, `keyframes()` or a combination of the two within a\n * `sequence()` then it will generate a sub timeline for each step as well as a new one after\n * they are complete.\n *\n * As the AST is traversed, the timing state on each of the timelines will be incremented. If a sub\n * timeline was created (based on one of the cases above) then the parent timeline will attempt to\n * merge the styles used within the sub timelines into itself (only with group() this will happen).\n * This happens with a merge operation (much like how the merge works in mergeSort) and it will only\n * copy the most recently used styles from the sub timelines into the parent timeline. This ensures\n * that if the styles are used later on in another phase of the animation then they will be the most\n * up-to-date values.\n *\n * [How Missing Styles Are Updated]\n * Each timeline has a `backFill` property which is responsible for filling in new styles into\n * already processed keyframes if a new style shows up later within the animation sequence.\n *\n * ```\n * sequence([\n * style({ width: 0 }),\n * animate(1000, style({ width: 100 })),\n * animate(1000, style({ width: 200 })),\n * animate(1000, style({ width: 300 }))\n * animate(1000, style({ width: 400, height: 400 })) // notice how `height` doesn't exist anywhere\n * else\n * ])\n * ```\n *\n * What is happening here is that the `height` value is added later in the sequence, but is missing\n * from all previous animation steps. Therefore when a keyframe is created it would also be missing\n * from all previous keyframes up until where it is first used. For the timeline keyframe generation\n * to properly fill in the style it will place the previous value (the value from the parent\n * timeline) or a default value of `*` into the backFill map.\n *\n * When a sub-timeline is created it will have its own backFill property. This is done so that\n * styles present within the sub-timeline do not accidentally seep into the previous/future timeline\n * keyframes\n *\n * [Validation]\n * The code in this file is not responsible for validation. That functionality happens with within\n * the `AnimationValidatorVisitor` code.\n */\nfunction buildAnimationTimelines(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles = new Map(), finalStyles = new Map(), options, subInstructions, errors = []) {\n return new AnimationTimelineBuilderVisitor().buildKeyframes(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors);\n}\nclass AnimationTimelineBuilderVisitor {\n buildKeyframes(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors = []) {\n subInstructions = subInstructions || new ElementInstructionMap();\n const context = new AnimationTimelineContext(driver, rootElement, subInstructions, enterClassName, leaveClassName, errors, []);\n context.options = options;\n const delay = options.delay ? resolveTimingValue(options.delay) : 0;\n context.currentTimeline.delayNextStep(delay);\n context.currentTimeline.setStyles([startingStyles], null, context.errors, options);\n visitDslNode(this, ast, context);\n // this checks to see if an actual animation happened\n const timelines = context.timelines.filter(timeline => timeline.containsAnimation());\n // note: we just want to apply the final styles for the rootElement, so we do not\n // just apply the styles to the last timeline but the last timeline which\n // element is the root one (basically `*`-styles are replaced with the actual\n // state style values only for the root element)\n if (timelines.length && finalStyles.size) {\n let lastRootTimeline;\n for (let i = timelines.length - 1; i >= 0; i--) {\n const timeline = timelines[i];\n if (timeline.element === rootElement) {\n lastRootTimeline = timeline;\n break;\n }\n }\n if (lastRootTimeline && !lastRootTimeline.allowOnlyTimelineStyles()) {\n lastRootTimeline.setStyles([finalStyles], null, context.errors, options);\n }\n }\n return timelines.length ? timelines.map(timeline => timeline.buildKeyframes()) : [createTimelineInstruction(rootElement, [], [], [], 0, delay, '', false)];\n }\n visitTrigger(ast, context) {\n // these values are not visited in this AST\n }\n visitState(ast, context) {\n // these values are not visited in this AST\n }\n visitTransition(ast, context) {\n // these values are not visited in this AST\n }\n visitAnimateChild(ast, context) {\n const elementInstructions = context.subInstructions.get(context.element);\n if (elementInstructions) {\n const innerContext = context.createSubContext(ast.options);\n const startTime = context.currentTimeline.currentTime;\n const endTime = this._visitSubInstructions(elementInstructions, innerContext, innerContext.options);\n if (startTime != endTime) {\n // we do this on the upper context because we created a sub context for\n // the sub child animations\n context.transformIntoNewTimeline(endTime);\n }\n }\n context.previousNode = ast;\n }\n visitAnimateRef(ast, context) {\n const innerContext = context.createSubContext(ast.options);\n innerContext.transformIntoNewTimeline();\n this._applyAnimationRefDelays([ast.options, ast.animation.options], context, innerContext);\n this.visitReference(ast.animation, innerContext);\n context.transformIntoNewTimeline(innerContext.currentTimeline.currentTime);\n context.previousNode = ast;\n }\n _applyAnimationRefDelays(animationsRefsOptions, context, innerContext) {\n for (const animationRefOptions of animationsRefsOptions) {\n const animationDelay = animationRefOptions?.delay;\n if (animationDelay) {\n const animationDelayValue = typeof animationDelay === 'number' ? animationDelay : resolveTimingValue(interpolateParams(animationDelay, animationRefOptions?.params ?? {}, context.errors));\n innerContext.delayNextStep(animationDelayValue);\n }\n }\n }\n _visitSubInstructions(instructions, context, options) {\n const startTime = context.currentTimeline.currentTime;\n let furthestTime = startTime;\n // this is a special-case for when a user wants to skip a sub\n // animation from being fired entirely.\n const duration = options.duration != null ? resolveTimingValue(options.duration) : null;\n const delay = options.delay != null ? resolveTimingValue(options.delay) : null;\n if (duration !== 0) {\n instructions.forEach(instruction => {\n const instructionTimings = context.appendInstructionToTimeline(instruction, duration, delay);\n furthestTime = Math.max(furthestTime, instructionTimings.duration + instructionTimings.delay);\n });\n }\n return furthestTime;\n }\n visitReference(ast, context) {\n context.updateOptions(ast.options, true);\n visitDslNode(this, ast.animation, context);\n context.previousNode = ast;\n }\n visitSequence(ast, context) {\n const subContextCount = context.subContextCount;\n let ctx = context;\n const options = ast.options;\n if (options && (options.params || options.delay)) {\n ctx = context.createSubContext(options);\n ctx.transformIntoNewTimeline();\n if (options.delay != null) {\n if (ctx.previousNode.type == AnimationMetadataType.Style) {\n ctx.currentTimeline.snapshotCurrentStyles();\n ctx.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;\n }\n const delay = resolveTimingValue(options.delay);\n ctx.delayNextStep(delay);\n }\n }\n if (ast.steps.length) {\n ast.steps.forEach(s => visitDslNode(this, s, ctx));\n // this is here just in case the inner steps only contain or end with a style() call\n ctx.currentTimeline.applyStylesToKeyframe();\n // this means that some animation function within the sequence\n // ended up creating a sub timeline (which means the current\n // timeline cannot overlap with the contents of the sequence)\n if (ctx.subContextCount > subContextCount) {\n ctx.transformIntoNewTimeline();\n }\n }\n context.previousNode = ast;\n }\n visitGroup(ast, context) {\n const innerTimelines = [];\n let furthestTime = context.currentTimeline.currentTime;\n const delay = ast.options && ast.options.delay ? resolveTimingValue(ast.options.delay) : 0;\n ast.steps.forEach(s => {\n const innerContext = context.createSubContext(ast.options);\n if (delay) {\n innerContext.delayNextStep(delay);\n }\n visitDslNode(this, s, innerContext);\n furthestTime = Math.max(furthestTime, innerContext.currentTimeline.currentTime);\n innerTimelines.push(innerContext.currentTimeline);\n });\n // this operation is run after the AST loop because otherwise\n // if the parent timeline's collected styles were updated then\n // it would pass in invalid data into the new-to-be forked items\n innerTimelines.forEach(timeline => context.currentTimeline.mergeTimelineCollectedStyles(timeline));\n context.transformIntoNewTimeline(furthestTime);\n context.previousNode = ast;\n }\n _visitTiming(ast, context) {\n if (ast.dynamic) {\n const strValue = ast.strValue;\n const timingValue = context.params ? interpolateParams(strValue, context.params, context.errors) : strValue;\n return resolveTiming(timingValue, context.errors);\n } else {\n return {\n duration: ast.duration,\n delay: ast.delay,\n easing: ast.easing\n };\n }\n }\n visitAnimate(ast, context) {\n const timings = context.currentAnimateTimings = this._visitTiming(ast.timings, context);\n const timeline = context.currentTimeline;\n if (timings.delay) {\n context.incrementTime(timings.delay);\n timeline.snapshotCurrentStyles();\n }\n const style = ast.style;\n if (style.type == AnimationMetadataType.Keyframes) {\n this.visitKeyframes(style, context);\n } else {\n context.incrementTime(timings.duration);\n this.visitStyle(style, context);\n timeline.applyStylesToKeyframe();\n }\n context.currentAnimateTimings = null;\n context.previousNode = ast;\n }\n visitStyle(ast, context) {\n const timeline = context.currentTimeline;\n const timings = context.currentAnimateTimings;\n // this is a special case for when a style() call\n // directly follows an animate() call (but not inside of an animate() call)\n if (!timings && timeline.hasCurrentStyleProperties()) {\n timeline.forwardFrame();\n }\n const easing = timings && timings.easing || ast.easing;\n if (ast.isEmptyStep) {\n timeline.applyEmptyStep(easing);\n } else {\n timeline.setStyles(ast.styles, easing, context.errors, context.options);\n }\n context.previousNode = ast;\n }\n visitKeyframes(ast, context) {\n const currentAnimateTimings = context.currentAnimateTimings;\n const startTime = context.currentTimeline.duration;\n const duration = currentAnimateTimings.duration;\n const innerContext = context.createSubContext();\n const innerTimeline = innerContext.currentTimeline;\n innerTimeline.easing = currentAnimateTimings.easing;\n ast.styles.forEach(step => {\n const offset = step.offset || 0;\n innerTimeline.forwardTime(offset * duration);\n innerTimeline.setStyles(step.styles, step.easing, context.errors, context.options);\n innerTimeline.applyStylesToKeyframe();\n });\n // this will ensure that the parent timeline gets all the styles from\n // the child even if the new timeline below is not used\n context.currentTimeline.mergeTimelineCollectedStyles(innerTimeline);\n // we do this because the window between this timeline and the sub timeline\n // should ensure that the styles within are exactly the same as they were before\n context.transformIntoNewTimeline(startTime + duration);\n context.previousNode = ast;\n }\n visitQuery(ast, context) {\n // in the event that the first step before this is a style step we need\n // to ensure the styles are applied before the children are animated\n const startTime = context.currentTimeline.currentTime;\n const options = ast.options || {};\n const delay = options.delay ? resolveTimingValue(options.delay) : 0;\n if (delay && (context.previousNode.type === AnimationMetadataType.Style || startTime == 0 && context.currentTimeline.hasCurrentStyleProperties())) {\n context.currentTimeline.snapshotCurrentStyles();\n context.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;\n }\n let furthestTime = startTime;\n const elms = context.invokeQuery(ast.selector, ast.originalSelector, ast.limit, ast.includeSelf, options.optional ? true : false, context.errors);\n context.currentQueryTotal = elms.length;\n let sameElementTimeline = null;\n elms.forEach((element, i) => {\n context.currentQueryIndex = i;\n const innerContext = context.createSubContext(ast.options, element);\n if (delay) {\n innerContext.delayNextStep(delay);\n }\n if (element === context.element) {\n sameElementTimeline = innerContext.currentTimeline;\n }\n visitDslNode(this, ast.animation, innerContext);\n // this is here just incase the inner steps only contain or end\n // with a style() call (which is here to signal that this is a preparatory\n // call to style an element before it is animated again)\n innerContext.currentTimeline.applyStylesToKeyframe();\n const endTime = innerContext.currentTimeline.currentTime;\n furthestTime = Math.max(furthestTime, endTime);\n });\n context.currentQueryIndex = 0;\n context.currentQueryTotal = 0;\n context.transformIntoNewTimeline(furthestTime);\n if (sameElementTimeline) {\n context.currentTimeline.mergeTimelineCollectedStyles(sameElementTimeline);\n context.currentTimeline.snapshotCurrentStyles();\n }\n context.previousNode = ast;\n }\n visitStagger(ast, context) {\n const parentContext = context.parentContext;\n const tl = context.currentTimeline;\n const timings = ast.timings;\n const duration = Math.abs(timings.duration);\n const maxTime = duration * (context.currentQueryTotal - 1);\n let delay = duration * context.currentQueryIndex;\n let staggerTransformer = timings.duration < 0 ? 'reverse' : timings.easing;\n switch (staggerTransformer) {\n case 'reverse':\n delay = maxTime - delay;\n break;\n case 'full':\n delay = parentContext.currentStaggerTime;\n break;\n }\n const timeline = context.currentTimeline;\n if (delay) {\n timeline.delayNextStep(delay);\n }\n const startingTime = timeline.currentTime;\n visitDslNode(this, ast.animation, context);\n context.previousNode = ast;\n // time = duration + delay\n // the reason why this computation is so complex is because\n // the inner timeline may either have a delay value or a stretched\n // keyframe depending on if a subtimeline is not used or is used.\n parentContext.currentStaggerTime = tl.currentTime - startingTime + (tl.startTime - parentContext.currentTimeline.startTime);\n }\n}\nconst DEFAULT_NOOP_PREVIOUS_NODE = {};\nclass AnimationTimelineContext {\n constructor(_driver, element, subInstructions, _enterClassName, _leaveClassName, errors, timelines, initialTimeline) {\n this._driver = _driver;\n this.element = element;\n this.subInstructions = subInstructions;\n this._enterClassName = _enterClassName;\n this._leaveClassName = _leaveClassName;\n this.errors = errors;\n this.timelines = timelines;\n this.parentContext = null;\n this.currentAnimateTimings = null;\n this.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;\n this.subContextCount = 0;\n this.options = {};\n this.currentQueryIndex = 0;\n this.currentQueryTotal = 0;\n this.currentStaggerTime = 0;\n this.currentTimeline = initialTimeline || new TimelineBuilder(this._driver, element, 0);\n timelines.push(this.currentTimeline);\n }\n get params() {\n return this.options.params;\n }\n updateOptions(options, skipIfExists) {\n if (!options) return;\n const newOptions = options;\n let optionsToUpdate = this.options;\n // NOTE: this will get patched up when other animation methods support duration overrides\n if (newOptions.duration != null) {\n optionsToUpdate.duration = resolveTimingValue(newOptions.duration);\n }\n if (newOptions.delay != null) {\n optionsToUpdate.delay = resolveTimingValue(newOptions.delay);\n }\n const newParams = newOptions.params;\n if (newParams) {\n let paramsToUpdate = optionsToUpdate.params;\n if (!paramsToUpdate) {\n paramsToUpdate = this.options.params = {};\n }\n Object.keys(newParams).forEach(name => {\n if (!skipIfExists || !paramsToUpdate.hasOwnProperty(name)) {\n paramsToUpdate[name] = interpolateParams(newParams[name], paramsToUpdate, this.errors);\n }\n });\n }\n }\n _copyOptions() {\n const options = {};\n if (this.options) {\n const oldParams = this.options.params;\n if (oldParams) {\n const params = options['params'] = {};\n Object.keys(oldParams).forEach(name => {\n params[name] = oldParams[name];\n });\n }\n }\n return options;\n }\n createSubContext(options = null, element, newTime) {\n const target = element || this.element;\n const context = new AnimationTimelineContext(this._driver, target, this.subInstructions, this._enterClassName, this._leaveClassName, this.errors, this.timelines, this.currentTimeline.fork(target, newTime || 0));\n context.previousNode = this.previousNode;\n context.currentAnimateTimings = this.currentAnimateTimings;\n context.options = this._copyOptions();\n context.updateOptions(options);\n context.currentQueryIndex = this.currentQueryIndex;\n context.currentQueryTotal = this.currentQueryTotal;\n context.parentContext = this;\n this.subContextCount++;\n return context;\n }\n transformIntoNewTimeline(newTime) {\n this.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;\n this.currentTimeline = this.currentTimeline.fork(this.element, newTime);\n this.timelines.push(this.currentTimeline);\n return this.currentTimeline;\n }\n appendInstructionToTimeline(instruction, duration, delay) {\n const updatedTimings = {\n duration: duration != null ? duration : instruction.duration,\n delay: this.currentTimeline.currentTime + (delay != null ? delay : 0) + instruction.delay,\n easing: ''\n };\n const builder = new SubTimelineBuilder(this._driver, instruction.element, instruction.keyframes, instruction.preStyleProps, instruction.postStyleProps, updatedTimings, instruction.stretchStartingKeyframe);\n this.timelines.push(builder);\n return updatedTimings;\n }\n incrementTime(time) {\n this.currentTimeline.forwardTime(this.currentTimeline.duration + time);\n }\n delayNextStep(delay) {\n // negative delays are not yet supported\n if (delay > 0) {\n this.currentTimeline.delayNextStep(delay);\n }\n }\n invokeQuery(selector, originalSelector, limit, includeSelf, optional, errors) {\n let results = [];\n if (includeSelf) {\n results.push(this.element);\n }\n if (selector.length > 0) {\n // only if :self is used then the selector can be empty\n selector = selector.replace(ENTER_TOKEN_REGEX, '.' + this._enterClassName);\n selector = selector.replace(LEAVE_TOKEN_REGEX, '.' + this._leaveClassName);\n const multi = limit != 1;\n let elements = this._driver.query(this.element, selector, multi);\n if (limit !== 0) {\n elements = limit < 0 ? elements.slice(elements.length + limit, elements.length) : elements.slice(0, limit);\n }\n results.push(...elements);\n }\n if (!optional && results.length == 0) {\n errors.push(invalidQuery(originalSelector));\n }\n return results;\n }\n}\nclass TimelineBuilder {\n constructor(_driver, element, startTime, _elementTimelineStylesLookup) {\n this._driver = _driver;\n this.element = element;\n this.startTime = startTime;\n this._elementTimelineStylesLookup = _elementTimelineStylesLookup;\n this.duration = 0;\n this.easing = null;\n this._previousKeyframe = new Map();\n this._currentKeyframe = new Map();\n this._keyframes = new Map();\n this._styleSummary = new Map();\n this._localTimelineStyles = new Map();\n this._pendingStyles = new Map();\n this._backFill = new Map();\n this._currentEmptyStepKeyframe = null;\n if (!this._elementTimelineStylesLookup) {\n this._elementTimelineStylesLookup = new Map();\n }\n this._globalTimelineStyles = this._elementTimelineStylesLookup.get(element);\n if (!this._globalTimelineStyles) {\n this._globalTimelineStyles = this._localTimelineStyles;\n this._elementTimelineStylesLookup.set(element, this._localTimelineStyles);\n }\n this._loadKeyframe();\n }\n containsAnimation() {\n switch (this._keyframes.size) {\n case 0:\n return false;\n case 1:\n return this.hasCurrentStyleProperties();\n default:\n return true;\n }\n }\n hasCurrentStyleProperties() {\n return this._currentKeyframe.size > 0;\n }\n get currentTime() {\n return this.startTime + this.duration;\n }\n delayNextStep(delay) {\n // in the event that a style() step is placed right before a stagger()\n // and that style() step is the very first style() value in the animation\n // then we need to make a copy of the keyframe [0, copy, 1] so that the delay\n // properly applies the style() values to work with the stagger...\n const hasPreStyleStep = this._keyframes.size === 1 && this._pendingStyles.size;\n if (this.duration || hasPreStyleStep) {\n this.forwardTime(this.currentTime + delay);\n if (hasPreStyleStep) {\n this.snapshotCurrentStyles();\n }\n } else {\n this.startTime += delay;\n }\n }\n fork(element, currentTime) {\n this.applyStylesToKeyframe();\n return new TimelineBuilder(this._driver, element, currentTime || this.currentTime, this._elementTimelineStylesLookup);\n }\n _loadKeyframe() {\n if (this._currentKeyframe) {\n this._previousKeyframe = this._currentKeyframe;\n }\n this._currentKeyframe = this._keyframes.get(this.duration);\n if (!this._currentKeyframe) {\n this._currentKeyframe = new Map();\n this._keyframes.set(this.duration, this._currentKeyframe);\n }\n }\n forwardFrame() {\n this.duration += ONE_FRAME_IN_MILLISECONDS;\n this._loadKeyframe();\n }\n forwardTime(time) {\n this.applyStylesToKeyframe();\n this.duration = time;\n this._loadKeyframe();\n }\n _updateStyle(prop, value) {\n this._localTimelineStyles.set(prop, value);\n this._globalTimelineStyles.set(prop, value);\n this._styleSummary.set(prop, {\n time: this.currentTime,\n value\n });\n }\n allowOnlyTimelineStyles() {\n return this._currentEmptyStepKeyframe !== this._currentKeyframe;\n }\n applyEmptyStep(easing) {\n if (easing) {\n this._previousKeyframe.set('easing', easing);\n }\n // special case for animate(duration):\n // all missing styles are filled with a `*` value then\n // if any destination styles are filled in later on the same\n // keyframe then they will override the overridden styles\n // We use `_globalTimelineStyles` here because there may be\n // styles in previous keyframes that are not present in this timeline\n for (let [prop, value] of this._globalTimelineStyles) {\n this._backFill.set(prop, value || AUTO_STYLE);\n this._currentKeyframe.set(prop, AUTO_STYLE);\n }\n this._currentEmptyStepKeyframe = this._currentKeyframe;\n }\n setStyles(input, easing, errors, options) {\n if (easing) {\n this._previousKeyframe.set('easing', easing);\n }\n const params = options && options.params || {};\n const styles = flattenStyles(input, this._globalTimelineStyles);\n for (let [prop, value] of styles) {\n const val = interpolateParams(value, params, errors);\n this._pendingStyles.set(prop, val);\n if (!this._localTimelineStyles.has(prop)) {\n this._backFill.set(prop, this._globalTimelineStyles.get(prop) ?? AUTO_STYLE);\n }\n this._updateStyle(prop, val);\n }\n }\n applyStylesToKeyframe() {\n if (this._pendingStyles.size == 0) return;\n this._pendingStyles.forEach((val, prop) => {\n this._currentKeyframe.set(prop, val);\n });\n this._pendingStyles.clear();\n this._localTimelineStyles.forEach((val, prop) => {\n if (!this._currentKeyframe.has(prop)) {\n this._currentKeyframe.set(prop, val);\n }\n });\n }\n snapshotCurrentStyles() {\n for (let [prop, val] of this._localTimelineStyles) {\n this._pendingStyles.set(prop, val);\n this._updateStyle(prop, val);\n }\n }\n getFinalKeyframe() {\n return this._keyframes.get(this.duration);\n }\n get properties() {\n const properties = [];\n for (let prop in this._currentKeyframe) {\n properties.push(prop);\n }\n return properties;\n }\n mergeTimelineCollectedStyles(timeline) {\n timeline._styleSummary.forEach((details1, prop) => {\n const details0 = this._styleSummary.get(prop);\n if (!details0 || details1.time > details0.time) {\n this._updateStyle(prop, details1.value);\n }\n });\n }\n buildKeyframes() {\n this.applyStylesToKeyframe();\n const preStyleProps = new Set();\n const postStyleProps = new Set();\n const isEmpty = this._keyframes.size === 1 && this.duration === 0;\n let finalKeyframes = [];\n this._keyframes.forEach((keyframe, time) => {\n const finalKeyframe = new Map([...this._backFill, ...keyframe]);\n finalKeyframe.forEach((value, prop) => {\n if (value === ɵPRE_STYLE) {\n preStyleProps.add(prop);\n } else if (value === AUTO_STYLE) {\n postStyleProps.add(prop);\n }\n });\n if (!isEmpty) {\n finalKeyframe.set('offset', time / this.duration);\n }\n finalKeyframes.push(finalKeyframe);\n });\n const preProps = [...preStyleProps.values()];\n const postProps = [...postStyleProps.values()];\n // special case for a 0-second animation (which is designed just to place styles onscreen)\n if (isEmpty) {\n const kf0 = finalKeyframes[0];\n const kf1 = new Map(kf0);\n kf0.set('offset', 0);\n kf1.set('offset', 1);\n finalKeyframes = [kf0, kf1];\n }\n return createTimelineInstruction(this.element, finalKeyframes, preProps, postProps, this.duration, this.startTime, this.easing, false);\n }\n}\nclass SubTimelineBuilder extends TimelineBuilder {\n constructor(driver, element, keyframes, preStyleProps, postStyleProps, timings, _stretchStartingKeyframe = false) {\n super(driver, element, timings.delay);\n this.keyframes = keyframes;\n this.preStyleProps = preStyleProps;\n this.postStyleProps = postStyleProps;\n this._stretchStartingKeyframe = _stretchStartingKeyframe;\n this.timings = {\n duration: timings.duration,\n delay: timings.delay,\n easing: timings.easing\n };\n }\n containsAnimation() {\n return this.keyframes.length > 1;\n }\n buildKeyframes() {\n let keyframes = this.keyframes;\n let {\n delay,\n duration,\n easing\n } = this.timings;\n if (this._stretchStartingKeyframe && delay) {\n const newKeyframes = [];\n const totalTime = duration + delay;\n const startingGap = delay / totalTime;\n // the original starting keyframe now starts once the delay is done\n const newFirstKeyframe = new Map(keyframes[0]);\n newFirstKeyframe.set('offset', 0);\n newKeyframes.push(newFirstKeyframe);\n const oldFirstKeyframe = new Map(keyframes[0]);\n oldFirstKeyframe.set('offset', roundOffset(startingGap));\n newKeyframes.push(oldFirstKeyframe);\n /*\n When the keyframe is stretched then it means that the delay before the animation\n starts is gone. Instead the first keyframe is placed at the start of the animation\n and it is then copied to where it starts when the original delay is over. This basically\n means nothing animates during that delay, but the styles are still rendered. For this\n to work the original offset values that exist in the original keyframes must be \"warped\"\n so that they can take the new keyframe + delay into account.\n delay=1000, duration=1000, keyframes = 0 .5 1\n turns into\n delay=0, duration=2000, keyframes = 0 .33 .66 1\n */\n // offsets between 1 ... n -1 are all warped by the keyframe stretch\n const limit = keyframes.length - 1;\n for (let i = 1; i <= limit; i++) {\n let kf = new Map(keyframes[i]);\n const oldOffset = kf.get('offset');\n const timeAtKeyframe = delay + oldOffset * duration;\n kf.set('offset', roundOffset(timeAtKeyframe / totalTime));\n newKeyframes.push(kf);\n }\n // the new starting keyframe should be added at the start\n duration = totalTime;\n delay = 0;\n easing = '';\n keyframes = newKeyframes;\n }\n return createTimelineInstruction(this.element, keyframes, this.preStyleProps, this.postStyleProps, duration, delay, easing, true);\n }\n}\nfunction roundOffset(offset, decimalPoints = 3) {\n const mult = Math.pow(10, decimalPoints - 1);\n return Math.round(offset * mult) / mult;\n}\nfunction flattenStyles(input, allStyles) {\n const styles = new Map();\n let allProperties;\n input.forEach(token => {\n if (token === '*') {\n allProperties ??= allStyles.keys();\n for (let prop of allProperties) {\n styles.set(prop, AUTO_STYLE);\n }\n } else {\n for (let [prop, val] of token) {\n styles.set(prop, val);\n }\n }\n });\n return styles;\n}\nfunction createTransitionInstruction(element, triggerName, fromState, toState, isRemovalTransition, fromStyles, toStyles, timelines, queriedElements, preStyleProps, postStyleProps, totalTime, errors) {\n return {\n type: 0 /* AnimationTransitionInstructionType.TransitionAnimation */,\n element,\n triggerName,\n isRemovalTransition,\n fromState,\n fromStyles,\n toState,\n toStyles,\n timelines,\n queriedElements,\n preStyleProps,\n postStyleProps,\n totalTime,\n errors\n };\n}\nconst EMPTY_OBJECT = {};\nclass AnimationTransitionFactory {\n constructor(_triggerName, ast, _stateStyles) {\n this._triggerName = _triggerName;\n this.ast = ast;\n this._stateStyles = _stateStyles;\n }\n match(currentState, nextState, element, params) {\n return oneOrMoreTransitionsMatch(this.ast.matchers, currentState, nextState, element, params);\n }\n buildStyles(stateName, params, errors) {\n let styler = this._stateStyles.get('*');\n if (stateName !== undefined) {\n styler = this._stateStyles.get(stateName?.toString()) || styler;\n }\n return styler ? styler.buildStyles(params, errors) : new Map();\n }\n build(driver, element, currentState, nextState, enterClassName, leaveClassName, currentOptions, nextOptions, subInstructions, skipAstBuild) {\n const errors = [];\n const transitionAnimationParams = this.ast.options && this.ast.options.params || EMPTY_OBJECT;\n const currentAnimationParams = currentOptions && currentOptions.params || EMPTY_OBJECT;\n const currentStateStyles = this.buildStyles(currentState, currentAnimationParams, errors);\n const nextAnimationParams = nextOptions && nextOptions.params || EMPTY_OBJECT;\n const nextStateStyles = this.buildStyles(nextState, nextAnimationParams, errors);\n const queriedElements = new Set();\n const preStyleMap = new Map();\n const postStyleMap = new Map();\n const isRemoval = nextState === 'void';\n const animationOptions = {\n params: applyParamDefaults(nextAnimationParams, transitionAnimationParams),\n delay: this.ast.options?.delay\n };\n const timelines = skipAstBuild ? [] : buildAnimationTimelines(driver, element, this.ast.animation, enterClassName, leaveClassName, currentStateStyles, nextStateStyles, animationOptions, subInstructions, errors);\n let totalTime = 0;\n timelines.forEach(tl => {\n totalTime = Math.max(tl.duration + tl.delay, totalTime);\n });\n if (errors.length) {\n return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, [], [], preStyleMap, postStyleMap, totalTime, errors);\n }\n timelines.forEach(tl => {\n const elm = tl.element;\n const preProps = getOrSetDefaultValue(preStyleMap, elm, new Set());\n tl.preStyleProps.forEach(prop => preProps.add(prop));\n const postProps = getOrSetDefaultValue(postStyleMap, elm, new Set());\n tl.postStyleProps.forEach(prop => postProps.add(prop));\n if (elm !== element) {\n queriedElements.add(elm);\n }\n });\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n checkNonAnimatableInTimelines(timelines, this._triggerName, driver);\n }\n return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, timelines, [...queriedElements.values()], preStyleMap, postStyleMap, totalTime);\n }\n}\n/**\n * Checks inside a set of timelines if they try to animate a css property which is not considered\n * animatable, in that case it prints a warning on the console.\n * Besides that the function doesn't have any other effect.\n *\n * Note: this check is done here after the timelines are built instead of doing on a lower level so\n * that we can make sure that the warning appears only once per instruction (we can aggregate here\n * all the issues instead of finding them separately).\n *\n * @param timelines The built timelines for the current instruction.\n * @param triggerName The name of the trigger for the current instruction.\n * @param driver Animation driver used to perform the check.\n *\n */\nfunction checkNonAnimatableInTimelines(timelines, triggerName, driver) {\n if (!driver.validateAnimatableStyleProperty) {\n return;\n }\n const allowedNonAnimatableProps = new Set([\n // 'easing' is a utility/synthetic prop we use to represent\n // easing functions, it represents a property of the animation\n // which is not animatable but different values can be used\n // in different steps\n 'easing']);\n const invalidNonAnimatableProps = new Set();\n timelines.forEach(({\n keyframes\n }) => {\n const nonAnimatablePropsInitialValues = new Map();\n keyframes.forEach(keyframe => {\n const entriesToCheck = Array.from(keyframe.entries()).filter(([prop]) => !allowedNonAnimatableProps.has(prop));\n for (const [prop, value] of entriesToCheck) {\n if (!driver.validateAnimatableStyleProperty(prop)) {\n if (nonAnimatablePropsInitialValues.has(prop) && !invalidNonAnimatableProps.has(prop)) {\n const propInitialValue = nonAnimatablePropsInitialValues.get(prop);\n if (propInitialValue !== value) {\n invalidNonAnimatableProps.add(prop);\n }\n } else {\n nonAnimatablePropsInitialValues.set(prop, value);\n }\n }\n }\n });\n });\n if (invalidNonAnimatableProps.size > 0) {\n console.warn(`Warning: The animation trigger \"${triggerName}\" is attempting to animate the following` + ' not animatable properties: ' + Array.from(invalidNonAnimatableProps).join(', ') + '\\n' + '(to check the list of all animatable properties visit https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties)');\n }\n}\nfunction oneOrMoreTransitionsMatch(matchFns, currentState, nextState, element, params) {\n return matchFns.some(fn => fn(currentState, nextState, element, params));\n}\nfunction applyParamDefaults(userParams, defaults) {\n const result = {\n ...defaults\n };\n Object.entries(userParams).forEach(([key, value]) => {\n if (value != null) {\n result[key] = value;\n }\n });\n return result;\n}\nclass AnimationStateStyles {\n constructor(styles, defaultParams, normalizer) {\n this.styles = styles;\n this.defaultParams = defaultParams;\n this.normalizer = normalizer;\n }\n buildStyles(params, errors) {\n const finalStyles = new Map();\n const combinedParams = applyParamDefaults(params, this.defaultParams);\n this.styles.styles.forEach(value => {\n if (typeof value !== 'string') {\n value.forEach((val, prop) => {\n if (val) {\n val = interpolateParams(val, combinedParams, errors);\n }\n const normalizedProp = this.normalizer.normalizePropertyName(prop, errors);\n val = this.normalizer.normalizeStyleValue(prop, normalizedProp, val, errors);\n finalStyles.set(prop, val);\n });\n }\n });\n return finalStyles;\n }\n}\nfunction buildTrigger(name, ast, normalizer) {\n return new AnimationTrigger(name, ast, normalizer);\n}\nclass AnimationTrigger {\n constructor(name, ast, _normalizer) {\n this.name = name;\n this.ast = ast;\n this._normalizer = _normalizer;\n this.transitionFactories = [];\n this.states = new Map();\n ast.states.forEach(ast => {\n const defaultParams = ast.options && ast.options.params || {};\n this.states.set(ast.name, new AnimationStateStyles(ast.style, defaultParams, _normalizer));\n });\n balanceProperties(this.states, 'true', '1');\n balanceProperties(this.states, 'false', '0');\n ast.transitions.forEach(ast => {\n this.transitionFactories.push(new AnimationTransitionFactory(name, ast, this.states));\n });\n this.fallbackTransition = createFallbackTransition(name, this.states, this._normalizer);\n }\n get containsQueries() {\n return this.ast.queryCount > 0;\n }\n matchTransition(currentState, nextState, element, params) {\n const entry = this.transitionFactories.find(f => f.match(currentState, nextState, element, params));\n return entry || null;\n }\n matchStyles(currentState, params, errors) {\n return this.fallbackTransition.buildStyles(currentState, params, errors);\n }\n}\nfunction createFallbackTransition(triggerName, states, normalizer) {\n const matchers = [(fromState, toState) => true];\n const animation = {\n type: AnimationMetadataType.Sequence,\n steps: [],\n options: null\n };\n const transition = {\n type: AnimationMetadataType.Transition,\n animation,\n matchers,\n options: null,\n queryCount: 0,\n depCount: 0\n };\n return new AnimationTransitionFactory(triggerName, transition, states);\n}\nfunction balanceProperties(stateMap, key1, key2) {\n if (stateMap.has(key1)) {\n if (!stateMap.has(key2)) {\n stateMap.set(key2, stateMap.get(key1));\n }\n } else if (stateMap.has(key2)) {\n stateMap.set(key1, stateMap.get(key2));\n }\n}\nconst EMPTY_INSTRUCTION_MAP = /*#__PURE__*/new ElementInstructionMap();\nclass TimelineAnimationEngine {\n constructor(bodyNode, _driver, _normalizer) {\n this.bodyNode = bodyNode;\n this._driver = _driver;\n this._normalizer = _normalizer;\n this._animations = new Map();\n this._playersById = new Map();\n this.players = [];\n }\n register(id, metadata) {\n const errors = [];\n const warnings = [];\n const ast = buildAnimationAst(this._driver, metadata, errors, warnings);\n if (errors.length) {\n throw registerFailed(errors);\n } else {\n if (warnings.length) {\n warnRegister(warnings);\n }\n this._animations.set(id, ast);\n }\n }\n _buildPlayer(i, preStyles, postStyles) {\n const element = i.element;\n const keyframes = normalizeKeyframes$1(this._normalizer, i.keyframes, preStyles, postStyles);\n return this._driver.animate(element, keyframes, i.duration, i.delay, i.easing, [], true);\n }\n create(id, element, options = {}) {\n const errors = [];\n const ast = this._animations.get(id);\n let instructions;\n const autoStylesMap = new Map();\n if (ast) {\n instructions = buildAnimationTimelines(this._driver, element, ast, ENTER_CLASSNAME, LEAVE_CLASSNAME, new Map(), new Map(), options, EMPTY_INSTRUCTION_MAP, errors);\n instructions.forEach(inst => {\n const styles = getOrSetDefaultValue(autoStylesMap, inst.element, new Map());\n inst.postStyleProps.forEach(prop => styles.set(prop, null));\n });\n } else {\n errors.push(missingOrDestroyedAnimation());\n instructions = [];\n }\n if (errors.length) {\n throw createAnimationFailed(errors);\n }\n autoStylesMap.forEach((styles, element) => {\n styles.forEach((_, prop) => {\n styles.set(prop, this._driver.computeStyle(element, prop, AUTO_STYLE));\n });\n });\n const players = instructions.map(i => {\n const styles = autoStylesMap.get(i.element);\n return this._buildPlayer(i, new Map(), styles);\n });\n const player = optimizeGroupPlayer(players);\n this._playersById.set(id, player);\n player.onDestroy(() => this.destroy(id));\n this.players.push(player);\n return player;\n }\n destroy(id) {\n const player = this._getPlayer(id);\n player.destroy();\n this._playersById.delete(id);\n const index = this.players.indexOf(player);\n if (index >= 0) {\n this.players.splice(index, 1);\n }\n }\n _getPlayer(id) {\n const player = this._playersById.get(id);\n if (!player) {\n throw missingPlayer(id);\n }\n return player;\n }\n listen(id, element, eventName, callback) {\n // triggerName, fromState, toState are all ignored for timeline animations\n const baseEvent = makeAnimationEvent(element, '', '', '');\n listenOnPlayer(this._getPlayer(id), eventName, baseEvent, callback);\n return () => {};\n }\n command(id, element, command, args) {\n if (command == 'register') {\n this.register(id, args[0]);\n return;\n }\n if (command == 'create') {\n const options = args[0] || {};\n this.create(id, element, options);\n return;\n }\n const player = this._getPlayer(id);\n switch (command) {\n case 'play':\n player.play();\n break;\n case 'pause':\n player.pause();\n break;\n case 'reset':\n player.reset();\n break;\n case 'restart':\n player.restart();\n break;\n case 'finish':\n player.finish();\n break;\n case 'init':\n player.init();\n break;\n case 'setPosition':\n player.setPosition(parseFloat(args[0]));\n break;\n case 'destroy':\n this.destroy(id);\n break;\n }\n }\n}\nconst QUEUED_CLASSNAME = 'ng-animate-queued';\nconst QUEUED_SELECTOR = '.ng-animate-queued';\nconst DISABLED_CLASSNAME = 'ng-animate-disabled';\nconst DISABLED_SELECTOR = '.ng-animate-disabled';\nconst STAR_CLASSNAME = 'ng-star-inserted';\nconst STAR_SELECTOR = '.ng-star-inserted';\nconst EMPTY_PLAYER_ARRAY = [];\nconst NULL_REMOVAL_STATE = {\n namespaceId: '',\n setForRemoval: false,\n setForMove: false,\n hasAnimation: false,\n removedBeforeQueried: false\n};\nconst NULL_REMOVED_QUERIED_STATE = {\n namespaceId: '',\n setForMove: false,\n setForRemoval: false,\n hasAnimation: false,\n removedBeforeQueried: true\n};\nconst REMOVAL_FLAG = '__ng_removed';\nclass StateValue {\n get params() {\n return this.options.params;\n }\n constructor(input, namespaceId = '') {\n this.namespaceId = namespaceId;\n const isObj = input && input.hasOwnProperty('value');\n const value = isObj ? input['value'] : input;\n this.value = normalizeTriggerValue(value);\n if (isObj) {\n // we drop the value property from options.\n const {\n value,\n ...options\n } = input;\n this.options = options;\n } else {\n this.options = {};\n }\n if (!this.options.params) {\n this.options.params = {};\n }\n }\n absorbOptions(options) {\n const newParams = options.params;\n if (newParams) {\n const oldParams = this.options.params;\n Object.keys(newParams).forEach(prop => {\n if (oldParams[prop] == null) {\n oldParams[prop] = newParams[prop];\n }\n });\n }\n }\n}\nconst VOID_VALUE = 'void';\nconst DEFAULT_STATE_VALUE = /*#__PURE__*/new StateValue(VOID_VALUE);\nclass AnimationTransitionNamespace {\n constructor(id, hostElement, _engine) {\n this.id = id;\n this.hostElement = hostElement;\n this._engine = _engine;\n this.players = [];\n this._triggers = new Map();\n this._queue = [];\n this._elementListeners = new Map();\n this._hostClassName = 'ng-tns-' + id;\n addClass(hostElement, this._hostClassName);\n }\n listen(element, name, phase, callback) {\n if (!this._triggers.has(name)) {\n throw missingTrigger(phase, name);\n }\n if (phase == null || phase.length == 0) {\n throw missingEvent(name);\n }\n if (!isTriggerEventValid(phase)) {\n throw unsupportedTriggerEvent(phase, name);\n }\n const listeners = getOrSetDefaultValue(this._elementListeners, element, []);\n const data = {\n name,\n phase,\n callback\n };\n listeners.push(data);\n const triggersWithStates = getOrSetDefaultValue(this._engine.statesByElement, element, new Map());\n if (!triggersWithStates.has(name)) {\n addClass(element, NG_TRIGGER_CLASSNAME);\n addClass(element, NG_TRIGGER_CLASSNAME + '-' + name);\n triggersWithStates.set(name, DEFAULT_STATE_VALUE);\n }\n return () => {\n // the event listener is removed AFTER the flush has occurred such\n // that leave animations callbacks can fire (otherwise if the node\n // is removed in between then the listeners would be deregistered)\n this._engine.afterFlush(() => {\n const index = listeners.indexOf(data);\n if (index >= 0) {\n listeners.splice(index, 1);\n }\n if (!this._triggers.has(name)) {\n triggersWithStates.delete(name);\n }\n });\n };\n }\n register(name, ast) {\n if (this._triggers.has(name)) {\n // throw\n return false;\n } else {\n this._triggers.set(name, ast);\n return true;\n }\n }\n _getTrigger(name) {\n const trigger = this._triggers.get(name);\n if (!trigger) {\n throw unregisteredTrigger(name);\n }\n return trigger;\n }\n trigger(element, triggerName, value, defaultToFallback = true) {\n const trigger = this._getTrigger(triggerName);\n const player = new TransitionAnimationPlayer(this.id, triggerName, element);\n let triggersWithStates = this._engine.statesByElement.get(element);\n if (!triggersWithStates) {\n addClass(element, NG_TRIGGER_CLASSNAME);\n addClass(element, NG_TRIGGER_CLASSNAME + '-' + triggerName);\n this._engine.statesByElement.set(element, triggersWithStates = new Map());\n }\n let fromState = triggersWithStates.get(triggerName);\n const toState = new StateValue(value, this.id);\n const isObj = value && value.hasOwnProperty('value');\n if (!isObj && fromState) {\n toState.absorbOptions(fromState.options);\n }\n triggersWithStates.set(triggerName, toState);\n if (!fromState) {\n fromState = DEFAULT_STATE_VALUE;\n }\n const isRemoval = toState.value === VOID_VALUE;\n // normally this isn't reached by here, however, if an object expression\n // is passed in then it may be a new object each time. Comparing the value\n // is important since that will stay the same despite there being a new object.\n // The removal arc here is special cased because the same element is triggered\n // twice in the event that it contains animations on the outer/inner portions\n // of the host container\n if (!isRemoval && fromState.value === toState.value) {\n // this means that despite the value not changing, some inner params\n // have changed which means that the animation final styles need to be applied\n if (!objEquals(fromState.params, toState.params)) {\n const errors = [];\n const fromStyles = trigger.matchStyles(fromState.value, fromState.params, errors);\n const toStyles = trigger.matchStyles(toState.value, toState.params, errors);\n if (errors.length) {\n this._engine.reportError(errors);\n } else {\n this._engine.afterFlush(() => {\n eraseStyles(element, fromStyles);\n setStyles(element, toStyles);\n });\n }\n }\n return;\n }\n const playersOnElement = getOrSetDefaultValue(this._engine.playersByElement, element, []);\n playersOnElement.forEach(player => {\n // only remove the player if it is queued on the EXACT same trigger/namespace\n // we only also deal with queued players here because if the animation has\n // started then we want to keep the player alive until the flush happens\n // (which is where the previousPlayers are passed into the new player)\n if (player.namespaceId == this.id && player.triggerName == triggerName && player.queued) {\n player.destroy();\n }\n });\n let transition = trigger.matchTransition(fromState.value, toState.value, element, toState.params);\n let isFallbackTransition = false;\n if (!transition) {\n if (!defaultToFallback) return;\n transition = trigger.fallbackTransition;\n isFallbackTransition = true;\n }\n this._engine.totalQueuedPlayers++;\n this._queue.push({\n element,\n triggerName,\n transition,\n fromState,\n toState,\n player,\n isFallbackTransition\n });\n if (!isFallbackTransition) {\n addClass(element, QUEUED_CLASSNAME);\n player.onStart(() => {\n removeClass(element, QUEUED_CLASSNAME);\n });\n }\n player.onDone(() => {\n let index = this.players.indexOf(player);\n if (index >= 0) {\n this.players.splice(index, 1);\n }\n const players = this._engine.playersByElement.get(element);\n if (players) {\n let index = players.indexOf(player);\n if (index >= 0) {\n players.splice(index, 1);\n }\n }\n });\n this.players.push(player);\n playersOnElement.push(player);\n return player;\n }\n deregister(name) {\n this._triggers.delete(name);\n this._engine.statesByElement.forEach(stateMap => stateMap.delete(name));\n this._elementListeners.forEach((listeners, element) => {\n this._elementListeners.set(element, listeners.filter(entry => {\n return entry.name != name;\n }));\n });\n }\n clearElementCache(element) {\n this._engine.statesByElement.delete(element);\n this._elementListeners.delete(element);\n const elementPlayers = this._engine.playersByElement.get(element);\n if (elementPlayers) {\n elementPlayers.forEach(player => player.destroy());\n this._engine.playersByElement.delete(element);\n }\n }\n _signalRemovalForInnerTriggers(rootElement, context) {\n const elements = this._engine.driver.query(rootElement, NG_TRIGGER_SELECTOR, true);\n // emulate a leave animation for all inner nodes within this node.\n // If there are no animations found for any of the nodes then clear the cache\n // for the element.\n elements.forEach(elm => {\n // this means that an inner remove() operation has already kicked off\n // the animation on this element...\n if (elm[REMOVAL_FLAG]) return;\n const namespaces = this._engine.fetchNamespacesByElement(elm);\n if (namespaces.size) {\n namespaces.forEach(ns => ns.triggerLeaveAnimation(elm, context, false, true));\n } else {\n this.clearElementCache(elm);\n }\n });\n // If the child elements were removed along with the parent, their animations might not\n // have completed. Clear all the elements from the cache so we don't end up with a memory leak.\n this._engine.afterFlushAnimationsDone(() => elements.forEach(elm => this.clearElementCache(elm)));\n }\n triggerLeaveAnimation(element, context, destroyAfterComplete, defaultToFallback) {\n const triggerStates = this._engine.statesByElement.get(element);\n const previousTriggersValues = new Map();\n if (triggerStates) {\n const players = [];\n triggerStates.forEach((state, triggerName) => {\n previousTriggersValues.set(triggerName, state.value);\n // this check is here in the event that an element is removed\n // twice (both on the host level and the component level)\n if (this._triggers.has(triggerName)) {\n const player = this.trigger(element, triggerName, VOID_VALUE, defaultToFallback);\n if (player) {\n players.push(player);\n }\n }\n });\n if (players.length) {\n this._engine.markElementAsRemoved(this.id, element, true, context, previousTriggersValues);\n if (destroyAfterComplete) {\n optimizeGroupPlayer(players).onDone(() => this._engine.processLeaveNode(element));\n }\n return true;\n }\n }\n return false;\n }\n prepareLeaveAnimationListeners(element) {\n const listeners = this._elementListeners.get(element);\n const elementStates = this._engine.statesByElement.get(element);\n // if this statement fails then it means that the element was picked up\n // by an earlier flush (or there are no listeners at all to track the leave).\n if (listeners && elementStates) {\n const visitedTriggers = new Set();\n listeners.forEach(listener => {\n const triggerName = listener.name;\n if (visitedTriggers.has(triggerName)) return;\n visitedTriggers.add(triggerName);\n const trigger = this._triggers.get(triggerName);\n const transition = trigger.fallbackTransition;\n const fromState = elementStates.get(triggerName) || DEFAULT_STATE_VALUE;\n const toState = new StateValue(VOID_VALUE);\n const player = new TransitionAnimationPlayer(this.id, triggerName, element);\n this._engine.totalQueuedPlayers++;\n this._queue.push({\n element,\n triggerName,\n transition,\n fromState,\n toState,\n player,\n isFallbackTransition: true\n });\n });\n }\n }\n removeNode(element, context) {\n const engine = this._engine;\n if (element.childElementCount) {\n this._signalRemovalForInnerTriggers(element, context);\n }\n // this means that a * => VOID animation was detected and kicked off\n if (this.triggerLeaveAnimation(element, context, true)) return;\n // find the player that is animating and make sure that the\n // removal is delayed until that player has completed\n let containsPotentialParentTransition = false;\n if (engine.totalAnimations) {\n const currentPlayers = engine.players.length ? engine.playersByQueriedElement.get(element) : [];\n // when this `if statement` does not continue forward it means that\n // a previous animation query has selected the current element and\n // is animating it. In this situation want to continue forwards and\n // allow the element to be queued up for animation later.\n if (currentPlayers && currentPlayers.length) {\n containsPotentialParentTransition = true;\n } else {\n let parent = element;\n while (parent = parent.parentNode) {\n const triggers = engine.statesByElement.get(parent);\n if (triggers) {\n containsPotentialParentTransition = true;\n break;\n }\n }\n }\n }\n // at this stage we know that the element will either get removed\n // during flush or will be picked up by a parent query. Either way\n // we need to fire the listeners for this element when it DOES get\n // removed (once the query parent animation is done or after flush)\n this.prepareLeaveAnimationListeners(element);\n // whether or not a parent has an animation we need to delay the deferral of the leave\n // operation until we have more information (which we do after flush() has been called)\n if (containsPotentialParentTransition) {\n engine.markElementAsRemoved(this.id, element, false, context);\n } else {\n const removalFlag = element[REMOVAL_FLAG];\n if (!removalFlag || removalFlag === NULL_REMOVAL_STATE) {\n // we do this after the flush has occurred such\n // that the callbacks can be fired\n engine.afterFlush(() => this.clearElementCache(element));\n engine.destroyInnerAnimations(element);\n engine._onRemovalComplete(element, context);\n }\n }\n }\n insertNode(element, parent) {\n addClass(element, this._hostClassName);\n }\n drainQueuedTransitions(microtaskId) {\n const instructions = [];\n this._queue.forEach(entry => {\n const player = entry.player;\n if (player.destroyed) return;\n const element = entry.element;\n const listeners = this._elementListeners.get(element);\n if (listeners) {\n listeners.forEach(listener => {\n if (listener.name == entry.triggerName) {\n const baseEvent = makeAnimationEvent(element, entry.triggerName, entry.fromState.value, entry.toState.value);\n baseEvent['_data'] = microtaskId;\n listenOnPlayer(entry.player, listener.phase, baseEvent, listener.callback);\n }\n });\n }\n if (player.markedForDestroy) {\n this._engine.afterFlush(() => {\n // now we can destroy the element properly since the event listeners have\n // been bound to the player\n player.destroy();\n });\n } else {\n instructions.push(entry);\n }\n });\n this._queue = [];\n return instructions.sort((a, b) => {\n // if depCount == 0 them move to front\n // otherwise if a contains b then move back\n const d0 = a.transition.ast.depCount;\n const d1 = b.transition.ast.depCount;\n if (d0 == 0 || d1 == 0) {\n return d0 - d1;\n }\n return this._engine.driver.containsElement(a.element, b.element) ? 1 : -1;\n });\n }\n destroy(context) {\n this.players.forEach(p => p.destroy());\n this._signalRemovalForInnerTriggers(this.hostElement, context);\n }\n}\nclass TransitionAnimationEngine {\n /** @internal */\n _onRemovalComplete(element, context) {\n this.onRemovalComplete(element, context);\n }\n constructor(bodyNode, driver, _normalizer, scheduler) {\n this.bodyNode = bodyNode;\n this.driver = driver;\n this._normalizer = _normalizer;\n this.scheduler = scheduler;\n this.players = [];\n this.newHostElements = new Map();\n this.playersByElement = new Map();\n this.playersByQueriedElement = new Map();\n this.statesByElement = new Map();\n this.disabledNodes = new Set();\n this.totalAnimations = 0;\n this.totalQueuedPlayers = 0;\n this._namespaceLookup = {};\n this._namespaceList = [];\n this._flushFns = [];\n this._whenQuietFns = [];\n this.namespacesByHostElement = new Map();\n this.collectedEnterElements = [];\n this.collectedLeaveElements = [];\n // this method is designed to be overridden by the code that uses this engine\n this.onRemovalComplete = (element, context) => {};\n }\n get queuedPlayers() {\n const players = [];\n this._namespaceList.forEach(ns => {\n ns.players.forEach(player => {\n if (player.queued) {\n players.push(player);\n }\n });\n });\n return players;\n }\n createNamespace(namespaceId, hostElement) {\n const ns = new AnimationTransitionNamespace(namespaceId, hostElement, this);\n if (this.bodyNode && this.driver.containsElement(this.bodyNode, hostElement)) {\n this._balanceNamespaceList(ns, hostElement);\n } else {\n // defer this later until flush during when the host element has\n // been inserted so that we know exactly where to place it in\n // the namespace list\n this.newHostElements.set(hostElement, ns);\n // given that this host element is a part of the animation code, it\n // may or may not be inserted by a parent node that is of an\n // animation renderer type. If this happens then we can still have\n // access to this item when we query for :enter nodes. If the parent\n // is a renderer then the set data-structure will normalize the entry\n this.collectEnterElement(hostElement);\n }\n return this._namespaceLookup[namespaceId] = ns;\n }\n _balanceNamespaceList(ns, hostElement) {\n const namespaceList = this._namespaceList;\n const namespacesByHostElement = this.namespacesByHostElement;\n const limit = namespaceList.length - 1;\n if (limit >= 0) {\n let found = false;\n // Find the closest ancestor with an existing namespace so we can then insert `ns` after it,\n // establishing a top-down ordering of namespaces in `this._namespaceList`.\n let ancestor = this.driver.getParentElement(hostElement);\n while (ancestor) {\n const ancestorNs = namespacesByHostElement.get(ancestor);\n if (ancestorNs) {\n // An animation namespace has been registered for this ancestor, so we insert `ns`\n // right after it to establish top-down ordering of animation namespaces.\n const index = namespaceList.indexOf(ancestorNs);\n namespaceList.splice(index + 1, 0, ns);\n found = true;\n break;\n }\n ancestor = this.driver.getParentElement(ancestor);\n }\n if (!found) {\n // No namespace exists that is an ancestor of `ns`, so `ns` is inserted at the front to\n // ensure that any existing descendants are ordered after `ns`, retaining the desired\n // top-down ordering.\n namespaceList.unshift(ns);\n }\n } else {\n namespaceList.push(ns);\n }\n namespacesByHostElement.set(hostElement, ns);\n return ns;\n }\n register(namespaceId, hostElement) {\n let ns = this._namespaceLookup[namespaceId];\n if (!ns) {\n ns = this.createNamespace(namespaceId, hostElement);\n }\n return ns;\n }\n registerTrigger(namespaceId, name, trigger) {\n let ns = this._namespaceLookup[namespaceId];\n if (ns && ns.register(name, trigger)) {\n this.totalAnimations++;\n }\n }\n destroy(namespaceId, context) {\n if (!namespaceId) return;\n this.afterFlush(() => {});\n this.afterFlushAnimationsDone(() => {\n const ns = this._fetchNamespace(namespaceId);\n this.namespacesByHostElement.delete(ns.hostElement);\n const index = this._namespaceList.indexOf(ns);\n if (index >= 0) {\n this._namespaceList.splice(index, 1);\n }\n ns.destroy(context);\n delete this._namespaceLookup[namespaceId];\n });\n }\n _fetchNamespace(id) {\n return this._namespaceLookup[id];\n }\n fetchNamespacesByElement(element) {\n // normally there should only be one namespace per element, however\n // if @triggers are placed on both the component element and then\n // its host element (within the component code) then there will be\n // two namespaces returned. We use a set here to simply deduplicate\n // the namespaces in case (for the reason described above) there are multiple triggers\n const namespaces = new Set();\n const elementStates = this.statesByElement.get(element);\n if (elementStates) {\n for (let stateValue of elementStates.values()) {\n if (stateValue.namespaceId) {\n const ns = this._fetchNamespace(stateValue.namespaceId);\n if (ns) {\n namespaces.add(ns);\n }\n }\n }\n }\n return namespaces;\n }\n trigger(namespaceId, element, name, value) {\n if (isElementNode(element)) {\n const ns = this._fetchNamespace(namespaceId);\n if (ns) {\n ns.trigger(element, name, value);\n return true;\n }\n }\n return false;\n }\n insertNode(namespaceId, element, parent, insertBefore) {\n if (!isElementNode(element)) return;\n // special case for when an element is removed and reinserted (move operation)\n // when this occurs we do not want to use the element for deletion later\n const details = element[REMOVAL_FLAG];\n if (details && details.setForRemoval) {\n details.setForRemoval = false;\n details.setForMove = true;\n const index = this.collectedLeaveElements.indexOf(element);\n if (index >= 0) {\n this.collectedLeaveElements.splice(index, 1);\n }\n }\n // in the event that the namespaceId is blank then the caller\n // code does not contain any animation code in it, but it is\n // just being called so that the node is marked as being inserted\n if (namespaceId) {\n const ns = this._fetchNamespace(namespaceId);\n // This if-statement is a workaround for router issue #21947.\n // The router sometimes hits a race condition where while a route\n // is being instantiated a new navigation arrives, triggering leave\n // animation of DOM that has not been fully initialized, until this\n // is resolved, we need to handle the scenario when DOM is not in a\n // consistent state during the animation.\n if (ns) {\n ns.insertNode(element, parent);\n }\n }\n // only *directives and host elements are inserted before\n if (insertBefore) {\n this.collectEnterElement(element);\n }\n }\n collectEnterElement(element) {\n this.collectedEnterElements.push(element);\n }\n markElementAsDisabled(element, value) {\n if (value) {\n if (!this.disabledNodes.has(element)) {\n this.disabledNodes.add(element);\n addClass(element, DISABLED_CLASSNAME);\n }\n } else if (this.disabledNodes.has(element)) {\n this.disabledNodes.delete(element);\n removeClass(element, DISABLED_CLASSNAME);\n }\n }\n removeNode(namespaceId, element, context) {\n if (isElementNode(element)) {\n this.scheduler?.notify();\n const ns = namespaceId ? this._fetchNamespace(namespaceId) : null;\n if (ns) {\n ns.removeNode(element, context);\n } else {\n this.markElementAsRemoved(namespaceId, element, false, context);\n }\n const hostNS = this.namespacesByHostElement.get(element);\n if (hostNS && hostNS.id !== namespaceId) {\n hostNS.removeNode(element, context);\n }\n } else {\n this._onRemovalComplete(element, context);\n }\n }\n markElementAsRemoved(namespaceId, element, hasAnimation, context, previousTriggersValues) {\n this.collectedLeaveElements.push(element);\n element[REMOVAL_FLAG] = {\n namespaceId,\n setForRemoval: context,\n hasAnimation,\n removedBeforeQueried: false,\n previousTriggersValues\n };\n }\n listen(namespaceId, element, name, phase, callback) {\n if (isElementNode(element)) {\n return this._fetchNamespace(namespaceId).listen(element, name, phase, callback);\n }\n return () => {};\n }\n _buildInstruction(entry, subTimelines, enterClassName, leaveClassName, skipBuildAst) {\n return entry.transition.build(this.driver, entry.element, entry.fromState.value, entry.toState.value, enterClassName, leaveClassName, entry.fromState.options, entry.toState.options, subTimelines, skipBuildAst);\n }\n destroyInnerAnimations(containerElement) {\n let elements = this.driver.query(containerElement, NG_TRIGGER_SELECTOR, true);\n elements.forEach(element => this.destroyActiveAnimationsForElement(element));\n if (this.playersByQueriedElement.size == 0) return;\n elements = this.driver.query(containerElement, NG_ANIMATING_SELECTOR, true);\n elements.forEach(element => this.finishActiveQueriedAnimationOnElement(element));\n }\n destroyActiveAnimationsForElement(element) {\n const players = this.playersByElement.get(element);\n if (players) {\n players.forEach(player => {\n // special case for when an element is set for destruction, but hasn't started.\n // in this situation we want to delay the destruction until the flush occurs\n // so that any event listeners attached to the player are triggered.\n if (player.queued) {\n player.markedForDestroy = true;\n } else {\n player.destroy();\n }\n });\n }\n }\n finishActiveQueriedAnimationOnElement(element) {\n const players = this.playersByQueriedElement.get(element);\n if (players) {\n players.forEach(player => player.finish());\n }\n }\n whenRenderingDone() {\n return new Promise(resolve => {\n if (this.players.length) {\n return optimizeGroupPlayer(this.players).onDone(() => resolve());\n } else {\n resolve();\n }\n });\n }\n processLeaveNode(element) {\n const details = element[REMOVAL_FLAG];\n if (details && details.setForRemoval) {\n // this will prevent it from removing it twice\n element[REMOVAL_FLAG] = NULL_REMOVAL_STATE;\n if (details.namespaceId) {\n this.destroyInnerAnimations(element);\n const ns = this._fetchNamespace(details.namespaceId);\n if (ns) {\n ns.clearElementCache(element);\n }\n }\n this._onRemovalComplete(element, details.setForRemoval);\n }\n if (element.classList?.contains(DISABLED_CLASSNAME)) {\n this.markElementAsDisabled(element, false);\n }\n this.driver.query(element, DISABLED_SELECTOR, true).forEach(node => {\n this.markElementAsDisabled(node, false);\n });\n }\n flush(microtaskId = -1) {\n let players = [];\n if (this.newHostElements.size) {\n this.newHostElements.forEach((ns, element) => this._balanceNamespaceList(ns, element));\n this.newHostElements.clear();\n }\n if (this.totalAnimations && this.collectedEnterElements.length) {\n for (let i = 0; i < this.collectedEnterElements.length; i++) {\n const elm = this.collectedEnterElements[i];\n addClass(elm, STAR_CLASSNAME);\n }\n }\n if (this._namespaceList.length && (this.totalQueuedPlayers || this.collectedLeaveElements.length)) {\n const cleanupFns = [];\n try {\n players = this._flushAnimations(cleanupFns, microtaskId);\n } finally {\n for (let i = 0; i < cleanupFns.length; i++) {\n cleanupFns[i]();\n }\n }\n } else {\n for (let i = 0; i < this.collectedLeaveElements.length; i++) {\n const element = this.collectedLeaveElements[i];\n this.processLeaveNode(element);\n }\n }\n this.totalQueuedPlayers = 0;\n this.collectedEnterElements.length = 0;\n this.collectedLeaveElements.length = 0;\n this._flushFns.forEach(fn => fn());\n this._flushFns = [];\n if (this._whenQuietFns.length) {\n // we move these over to a variable so that\n // if any new callbacks are registered in another\n // flush they do not populate the existing set\n const quietFns = this._whenQuietFns;\n this._whenQuietFns = [];\n if (players.length) {\n optimizeGroupPlayer(players).onDone(() => {\n quietFns.forEach(fn => fn());\n });\n } else {\n quietFns.forEach(fn => fn());\n }\n }\n }\n reportError(errors) {\n throw triggerTransitionsFailed(errors);\n }\n _flushAnimations(cleanupFns, microtaskId) {\n const subTimelines = new ElementInstructionMap();\n const skippedPlayers = [];\n const skippedPlayersMap = new Map();\n const queuedInstructions = [];\n const queriedElements = new Map();\n const allPreStyleElements = new Map();\n const allPostStyleElements = new Map();\n const disabledElementsSet = new Set();\n this.disabledNodes.forEach(node => {\n disabledElementsSet.add(node);\n const nodesThatAreDisabled = this.driver.query(node, QUEUED_SELECTOR, true);\n for (let i = 0; i < nodesThatAreDisabled.length; i++) {\n disabledElementsSet.add(nodesThatAreDisabled[i]);\n }\n });\n const bodyNode = this.bodyNode;\n const allTriggerElements = Array.from(this.statesByElement.keys());\n const enterNodeMap = buildRootMap(allTriggerElements, this.collectedEnterElements);\n // this must occur before the instructions are built below such that\n // the :enter queries match the elements (since the timeline queries\n // are fired during instruction building).\n const enterNodeMapIds = new Map();\n let i = 0;\n enterNodeMap.forEach((nodes, root) => {\n const className = ENTER_CLASSNAME + i++;\n enterNodeMapIds.set(root, className);\n nodes.forEach(node => addClass(node, className));\n });\n const allLeaveNodes = [];\n const mergedLeaveNodes = new Set();\n const leaveNodesWithoutAnimations = new Set();\n for (let i = 0; i < this.collectedLeaveElements.length; i++) {\n const element = this.collectedLeaveElements[i];\n const details = element[REMOVAL_FLAG];\n if (details && details.setForRemoval) {\n allLeaveNodes.push(element);\n mergedLeaveNodes.add(element);\n if (details.hasAnimation) {\n this.driver.query(element, STAR_SELECTOR, true).forEach(elm => mergedLeaveNodes.add(elm));\n } else {\n leaveNodesWithoutAnimations.add(element);\n }\n }\n }\n const leaveNodeMapIds = new Map();\n const leaveNodeMap = buildRootMap(allTriggerElements, Array.from(mergedLeaveNodes));\n leaveNodeMap.forEach((nodes, root) => {\n const className = LEAVE_CLASSNAME + i++;\n leaveNodeMapIds.set(root, className);\n nodes.forEach(node => addClass(node, className));\n });\n cleanupFns.push(() => {\n enterNodeMap.forEach((nodes, root) => {\n const className = enterNodeMapIds.get(root);\n nodes.forEach(node => removeClass(node, className));\n });\n leaveNodeMap.forEach((nodes, root) => {\n const className = leaveNodeMapIds.get(root);\n nodes.forEach(node => removeClass(node, className));\n });\n allLeaveNodes.forEach(element => {\n this.processLeaveNode(element);\n });\n });\n const allPlayers = [];\n const erroneousTransitions = [];\n for (let i = this._namespaceList.length - 1; i >= 0; i--) {\n const ns = this._namespaceList[i];\n ns.drainQueuedTransitions(microtaskId).forEach(entry => {\n const player = entry.player;\n const element = entry.element;\n allPlayers.push(player);\n if (this.collectedEnterElements.length) {\n const details = element[REMOVAL_FLAG];\n // animations for move operations (elements being removed and reinserted,\n // e.g. when the order of an *ngFor list changes) are currently not supported\n if (details && details.setForMove) {\n if (details.previousTriggersValues && details.previousTriggersValues.has(entry.triggerName)) {\n const previousValue = details.previousTriggersValues.get(entry.triggerName);\n // we need to restore the previous trigger value since the element has\n // only been moved and hasn't actually left the DOM\n const triggersWithStates = this.statesByElement.get(entry.element);\n if (triggersWithStates && triggersWithStates.has(entry.triggerName)) {\n const state = triggersWithStates.get(entry.triggerName);\n state.value = previousValue;\n triggersWithStates.set(entry.triggerName, state);\n }\n }\n player.destroy();\n return;\n }\n }\n const nodeIsOrphaned = !bodyNode || !this.driver.containsElement(bodyNode, element);\n const leaveClassName = leaveNodeMapIds.get(element);\n const enterClassName = enterNodeMapIds.get(element);\n const instruction = this._buildInstruction(entry, subTimelines, enterClassName, leaveClassName, nodeIsOrphaned);\n if (instruction.errors && instruction.errors.length) {\n erroneousTransitions.push(instruction);\n return;\n }\n // even though the element may not be in the DOM, it may still\n // be added at a later point (due to the mechanics of content\n // projection and/or dynamic component insertion) therefore it's\n // important to still style the element.\n if (nodeIsOrphaned) {\n player.onStart(() => eraseStyles(element, instruction.fromStyles));\n player.onDestroy(() => setStyles(element, instruction.toStyles));\n skippedPlayers.push(player);\n return;\n }\n // if an unmatched transition is queued and ready to go\n // then it SHOULD NOT render an animation and cancel the\n // previously running animations.\n if (entry.isFallbackTransition) {\n player.onStart(() => eraseStyles(element, instruction.fromStyles));\n player.onDestroy(() => setStyles(element, instruction.toStyles));\n skippedPlayers.push(player);\n return;\n }\n // this means that if a parent animation uses this animation as a sub-trigger\n // then it will instruct the timeline builder not to add a player delay, but\n // instead stretch the first keyframe gap until the animation starts. This is\n // important in order to prevent extra initialization styles from being\n // required by the user for the animation.\n const timelines = [];\n instruction.timelines.forEach(tl => {\n tl.stretchStartingKeyframe = true;\n if (!this.disabledNodes.has(tl.element)) {\n timelines.push(tl);\n }\n });\n instruction.timelines = timelines;\n subTimelines.append(element, instruction.timelines);\n const tuple = {\n instruction,\n player,\n element\n };\n queuedInstructions.push(tuple);\n instruction.queriedElements.forEach(element => getOrSetDefaultValue(queriedElements, element, []).push(player));\n instruction.preStyleProps.forEach((stringMap, element) => {\n if (stringMap.size) {\n let setVal = allPreStyleElements.get(element);\n if (!setVal) {\n allPreStyleElements.set(element, setVal = new Set());\n }\n stringMap.forEach((_, prop) => setVal.add(prop));\n }\n });\n instruction.postStyleProps.forEach((stringMap, element) => {\n let setVal = allPostStyleElements.get(element);\n if (!setVal) {\n allPostStyleElements.set(element, setVal = new Set());\n }\n stringMap.forEach((_, prop) => setVal.add(prop));\n });\n });\n }\n if (erroneousTransitions.length) {\n const errors = [];\n erroneousTransitions.forEach(instruction => {\n errors.push(transitionFailed(instruction.triggerName, instruction.errors));\n });\n allPlayers.forEach(player => player.destroy());\n this.reportError(errors);\n }\n const allPreviousPlayersMap = new Map();\n // this map tells us which element in the DOM tree is contained by\n // which animation. Further down this map will get populated once\n // the players are built and in doing so we can use it to efficiently\n // figure out if a sub player is skipped due to a parent player having priority.\n const animationElementMap = new Map();\n queuedInstructions.forEach(entry => {\n const element = entry.element;\n if (subTimelines.has(element)) {\n animationElementMap.set(element, element);\n this._beforeAnimationBuild(entry.player.namespaceId, entry.instruction, allPreviousPlayersMap);\n }\n });\n skippedPlayers.forEach(player => {\n const element = player.element;\n const previousPlayers = this._getPreviousPlayers(element, false, player.namespaceId, player.triggerName, null);\n previousPlayers.forEach(prevPlayer => {\n getOrSetDefaultValue(allPreviousPlayersMap, element, []).push(prevPlayer);\n prevPlayer.destroy();\n });\n });\n // this is a special case for nodes that will be removed either by\n // having their own leave animations or by being queried in a container\n // that will be removed once a parent animation is complete. The idea\n // here is that * styles must be identical to ! styles because of\n // backwards compatibility (* is also filled in by default in many places).\n // Otherwise * styles will return an empty value or \"auto\" since the element\n // passed to getComputedStyle will not be visible (since * === destination)\n const replaceNodes = allLeaveNodes.filter(node => {\n return replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements);\n });\n // POST STAGE: fill the * styles\n const postStylesMap = new Map();\n const allLeaveQueriedNodes = cloakAndComputeStyles(postStylesMap, this.driver, leaveNodesWithoutAnimations, allPostStyleElements, AUTO_STYLE);\n allLeaveQueriedNodes.forEach(node => {\n if (replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements)) {\n replaceNodes.push(node);\n }\n });\n // PRE STAGE: fill the ! styles\n const preStylesMap = new Map();\n enterNodeMap.forEach((nodes, root) => {\n cloakAndComputeStyles(preStylesMap, this.driver, new Set(nodes), allPreStyleElements, ɵPRE_STYLE);\n });\n replaceNodes.forEach(node => {\n const post = postStylesMap.get(node);\n const pre = preStylesMap.get(node);\n postStylesMap.set(node, new Map([...(post?.entries() ?? []), ...(pre?.entries() ?? [])]));\n });\n const rootPlayers = [];\n const subPlayers = [];\n const NO_PARENT_ANIMATION_ELEMENT_DETECTED = {};\n queuedInstructions.forEach(entry => {\n const {\n element,\n player,\n instruction\n } = entry;\n // this means that it was never consumed by a parent animation which\n // means that it is independent and therefore should be set for animation\n if (subTimelines.has(element)) {\n if (disabledElementsSet.has(element)) {\n player.onDestroy(() => setStyles(element, instruction.toStyles));\n player.disabled = true;\n player.overrideTotalTime(instruction.totalTime);\n skippedPlayers.push(player);\n return;\n }\n // this will flow up the DOM and query the map to figure out\n // if a parent animation has priority over it. In the situation\n // that a parent is detected then it will cancel the loop. If\n // nothing is detected, or it takes a few hops to find a parent,\n // then it will fill in the missing nodes and signal them as having\n // a detected parent (or a NO_PARENT value via a special constant).\n let parentWithAnimation = NO_PARENT_ANIMATION_ELEMENT_DETECTED;\n if (animationElementMap.size > 1) {\n let elm = element;\n const parentsToAdd = [];\n while (elm = elm.parentNode) {\n const detectedParent = animationElementMap.get(elm);\n if (detectedParent) {\n parentWithAnimation = detectedParent;\n break;\n }\n parentsToAdd.push(elm);\n }\n parentsToAdd.forEach(parent => animationElementMap.set(parent, parentWithAnimation));\n }\n const innerPlayer = this._buildAnimation(player.namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap);\n player.setRealPlayer(innerPlayer);\n if (parentWithAnimation === NO_PARENT_ANIMATION_ELEMENT_DETECTED) {\n rootPlayers.push(player);\n } else {\n const parentPlayers = this.playersByElement.get(parentWithAnimation);\n if (parentPlayers && parentPlayers.length) {\n player.parentPlayer = optimizeGroupPlayer(parentPlayers);\n }\n skippedPlayers.push(player);\n }\n } else {\n eraseStyles(element, instruction.fromStyles);\n player.onDestroy(() => setStyles(element, instruction.toStyles));\n // there still might be a ancestor player animating this\n // element therefore we will still add it as a sub player\n // even if its animation may be disabled\n subPlayers.push(player);\n if (disabledElementsSet.has(element)) {\n skippedPlayers.push(player);\n }\n }\n });\n // find all of the sub players' corresponding inner animation players\n subPlayers.forEach(player => {\n // even if no players are found for a sub animation it\n // will still complete itself after the next tick since it's Noop\n const playersForElement = skippedPlayersMap.get(player.element);\n if (playersForElement && playersForElement.length) {\n const innerPlayer = optimizeGroupPlayer(playersForElement);\n player.setRealPlayer(innerPlayer);\n }\n });\n // the reason why we don't actually play the animation is\n // because all that a skipped player is designed to do is to\n // fire the start/done transition callback events\n skippedPlayers.forEach(player => {\n if (player.parentPlayer) {\n player.syncPlayerEvents(player.parentPlayer);\n } else {\n player.destroy();\n }\n });\n // run through all of the queued removals and see if they\n // were picked up by a query. If not then perform the removal\n // operation right away unless a parent animation is ongoing.\n for (let i = 0; i < allLeaveNodes.length; i++) {\n const element = allLeaveNodes[i];\n const details = element[REMOVAL_FLAG];\n removeClass(element, LEAVE_CLASSNAME);\n // this means the element has a removal animation that is being\n // taken care of and therefore the inner elements will hang around\n // until that animation is over (or the parent queried animation)\n if (details && details.hasAnimation) continue;\n let players = [];\n // if this element is queried or if it contains queried children\n // then we want for the element not to be removed from the page\n // until the queried animations have finished\n if (queriedElements.size) {\n let queriedPlayerResults = queriedElements.get(element);\n if (queriedPlayerResults && queriedPlayerResults.length) {\n players.push(...queriedPlayerResults);\n }\n let queriedInnerElements = this.driver.query(element, NG_ANIMATING_SELECTOR, true);\n for (let j = 0; j < queriedInnerElements.length; j++) {\n let queriedPlayers = queriedElements.get(queriedInnerElements[j]);\n if (queriedPlayers && queriedPlayers.length) {\n players.push(...queriedPlayers);\n }\n }\n }\n const activePlayers = players.filter(p => !p.destroyed);\n if (activePlayers.length) {\n removeNodesAfterAnimationDone(this, element, activePlayers);\n } else {\n this.processLeaveNode(element);\n }\n }\n // this is required so the cleanup method doesn't remove them\n allLeaveNodes.length = 0;\n rootPlayers.forEach(player => {\n this.players.push(player);\n player.onDone(() => {\n player.destroy();\n const index = this.players.indexOf(player);\n this.players.splice(index, 1);\n });\n player.play();\n });\n return rootPlayers;\n }\n afterFlush(callback) {\n this._flushFns.push(callback);\n }\n afterFlushAnimationsDone(callback) {\n this._whenQuietFns.push(callback);\n }\n _getPreviousPlayers(element, isQueriedElement, namespaceId, triggerName, toStateValue) {\n let players = [];\n if (isQueriedElement) {\n const queriedElementPlayers = this.playersByQueriedElement.get(element);\n if (queriedElementPlayers) {\n players = queriedElementPlayers;\n }\n } else {\n const elementPlayers = this.playersByElement.get(element);\n if (elementPlayers) {\n const isRemovalAnimation = !toStateValue || toStateValue == VOID_VALUE;\n elementPlayers.forEach(player => {\n if (player.queued) return;\n if (!isRemovalAnimation && player.triggerName != triggerName) return;\n players.push(player);\n });\n }\n }\n if (namespaceId || triggerName) {\n players = players.filter(player => {\n if (namespaceId && namespaceId != player.namespaceId) return false;\n if (triggerName && triggerName != player.triggerName) return false;\n return true;\n });\n }\n return players;\n }\n _beforeAnimationBuild(namespaceId, instruction, allPreviousPlayersMap) {\n const triggerName = instruction.triggerName;\n const rootElement = instruction.element;\n // when a removal animation occurs, ALL previous players are collected\n // and destroyed (even if they are outside of the current namespace)\n const targetNameSpaceId = instruction.isRemovalTransition ? undefined : namespaceId;\n const targetTriggerName = instruction.isRemovalTransition ? undefined : triggerName;\n for (const timelineInstruction of instruction.timelines) {\n const element = timelineInstruction.element;\n const isQueriedElement = element !== rootElement;\n const players = getOrSetDefaultValue(allPreviousPlayersMap, element, []);\n const previousPlayers = this._getPreviousPlayers(element, isQueriedElement, targetNameSpaceId, targetTriggerName, instruction.toState);\n previousPlayers.forEach(player => {\n const realPlayer = player.getRealPlayer();\n if (realPlayer.beforeDestroy) {\n realPlayer.beforeDestroy();\n }\n player.destroy();\n players.push(player);\n });\n }\n // this needs to be done so that the PRE/POST styles can be\n // computed properly without interfering with the previous animation\n eraseStyles(rootElement, instruction.fromStyles);\n }\n _buildAnimation(namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap) {\n const triggerName = instruction.triggerName;\n const rootElement = instruction.element;\n // we first run this so that the previous animation player\n // data can be passed into the successive animation players\n const allQueriedPlayers = [];\n const allConsumedElements = new Set();\n const allSubElements = new Set();\n const allNewPlayers = instruction.timelines.map(timelineInstruction => {\n const element = timelineInstruction.element;\n allConsumedElements.add(element);\n // FIXME (matsko): make sure to-be-removed animations are removed properly\n const details = element[REMOVAL_FLAG];\n if (details && details.removedBeforeQueried) return new NoopAnimationPlayer(timelineInstruction.duration, timelineInstruction.delay);\n const isQueriedElement = element !== rootElement;\n const previousPlayers = flattenGroupPlayers((allPreviousPlayersMap.get(element) || EMPTY_PLAYER_ARRAY).map(p => p.getRealPlayer())).filter(p => {\n // the `element` is not apart of the AnimationPlayer definition, but\n // Mock/WebAnimations\n // use the element within their implementation. This will be added in Angular5 to\n // AnimationPlayer\n const pp = p;\n return pp.element ? pp.element === element : false;\n });\n const preStyles = preStylesMap.get(element);\n const postStyles = postStylesMap.get(element);\n const keyframes = normalizeKeyframes$1(this._normalizer, timelineInstruction.keyframes, preStyles, postStyles);\n const player = this._buildPlayer(timelineInstruction, keyframes, previousPlayers);\n // this means that this particular player belongs to a sub trigger. It is\n // important that we match this player up with the corresponding (@trigger.listener)\n if (timelineInstruction.subTimeline && skippedPlayersMap) {\n allSubElements.add(element);\n }\n if (isQueriedElement) {\n const wrappedPlayer = new TransitionAnimationPlayer(namespaceId, triggerName, element);\n wrappedPlayer.setRealPlayer(player);\n allQueriedPlayers.push(wrappedPlayer);\n }\n return player;\n });\n allQueriedPlayers.forEach(player => {\n getOrSetDefaultValue(this.playersByQueriedElement, player.element, []).push(player);\n player.onDone(() => deleteOrUnsetInMap(this.playersByQueriedElement, player.element, player));\n });\n allConsumedElements.forEach(element => addClass(element, NG_ANIMATING_CLASSNAME));\n const player = optimizeGroupPlayer(allNewPlayers);\n player.onDestroy(() => {\n allConsumedElements.forEach(element => removeClass(element, NG_ANIMATING_CLASSNAME));\n setStyles(rootElement, instruction.toStyles);\n });\n // this basically makes all of the callbacks for sub element animations\n // be dependent on the upper players for when they finish\n allSubElements.forEach(element => {\n getOrSetDefaultValue(skippedPlayersMap, element, []).push(player);\n });\n return player;\n }\n _buildPlayer(instruction, keyframes, previousPlayers) {\n if (keyframes.length > 0) {\n return this.driver.animate(instruction.element, keyframes, instruction.duration, instruction.delay, instruction.easing, previousPlayers);\n }\n // special case for when an empty transition|definition is provided\n // ... there is no point in rendering an empty animation\n return new NoopAnimationPlayer(instruction.duration, instruction.delay);\n }\n}\nclass TransitionAnimationPlayer {\n constructor(namespaceId, triggerName, element) {\n this.namespaceId = namespaceId;\n this.triggerName = triggerName;\n this.element = element;\n this._player = new NoopAnimationPlayer();\n this._containsRealPlayer = false;\n this._queuedCallbacks = new Map();\n this.destroyed = false;\n this.parentPlayer = null;\n this.markedForDestroy = false;\n this.disabled = false;\n this.queued = true;\n this.totalTime = 0;\n }\n setRealPlayer(player) {\n if (this._containsRealPlayer) return;\n this._player = player;\n this._queuedCallbacks.forEach((callbacks, phase) => {\n callbacks.forEach(callback => listenOnPlayer(player, phase, undefined, callback));\n });\n this._queuedCallbacks.clear();\n this._containsRealPlayer = true;\n this.overrideTotalTime(player.totalTime);\n this.queued = false;\n }\n getRealPlayer() {\n return this._player;\n }\n overrideTotalTime(totalTime) {\n this.totalTime = totalTime;\n }\n syncPlayerEvents(player) {\n const p = this._player;\n if (p.triggerCallback) {\n player.onStart(() => p.triggerCallback('start'));\n }\n player.onDone(() => this.finish());\n player.onDestroy(() => this.destroy());\n }\n _queueEvent(name, callback) {\n getOrSetDefaultValue(this._queuedCallbacks, name, []).push(callback);\n }\n onDone(fn) {\n if (this.queued) {\n this._queueEvent('done', fn);\n }\n this._player.onDone(fn);\n }\n onStart(fn) {\n if (this.queued) {\n this._queueEvent('start', fn);\n }\n this._player.onStart(fn);\n }\n onDestroy(fn) {\n if (this.queued) {\n this._queueEvent('destroy', fn);\n }\n this._player.onDestroy(fn);\n }\n init() {\n this._player.init();\n }\n hasStarted() {\n return this.queued ? false : this._player.hasStarted();\n }\n play() {\n !this.queued && this._player.play();\n }\n pause() {\n !this.queued && this._player.pause();\n }\n restart() {\n !this.queued && this._player.restart();\n }\n finish() {\n this._player.finish();\n }\n destroy() {\n this.destroyed = true;\n this._player.destroy();\n }\n reset() {\n !this.queued && this._player.reset();\n }\n setPosition(p) {\n if (!this.queued) {\n this._player.setPosition(p);\n }\n }\n getPosition() {\n return this.queued ? 0 : this._player.getPosition();\n }\n /** @internal */\n triggerCallback(phaseName) {\n const p = this._player;\n if (p.triggerCallback) {\n p.triggerCallback(phaseName);\n }\n }\n}\nfunction deleteOrUnsetInMap(map, key, value) {\n let currentValues = map.get(key);\n if (currentValues) {\n if (currentValues.length) {\n const index = currentValues.indexOf(value);\n currentValues.splice(index, 1);\n }\n if (currentValues.length == 0) {\n map.delete(key);\n }\n }\n return currentValues;\n}\nfunction normalizeTriggerValue(value) {\n // we use `!= null` here because it's the most simple\n // way to test against a \"falsy\" value without mixing\n // in empty strings or a zero value. DO NOT OPTIMIZE.\n return value != null ? value : null;\n}\nfunction isElementNode(node) {\n return node && node['nodeType'] === 1;\n}\nfunction isTriggerEventValid(eventName) {\n return eventName == 'start' || eventName == 'done';\n}\nfunction cloakElement(element, value) {\n const oldValue = element.style.display;\n element.style.display = value != null ? value : 'none';\n return oldValue;\n}\nfunction cloakAndComputeStyles(valuesMap, driver, elements, elementPropsMap, defaultStyle) {\n const cloakVals = [];\n elements.forEach(element => cloakVals.push(cloakElement(element)));\n const failedElements = [];\n elementPropsMap.forEach((props, element) => {\n const styles = new Map();\n props.forEach(prop => {\n const value = driver.computeStyle(element, prop, defaultStyle);\n styles.set(prop, value);\n // there is no easy way to detect this because a sub element could be removed\n // by a parent animation element being detached.\n if (!value || value.length == 0) {\n element[REMOVAL_FLAG] = NULL_REMOVED_QUERIED_STATE;\n failedElements.push(element);\n }\n });\n valuesMap.set(element, styles);\n });\n // we use a index variable here since Set.forEach(a, i) does not return\n // an index value for the closure (but instead just the value)\n let i = 0;\n elements.forEach(element => cloakElement(element, cloakVals[i++]));\n return failedElements;\n}\n/*\nSince the Angular renderer code will return a collection of inserted\nnodes in all areas of a DOM tree, it's up to this algorithm to figure\nout which nodes are roots for each animation @trigger.\n\nBy placing each inserted node into a Set and traversing upwards, it\nis possible to find the @trigger elements and well any direct *star\ninsertion nodes, if a @trigger root is found then the enter element\nis placed into the Map[@trigger] spot.\n */\nfunction buildRootMap(roots, nodes) {\n const rootMap = new Map();\n roots.forEach(root => rootMap.set(root, []));\n if (nodes.length == 0) return rootMap;\n const NULL_NODE = 1;\n const nodeSet = new Set(nodes);\n const localRootMap = new Map();\n function getRoot(node) {\n if (!node) return NULL_NODE;\n let root = localRootMap.get(node);\n if (root) return root;\n const parent = node.parentNode;\n if (rootMap.has(parent)) {\n // ngIf inside @trigger\n root = parent;\n } else if (nodeSet.has(parent)) {\n // ngIf inside ngIf\n root = NULL_NODE;\n } else {\n // recurse upwards\n root = getRoot(parent);\n }\n localRootMap.set(node, root);\n return root;\n }\n nodes.forEach(node => {\n const root = getRoot(node);\n if (root !== NULL_NODE) {\n rootMap.get(root).push(node);\n }\n });\n return rootMap;\n}\nfunction addClass(element, className) {\n element.classList?.add(className);\n}\nfunction removeClass(element, className) {\n element.classList?.remove(className);\n}\nfunction removeNodesAfterAnimationDone(engine, element, players) {\n optimizeGroupPlayer(players).onDone(() => engine.processLeaveNode(element));\n}\nfunction flattenGroupPlayers(players) {\n const finalPlayers = [];\n _flattenGroupPlayersRecur(players, finalPlayers);\n return finalPlayers;\n}\nfunction _flattenGroupPlayersRecur(players, finalPlayers) {\n for (let i = 0; i < players.length; i++) {\n const player = players[i];\n if (player instanceof ɵAnimationGroupPlayer) {\n _flattenGroupPlayersRecur(player.players, finalPlayers);\n } else {\n finalPlayers.push(player);\n }\n }\n}\nfunction objEquals(a, b) {\n const k1 = Object.keys(a);\n const k2 = Object.keys(b);\n if (k1.length != k2.length) return false;\n for (let i = 0; i < k1.length; i++) {\n const prop = k1[i];\n if (!b.hasOwnProperty(prop) || a[prop] !== b[prop]) return false;\n }\n return true;\n}\nfunction replacePostStylesAsPre(element, allPreStyleElements, allPostStyleElements) {\n const postEntry = allPostStyleElements.get(element);\n if (!postEntry) return false;\n let preEntry = allPreStyleElements.get(element);\n if (preEntry) {\n postEntry.forEach(data => preEntry.add(data));\n } else {\n allPreStyleElements.set(element, postEntry);\n }\n allPostStyleElements.delete(element);\n return true;\n}\nclass AnimationEngine {\n constructor(doc, _driver, _normalizer, scheduler) {\n this._driver = _driver;\n this._normalizer = _normalizer;\n this._triggerCache = {};\n // this method is designed to be overridden by the code that uses this engine\n this.onRemovalComplete = (element, context) => {};\n this._transitionEngine = new TransitionAnimationEngine(doc.body, _driver, _normalizer, scheduler);\n this._timelineEngine = new TimelineAnimationEngine(doc.body, _driver, _normalizer);\n this._transitionEngine.onRemovalComplete = (element, context) => this.onRemovalComplete(element, context);\n }\n registerTrigger(componentId, namespaceId, hostElement, name, metadata) {\n const cacheKey = componentId + '-' + name;\n let trigger = this._triggerCache[cacheKey];\n if (!trigger) {\n const errors = [];\n const warnings = [];\n const ast = buildAnimationAst(this._driver, metadata, errors, warnings);\n if (errors.length) {\n throw triggerBuildFailed(name, errors);\n }\n if (warnings.length) {\n warnTriggerBuild(name, warnings);\n }\n trigger = buildTrigger(name, ast, this._normalizer);\n this._triggerCache[cacheKey] = trigger;\n }\n this._transitionEngine.registerTrigger(namespaceId, name, trigger);\n }\n register(namespaceId, hostElement) {\n this._transitionEngine.register(namespaceId, hostElement);\n }\n destroy(namespaceId, context) {\n this._transitionEngine.destroy(namespaceId, context);\n }\n onInsert(namespaceId, element, parent, insertBefore) {\n this._transitionEngine.insertNode(namespaceId, element, parent, insertBefore);\n }\n onRemove(namespaceId, element, context) {\n this._transitionEngine.removeNode(namespaceId, element, context);\n }\n disableAnimations(element, disable) {\n this._transitionEngine.markElementAsDisabled(element, disable);\n }\n process(namespaceId, element, property, value) {\n if (property.charAt(0) == '@') {\n const [id, action] = parseTimelineCommand(property);\n const args = value;\n this._timelineEngine.command(id, element, action, args);\n } else {\n this._transitionEngine.trigger(namespaceId, element, property, value);\n }\n }\n listen(namespaceId, element, eventName, eventPhase, callback) {\n // @@listen\n if (eventName.charAt(0) == '@') {\n const [id, action] = parseTimelineCommand(eventName);\n return this._timelineEngine.listen(id, element, action, callback);\n }\n return this._transitionEngine.listen(namespaceId, element, eventName, eventPhase, callback);\n }\n flush(microtaskId = -1) {\n this._transitionEngine.flush(microtaskId);\n }\n get players() {\n return [...this._transitionEngine.players, ...this._timelineEngine.players];\n }\n whenRenderingDone() {\n return this._transitionEngine.whenRenderingDone();\n }\n afterFlushAnimationsDone(cb) {\n this._transitionEngine.afterFlushAnimationsDone(cb);\n }\n}\n\n/**\n * Returns an instance of `SpecialCasedStyles` if and when any special (non animateable) styles are\n * detected.\n *\n * In CSS there exist properties that cannot be animated within a keyframe animation\n * (whether it be via CSS keyframes or web-animations) and the animation implementation\n * will ignore them. This function is designed to detect those special cased styles and\n * return a container that will be executed at the start and end of the animation.\n *\n * @returns an instance of `SpecialCasedStyles` if any special styles are detected otherwise `null`\n */\nfunction packageNonAnimatableStyles(element, styles) {\n let startStyles = null;\n let endStyles = null;\n if (Array.isArray(styles) && styles.length) {\n startStyles = filterNonAnimatableStyles(styles[0]);\n if (styles.length > 1) {\n endStyles = filterNonAnimatableStyles(styles[styles.length - 1]);\n }\n } else if (styles instanceof Map) {\n startStyles = filterNonAnimatableStyles(styles);\n }\n return startStyles || endStyles ? new SpecialCasedStyles(element, startStyles, endStyles) : null;\n}\n/**\n * Designed to be executed during a keyframe-based animation to apply any special-cased styles.\n *\n * When started (when the `start()` method is run) then the provided `startStyles`\n * will be applied. When finished (when the `finish()` method is called) the\n * `endStyles` will be applied as well any any starting styles. Finally when\n * `destroy()` is called then all styles will be removed.\n */\nclass SpecialCasedStyles {\n static {\n this.initialStylesByElement = /*#__PURE__*/new WeakMap();\n }\n constructor(_element, _startStyles, _endStyles) {\n this._element = _element;\n this._startStyles = _startStyles;\n this._endStyles = _endStyles;\n this._state = 0 /* SpecialCasedStylesState.Pending */;\n let initialStyles = SpecialCasedStyles.initialStylesByElement.get(_element);\n if (!initialStyles) {\n SpecialCasedStyles.initialStylesByElement.set(_element, initialStyles = new Map());\n }\n this._initialStyles = initialStyles;\n }\n start() {\n if (this._state < 1 /* SpecialCasedStylesState.Started */) {\n if (this._startStyles) {\n setStyles(this._element, this._startStyles, this._initialStyles);\n }\n this._state = 1 /* SpecialCasedStylesState.Started */;\n }\n }\n finish() {\n this.start();\n if (this._state < 2 /* SpecialCasedStylesState.Finished */) {\n setStyles(this._element, this._initialStyles);\n if (this._endStyles) {\n setStyles(this._element, this._endStyles);\n this._endStyles = null;\n }\n this._state = 1 /* SpecialCasedStylesState.Started */;\n }\n }\n destroy() {\n this.finish();\n if (this._state < 3 /* SpecialCasedStylesState.Destroyed */) {\n SpecialCasedStyles.initialStylesByElement.delete(this._element);\n if (this._startStyles) {\n eraseStyles(this._element, this._startStyles);\n this._endStyles = null;\n }\n if (this._endStyles) {\n eraseStyles(this._element, this._endStyles);\n this._endStyles = null;\n }\n setStyles(this._element, this._initialStyles);\n this._state = 3 /* SpecialCasedStylesState.Destroyed */;\n }\n }\n}\nfunction filterNonAnimatableStyles(styles) {\n let result = null;\n styles.forEach((val, prop) => {\n if (isNonAnimatableStyle(prop)) {\n result = result || new Map();\n result.set(prop, val);\n }\n });\n return result;\n}\nfunction isNonAnimatableStyle(prop) {\n return prop === 'display' || prop === 'position';\n}\nclass WebAnimationsPlayer {\n constructor(element, keyframes, options, _specialStyles) {\n this.element = element;\n this.keyframes = keyframes;\n this.options = options;\n this._specialStyles = _specialStyles;\n this._onDoneFns = [];\n this._onStartFns = [];\n this._onDestroyFns = [];\n this._initialized = false;\n this._finished = false;\n this._started = false;\n this._destroyed = false;\n // the following original fns are persistent copies of the _onStartFns and _onDoneFns\n // and are used to reset the fns to their original values upon reset()\n // (since the _onStartFns and _onDoneFns get deleted after they are called)\n this._originalOnDoneFns = [];\n this._originalOnStartFns = [];\n this.time = 0;\n this.parentPlayer = null;\n this.currentSnapshot = new Map();\n this._duration = options['duration'];\n this._delay = options['delay'] || 0;\n this.time = this._duration + this._delay;\n }\n _onFinish() {\n if (!this._finished) {\n this._finished = true;\n this._onDoneFns.forEach(fn => fn());\n this._onDoneFns = [];\n }\n }\n init() {\n this._buildPlayer();\n this._preparePlayerBeforeStart();\n }\n _buildPlayer() {\n if (this._initialized) return;\n this._initialized = true;\n const keyframes = this.keyframes;\n // @ts-expect-error overwriting a readonly property\n this.domPlayer = this._triggerWebAnimation(this.element, keyframes, this.options);\n this._finalKeyframe = keyframes.length ? keyframes[keyframes.length - 1] : new Map();\n const onFinish = () => this._onFinish();\n this.domPlayer.addEventListener('finish', onFinish);\n this.onDestroy(() => {\n // We must remove the `finish` event listener once an animation has completed all its\n // iterations. This action is necessary to prevent a memory leak since the listener captures\n // `this`, creating a closure that prevents `this` from being garbage collected.\n this.domPlayer.removeEventListener('finish', onFinish);\n });\n }\n _preparePlayerBeforeStart() {\n // this is required so that the player doesn't start to animate right away\n if (this._delay) {\n this._resetDomPlayerState();\n } else {\n this.domPlayer.pause();\n }\n }\n _convertKeyframesToObject(keyframes) {\n const kfs = [];\n keyframes.forEach(frame => {\n kfs.push(Object.fromEntries(frame));\n });\n return kfs;\n }\n /** @internal */\n _triggerWebAnimation(element, keyframes, options) {\n return element.animate(this._convertKeyframesToObject(keyframes), options);\n }\n onStart(fn) {\n this._originalOnStartFns.push(fn);\n this._onStartFns.push(fn);\n }\n onDone(fn) {\n this._originalOnDoneFns.push(fn);\n this._onDoneFns.push(fn);\n }\n onDestroy(fn) {\n this._onDestroyFns.push(fn);\n }\n play() {\n this._buildPlayer();\n if (!this.hasStarted()) {\n this._onStartFns.forEach(fn => fn());\n this._onStartFns = [];\n this._started = true;\n if (this._specialStyles) {\n this._specialStyles.start();\n }\n }\n this.domPlayer.play();\n }\n pause() {\n this.init();\n this.domPlayer.pause();\n }\n finish() {\n this.init();\n if (this._specialStyles) {\n this._specialStyles.finish();\n }\n this._onFinish();\n this.domPlayer.finish();\n }\n reset() {\n this._resetDomPlayerState();\n this._destroyed = false;\n this._finished = false;\n this._started = false;\n this._onStartFns = this._originalOnStartFns;\n this._onDoneFns = this._originalOnDoneFns;\n }\n _resetDomPlayerState() {\n if (this.domPlayer) {\n this.domPlayer.cancel();\n }\n }\n restart() {\n this.reset();\n this.play();\n }\n hasStarted() {\n return this._started;\n }\n destroy() {\n if (!this._destroyed) {\n this._destroyed = true;\n this._resetDomPlayerState();\n this._onFinish();\n if (this._specialStyles) {\n this._specialStyles.destroy();\n }\n this._onDestroyFns.forEach(fn => fn());\n this._onDestroyFns = [];\n }\n }\n setPosition(p) {\n if (this.domPlayer === undefined) {\n this.init();\n }\n this.domPlayer.currentTime = p * this.time;\n }\n getPosition() {\n // tsc is complaining with TS2362 without the conversion to number\n return +(this.domPlayer.currentTime ?? 0) / this.time;\n }\n get totalTime() {\n return this._delay + this._duration;\n }\n beforeDestroy() {\n const styles = new Map();\n if (this.hasStarted()) {\n // note: this code is invoked only when the `play` function was called prior to this\n // (thus `hasStarted` returns true), this implies that the code that initializes\n // `_finalKeyframe` has also been executed and the non-null assertion can be safely used here\n const finalKeyframe = this._finalKeyframe;\n finalKeyframe.forEach((val, prop) => {\n if (prop !== 'offset') {\n styles.set(prop, this._finished ? val : computeStyle(this.element, prop));\n }\n });\n }\n this.currentSnapshot = styles;\n }\n /** @internal */\n triggerCallback(phaseName) {\n const methods = phaseName === 'start' ? this._onStartFns : this._onDoneFns;\n methods.forEach(fn => fn());\n methods.length = 0;\n }\n}\nclass WebAnimationsDriver {\n validateStyleProperty(prop) {\n // Perform actual validation in dev mode only, in prod mode this check is a noop.\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n return validateStyleProperty(prop);\n }\n return true;\n }\n validateAnimatableStyleProperty(prop) {\n // Perform actual validation in dev mode only, in prod mode this check is a noop.\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n const cssProp = camelCaseToDashCase(prop);\n return validateWebAnimatableStyleProperty(cssProp);\n }\n return true;\n }\n matchesElement(_element, _selector) {\n // This method is deprecated and no longer in use so we return false.\n return false;\n }\n containsElement(elm1, elm2) {\n return containsElement(elm1, elm2);\n }\n getParentElement(element) {\n return getParentElement(element);\n }\n query(element, selector, multi) {\n return invokeQuery(element, selector, multi);\n }\n computeStyle(element, prop, defaultValue) {\n return computeStyle(element, prop);\n }\n animate(element, keyframes, duration, delay, easing, previousPlayers = []) {\n const fill = delay == 0 ? 'both' : 'forwards';\n const playerOptions = {\n duration,\n delay,\n fill\n };\n // we check for this to avoid having a null|undefined value be present\n // for the easing (which results in an error for certain browsers #9752)\n if (easing) {\n playerOptions['easing'] = easing;\n }\n const previousStyles = new Map();\n const previousWebAnimationPlayers = previousPlayers.filter(player => player instanceof WebAnimationsPlayer);\n if (allowPreviousPlayerStylesMerge(duration, delay)) {\n previousWebAnimationPlayers.forEach(player => {\n player.currentSnapshot.forEach((val, prop) => previousStyles.set(prop, val));\n });\n }\n let _keyframes = normalizeKeyframes(keyframes).map(styles => new Map(styles));\n _keyframes = balancePreviousStylesIntoKeyframes(element, _keyframes, previousStyles);\n const specialStyles = packageNonAnimatableStyles(element, _keyframes);\n return new WebAnimationsPlayer(element, _keyframes, playerOptions, specialStyles);\n }\n}\nfunction createEngine(type, doc, scheduler) {\n // TODO: find a way to make this tree shakable.\n if (type === 'noop') {\n return new AnimationEngine(doc, new NoopAnimationDriver(), new NoopAnimationStyleNormalizer(), scheduler);\n }\n return new AnimationEngine(doc, new WebAnimationsDriver(), new WebAnimationsStyleNormalizer(), scheduler);\n}\nclass Animation {\n constructor(_driver, input) {\n this._driver = _driver;\n const errors = [];\n const warnings = [];\n const ast = buildAnimationAst(_driver, input, errors, warnings);\n if (errors.length) {\n throw validationFailed(errors);\n }\n if (warnings.length) {\n warnValidation(warnings);\n }\n this._animationAst = ast;\n }\n buildTimelines(element, startingStyles, destinationStyles, options, subInstructions) {\n const start = Array.isArray(startingStyles) ? normalizeStyles(startingStyles) : startingStyles;\n const dest = Array.isArray(destinationStyles) ? normalizeStyles(destinationStyles) : destinationStyles;\n const errors = [];\n subInstructions = subInstructions || new ElementInstructionMap();\n const result = buildAnimationTimelines(this._driver, element, this._animationAst, ENTER_CLASSNAME, LEAVE_CLASSNAME, start, dest, options, subInstructions, errors);\n if (errors.length) {\n throw buildingFailed(errors);\n }\n return result;\n }\n}\nconst ANIMATION_PREFIX = '@';\nconst DISABLE_ANIMATIONS_FLAG = '@.disabled';\nclass BaseAnimationRenderer {\n constructor(namespaceId, delegate, engine, _onDestroy) {\n this.namespaceId = namespaceId;\n this.delegate = delegate;\n this.engine = engine;\n this._onDestroy = _onDestroy;\n // We need to explicitly type this property because of an api-extractor bug\n // See https://github.com/microsoft/rushstack/issues/4390\n this.ɵtype = 0 /* AnimationRendererType.Regular */;\n }\n get data() {\n return this.delegate.data;\n }\n destroyNode(node) {\n this.delegate.destroyNode?.(node);\n }\n destroy() {\n this.engine.destroy(this.namespaceId, this.delegate);\n this.engine.afterFlushAnimationsDone(() => {\n // Call the renderer destroy method after the animations has finished as otherwise\n // styles will be removed too early which will cause an unstyled animation.\n queueMicrotask(() => {\n this.delegate.destroy();\n });\n });\n this._onDestroy?.();\n }\n createElement(name, namespace) {\n return this.delegate.createElement(name, namespace);\n }\n createComment(value) {\n return this.delegate.createComment(value);\n }\n createText(value) {\n return this.delegate.createText(value);\n }\n appendChild(parent, newChild) {\n this.delegate.appendChild(parent, newChild);\n this.engine.onInsert(this.namespaceId, newChild, parent, false);\n }\n insertBefore(parent, newChild, refChild, isMove = true) {\n this.delegate.insertBefore(parent, newChild, refChild);\n // If `isMove` true than we should animate this insert.\n this.engine.onInsert(this.namespaceId, newChild, parent, isMove);\n }\n removeChild(parent, oldChild, isHostElement) {\n this.engine.onRemove(this.namespaceId, oldChild, this.delegate);\n }\n selectRootElement(selectorOrNode, preserveContent) {\n return this.delegate.selectRootElement(selectorOrNode, preserveContent);\n }\n parentNode(node) {\n return this.delegate.parentNode(node);\n }\n nextSibling(node) {\n return this.delegate.nextSibling(node);\n }\n setAttribute(el, name, value, namespace) {\n this.delegate.setAttribute(el, name, value, namespace);\n }\n removeAttribute(el, name, namespace) {\n this.delegate.removeAttribute(el, name, namespace);\n }\n addClass(el, name) {\n this.delegate.addClass(el, name);\n }\n removeClass(el, name) {\n this.delegate.removeClass(el, name);\n }\n setStyle(el, style, value, flags) {\n this.delegate.setStyle(el, style, value, flags);\n }\n removeStyle(el, style, flags) {\n this.delegate.removeStyle(el, style, flags);\n }\n setProperty(el, name, value) {\n if (name.charAt(0) == ANIMATION_PREFIX && name == DISABLE_ANIMATIONS_FLAG) {\n this.disableAnimations(el, !!value);\n } else {\n this.delegate.setProperty(el, name, value);\n }\n }\n setValue(node, value) {\n this.delegate.setValue(node, value);\n }\n listen(target, eventName, callback) {\n return this.delegate.listen(target, eventName, callback);\n }\n disableAnimations(element, value) {\n this.engine.disableAnimations(element, value);\n }\n}\nclass AnimationRenderer extends BaseAnimationRenderer {\n constructor(factory, namespaceId, delegate, engine, onDestroy) {\n super(namespaceId, delegate, engine, onDestroy);\n this.factory = factory;\n this.namespaceId = namespaceId;\n }\n setProperty(el, name, value) {\n if (name.charAt(0) == ANIMATION_PREFIX) {\n if (name.charAt(1) == '.' && name == DISABLE_ANIMATIONS_FLAG) {\n value = value === undefined ? true : !!value;\n this.disableAnimations(el, value);\n } else {\n this.engine.process(this.namespaceId, el, name.slice(1), value);\n }\n } else {\n this.delegate.setProperty(el, name, value);\n }\n }\n listen(target, eventName, callback) {\n if (eventName.charAt(0) == ANIMATION_PREFIX) {\n const element = resolveElementFromTarget(target);\n let name = eventName.slice(1);\n let phase = '';\n // @listener.phase is for trigger animation callbacks\n // @@listener is for animation builder callbacks\n if (name.charAt(0) != ANIMATION_PREFIX) {\n [name, phase] = parseTriggerCallbackName(name);\n }\n return this.engine.listen(this.namespaceId, element, name, phase, event => {\n const countId = event['_data'] || -1;\n this.factory.scheduleListenerCallback(countId, callback, event);\n });\n }\n return this.delegate.listen(target, eventName, callback);\n }\n}\nfunction resolveElementFromTarget(target) {\n switch (target) {\n case 'body':\n return document.body;\n case 'document':\n return document;\n case 'window':\n return window;\n default:\n return target;\n }\n}\nfunction parseTriggerCallbackName(triggerName) {\n const dotIndex = triggerName.indexOf('.');\n const trigger = triggerName.substring(0, dotIndex);\n const phase = triggerName.slice(dotIndex + 1);\n return [trigger, phase];\n}\nclass AnimationRendererFactory {\n constructor(delegate, engine, _zone) {\n this.delegate = delegate;\n this.engine = engine;\n this._zone = _zone;\n this._currentId = 0;\n this._microtaskId = 1;\n this._animationCallbacksBuffer = [];\n this._rendererCache = new Map();\n this._cdRecurDepth = 0;\n engine.onRemovalComplete = (element, delegate) => {\n // Note: if a component element has a leave animation, and a host leave animation,\n // the view engine will call `removeChild` for the parent\n // component renderer as well as for the child component renderer.\n // Therefore, we need to check if we already removed the element.\n const parentNode = delegate?.parentNode(element);\n if (parentNode) {\n delegate.removeChild(parentNode, element);\n }\n };\n }\n createRenderer(hostElement, type) {\n const EMPTY_NAMESPACE_ID = '';\n // cache the delegates to find out which cached delegate can\n // be used by which cached renderer\n const delegate = this.delegate.createRenderer(hostElement, type);\n if (!hostElement || !type?.data?.['animation']) {\n const cache = this._rendererCache;\n let renderer = cache.get(delegate);\n if (!renderer) {\n // Ensure that the renderer is removed from the cache on destroy\n // since it may contain references to detached DOM nodes.\n const onRendererDestroy = () => cache.delete(delegate);\n renderer = new BaseAnimationRenderer(EMPTY_NAMESPACE_ID, delegate, this.engine, onRendererDestroy);\n // only cache this result when the base renderer is used\n cache.set(delegate, renderer);\n }\n return renderer;\n }\n const componentId = type.id;\n const namespaceId = type.id + '-' + this._currentId;\n this._currentId++;\n this.engine.register(namespaceId, hostElement);\n const registerTrigger = trigger => {\n if (Array.isArray(trigger)) {\n trigger.forEach(registerTrigger);\n } else {\n this.engine.registerTrigger(componentId, namespaceId, hostElement, trigger.name, trigger);\n }\n };\n const animationTriggers = type.data['animation'];\n animationTriggers.forEach(registerTrigger);\n return new AnimationRenderer(this, namespaceId, delegate, this.engine);\n }\n begin() {\n this._cdRecurDepth++;\n if (this.delegate.begin) {\n this.delegate.begin();\n }\n }\n _scheduleCountTask() {\n queueMicrotask(() => {\n this._microtaskId++;\n });\n }\n /** @internal */\n scheduleListenerCallback(count, fn, data) {\n if (count >= 0 && count < this._microtaskId) {\n this._zone.run(() => fn(data));\n return;\n }\n const animationCallbacksBuffer = this._animationCallbacksBuffer;\n if (animationCallbacksBuffer.length == 0) {\n queueMicrotask(() => {\n this._zone.run(() => {\n animationCallbacksBuffer.forEach(tuple => {\n const [fn, data] = tuple;\n fn(data);\n });\n this._animationCallbacksBuffer = [];\n });\n });\n }\n animationCallbacksBuffer.push([fn, data]);\n }\n end() {\n this._cdRecurDepth--;\n // this is to prevent animations from running twice when an inner\n // component does CD when a parent component instead has inserted it\n if (this._cdRecurDepth == 0) {\n this._zone.runOutsideAngular(() => {\n this._scheduleCountTask();\n this.engine.flush(this._microtaskId);\n });\n }\n if (this.delegate.end) {\n this.delegate.end();\n }\n }\n whenRenderingDone() {\n return this.engine.whenRenderingDone();\n }\n}\n\n/**\n * @module\n * @description\n * Entry point for all animation APIs of the animation browser package.\n */\n\n/**\n * @module\n * @description\n * Entry point for all public APIs of this package.\n */\n\n// This file is not used to build this module. It is only used during editing\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { AnimationDriver, NoopAnimationDriver, Animation as ɵAnimation, AnimationEngine as ɵAnimationEngine, AnimationRenderer as ɵAnimationRenderer, AnimationRendererFactory as ɵAnimationRendererFactory, AnimationStyleNormalizer as ɵAnimationStyleNormalizer, BaseAnimationRenderer as ɵBaseAnimationRenderer, NoopAnimationStyleNormalizer as ɵNoopAnimationStyleNormalizer, WebAnimationsDriver as ɵWebAnimationsDriver, WebAnimationsPlayer as ɵWebAnimationsPlayer, WebAnimationsStyleNormalizer as ɵWebAnimationsStyleNormalizer, allowPreviousPlayerStylesMerge as ɵallowPreviousPlayerStylesMerge, camelCaseToDashCase as ɵcamelCaseToDashCase, containsElement as ɵcontainsElement, createEngine as ɵcreateEngine, getParentElement as ɵgetParentElement, invokeQuery as ɵinvokeQuery, normalizeKeyframes as ɵnormalizeKeyframes, validateStyleProperty as ɵvalidateStyleProperty, validateWebAnimatableStyleProperty as ɵvalidateWebAnimatableStyleProperty };\n","import * as i0 from '@angular/core';\nimport { EventEmitter, Component, Input, Output, ViewChild, ApplicationRef, createComponent, forwardRef, ViewEncapsulation, Injectable, Optional, Pipe, HostListener, HostBinding, NgModule, InjectionToken } from '@angular/core';\nimport * as i4 from '@angular/forms';\nimport { NG_VALUE_ACCESSOR, FormGroup, FormControl, Validators as Validators$1, ReactiveFormsModule } from '@angular/forms';\nimport { Subject, isObservable, of, fromEvent, asyncScheduler } from 'rxjs';\nimport { takeUntil, throttleTime } from 'rxjs/operators';\nimport { NgxEditorError, clamp, uniq, isNil } from 'ngx-editor/utils';\nimport { Plugin, PluginKey, NodeSelection, Selection, EditorState } from 'prosemirror-state';\nimport { DecorationSet, Decoration, EditorView } from 'prosemirror-view';\nimport * as i3 from '@angular/common';\nimport { CommonModule } from '@angular/common';\nimport { Fragment, Slice, DOMSerializer, DOMParser } from 'prosemirror-model';\nimport { schema } from 'ngx-editor/schema';\nexport { marks, nodes, schema } from 'ngx-editor/schema';\nimport { toggleMark, lift, wrapIn, setBlockType, newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock, chainCommands, exitCode, baseKeymap } from 'prosemirror-commands';\nimport { applyMark, removeLink, removeMark } from 'ngx-editor/commands';\nimport { isMarkActive, isNodeActive, canInsert, getSelectionNodes, getSelectionMarks, markInputRule } from 'ngx-editor/helpers';\nimport { liftListItem, wrapInList, splitListItem, sinkListItem } from 'prosemirror-schema-list';\nimport { undo as undo$1, redo as redo$1, history } from 'prosemirror-history';\nimport * as i1 from '@angular/platform-browser';\nimport { computePosition, offset, autoPlacement, detectOverflow } from '@floating-ui/dom';\nimport { keymap } from 'prosemirror-keymap';\nimport { wrappingInputRule, textblockTypeInputRule, smartQuotes, ellipsis, emDash, inputRules } from 'prosemirror-inputrules';\nconst _c0 = [\"imgEl\"];\nconst _c1 = a0 => ({\n \"NgxEditor__Resizer--Active\": a0\n});\nfunction ImageViewComponent_span_1_Template(rf, ctx) {\n if (rf & 1) {\n const _r1 = i0.ɵɵgetCurrentView();\n i0.ɵɵelementStart(0, \"span\", 4)(1, \"span\", 5);\n i0.ɵɵlistener(\"mousedown\", function ImageViewComponent_span_1_Template_span_mousedown_1_listener($event) {\n i0.ɵɵrestoreView(_r1);\n const ctx_r1 = i0.ɵɵnextContext();\n return i0.ɵɵresetView(ctx_r1.startResizing($event, \"left\"));\n });\n i0.ɵɵelementEnd();\n i0.ɵɵelementStart(2, \"span\", 6);\n i0.ɵɵlistener(\"mousedown\", function ImageViewComponent_span_1_Template_span_mousedown_2_listener($event) {\n i0.ɵɵrestoreView(_r1);\n const ctx_r1 = i0.ɵɵnextContext();\n return i0.ɵɵresetView(ctx_r1.startResizing($event, \"right\"));\n });\n i0.ɵɵelementEnd();\n i0.ɵɵelementStart(3, \"span\", 7);\n i0.ɵɵlistener(\"mousedown\", function ImageViewComponent_span_1_Template_span_mousedown_3_listener($event) {\n i0.ɵɵrestoreView(_r1);\n const ctx_r1 = i0.ɵɵnextContext();\n return i0.ɵɵresetView(ctx_r1.startResizing($event, \"left\"));\n });\n i0.ɵɵelementEnd();\n i0.ɵɵelementStart(4, \"span\", 8);\n i0.ɵɵlistener(\"mousedown\", function ImageViewComponent_span_1_Template_span_mousedown_4_listener($event) {\n i0.ɵɵrestoreView(_r1);\n const ctx_r1 = i0.ɵɵnextContext();\n return i0.ɵɵresetView(ctx_r1.startResizing($event, \"right\"));\n });\n i0.ɵɵelementEnd()();\n }\n}\nconst _c2 = [\"ngxEditor\"];\nconst _c3 = [\"*\"];\nfunction LinkComponent_div_4_div_8_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"div\", 12);\n i0.ɵɵtext(1);\n i0.ɵɵpipe(2, \"async\");\n i0.ɵɵelementEnd();\n }\n if (rf & 2) {\n const ctx_r1 = i0.ɵɵnextContext(2);\n i0.ɵɵadvance();\n i0.ɵɵtextInterpolate1(\" \", i0.ɵɵpipeBind1(2, 1, (ctx_r1.href.errors == null ? null : ctx_r1.href.errors[\"pattern\"]) && ctx_r1.getLabel(\"enterValidUrl\")), \" \");\n }\n}\nfunction LinkComponent_div_4_div_15_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"div\", 12);\n i0.ɵɵtext(1);\n i0.ɵɵelementEnd();\n }\n if (rf & 2) {\n const ctx_r1 = i0.ɵɵnextContext(2);\n i0.ɵɵadvance();\n i0.ɵɵtextInterpolate1(\" \", (ctx_r1.text.errors == null ? null : ctx_r1.text.errors[\"required\"]) && \"This is required\", \" \");\n }\n}\nfunction LinkComponent_div_4_div_16_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"div\", 4)(1, \"div\", 5)(2, \"label\");\n i0.ɵɵelement(3, \"input\", 13);\n i0.ɵɵtext(4);\n i0.ɵɵpipe(5, \"async\");\n i0.ɵɵelementEnd()()();\n }\n if (rf & 2) {\n const ctx_r1 = i0.ɵɵnextContext(2);\n i0.ɵɵadvance(4);\n i0.ɵɵtextInterpolate1(\" \", i0.ɵɵpipeBind1(5, 1, ctx_r1.getLabel(\"openInNewTab\")), \" \");\n }\n}\nfunction LinkComponent_div_4_Template(rf, ctx) {\n if (rf & 1) {\n const _r1 = i0.ɵɵgetCurrentView();\n i0.ɵɵelementStart(0, \"div\", 2)(1, \"form\", 3);\n i0.ɵɵlistener(\"ngSubmit\", function LinkComponent_div_4_Template_form_ngSubmit_1_listener($event) {\n i0.ɵɵrestoreView(_r1);\n const ctx_r1 = i0.ɵɵnextContext();\n return i0.ɵɵresetView(ctx_r1.insertLink($event));\n });\n i0.ɵɵelementStart(2, \"div\", 4)(3, \"div\", 5)(4, \"label\", 6);\n i0.ɵɵtext(5);\n i0.ɵɵpipe(6, \"async\");\n i0.ɵɵelementEnd();\n i0.ɵɵelement(7, \"input\", 7);\n i0.ɵɵtemplate(8, LinkComponent_div_4_div_8_Template, 3, 3, \"div\", 8);\n i0.ɵɵelementEnd()();\n i0.ɵɵelementStart(9, \"div\", 4)(10, \"div\", 5)(11, \"label\", 6);\n i0.ɵɵtext(12);\n i0.ɵɵpipe(13, \"async\");\n i0.ɵɵelementEnd();\n i0.ɵɵelement(14, \"input\", 9);\n i0.ɵɵtemplate(15, LinkComponent_div_4_div_15_Template, 2, 1, \"div\", 8);\n i0.ɵɵelementEnd()();\n i0.ɵɵtemplate(16, LinkComponent_div_4_div_16_Template, 6, 3, \"div\", 10);\n i0.ɵɵelementStart(17, \"button\", 11);\n i0.ɵɵtext(18);\n i0.ɵɵpipe(19, \"async\");\n i0.ɵɵelementEnd()()();\n }\n if (rf & 2) {\n const ctx_r1 = i0.ɵɵnextContext();\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"formGroup\", ctx_r1.form);\n i0.ɵɵadvance(3);\n i0.ɵɵproperty(\"htmlFor\", ctx_r1.getId(\"link-popup-url\"));\n i0.ɵɵadvance();\n i0.ɵɵtextInterpolate(i0.ɵɵpipeBind1(6, 12, ctx_r1.getLabel(\"url\")));\n i0.ɵɵadvance(2);\n i0.ɵɵproperty(\"id\", ctx_r1.getId(\"link-popup-url\"));\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", ctx_r1.href.touched && ctx_r1.href.invalid);\n i0.ɵɵadvance(3);\n i0.ɵɵproperty(\"htmlFor\", ctx_r1.getId(\"link-popup-label\"));\n i0.ɵɵadvance();\n i0.ɵɵtextInterpolate(i0.ɵɵpipeBind1(13, 14, ctx_r1.getLabel(\"text\")));\n i0.ɵɵadvance(2);\n i0.ɵɵproperty(\"id\", ctx_r1.getId(\"link-popup-label\"));\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", ctx_r1.text.touched && ctx_r1.text.invalid);\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", ctx_r1.options.showOpenInNewTab);\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"disabled\", !ctx_r1.form.valid);\n i0.ɵɵadvance();\n i0.ɵɵtextInterpolate(i0.ɵɵpipeBind1(19, 16, ctx_r1.getLabel(\"insert\")));\n }\n}\nconst _c4 = (a0, a1) => ({\n \"NgxEditor__Dropdown--Active\": a0,\n \"NgxEditor--Disabled\": a1\n});\nfunction DropdownComponent_div_4_button_1_Template(rf, ctx) {\n if (rf & 1) {\n const _r1 = i0.ɵɵgetCurrentView();\n i0.ɵɵelementStart(0, \"button\", 4);\n i0.ɵɵpipe(1, \"async\");\n i0.ɵɵlistener(\"mousedown\", function DropdownComponent_div_4_button_1_Template_button_mousedown_0_listener($event) {\n const item_r2 = i0.ɵɵrestoreView(_r1).$implicit;\n const ctx_r2 = i0.ɵɵnextContext(2);\n return i0.ɵɵresetView(ctx_r2.onDropdownItemMouseClick($event, item_r2));\n })(\"keydown.enter\", function DropdownComponent_div_4_button_1_Template_button_keydown_enter_0_listener($event) {\n const item_r2 = i0.ɵɵrestoreView(_r1).$implicit;\n const ctx_r2 = i0.ɵɵnextContext(2);\n return i0.ɵɵresetView(ctx_r2.onDropdownItemKeydown($event, item_r2));\n })(\"keydown.space\", function DropdownComponent_div_4_button_1_Template_button_keydown_space_0_listener($event) {\n const item_r2 = i0.ɵɵrestoreView(_r1).$implicit;\n const ctx_r2 = i0.ɵɵnextContext(2);\n return i0.ɵɵresetView(ctx_r2.onDropdownItemKeydown($event, item_r2));\n });\n i0.ɵɵtext(2);\n i0.ɵɵpipe(3, \"async\");\n i0.ɵɵelementEnd();\n }\n if (rf & 2) {\n const item_r2 = ctx.$implicit;\n const ctx_r2 = i0.ɵɵnextContext(2);\n i0.ɵɵproperty(\"ngClass\", i0.ɵɵpureFunction2(8, _c4, item_r2 === ctx_r2.activeItem, ctx_r2.disabledItems.includes(item_r2)))(\"ariaLabel\", i0.ɵɵpipeBind1(1, 4, ctx_r2.getName(item_r2)));\n i0.ɵɵattribute(\"aria-selected\", item_r2 === ctx_r2.activeItem);\n i0.ɵɵadvance(2);\n i0.ɵɵtextInterpolate1(\" \", i0.ɵɵpipeBind1(3, 6, ctx_r2.getName(item_r2)), \" \");\n }\n}\nfunction DropdownComponent_div_4_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"div\", 2);\n i0.ɵɵtemplate(1, DropdownComponent_div_4_button_1_Template, 4, 11, \"button\", 3);\n i0.ɵɵelementEnd();\n }\n if (rf & 2) {\n const ctx_r2 = i0.ɵɵnextContext();\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngForOf\", ctx_r2.items)(\"ngForTrackBy\", ctx_r2.trackByIndex);\n }\n}\nfunction ImageComponent_div_4_div_8_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"div\", 12);\n i0.ɵɵtext(1);\n i0.ɵɵpipe(2, \"async\");\n i0.ɵɵelementEnd();\n }\n if (rf & 2) {\n const ctx_r1 = i0.ɵɵnextContext(2);\n i0.ɵɵadvance();\n i0.ɵɵtextInterpolate1(\" \", i0.ɵɵpipeBind1(2, 1, (ctx_r1.src.errors == null ? null : ctx_r1.src.errors[\"pattern\"]) && ctx_r1.getLabel(\"enterValidUrl\")), \" \");\n }\n}\nfunction ImageComponent_div_4_Template(rf, ctx) {\n if (rf & 1) {\n const _r1 = i0.ɵɵgetCurrentView();\n i0.ɵɵelementStart(0, \"div\", 2)(1, \"form\", 3);\n i0.ɵɵlistener(\"ngSubmit\", function ImageComponent_div_4_Template_form_ngSubmit_1_listener($event) {\n i0.ɵɵrestoreView(_r1);\n const ctx_r1 = i0.ɵɵnextContext();\n return i0.ɵɵresetView(ctx_r1.insertLink($event));\n });\n i0.ɵɵelementStart(2, \"div\", 4)(3, \"div\", 5)(4, \"label\", 6);\n i0.ɵɵtext(5);\n i0.ɵɵpipe(6, \"async\");\n i0.ɵɵelementEnd();\n i0.ɵɵelement(7, \"input\", 7);\n i0.ɵɵtemplate(8, ImageComponent_div_4_div_8_Template, 3, 3, \"div\", 8);\n i0.ɵɵelementEnd()();\n i0.ɵɵelementStart(9, \"div\", 4)(10, \"div\", 5)(11, \"label\", 6);\n i0.ɵɵtext(12);\n i0.ɵɵpipe(13, \"async\");\n i0.ɵɵelementEnd();\n i0.ɵɵelement(14, \"input\", 9);\n i0.ɵɵelementEnd()();\n i0.ɵɵelementStart(15, \"div\", 4)(16, \"div\", 5)(17, \"label\", 6);\n i0.ɵɵtext(18);\n i0.ɵɵpipe(19, \"async\");\n i0.ɵɵelementEnd();\n i0.ɵɵelement(20, \"input\", 10);\n i0.ɵɵelementEnd()();\n i0.ɵɵelementStart(21, \"button\", 11);\n i0.ɵɵtext(22);\n i0.ɵɵpipe(23, \"async\");\n i0.ɵɵelementEnd()()();\n }\n if (rf & 2) {\n const ctx_r1 = i0.ɵɵnextContext();\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"formGroup\", ctx_r1.form);\n i0.ɵɵadvance(3);\n i0.ɵɵproperty(\"htmlFor\", ctx_r1.getId(\"image-popup-url\"));\n i0.ɵɵadvance();\n i0.ɵɵtextInterpolate(i0.ɵɵpipeBind1(6, 13, ctx_r1.getLabel(\"url\")));\n i0.ɵɵadvance(2);\n i0.ɵɵproperty(\"id\", ctx_r1.getId(\"image-popup-url\"));\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", ctx_r1.src.touched && ctx_r1.src.invalid);\n i0.ɵɵadvance(3);\n i0.ɵɵproperty(\"htmlFor\", ctx_r1.getId(\"image-popup-label\"));\n i0.ɵɵadvance();\n i0.ɵɵtextInterpolate(i0.ɵɵpipeBind1(13, 15, ctx_r1.getLabel(\"altText\")));\n i0.ɵɵadvance(2);\n i0.ɵɵproperty(\"id\", ctx_r1.getId(\"image-popup-label\"));\n i0.ɵɵadvance(3);\n i0.ɵɵproperty(\"htmlFor\", ctx_r1.getId(\"image-popup-title\"));\n i0.ɵɵadvance();\n i0.ɵɵtextInterpolate(i0.ɵɵpipeBind1(19, 17, ctx_r1.getLabel(\"title\")));\n i0.ɵɵadvance(2);\n i0.ɵɵproperty(\"id\", ctx_r1.getId(\"image-popup-title\"));\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"disabled\", !ctx_r1.form.valid || !ctx_r1.form.dirty);\n i0.ɵɵadvance();\n i0.ɵɵtextInterpolate(i0.ɵɵpipeBind1(23, 19, ctx_r1.getLabel(\"insert\")));\n }\n}\nconst _c5 = (a0, a1) => ({\n backgroundColor: a0,\n color: a1\n});\nconst _c6 = a0 => ({\n \"NgxEditor__Color--Active\": a0\n});\nfunction ColorPickerComponent_div_4_div_1_button_1_Template(rf, ctx) {\n if (rf & 1) {\n const _r2 = i0.ɵɵgetCurrentView();\n i0.ɵɵelementStart(0, \"button\", 7);\n i0.ɵɵlistener(\"mousedown\", function ColorPickerComponent_div_4_div_1_button_1_Template_button_mousedown_0_listener($event) {\n const color_r3 = i0.ɵɵrestoreView(_r2).$implicit;\n const ctx_r3 = i0.ɵɵnextContext(3);\n return i0.ɵɵresetView(ctx_r3.onColorSelectMouseClick($event, color_r3));\n })(\"keydown.enter\", function ColorPickerComponent_div_4_div_1_button_1_Template_button_keydown_enter_0_listener() {\n const color_r3 = i0.ɵɵrestoreView(_r2).$implicit;\n const ctx_r3 = i0.ɵɵnextContext(3);\n return i0.ɵɵresetView(ctx_r3.onColorSelectKeydown(color_r3));\n })(\"keydown.space\", function ColorPickerComponent_div_4_div_1_button_1_Template_button_keydown_space_0_listener() {\n const color_r3 = i0.ɵɵrestoreView(_r2).$implicit;\n const ctx_r3 = i0.ɵɵnextContext(3);\n return i0.ɵɵresetView(ctx_r3.onColorSelectKeydown(color_r3));\n });\n i0.ɵɵelementEnd();\n }\n if (rf & 2) {\n const color_r3 = ctx.$implicit;\n const ctx_r3 = i0.ɵɵnextContext(3);\n i0.ɵɵproperty(\"ngStyle\", i0.ɵɵpureFunction2(3, _c5, color_r3, ctx_r3.getContrastYIQ(color_r3)))(\"title\", color_r3)(\"ngClass\", i0.ɵɵpureFunction1(6, _c6, ctx_r3.activeColors.includes(color_r3)));\n }\n}\nfunction ColorPickerComponent_div_4_div_1_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"div\", 5);\n i0.ɵɵtemplate(1, ColorPickerComponent_div_4_div_1_button_1_Template, 1, 8, \"button\", 6);\n i0.ɵɵelementEnd();\n }\n if (rf & 2) {\n const colorGroup_r5 = ctx.$implicit;\n const ctx_r3 = i0.ɵɵnextContext(2);\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngForOf\", colorGroup_r5)(\"ngForTrackBy\", ctx_r3.trackByIndex);\n }\n}\nfunction ColorPickerComponent_div_4_Template(rf, ctx) {\n if (rf & 1) {\n const _r1 = i0.ɵɵgetCurrentView();\n i0.ɵɵelementStart(0, \"div\", 2);\n i0.ɵɵtemplate(1, ColorPickerComponent_div_4_div_1_Template, 2, 2, \"div\", 3);\n i0.ɵɵelementStart(2, \"button\", 4);\n i0.ɵɵlistener(\"mousedown\", function ColorPickerComponent_div_4_Template_button_mousedown_2_listener($event) {\n i0.ɵɵrestoreView(_r1);\n const ctx_r3 = i0.ɵɵnextContext();\n return i0.ɵɵresetView(ctx_r3.onRemoveMouseClick($event));\n })(\"keydown.enter\", function ColorPickerComponent_div_4_Template_button_keydown_enter_2_listener() {\n i0.ɵɵrestoreView(_r1);\n const ctx_r3 = i0.ɵɵnextContext();\n return i0.ɵɵresetView(ctx_r3.onRemoveKeydown());\n })(\"keydown.space\", function ColorPickerComponent_div_4_Template_button_keydown_space_2_listener() {\n i0.ɵɵrestoreView(_r1);\n const ctx_r3 = i0.ɵɵnextContext();\n return i0.ɵɵresetView(ctx_r3.onRemoveKeydown());\n });\n i0.ɵɵtext(3);\n i0.ɵɵpipe(4, \"async\");\n i0.ɵɵelementEnd()();\n }\n if (rf & 2) {\n const ctx_r3 = i0.ɵɵnextContext();\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngForOf\", ctx_r3.presets)(\"ngForTrackBy\", ctx_r3.trackByIndex);\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"disabled\", !ctx_r3.isActive);\n i0.ɵɵadvance();\n i0.ɵɵtextInterpolate1(\" \", i0.ɵɵpipeBind1(4, 4, ctx_r3.getLabel(\"remove\")), \" \");\n }\n}\nconst _c7 = (a0, a1) => ({\n \"NgxEditor--Disabled\": a0,\n \"NgxEditor__MenuBar--Reverse\": a1\n});\nfunction MenuComponent_ng_container_1_ng_container_1_ngx_toggle_command_1_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelement(0, \"ngx-toggle-command\", 7);\n }\n if (rf & 2) {\n const item_r1 = i0.ɵɵnextContext().$implicit;\n const ctx_r1 = i0.ɵɵnextContext(2);\n i0.ɵɵclassMap(ctx_r1.iconContainerClass);\n i0.ɵɵproperty(\"toolbarItem\", item_r1);\n }\n}\nfunction MenuComponent_ng_container_1_ng_container_1_ngx_insert_command_2_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelement(0, \"ngx-insert-command\", 7);\n }\n if (rf & 2) {\n const item_r1 = i0.ɵɵnextContext().$implicit;\n const ctx_r1 = i0.ɵɵnextContext(2);\n i0.ɵɵclassMap(ctx_r1.iconContainerClass);\n i0.ɵɵproperty(\"toolbarItem\", item_r1);\n }\n}\nfunction MenuComponent_ng_container_1_ng_container_1_ng_container_3_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementContainerStart(0);\n i0.ɵɵelement(1, \"ngx-link\", 8);\n i0.ɵɵelementContainerEnd();\n }\n if (rf & 2) {\n const item_r1 = i0.ɵɵnextContext().$implicit;\n const ctx_r1 = i0.ɵɵnextContext(2);\n i0.ɵɵadvance();\n i0.ɵɵclassMap(ctx_r1.iconContainerClass);\n i0.ɵɵproperty(\"options\", ctx_r1.getLinkOptions(item_r1));\n }\n}\nfunction MenuComponent_ng_container_1_ng_container_1_ngx_image_4_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelement(0, \"ngx-image\");\n }\n if (rf & 2) {\n const ctx_r1 = i0.ɵɵnextContext(3);\n i0.ɵɵclassMap(ctx_r1.iconContainerClass);\n }\n}\nfunction MenuComponent_ng_container_1_ng_container_1_ng_container_5_ngx_dropdown_1_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelement(0, \"ngx-dropdown\", 10);\n }\n if (rf & 2) {\n const dropdownItem_r3 = ctx.$implicit;\n const ctx_r1 = i0.ɵɵnextContext(4);\n i0.ɵɵclassMap(ctx_r1.dropdownContainerClass);\n i0.ɵɵproperty(\"group\", dropdownItem_r3.key)(\"items\", dropdownItem_r3.value);\n }\n}\nfunction MenuComponent_ng_container_1_ng_container_1_ng_container_5_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementContainerStart(0);\n i0.ɵɵtemplate(1, MenuComponent_ng_container_1_ng_container_1_ng_container_5_ngx_dropdown_1_Template, 1, 4, \"ngx-dropdown\", 9);\n i0.ɵɵpipe(2, \"keyvalue\");\n i0.ɵɵelementContainerEnd();\n }\n if (rf & 2) {\n const item_r1 = i0.ɵɵnextContext().$implicit;\n const ctx_r1 = i0.ɵɵnextContext(2);\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngForOf\", i0.ɵɵpipeBind1(2, 2, ctx_r1.getDropdownItems(item_r1)))(\"ngForTrackBy\", ctx_r1.trackByIndex);\n }\n}\nfunction MenuComponent_ng_container_1_ng_container_1_ngx_color_picker_6_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelement(0, \"ngx-color-picker\", 11);\n }\n if (rf & 2) {\n const ctx_r1 = i0.ɵɵnextContext(3);\n i0.ɵɵclassMap(ctx_r1.iconContainerClass);\n i0.ɵɵproperty(\"presets\", ctx_r1.presets);\n }\n}\nfunction MenuComponent_ng_container_1_ng_container_1_ngx_color_picker_7_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelement(0, \"ngx-color-picker\", 12);\n }\n if (rf & 2) {\n const ctx_r1 = i0.ɵɵnextContext(3);\n i0.ɵɵclassMap(ctx_r1.iconContainerClass);\n i0.ɵɵproperty(\"presets\", ctx_r1.presets);\n }\n}\nfunction MenuComponent_ng_container_1_ng_container_1_div_8_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelement(0, \"div\");\n }\n if (rf & 2) {\n const ctx_r1 = i0.ɵɵnextContext(3);\n i0.ɵɵclassMap(ctx_r1.seperatorClass);\n }\n}\nfunction MenuComponent_ng_container_1_ng_container_1_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementContainerStart(0);\n i0.ɵɵtemplate(1, MenuComponent_ng_container_1_ng_container_1_ngx_toggle_command_1_Template, 1, 3, \"ngx-toggle-command\", 3)(2, MenuComponent_ng_container_1_ng_container_1_ngx_insert_command_2_Template, 1, 3, \"ngx-insert-command\", 3)(3, MenuComponent_ng_container_1_ng_container_1_ng_container_3_Template, 2, 3, \"ng-container\", 2)(4, MenuComponent_ng_container_1_ng_container_1_ngx_image_4_Template, 1, 2, \"ngx-image\", 4)(5, MenuComponent_ng_container_1_ng_container_1_ng_container_5_Template, 3, 4, \"ng-container\", 2)(6, MenuComponent_ng_container_1_ng_container_1_ngx_color_picker_6_Template, 1, 3, \"ngx-color-picker\", 5)(7, MenuComponent_ng_container_1_ng_container_1_ngx_color_picker_7_Template, 1, 3, \"ngx-color-picker\", 6)(8, MenuComponent_ng_container_1_ng_container_1_div_8_Template, 1, 2, \"div\", 4);\n i0.ɵɵelementContainerEnd();\n }\n if (rf & 2) {\n const item_r1 = ctx.$implicit;\n const lastItem_r4 = ctx.last;\n const lastToolbarItem_r5 = i0.ɵɵnextContext().last;\n const ctx_r1 = i0.ɵɵnextContext();\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", ctx_r1.toggleCommands.includes(item_r1));\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", ctx_r1.insertCommands.includes(item_r1));\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", ctx_r1.isLinkItem(item_r1));\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", item_r1 === \"image\");\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", ctx_r1.isDropDown(item_r1));\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", item_r1 === \"text_color\");\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", item_r1 === \"background_color\");\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", lastItem_r4 && !lastToolbarItem_r5);\n }\n}\nfunction MenuComponent_ng_container_1_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementContainerStart(0);\n i0.ɵɵtemplate(1, MenuComponent_ng_container_1_ng_container_1_Template, 9, 8, \"ng-container\", 1);\n i0.ɵɵelementContainerEnd();\n }\n if (rf & 2) {\n const toolbarItem_r6 = ctx.$implicit;\n const ctx_r1 = i0.ɵɵnextContext();\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngForOf\", toolbarItem_r6)(\"ngForTrackBy\", ctx_r1.trackByIndex);\n }\n}\nfunction MenuComponent_ng_container_2_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementContainerStart(0);\n i0.ɵɵelementContainer(1, 13);\n i0.ɵɵelementContainerEnd();\n }\n if (rf & 2) {\n const ctx_r1 = i0.ɵɵnextContext();\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngTemplateOutlet\", ctx_r1.customMenuRef);\n }\n}\nconst _c8 = (a0, a1) => ({\n \"NgxBubbleMenu__Icon--Active\": a0,\n \"NgxEditor--Disabled\": a1\n});\nfunction BubbleComponent_ng_container_0_ng_container_1_button_1_Template(rf, ctx) {\n if (rf & 1) {\n const _r1 = i0.ɵɵgetCurrentView();\n i0.ɵɵelementStart(0, \"button\", 3);\n i0.ɵɵpipe(1, \"async\");\n i0.ɵɵlistener(\"mousedown\", function BubbleComponent_ng_container_0_ng_container_1_button_1_Template_button_mousedown_0_listener($event) {\n i0.ɵɵrestoreView(_r1);\n const item_r2 = i0.ɵɵnextContext().$implicit;\n const ctx_r2 = i0.ɵɵnextContext(2);\n return i0.ɵɵresetView(ctx_r2.onClick($event, item_r2));\n });\n i0.ɵɵelementEnd();\n }\n if (rf & 2) {\n const item_r2 = i0.ɵɵnextContext().$implicit;\n const ctx_r2 = i0.ɵɵnextContext(2);\n i0.ɵɵproperty(\"ngClass\", i0.ɵɵpureFunction2(5, _c8, ctx_r2.activeItems.includes(item_r2), !ctx_r2.execulableItems.includes(item_r2)))(\"title\", i0.ɵɵpipeBind1(1, 3, ctx_r2.getTitle(item_r2)))(\"innerHTML\", ctx_r2.getIcon(item_r2), i0.ɵɵsanitizeHtml);\n }\n}\nfunction BubbleComponent_ng_container_0_ng_container_1_div_2_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelement(0, \"div\", 4);\n }\n}\nfunction BubbleComponent_ng_container_0_ng_container_1_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementContainerStart(0);\n i0.ɵɵtemplate(1, BubbleComponent_ng_container_0_ng_container_1_button_1_Template, 2, 8, \"button\", 1)(2, BubbleComponent_ng_container_0_ng_container_1_div_2_Template, 1, 0, \"div\", 2);\n i0.ɵɵelementContainerEnd();\n }\n if (rf & 2) {\n const item_r2 = ctx.$implicit;\n const lastItem_r4 = ctx.last;\n const lastToolbarItem_r5 = i0.ɵɵnextContext().last;\n const ctx_r2 = i0.ɵɵnextContext();\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", ctx_r2.toggleCommands.includes(item_r2));\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", lastItem_r4 && !lastToolbarItem_r5);\n }\n}\nfunction BubbleComponent_ng_container_0_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementContainerStart(0);\n i0.ɵɵtemplate(1, BubbleComponent_ng_container_0_ng_container_1_Template, 3, 2, \"ng-container\", 0);\n i0.ɵɵelementContainerEnd();\n }\n if (rf & 2) {\n const toolbarItem_r6 = ctx.$implicit;\n const ctx_r2 = i0.ɵɵnextContext();\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngForOf\", toolbarItem_r6)(\"ngForTrackBy\", ctx_r2.trackByIndex);\n }\n}\nfunction FloatingMenuComponent_ng_container_3_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementContainerStart(0);\n i0.ɵɵelement(1, \"ngx-bubble\", 2);\n i0.ɵɵelementContainerEnd();\n }\n if (rf & 2) {\n const ctx_r0 = i0.ɵɵnextContext();\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"editor\", ctx_r0.editor);\n }\n}\nconst editablePlugin = (editable = true) => {\n return new Plugin({\n key: new PluginKey('editable'),\n state: {\n init() {\n return editable;\n },\n apply(tr, previousVal) {\n return tr.getMeta('UPDATE_EDITABLE') ?? previousVal;\n }\n },\n props: {\n editable(state) {\n return this.getState(state);\n },\n attributes(state) {\n const isEnabled = this.getState(state);\n if (isEnabled) {\n return null;\n }\n return {\n class: 'NgxEditor__Content--Disabled'\n };\n }\n }\n });\n};\nconst PLACEHOLDER_CLASSNAME = 'NgxEditor__Placeholder';\nconst placeholderPlugin = text => {\n return new Plugin({\n key: new PluginKey('placeholder'),\n state: {\n init() {\n return text ?? '';\n },\n apply(tr, previousVal) {\n const placeholder = tr.getMeta('UPDATE_PLACEHOLDER') ?? previousVal;\n return placeholder;\n }\n },\n props: {\n decorations(state) {\n const {\n doc\n } = state;\n const {\n textContent,\n childCount\n } = doc;\n const placeholder = this.getState(state);\n if (!placeholder || childCount > 1) {\n return DecorationSet.empty;\n }\n const decorations = [];\n const decorate = (node, pos) => {\n if (node.type.isBlock && node.childCount === 0 && textContent.length === 0) {\n const from = pos;\n const to = pos + node.nodeSize;\n const placeholderNode = Decoration.node(from, to, {\n 'class': PLACEHOLDER_CLASSNAME,\n 'data-placeholder': placeholder,\n 'data-align': node.attrs['align'] ?? null\n });\n decorations.push(placeholderNode);\n }\n return false;\n };\n doc.descendants(decorate);\n return DecorationSet.create(doc, decorations);\n }\n }\n });\n};\nconst attributesPlugin = (attributes = {}) => {\n return new Plugin({\n key: new PluginKey('attributes'),\n props: {\n attributes\n }\n });\n};\nconst focusPlugin = cb => {\n return new Plugin({\n key: new PluginKey('focus'),\n props: {\n handleDOMEvents: {\n focus: () => {\n cb();\n return false;\n }\n }\n }\n });\n};\nconst blurPlugin = cb => {\n return new Plugin({\n key: new PluginKey('blur'),\n props: {\n handleDOMEvents: {\n blur: () => {\n cb();\n return false;\n }\n }\n }\n });\n};\nlet ImageViewComponent = /*#__PURE__*/(() => {\n class ImageViewComponent {\n constructor() {\n this.alt = '';\n this.title = '';\n this.outerWidth = '';\n this.selected = false;\n this.imageResize = new EventEmitter();\n }\n startResizing(e, direction) {\n e.preventDefault();\n this.resizeImage(e, direction);\n }\n resizeImage(evt, direction) {\n const startX = evt.pageX;\n const startWidth = this.imgEl.nativeElement.clientWidth;\n const isLeftResize = direction === 'left';\n const {\n width\n } = window.getComputedStyle(this.view.dom);\n const editorWidth = parseInt(width, 10);\n const onMouseMove = e => {\n const currentX = e.pageX;\n const diffInPx = currentX - startX;\n const computedWidth = isLeftResize ? startWidth - diffInPx : startWidth + diffInPx;\n // prevent image overflow the editor\n // prevent resizng below 20px\n if (computedWidth > editorWidth || computedWidth < 20) {\n return;\n }\n this.outerWidth = `${computedWidth}px`;\n };\n const onMouseUp = e => {\n e.preventDefault();\n document.removeEventListener('mousemove', onMouseMove);\n document.removeEventListener('mouseup', onMouseUp);\n this.imageResize.emit();\n };\n document.addEventListener('mousemove', onMouseMove);\n document.addEventListener('mouseup', onMouseUp);\n }\n static {\n this.ɵfac = function ImageViewComponent_Factory(t) {\n return new (t || ImageViewComponent)();\n };\n }\n static {\n this.ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: ImageViewComponent,\n selectors: [[\"ngx-image-view\"]],\n viewQuery: function ImageViewComponent_Query(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵviewQuery(_c0, 7);\n }\n if (rf & 2) {\n let _t;\n i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.imgEl = _t.first);\n }\n },\n inputs: {\n src: \"src\",\n alt: \"alt\",\n title: \"title\",\n outerWidth: \"outerWidth\",\n selected: \"selected\",\n view: \"view\"\n },\n outputs: {\n imageResize: \"imageResize\"\n },\n decls: 4,\n vars: 9,\n consts: [[\"imgEl\", \"\"], [1, \"NgxEditor__ImageWrapper\", 3, \"ngClass\"], [\"class\", \"NgxEditor__ResizeHandle\", 4, \"ngIf\"], [3, \"src\", \"alt\", \"title\"], [1, \"NgxEditor__ResizeHandle\"], [1, \"NgxEditor__ResizeHandle--TL\", 3, \"mousedown\"], [1, \"NgxEditor__ResizeHandle--TR\", 3, \"mousedown\"], [1, \"NgxEditor__ResizeHandle--BL\", 3, \"mousedown\"], [1, \"NgxEditor__ResizeHandle--BR\", 3, \"mousedown\"]],\n template: function ImageViewComponent_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"span\", 1);\n i0.ɵɵtemplate(1, ImageViewComponent_span_1_Template, 5, 0, \"span\", 2);\n i0.ɵɵelement(2, \"img\", 3, 0);\n i0.ɵɵelementEnd();\n }\n if (rf & 2) {\n i0.ɵɵstyleProp(\"width\", ctx.outerWidth);\n i0.ɵɵproperty(\"ngClass\", i0.ɵɵpureFunction1(7, _c1, ctx.selected));\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", ctx.selected);\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"src\", ctx.src, i0.ɵɵsanitizeUrl)(\"alt\", ctx.alt)(\"title\", ctx.title);\n }\n },\n dependencies: [i3.NgClass, i3.NgIf],\n styles: [\"*[_ngcontent-%COMP%], *[_ngcontent-%COMP%]:before, *[_ngcontent-%COMP%]:after{box-sizing:border-box}img[_ngcontent-%COMP%]{width:100%;height:100%}.NgxEditor__ImageWrapper[_ngcontent-%COMP%]{position:relative;display:inline-block;line-height:0;padding:2px}.NgxEditor__ImageWrapper.NgxEditor__Resizer--Active[_ngcontent-%COMP%]{padding:1px;border:1px solid #1a73e8}.NgxEditor__ImageWrapper[_ngcontent-%COMP%] .NgxEditor__ResizeHandle[_ngcontent-%COMP%]{position:absolute;height:100%;width:100%}.NgxEditor__ImageWrapper[_ngcontent-%COMP%] .NgxEditor__ResizeHandle[_ngcontent-%COMP%] .NgxEditor__ResizeHandle--TL[_ngcontent-%COMP%], .NgxEditor__ImageWrapper[_ngcontent-%COMP%] .NgxEditor__ResizeHandle[_ngcontent-%COMP%] .NgxEditor__ResizeHandle--BL[_ngcontent-%COMP%], .NgxEditor__ImageWrapper[_ngcontent-%COMP%] .NgxEditor__ResizeHandle[_ngcontent-%COMP%] .NgxEditor__ResizeHandle--TR[_ngcontent-%COMP%], .NgxEditor__ImageWrapper[_ngcontent-%COMP%] .NgxEditor__ResizeHandle[_ngcontent-%COMP%] .NgxEditor__ResizeHandle--BR[_ngcontent-%COMP%]{position:absolute;width:7px;height:7px;background-color:#1a73e8;border:1px solid white}.NgxEditor__ImageWrapper[_ngcontent-%COMP%] .NgxEditor__ResizeHandle[_ngcontent-%COMP%] .NgxEditor__ResizeHandle--BR[_ngcontent-%COMP%]{bottom:-5px;right:-5px;cursor:se-resize}.NgxEditor__ImageWrapper[_ngcontent-%COMP%] .NgxEditor__ResizeHandle[_ngcontent-%COMP%] .NgxEditor__ResizeHandle--TR[_ngcontent-%COMP%]{top:-5px;right:-5px;cursor:ne-resize}.NgxEditor__ImageWrapper[_ngcontent-%COMP%] .NgxEditor__ResizeHandle[_ngcontent-%COMP%] .NgxEditor__ResizeHandle--TL[_ngcontent-%COMP%]{top:-5px;left:-5px;cursor:nw-resize}.NgxEditor__ImageWrapper[_ngcontent-%COMP%] .NgxEditor__ResizeHandle[_ngcontent-%COMP%] .NgxEditor__ResizeHandle--BL[_ngcontent-%COMP%]{bottom:-5px;left:-5px;cursor:sw-resize}\"]\n });\n }\n }\n return ImageViewComponent;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nclass ImageRezieView {\n constructor(node, view, getPos, injector) {\n this.updating = false;\n this.handleResize = () => {\n if (this.updating) {\n return;\n }\n const {\n state,\n dispatch\n } = this.view;\n const {\n tr\n } = state;\n const transaction = tr.setNodeMarkup(this.getPos(), undefined, {\n ...this.node.attrs,\n width: this.imageComponentRef.instance.outerWidth\n });\n const resolvedPos = transaction.doc.resolve(this.getPos());\n const newSelection = new NodeSelection(resolvedPos);\n transaction.setSelection(newSelection);\n dispatch(transaction);\n };\n this.applicationRef = injector.get(ApplicationRef);\n // create component ref\n this.imageComponentRef = createComponent(ImageViewComponent, {\n environmentInjector: this.applicationRef.injector\n });\n // Attach to the view so that the change detector knows to run\n this.applicationRef.attachView(this.imageComponentRef.hostView);\n this.setNodeAttributes(node.attrs);\n this.imageComponentRef.instance.view = view;\n this.dom = this.imageComponentRef.location.nativeElement;\n this.view = view;\n this.node = node;\n this.getPos = getPos;\n this.resizeSubscription = this.imageComponentRef.instance.imageResize.subscribe(() => {\n this.handleResize();\n });\n }\n computeChanges(prevAttrs, newAttrs) {\n return JSON.stringify(prevAttrs) === JSON.stringify(newAttrs);\n }\n setNodeAttributes(attrs) {\n this.imageComponentRef.instance.src = attrs['src'];\n this.imageComponentRef.instance.alt = attrs['alt'];\n this.imageComponentRef.instance.title = attrs['title'];\n this.imageComponentRef.instance.outerWidth = attrs['width'];\n }\n update(node) {\n if (node.type !== this.node.type) {\n return false;\n }\n this.node = node;\n const changed = this.computeChanges(this.node.attrs, node.attrs);\n if (changed) {\n this.updating = true;\n this.setNodeAttributes(node.attrs);\n this.updating = false;\n }\n return true;\n }\n ignoreMutation() {\n return true;\n }\n selectNode() {\n this.imageComponentRef.instance.selected = true;\n }\n deselectNode() {\n this.imageComponentRef.instance.selected = false;\n }\n destroy() {\n this.resizeSubscription.unsubscribe();\n this.applicationRef.detachView(this.imageComponentRef.hostView);\n }\n}\nconst imageResizePlugin = injector => {\n return new Plugin({\n key: new PluginKey('image-resize'),\n props: {\n nodeViews: {\n image: (node, view, getPos) => {\n return new ImageRezieView(node, view, getPos, injector);\n }\n }\n }\n });\n};\nconst HTTP_LINK_REGEX = /(?:https?:\\/\\/)?[\\w-]+(?:\\.[\\w-]+)+\\.?(?:\\d+)?(?:\\/\\S*)?$/;\nconst linkify = fragment => {\n const linkified = [];\n fragment.forEach(child => {\n if (child.isText) {\n const text = child.text;\n let pos = 0;\n const match = HTTP_LINK_REGEX.exec(text);\n if (match) {\n const start = match.index;\n const end = start + match[0].length;\n const {\n link\n } = child.type.schema.marks;\n if (start > 0) {\n linkified.push(child.cut(pos, start));\n }\n const urlText = text.slice(start, end);\n linkified.push(child.cut(start, end).mark(link.create({\n href: urlText\n }).addToSet(child.marks)));\n pos = end;\n }\n if (pos < text.length) {\n linkified.push(child.cut(pos));\n }\n } else {\n linkified.push(child.copy(linkify(child.content)));\n }\n });\n return Fragment.fromArray(linkified);\n};\nconst linkifyPlugin = () => {\n return new Plugin({\n key: new PluginKey('linkify'),\n props: {\n transformPasted: slice => {\n return new Slice(linkify(slice.content), slice.openStart, slice.openEnd);\n }\n }\n });\n};\nconst isString = value => {\n return typeof value === 'string';\n};\nconst getTrustedTypes = () => {\n return window.trustedTypes;\n};\nconst isTrustedHtml = value => {\n return getTrustedTypes()?.isHTML(value) ?? false;\n};\nconst isHtml = value => {\n return isString(value) || isTrustedHtml(value);\n};\nconst emptyDoc = {\n type: 'doc',\n content: [{\n type: 'paragraph'\n }]\n};\n// https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment\nconst toHTML = (json, inputSchema) => {\n const schema$1 = inputSchema ?? schema;\n const contentNode = schema$1.nodeFromJSON(json);\n const html = DOMSerializer.fromSchema(schema$1).serializeFragment(contentNode.content);\n const div = document.createElement('div');\n div.appendChild(html);\n return div.innerHTML;\n};\nconst toDoc = (html, inputSchema, options) => {\n const schema$1 = inputSchema ?? schema;\n const el = document.createElement('div');\n el.innerHTML = html;\n return DOMParser.fromSchema(schema$1).parse(el, options).toJSON();\n};\nconst parseContent = (value, schema, options) => {\n if (!value) {\n return schema.nodeFromJSON(emptyDoc);\n }\n if (!isHtml(value)) {\n return schema.nodeFromJSON(value);\n }\n const docJson = toDoc(value, schema, options);\n return schema.nodeFromJSON(docJson);\n};\nlet NgxEditorComponent = /*#__PURE__*/(() => {\n class NgxEditorComponent {\n constructor(renderer, injector, elementRef) {\n this.renderer = renderer;\n this.injector = injector;\n this.elementRef = elementRef;\n this.placeholder = 'Type Here...';\n this.focusOut = new EventEmitter();\n this.focusIn = new EventEmitter();\n this.unsubscribe = new Subject();\n this.onChange = () => {};\n this.onTouched = () => {};\n }\n writeValue(value) {\n if (!this.outputFormat && isHtml(value)) {\n this.outputFormat = 'html';\n }\n this.editor.setContent(value ?? emptyDoc);\n }\n registerOnChange(fn) {\n this.onChange = fn;\n }\n registerOnTouched(fn) {\n this.onTouched = fn;\n }\n setDisabledState(isDisabled) {\n this.setMeta('UPDATE_EDITABLE', !isDisabled);\n this.renderer.setProperty(this.elementRef.nativeElement, 'disabled', isDisabled);\n }\n handleChange(jsonDoc) {\n if (this.outputFormat === 'html') {\n const html = toHTML(jsonDoc, this.editor.schema);\n this.onChange(html);\n return;\n }\n this.onChange(jsonDoc);\n }\n setMeta(key, value) {\n const {\n dispatch,\n state: {\n tr\n }\n } = this.editor.view;\n dispatch(tr.setMeta(key, value));\n }\n setPlaceholder(placeholder) {\n this.setMeta('UPDATE_PLACEHOLDER', placeholder);\n }\n registerPlugins() {\n this.editor.registerPlugin(editablePlugin());\n this.editor.registerPlugin(placeholderPlugin(this.placeholder));\n this.editor.registerPlugin(attributesPlugin({\n class: 'NgxEditor__Content'\n }));\n this.editor.registerPlugin(focusPlugin(() => {\n this.focusIn.emit();\n }));\n this.editor.registerPlugin(blurPlugin(() => {\n this.focusOut.emit();\n this.onTouched();\n }));\n if (this.editor.features.resizeImage) {\n this.editor.registerPlugin(imageResizePlugin(this.injector));\n }\n if (this.editor.features.linkOnPaste) {\n this.editor.registerPlugin(linkifyPlugin());\n }\n }\n ngOnInit() {\n if (!this.editor) {\n throw new NgxEditorError('Required editor instance for initializing editor component');\n }\n this.registerPlugins();\n this.renderer.appendChild(this.ngxEditor.nativeElement, this.editor.view.dom);\n this.editor.valueChanges.pipe(takeUntil(this.unsubscribe)).subscribe(jsonDoc => {\n this.handleChange(jsonDoc);\n });\n }\n ngOnChanges(changes) {\n if (changes['placeholder'] && !changes['placeholder'].isFirstChange()) {\n this.setPlaceholder(changes['placeholder'].currentValue);\n }\n }\n ngOnDestroy() {\n this.unsubscribe.next();\n this.unsubscribe.complete();\n }\n static {\n this.ɵfac = function NgxEditorComponent_Factory(t) {\n return new (t || NgxEditorComponent)(i0.ɵɵdirectiveInject(i0.Renderer2), i0.ɵɵdirectiveInject(i0.Injector), i0.ɵɵdirectiveInject(i0.ElementRef));\n };\n }\n static {\n this.ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: NgxEditorComponent,\n selectors: [[\"ngx-editor\"]],\n viewQuery: function NgxEditorComponent_Query(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵviewQuery(_c2, 7);\n }\n if (rf & 2) {\n let _t;\n i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.ngxEditor = _t.first);\n }\n },\n inputs: {\n editor: \"editor\",\n outputFormat: \"outputFormat\",\n placeholder: \"placeholder\"\n },\n outputs: {\n focusOut: \"focusOut\",\n focusIn: \"focusIn\"\n },\n features: [i0.ɵɵProvidersFeature([{\n provide: NG_VALUE_ACCESSOR,\n useExisting: forwardRef(() => NgxEditorComponent),\n multi: true\n }]), i0.ɵɵNgOnChangesFeature],\n ngContentSelectors: _c3,\n decls: 3,\n vars: 0,\n consts: [[\"ngxEditor\", \"\"], [1, \"NgxEditor\"]],\n template: function NgxEditorComponent_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵprojectionDef();\n i0.ɵɵelementStart(0, \"div\", 1, 0);\n i0.ɵɵprojection(2);\n i0.ɵɵelementEnd();\n }\n },\n styles: [\":root{--ngx-editor-border-radius: 4px;--ngx-editor-background-color: #fff;--ngx-editor-text-color: #000;--ngx-editor-placeholder-color: #6c757d;--ngx-editor-border-color: rgba(0, 0, 0, .2);--ngx-editor-wrapper-border-color: rgba(0, 0, 0, .2);--ngx-editor-menubar-bg-color: #fff;--ngx-editor-menubar-padding: 3px;--ngx-editor-menubar-height: 30px;--ngx-editor-blockquote-color: #ddd;--ngx-editor-blockquote-border-width: 3px;--ngx-editor-icon-size: 30px;--ngx-editor-popup-bg-color: #fff;--ngx-editor-popup-border-radius: 4px;--ngx-editor-popup-shadow: rgba(60, 64, 67, .15) 0px 2px 6px 2px;--ngx-editor-menu-item-border-radius: 2px;--ngx-editor-menu-item-active-color: #1a73e8;--ngx-editor-menu-item-hover-bg-color: #f1f1f1;--ngx-editor-menu-item-active-bg-color: #e8f0fe;--ngx-editor-seperator-color: #ccc;--ngx-editor-bubble-bg-color: #000;--ngx-editor-bubble-text-color: #fff;--ngx-editor-bubble-item-hover-color: #636262;--ngx-editor-bubble-seperator-color: #fff;--ngx-editor-focus-ring-color: #5e9ed6;--ngx-editor-error-color: red;--ngx-editor-click-pointer: default}.NgxEditor{background:var(--ngx-editor-background-color);color:var(--ngx-editor-text-color);background-clip:padding-box;border-radius:var(--ngx-editor-border-radius);border:1px solid var(--ngx-editor-border-color);position:relative}.NgxEditor--Disabled{opacity:.5!important;pointer-events:none!important}.NgxEditor__Placeholder:before{color:var(--ngx-editor-placeholder-color);opacity:1;-webkit-user-select:none;user-select:none;position:absolute;cursor:text;content:attr(data-placeholder)}.NgxEditor__Placeholder[data-align=right]:before{position:relative}.NgxEditor__Content{padding:8px;white-space:pre-wrap;outline:none;font-variant-ligatures:none;font-feature-settings:\\\"liga\\\" 0}.NgxEditor__Content p{margin:0 0 10px}.NgxEditor__Content blockquote{padding-left:16px;border-left:var(--ngx-editor-blockquote-border-width) solid var(--ngx-editor-blockquote-color);margin-left:0;margin-right:0}.NgxEditor__Content--Disabled{-webkit-user-select:none;user-select:none;pointer-events:none}.NgxEditor__Wrapper{border:1px solid var(--ngx-editor-wrapper-border-color);border-radius:var(--ngx-editor-border-radius)}.NgxEditor__Wrapper .NgxEditor__MenuBar{border-top-left-radius:var(--ngx-editor-border-radius);border-top-right-radius:var(--ngx-editor-border-radius);border-bottom:1px solid var(--ngx-editor-border-color)}.NgxEditor__Wrapper .NgxEditor{border-top-left-radius:0;border-top-right-radius:0;border:none}.NgxEditor__MenuBar{display:flex;flex-wrap:wrap;padding:var(--ngx-editor-menubar-padding);background-color:var(--ngx-editor-menubar-bg-color);gap:.25rem .1rem}.NgxEditor__MenuBar button:not(:disabled),.NgxEditor__MenuBar [role=button]:not(:disabled){cursor:var(--ngx-editor-click-pointer, default)}.NgxEditor__MenuItem{display:flex;align-items:center;justify-content:center;position:relative;flex-shrink:0}.NgxEditor__MenuItem.NgxEditor__MenuItem--IconContainer{display:flex;align-items:center;justify-content:center}.NgxEditor__MenuItem .NgxEditor__MenuItem--Icon{all:unset;appearance:none;height:var(--ngx-editor-icon-size);width:var(--ngx-editor-icon-size);transition:.2s ease-in-out;display:inline-flex;align-items:center;justify-content:center;border-radius:var(--ngx-editor-menu-item-border-radius)}.NgxEditor__MenuItem .NgxEditor__MenuItem--Icon+.NgxEditor__MenuItem--Icon{margin-left:2px}.NgxEditor__MenuItem .NgxEditor__MenuItem--Icon:focus-visible{outline:1px solid var(--ngx-editor-focus-ring-color)}.NgxEditor__MenuItem .NgxEditor__MenuItem--Icon:hover{background-color:var(--ngx-editor-menu-item-hover-bg-color)}.NgxEditor__MenuItem.NgxEditor__MenuItem--Text{padding:0 5px}.NgxEditor__MenuItem.NgxEditor__MenuItem--Active,.NgxEditor__MenuItem .NgxEditor__MenuItem--Active{background-color:var(--ngx-editor-menu-item-active-bg-color);color:var(--ngx-editor-menu-item-active-color)}.NgxEditor__Dropdown{min-width:64px;position:relative;display:flex;align-items:center;flex-shrink:0}.NgxEditor__Dropdown:hover{background-color:var(--ngx-editor-menu-item-hover-bg-color)}.NgxEditor__Dropdown .NgxEditor__Dropdown--Text{all:unset;appearance:none;display:flex;align-items:center;justify-content:center;padding:0 5px;height:100%;width:100%}.NgxEditor__Dropdown .NgxEditor__Dropdown--Text:focus-visible{outline:1px solid var(--ngx-editor-focus-ring-color)}.NgxEditor__Dropdown .NgxEditor__Dropdown--Text:after{display:inline-block;content:\\\"\\\";margin-left:24px;vertical-align:4px;border-top:4px solid;border-right:4px solid transparent;border-bottom:0;border-left:4px solid transparent}.NgxEditor__Dropdown .NgxEditor__Dropdown--DropdownMenu{position:absolute;left:0;box-shadow:var(--ngx-editor-popup-shadow);border-radius:var(--ngx-editor-popup-border-radius);background-color:var(--ngx-editor-popup-bg-color);z-index:10;width:100%;top:calc(var(--ngx-editor-menubar-height) + 2px);display:flex;flex-direction:column}.NgxEditor__Dropdown .NgxEditor__Dropdown--Item{all:unset;appearance:none;padding:8px;white-space:nowrap;color:inherit}.NgxEditor__Dropdown .NgxEditor__Dropdown--Item:focus-visible{outline:1px solid var(--ngx-editor-focus-ring-color)}.NgxEditor__Dropdown .NgxEditor__Dropdown--Item:hover{background-color:var(--ngx-editor-menu-item-hover-bg-color)}.NgxEditor__Dropdown .NgxEditor__Dropdown--Selected,.NgxEditor__Dropdown .NgxEditor__Dropdown--Open{color:var(--ngx-editor-menu-item-active-color);background-color:var(--ngx-editor-menu-item-active-bg-color)}.NgxEditor__Dropdown .NgxEditor__Dropdown--Active{background-color:var(--ngx-editor-menu-item-active-bg-color)}.NgxEditor__Dropdown .NgxEditor__Dropdown--Active:hover{background-color:var(--ngx-editor-menu-item-hover-bg-color)}.NgxEditor__MenuBar--Reverse .NgxEditor__Dropdown--DropdownMenu{top:unset;bottom:calc(var(--ngx-editor-menubar-height) + 2px)}.NgxEditor__MenuBar--Reverse .NgxEditor__Dropdown--Text:after{transform:rotate(180deg)}.NgxEditor__MenuBar--Reverse .NgxEditor__Popup{top:unset;bottom:calc(var(--ngx-editor-menubar-height) + 2px)}.NgxEditor__Popup{position:absolute;top:calc(var(--ngx-editor-menubar-height) + 2px);box-shadow:var(--ngx-editor-popup-shadow);border-radius:var(--ngx-editor-popup-border-radius);background-color:var(--ngx-editor-popup-bg-color);z-index:10;min-width:192px;padding:8px}.NgxEditor__Popup .NgxEditor__Popup--FormGroup{margin-bottom:8px}.NgxEditor__Popup .NgxEditor__Popup--FormGroup label{margin-bottom:3px}.NgxEditor__Popup .NgxEditor__Popup--FormGroup input[type=text],.NgxEditor__Popup .NgxEditor__Popup--FormGroup input[type=url]{padding:2px 4px}.NgxEditor__Popup .NgxEditor__Popup--Col{display:flex;flex-direction:column;position:relative}.NgxEditor__Popup .NgxEditor__Popup--Label{font-size:85%}.NgxEditor__Seperator{border-left:1px solid var(--ngx-editor-seperator-color);margin:0 5px}.NgxEditor__HelpText{font-size:80%}.NgxEditor__HelpText.NgxEditor__HelpText--Error{color:var(--ngx-editor-error-color)}\\n\"],\n encapsulation: 2\n });\n }\n }\n return NgxEditorComponent;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet MenuService = /*#__PURE__*/(() => {\n class MenuService {\n constructor() {\n this.customMenuRefChange = new Subject();\n }\n setCustomMenuRef(c) {\n this.customMenuRefChange.next(c);\n }\n static {\n this.ɵfac = function MenuService_Factory(t) {\n return new (t || MenuService)();\n };\n }\n static {\n this.ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: MenuService,\n factory: MenuService.ɵfac,\n providedIn: 'root'\n });\n }\n }\n return MenuService;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nclass Mark {\n constructor(name) {\n this.name = name;\n }\n apply() {\n return (state, dispatch) => {\n const {\n schema\n } = state;\n const type = schema.marks[this.name];\n if (!type) {\n return false;\n }\n return applyMark(type)(state, dispatch);\n };\n }\n toggle() {\n return (state, dispatch) => {\n const {\n schema\n } = state;\n const type = schema.marks[this.name];\n if (!type) {\n return false;\n }\n return toggleMark(type)(state, dispatch);\n };\n }\n isActive(state) {\n const {\n schema\n } = state;\n const type = schema.marks[this.name];\n if (!type) {\n return false;\n }\n return isMarkActive(state, type);\n }\n canExecute(state) {\n return this.toggle()(state);\n }\n}\nclass Blockqote {\n toggle() {\n return (state, dispatch) => {\n const {\n schema\n } = state;\n const type = schema.nodes['blockquote'];\n if (!type) {\n return false;\n }\n if (this.isActive(state)) {\n return lift(state, dispatch);\n }\n return wrapIn(type)(state, dispatch);\n };\n }\n isActive(state) {\n const {\n schema\n } = state;\n const type = schema.nodes['blockquote'];\n if (!type) {\n return false;\n }\n return isNodeActive(state, type);\n }\n canExecute(state) {\n return this.toggle()(state);\n }\n}\nclass HorizontalRule {\n insert() {\n return (state, dispatch) => {\n const {\n schema,\n tr\n } = state;\n const type = schema.nodes['horizontal_rule'];\n if (!type) {\n return false;\n }\n dispatch(tr.replaceSelectionWith(type.create()).scrollIntoView());\n return true;\n };\n }\n canExecute(state) {\n return canInsert(state, state.schema.nodes['horizontal_rule']);\n }\n}\nclass ListItem {\n constructor(isBulletList = false) {\n this.isBulletList = false;\n this.isBulletList = isBulletList;\n }\n getType(schema) {\n return this.isBulletList ? schema.nodes['bullet_list'] : schema.nodes['ordered_list'];\n }\n toggle() {\n return (state, dispatch) => {\n const {\n schema\n } = state;\n const type = this.getType(schema);\n if (!type) {\n return false;\n }\n if (this.isActive(state)) {\n return liftListItem(schema.nodes['list_item'])(state, dispatch);\n }\n return wrapInList(type)(state, dispatch);\n };\n }\n isActive(state) {\n const {\n schema\n } = state;\n const type = this.getType(schema);\n if (!type) {\n return false;\n }\n return isNodeActive(state, type);\n }\n canExecute(state) {\n return this.toggle()(state);\n }\n}\nclass Heading {\n constructor(level) {\n this.level = level;\n }\n apply() {\n return (state, dispatch) => {\n const {\n schema\n } = state;\n const type = schema.nodes['heading'];\n if (!type) {\n return false;\n }\n return setBlockType(type)(state, dispatch);\n };\n }\n toggle() {\n return (state, dispatch) => {\n const {\n schema,\n selection,\n doc\n } = state;\n const type = schema.nodes['heading'];\n if (!type) {\n return false;\n }\n const nodePos = selection.$from.before(1);\n const node = doc.nodeAt(nodePos);\n const attrs = node?.attrs ?? {};\n if (this.isActive(state)) {\n return setBlockType(schema.nodes['paragraph'], attrs)(state, dispatch);\n }\n return setBlockType(type, {\n ...attrs,\n level: this.level\n })(state, dispatch);\n };\n }\n isActive(state) {\n const {\n schema\n } = state;\n const nodesInSelection = getSelectionNodes(state);\n const type = schema.nodes['heading'];\n if (!type) {\n return false;\n }\n const supportedNodes = [type, schema.nodes['text'], schema.nodes['blockquote']];\n // heading is a text node\n // don't mark as active when it has more nodes\n const nodes = nodesInSelection.filter(node => {\n return supportedNodes.includes(node.type);\n });\n const acitveNode = nodes.find(node => {\n return node.attrs['level'] === this.level;\n });\n return Boolean(acitveNode);\n }\n canExecute(state) {\n return this.toggle()(state);\n }\n}\nclass TextAlign {\n constructor(align) {\n this.align = align;\n }\n toggle() {\n return (state, dispatch) => {\n const {\n doc,\n selection,\n tr,\n schema\n } = state;\n const {\n from,\n to\n } = selection;\n let applicable = false;\n doc.nodesBetween(from, to, (node, pos) => {\n const nodeType = node.type;\n if ([schema.nodes['paragraph'], schema.nodes['heading']].includes(nodeType)) {\n applicable = true;\n const align = node.attrs['align'] === this.align ? null : this.align;\n tr.setNodeMarkup(pos, nodeType, {\n ...node.attrs,\n align\n });\n }\n return true;\n });\n if (!applicable) {\n return false;\n }\n if (tr.docChanged) {\n dispatch?.(tr);\n }\n return true;\n };\n }\n isActive(state) {\n const nodes = getSelectionNodes(state);\n const active = nodes.find(node => {\n return node.attrs['align'] === this.align;\n });\n return Boolean(active);\n }\n canExecute(state) {\n return this.toggle()(state);\n }\n}\nconst defaultOptions = {\n strict: true\n};\nlet Link$1 = class Link {\n update(attrs) {\n return (state, dispatch) => {\n const {\n schema,\n selection\n } = state;\n const type = schema.marks['link'];\n if (!type) {\n return false;\n }\n if (selection.empty) {\n return false;\n }\n return toggleMark(type, attrs)(state, dispatch);\n };\n }\n insert(text, attrs) {\n return (state, dispatch) => {\n const {\n schema,\n tr\n } = state;\n const type = schema.marks['link'];\n if (!type) {\n return false;\n }\n const linkAttrs = {\n href: attrs.href,\n title: attrs.title ?? text,\n target: attrs.target ?? '_blank'\n };\n const node = schema.text(text, [schema.marks['link'].create(linkAttrs)]);\n tr.replaceSelectionWith(node, false).scrollIntoView();\n if (tr.docChanged) {\n dispatch?.(tr);\n return true;\n }\n return false;\n };\n }\n isActive(state, options = defaultOptions) {\n if (options.strict) {\n return true;\n }\n const {\n schema\n } = state;\n const type = schema.marks['link'];\n if (!type) {\n return false;\n }\n return isMarkActive(state, type);\n }\n remove(state, dispatch) {\n return removeLink()(state, dispatch);\n }\n canExecute(state) {\n const testAttrs = {\n href: ''\n };\n return this.insert('Exec', testAttrs)(state) || this.update(testAttrs)(state);\n }\n};\nlet Image$1 = class Image {\n insert(src, attrs) {\n return (state, dispatch) => {\n const {\n schema,\n tr,\n selection\n } = state;\n const type = schema.nodes['image'];\n if (!type) {\n return false;\n }\n const imageAttrs = {\n width: null,\n src,\n ...attrs\n };\n if (!imageAttrs.width && selection instanceof NodeSelection && selection.node.type === type) {\n imageAttrs.width = selection.node.attrs['width'];\n }\n tr.replaceSelectionWith(type.createAndFill(imageAttrs));\n const resolvedPos = tr.doc.resolve(tr.selection.anchor - tr.selection.$anchor.nodeBefore.nodeSize);\n tr.setSelection(new NodeSelection(resolvedPos)).scrollIntoView();\n if (tr.docChanged) {\n dispatch?.(tr);\n return true;\n }\n return false;\n };\n }\n isActive(state) {\n const {\n selection\n } = state;\n if (selection instanceof NodeSelection) {\n return selection.node.type.name === 'image';\n }\n return false;\n }\n};\nlet TextColor$1 = class TextColor {\n constructor(name, attrName = 'color') {\n this.name = name;\n this.attrName = attrName;\n }\n apply(attrs) {\n return (state, dispatch) => {\n const {\n schema,\n selection,\n doc\n } = state;\n const type = schema.marks[this.name];\n if (!type) {\n return false;\n }\n const {\n from,\n to,\n empty\n } = selection;\n if (!empty && from + 1 === to) {\n const node = doc.nodeAt(from);\n if (node?.isAtom && !node.isText && node.isLeaf) {\n // An atomic node (e.g. Image) is selected.\n return false;\n }\n }\n return applyMark(type, attrs)(state, dispatch);\n };\n }\n isActive(state) {\n const {\n schema\n } = state;\n const type = schema.marks[this.name];\n if (!type) {\n return false;\n }\n return isMarkActive(state, type);\n }\n getActiveColors(state) {\n if (!this.isActive(state)) {\n return [];\n }\n const {\n schema\n } = state;\n const marks = getSelectionMarks(state);\n const colors = marks.filter(mark => mark.type === schema.marks[this.name]).map(mark => {\n return mark.attrs[this.attrName];\n }).filter(Boolean);\n return colors;\n }\n remove() {\n return (state, dispatch) => {\n const {\n schema\n } = state;\n const type = schema.marks[this.name];\n if (!type) {\n return false;\n }\n return removeMark(type)(state, dispatch);\n };\n }\n canExecute(state) {\n const attrs = this.name === 'text_color' ? {\n color: ''\n } : {\n backgroundColor: ''\n };\n return this.apply(attrs)(state);\n }\n};\nconst SAFE_MARKS = ['link'];\nclass FormatClear {\n insert() {\n return (state, dispatch) => {\n const {\n tr\n } = state;\n const {\n ranges,\n empty\n } = tr.selection;\n if (empty) {\n return true;\n }\n Object.entries(state.schema.marks).forEach(([markType, mark]) => {\n if (SAFE_MARKS.includes(markType)) {\n return;\n }\n ranges.forEach(range => {\n tr.removeMark(range.$from.pos, range.$to.pos, mark);\n });\n });\n dispatch(tr);\n return true;\n };\n }\n canExecute() {\n return true;\n }\n}\nconst indentNodeTypes = ['paragraph', 'heading', 'blockquote'];\nconst minIndent = 0;\nconst maxIndent = 10;\nconst udpateIndentLevel = (tr, pos, method) => {\n const node = tr.doc.nodeAt(pos);\n if (!node) {\n return false;\n }\n const nodeIndent = node.attrs['indent'] ?? 0;\n const newIndent = clamp(nodeIndent + (method === 'increase' ? 1 : -1), minIndent, maxIndent);\n if (newIndent === nodeIndent || newIndent < minIndent || newIndent > maxIndent) {\n return false;\n }\n const attrs = {\n ...node.attrs,\n indent: newIndent\n };\n tr.setNodeMarkup(pos, node.type, attrs);\n return true;\n};\nclass Indent {\n constructor(method) {\n this.method = 'increase';\n this.method = method;\n }\n insert() {\n return (state, dispatch) => {\n const {\n tr,\n doc\n } = state;\n const {\n from,\n to\n } = tr.selection;\n let applicable = false;\n doc.nodesBetween(from, to, (node, pos) => {\n const nodeType = node.type;\n if (indentNodeTypes.includes(nodeType.name)) {\n applicable = udpateIndentLevel(tr, pos, this.method);\n return false;\n } else if (node.type.name.includes('list')) {\n return false;\n }\n return true;\n });\n if (!applicable) {\n return false;\n }\n if (tr.docChanged) {\n dispatch?.(tr);\n }\n return true;\n };\n }\n canExecute(state) {\n return this.insert()(state);\n }\n}\nclass History {\n constructor(mode) {\n this.mode = 'undo';\n this.mode = mode;\n }\n insert() {\n return (state, dispatch) => {\n if (this.mode === 'undo') {\n return undo$1(state, dispatch);\n }\n return redo$1(state, dispatch);\n };\n }\n canExecute(state) {\n return this.insert()(state);\n }\n}\nconst STRONG = new Mark('strong');\nconst EM = new Mark('em');\nconst CODE = new Mark('code');\nconst UNDERLINE = new Mark('u');\nconst STRIKE = new Mark('s');\nconst BLOCKQUOTE = new Blockqote();\nconst HORIZONTAL_RULE = new HorizontalRule();\nconst FORMAT_CLEAR = new FormatClear();\nconst UL = new ListItem(true);\nconst OL = new ListItem(false);\nconst H1 = new Heading(1);\nconst H2 = new Heading(2);\nconst H3 = new Heading(3);\nconst H4 = new Heading(4);\nconst H5 = new Heading(5);\nconst H6 = new Heading(6);\nconst ALIGN_LEFT = new TextAlign('left');\nconst ALIGN_CENTER = new TextAlign('center');\nconst ALIGN_RIGHT = new TextAlign('right');\nconst ALIGN_JUSTIFY = new TextAlign('justify');\nconst LINK = new Link$1();\nconst IMAGE = new Image$1();\nconst TEXT_COLOR = new TextColor$1('text_color', 'color');\nconst TEXT_BACKGROUND_COLOR = new TextColor$1('text_background_color', 'backgroundColor');\nconst INDENT = new Indent('increase');\nconst OUTDENT = new Indent('decrease');\nconst SUPERSCRIPT = new Mark('sup');\nconst SUBSCRIPT = new Mark('sub');\nconst UNDO = new History('undo');\nconst REDO = new History('redo');\nconst ToggleCommands = {\n bold: STRONG,\n italic: EM,\n code: CODE,\n underline: UNDERLINE,\n strike: STRIKE,\n blockquote: BLOCKQUOTE,\n bullet_list: UL,\n ordered_list: OL,\n h1: H1,\n h2: H2,\n h3: H3,\n h4: H4,\n h5: H5,\n h6: H6,\n align_left: ALIGN_LEFT,\n align_center: ALIGN_CENTER,\n align_right: ALIGN_RIGHT,\n align_justify: ALIGN_JUSTIFY,\n superscript: SUPERSCRIPT,\n subscript: SUBSCRIPT\n};\nconst InsertCommands = {\n horizontal_rule: HORIZONTAL_RULE,\n format_clear: FORMAT_CLEAR,\n indent: INDENT,\n outdent: OUTDENT,\n undo: UNDO,\n redo: REDO\n};\nconst Link = LINK;\nconst Image = IMAGE;\nconst TextColor = TEXT_COLOR;\nconst TextBackgroundColor = TEXT_BACKGROUND_COLOR;\nconst defaults = {\n // menu\n bold: 'Bold',\n italic: 'Italic',\n code: 'Code',\n underline: 'Underline',\n strike: 'Strike',\n blockquote: 'Blockquote',\n bullet_list: 'Bullet List',\n ordered_list: 'Ordered List',\n heading: 'Heading',\n h1: 'Header 1',\n h2: 'Header 2',\n h3: 'Header 3',\n h4: 'Header 4',\n h5: 'Header 5',\n h6: 'Header 6',\n align_left: 'Left Align',\n align_center: 'Center Align',\n align_right: 'Right Align',\n align_justify: 'Justify',\n text_color: 'Text Color',\n background_color: 'Background Color',\n horizontal_rule: 'Horizontal rule',\n format_clear: 'Clear Formatting',\n insertLink: 'Insert Link',\n removeLink: 'Remove Link',\n insertImage: 'Insert Image',\n indent: 'Increase Indent',\n outdent: 'Decrease Indent',\n superscript: 'Superscript',\n subscript: 'Subscript',\n undo: 'Undo',\n redo: 'Redo',\n // pupups, forms, others...\n url: 'URL',\n text: 'Text',\n openInNewTab: 'Open in new tab',\n insert: 'Insert',\n altText: 'Alt Text',\n title: 'Title',\n remove: 'Remove',\n enterValidUrl: 'Please enter a valid URL'\n};\nclass Locals {\n constructor(newLocals = {}) {\n this.locals = defaults;\n this.get = key => {\n const value = this.locals[key];\n if (value) {\n return isObservable(value) ? value : of(value);\n }\n return of('');\n };\n this.locals = {\n ...defaults,\n ...newLocals\n };\n }\n}\nvar bold = `\n \n`;\nvar italic = `\n \n`;\nvar code = `\n\n`;\nvar underline = `\n\n`;\nvar strike = `\n\n`;\nvar orderedList = `\n\n`;\nvar bulletList = `\n\n`;\nvar quote = `\n\n`;\nvar link = `\n\n`;\nvar unlink = `\n\n`;\nvar image = `\n\n`;\nvar alignLeft = `\n\n`;\nvar alignCenter = `\n\n`;\nvar alignRight = `\n\n`;\nvar alignJustify = `\n\n`;\nvar textColor = `\n\n`;\nvar colorFill = `\n\n`;\nvar horizontalRule = `\n \n \n \n \n`;\nvar formatClear = `\n\n`;\nvar indent = '';\nvar outdent = '';\nvar superscript = '';\nvar subscript = '';\nvar undo = '';\nvar redo = '';\n\n/* eslint-disable @typescript-eslint/naming-convention */\n// Icons source: https://material.io/\nconst DEFAULT_ICON_HEIGHT = 20;\nconst DEFAULT_ICON_WIDTH = 20;\nconst DEFAULT_ICON_FILL = 'currentColor';\nconst icons = {\n bold,\n italic,\n code,\n underline,\n strike,\n ordered_list: orderedList,\n bullet_list: bulletList,\n blockquote: quote,\n link,\n unlink,\n image,\n align_left: alignLeft,\n align_center: alignCenter,\n align_right: alignRight,\n align_justify: alignJustify,\n text_color: textColor,\n color_fill: colorFill,\n horizontal_rule: horizontalRule,\n format_clear: formatClear,\n indent,\n outdent,\n superscript,\n subscript,\n undo,\n redo,\n path: ''\n};\nclass Icon {\n static get(name, fill = DEFAULT_ICON_FILL) {\n const fullPath = icons[name];\n if (fullPath && (fullPath.includes('\n ${fullPath}\n \n `;\n }\n return fullPath;\n }\n}\nlet NgxEditorServiceConfig = /*#__PURE__*/(() => {\n class NgxEditorServiceConfig {\n constructor() {\n this.locals = {};\n this.icons = {};\n }\n static {\n this.ɵfac = function NgxEditorServiceConfig_Factory(t) {\n return new (t || NgxEditorServiceConfig)();\n };\n }\n static {\n this.ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: NgxEditorServiceConfig,\n factory: NgxEditorServiceConfig.ɵfac,\n providedIn: 'root'\n });\n }\n }\n return NgxEditorServiceConfig;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet NgxEditorService = /*#__PURE__*/(() => {\n class NgxEditorService {\n constructor(config) {\n this.config = config;\n }\n get locals() {\n return new Locals(this.config.locals);\n }\n getIcon(icon) {\n return this.config.icons[icon] ? this.config.icons[icon] : Icon.get(icon);\n }\n static {\n this.ɵfac = function NgxEditorService_Factory(t) {\n return new (t || NgxEditorService)(i0.ɵɵinject(NgxEditorServiceConfig, 8));\n };\n }\n static {\n this.ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: NgxEditorService,\n factory: NgxEditorService.ɵfac,\n providedIn: 'root'\n });\n }\n }\n return NgxEditorService;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nconst provideMyServiceOptions = config => {\n return {\n locals: config.locals ?? {},\n icons: config.icons ?? {}\n };\n};\nlet SanitizeHtmlPipe = /*#__PURE__*/(() => {\n class SanitizeHtmlPipe {\n constructor(sanitizer) {\n this.sanitizer = sanitizer;\n }\n transform(value) {\n if (isTrustedHtml(value)) {\n return value;\n }\n return this.sanitizer.bypassSecurityTrustHtml(value);\n }\n static {\n this.ɵfac = function SanitizeHtmlPipe_Factory(t) {\n return new (t || SanitizeHtmlPipe)(i0.ɵɵdirectiveInject(i1.DomSanitizer, 16));\n };\n }\n static {\n this.ɵpipe = /* @__PURE__ */i0.ɵɵdefinePipe({\n name: \"sanitizeHtml\",\n type: SanitizeHtmlPipe,\n pure: true\n });\n }\n }\n return SanitizeHtmlPipe;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet ToggleCommandComponent = /*#__PURE__*/(() => {\n class ToggleCommandComponent {\n get name() {\n return this.toolbarItem;\n }\n constructor(ngxeService, menuService) {\n this.ngxeService = ngxeService;\n this.menuService = menuService;\n this.isActive = false;\n this.disabled = false;\n this.update = view => {\n const {\n state\n } = view;\n const command = ToggleCommands[this.name];\n this.isActive = command.isActive(state);\n this.disabled = !command.canExecute(state);\n };\n }\n toggle() {\n const {\n state,\n dispatch\n } = this.editorView;\n const command = ToggleCommands[this.name];\n command.toggle()(state, dispatch);\n }\n onMouseClick(e) {\n e.preventDefault();\n if (e.button !== 0) {\n return;\n }\n this.toggle();\n }\n onKeydown() {\n this.toggle();\n }\n getTitle(name) {\n return this.ngxeService.locals.get(name);\n }\n ngOnInit() {\n this.html = this.ngxeService.getIcon(this.name);\n this.editorView = this.menuService.editor.view;\n this.updateSubscription = this.menuService.editor.update.subscribe(view => {\n this.update(view);\n });\n }\n ngOnDestroy() {\n this.updateSubscription.unsubscribe();\n }\n static {\n this.ɵfac = function ToggleCommandComponent_Factory(t) {\n return new (t || ToggleCommandComponent)(i0.ɵɵdirectiveInject(NgxEditorService), i0.ɵɵdirectiveInject(MenuService));\n };\n }\n static {\n this.ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: ToggleCommandComponent,\n selectors: [[\"ngx-toggle-command\"]],\n inputs: {\n toolbarItem: \"toolbarItem\"\n },\n decls: 4,\n vars: 14,\n consts: [[\"type\", \"button\", 1, \"NgxEditor__MenuItem--Icon\", 3, \"mousedown\", \"keydown.enter\", \"keydown.space\", \"disabled\", \"innerHTML\", \"title\", \"ariaLabel\"]],\n template: function ToggleCommandComponent_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"button\", 0);\n i0.ɵɵpipe(1, \"sanitizeHtml\");\n i0.ɵɵpipe(2, \"async\");\n i0.ɵɵpipe(3, \"async\");\n i0.ɵɵlistener(\"mousedown\", function ToggleCommandComponent_Template_button_mousedown_0_listener($event) {\n return ctx.onMouseClick($event);\n })(\"keydown.enter\", function ToggleCommandComponent_Template_button_keydown_enter_0_listener() {\n return ctx.onKeydown();\n })(\"keydown.space\", function ToggleCommandComponent_Template_button_keydown_space_0_listener() {\n return ctx.onKeydown();\n });\n i0.ɵɵelementEnd();\n }\n if (rf & 2) {\n i0.ɵɵclassProp(\"NgxEditor__MenuItem--Active\", ctx.isActive)(\"NgxEditor--Disabled\", ctx.disabled);\n i0.ɵɵproperty(\"disabled\", ctx.disabled)(\"innerHTML\", i0.ɵɵpipeBind1(1, 8, ctx.html), i0.ɵɵsanitizeHtml)(\"title\", i0.ɵɵpipeBind1(2, 10, ctx.getTitle(ctx.name)))(\"ariaLabel\", i0.ɵɵpipeBind1(3, 12, ctx.getTitle(ctx.name)));\n }\n },\n dependencies: [i3.AsyncPipe, SanitizeHtmlPipe]\n });\n }\n }\n return ToggleCommandComponent;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet InsertCommandComponent = /*#__PURE__*/(() => {\n class InsertCommandComponent {\n get name() {\n return this.toolbarItem;\n }\n constructor(ngxeService, menuService) {\n this.ngxeService = ngxeService;\n this.menuService = menuService;\n this.disabled = false;\n this.update = view => {\n const {\n state\n } = view;\n const command = InsertCommands[this.name];\n this.disabled = !command.canExecute(state);\n };\n }\n onMouseClick(e) {\n e.preventDefault();\n if (e.button !== 0) {\n return;\n }\n this.insert();\n }\n onKeydown() {\n this.insert();\n }\n insert() {\n const {\n state,\n dispatch\n } = this.editorView;\n const command = InsertCommands[this.name];\n command.insert()(state, dispatch);\n }\n getTitle(name) {\n return this.ngxeService.locals.get(name);\n }\n ngOnInit() {\n this.html = this.ngxeService.getIcon(this.name);\n this.editorView = this.menuService.editor.view;\n this.updateSubscription = this.menuService.editor.update.subscribe(view => {\n this.update(view);\n });\n }\n ngOnDestroy() {\n this.updateSubscription.unsubscribe();\n }\n static {\n this.ɵfac = function InsertCommandComponent_Factory(t) {\n return new (t || InsertCommandComponent)(i0.ɵɵdirectiveInject(NgxEditorService), i0.ɵɵdirectiveInject(MenuService));\n };\n }\n static {\n this.ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: InsertCommandComponent,\n selectors: [[\"ngx-insert-command\"]],\n inputs: {\n toolbarItem: \"toolbarItem\"\n },\n decls: 4,\n vars: 12,\n consts: [[1, \"NgxEditor__MenuItem--Icon\", 3, \"mousedown\", \"keydown.enter\", \"keydown.space\", \"disabled\", \"innerHTML\", \"title\", \"ariaLabel\"]],\n template: function InsertCommandComponent_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"button\", 0);\n i0.ɵɵpipe(1, \"sanitizeHtml\");\n i0.ɵɵpipe(2, \"async\");\n i0.ɵɵpipe(3, \"async\");\n i0.ɵɵlistener(\"mousedown\", function InsertCommandComponent_Template_button_mousedown_0_listener($event) {\n return ctx.onMouseClick($event);\n })(\"keydown.enter\", function InsertCommandComponent_Template_button_keydown_enter_0_listener() {\n return ctx.onKeydown();\n })(\"keydown.space\", function InsertCommandComponent_Template_button_keydown_space_0_listener() {\n return ctx.onKeydown();\n });\n i0.ɵɵelementEnd();\n }\n if (rf & 2) {\n i0.ɵɵclassProp(\"NgxEditor--Disabled\", ctx.disabled);\n i0.ɵɵproperty(\"disabled\", ctx.disabled)(\"innerHTML\", i0.ɵɵpipeBind1(1, 6, ctx.html), i0.ɵɵsanitizeHtml)(\"title\", i0.ɵɵpipeBind1(2, 8, ctx.getTitle(ctx.name)))(\"ariaLabel\", i0.ɵɵpipeBind1(3, 10, ctx.getTitle(ctx.name)));\n }\n },\n dependencies: [i3.AsyncPipe, SanitizeHtmlPipe]\n });\n }\n }\n return InsertCommandComponent;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nconst DEFAULT_LINK_OPTIONS = {\n showOpenInNewTab: true\n};\nlet LinkComponent = /*#__PURE__*/(() => {\n class LinkComponent {\n constructor(el, ngxeService, menuService) {\n this.el = el;\n this.ngxeService = ngxeService;\n this.menuService = menuService;\n this.options = DEFAULT_LINK_OPTIONS;\n this.showPopup = false;\n this.isActive = false;\n this.canExecute = true;\n this.componentId = uniq();\n this.setText = () => {\n const {\n state: {\n selection,\n doc\n }\n } = this.editorView;\n const {\n empty,\n from,\n to\n } = selection;\n const selectedText = !empty ? doc.textBetween(from, to) : '';\n if (selectedText) {\n this.text.patchValue(selectedText);\n this.text.disable();\n }\n };\n this.update = view => {\n const {\n state\n } = view;\n this.isActive = Link.isActive(state, {\n strict: false\n });\n this.canExecute = Link.canExecute(state);\n };\n }\n get icon() {\n return this.ngxeService.getIcon(this.isActive ? 'unlink' : 'link');\n }\n get title() {\n return this.ngxeService.locals.get(this.isActive ? 'removeLink' : 'insertLink');\n }\n get href() {\n return this.form.get('href');\n }\n get text() {\n return this.form.get('text');\n }\n onDocumentClick(e) {\n if (!this.el.nativeElement.contains(e.target) && this.showPopup) {\n this.hidePopup();\n }\n }\n getId(name) {\n return `${name}-${this.componentId}`;\n }\n getLabel(key) {\n return this.ngxeService.locals.get(key);\n }\n hidePopup() {\n this.showPopup = false;\n this.form.reset({\n href: '',\n text: '',\n openInNewTab: true\n });\n this.text.enable();\n }\n togglePopup() {\n const {\n state,\n dispatch\n } = this.editorView;\n if (this.isActive) {\n Link.remove(state, dispatch);\n return;\n }\n this.showPopup = !this.showPopup;\n if (this.showPopup) {\n this.setText();\n }\n }\n onTogglePopupMouseClick(e) {\n if (e.button !== 0) {\n return;\n }\n this.togglePopup();\n }\n onTogglePopupKeydown() {\n this.togglePopup();\n }\n insertLink(e) {\n e.preventDefault();\n const {\n text,\n href,\n openInNewTab\n } = this.form.getRawValue();\n const {\n dispatch,\n state\n } = this.editorView;\n const {\n selection\n } = state;\n let target;\n if (this.options.showOpenInNewTab) {\n target = openInNewTab ? '_blank' : '_self';\n }\n const attrs = {\n title: href,\n href,\n target\n };\n if (selection.empty) {\n Link.insert(text, attrs)(state, dispatch);\n this.editorView.focus();\n } else {\n Link.update(attrs)(state, dispatch);\n }\n this.hidePopup();\n }\n ngOnInit() {\n this.editorView = this.menuService.editor.view;\n this.form = new FormGroup({\n href: new FormControl('', [Validators$1.required, Validators$1.pattern(this.menuService.editor.linkValidationPattern)]),\n text: new FormControl('', [Validators$1.required]),\n openInNewTab: new FormControl(true)\n });\n this.updateSubscription = this.menuService.editor.update.subscribe(view => {\n this.update(view);\n });\n }\n ngOnDestroy() {\n this.updateSubscription.unsubscribe();\n }\n static {\n this.ɵfac = function LinkComponent_Factory(t) {\n return new (t || LinkComponent)(i0.ɵɵdirectiveInject(i0.ElementRef), i0.ɵɵdirectiveInject(NgxEditorService), i0.ɵɵdirectiveInject(MenuService));\n };\n }\n static {\n this.ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: LinkComponent,\n selectors: [[\"ngx-link\"]],\n hostBindings: function LinkComponent_HostBindings(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵlistener(\"mousedown\", function LinkComponent_mousedown_HostBindingHandler($event) {\n return ctx.onDocumentClick($event);\n }, false, i0.ɵɵresolveDocument);\n }\n },\n inputs: {\n options: [i0.ɵɵInputFlags.HasDecoratorInputTransform, \"options\", \"options\", value => ({\n ...DEFAULT_LINK_OPTIONS,\n ...value\n })]\n },\n features: [i0.ɵɵInputTransformsFeature],\n decls: 5,\n vars: 16,\n consts: [[\"type\", \"button\", \"aria-haspopup\", \"dialog\", 1, \"NgxEditor__MenuItem--Icon\", 3, \"mousedown\", \"keydown.enter\", \"keydown.space\", \"disabled\", \"innerHTML\", \"title\", \"ariaLabel\", \"ariaExpanded\"], [\"class\", \"NgxEditor__Popup\", 4, \"ngIf\"], [1, \"NgxEditor__Popup\"], [1, \"NgxEditor__Popup--Form\", 3, \"ngSubmit\", \"formGroup\"], [1, \"NgxEditor__Popup--FormGroup\"], [1, \"NgxEditor__Popup--Col\"], [1, \"NgxEditor__Popup--Label\", 3, \"htmlFor\"], [\"type\", \"href\", \"formControlName\", \"href\", \"autocomplete\", \"off\", 3, \"id\"], [\"class\", \"NgxEditor__HelpText NgxEditor__HelpText--Error\", 4, \"ngIf\"], [\"type\", \"text\", \"formControlName\", \"text\", \"autocomplete\", \"off\", 3, \"id\"], [\"class\", \"NgxEditor__Popup--FormGroup\", 4, \"ngIf\"], [\"type\", \"submit\", 3, \"disabled\"], [1, \"NgxEditor__HelpText\", \"NgxEditor__HelpText--Error\"], [\"type\", \"checkbox\", \"formControlName\", \"openInNewTab\"]],\n template: function LinkComponent_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"button\", 0);\n i0.ɵɵpipe(1, \"sanitizeHtml\");\n i0.ɵɵpipe(2, \"async\");\n i0.ɵɵpipe(3, \"async\");\n i0.ɵɵlistener(\"mousedown\", function LinkComponent_Template_button_mousedown_0_listener($event) {\n return ctx.onTogglePopupMouseClick($event);\n })(\"keydown.enter\", function LinkComponent_Template_button_keydown_enter_0_listener() {\n return ctx.onTogglePopupKeydown();\n })(\"keydown.space\", function LinkComponent_Template_button_keydown_space_0_listener() {\n return ctx.onTogglePopupKeydown();\n });\n i0.ɵɵelementEnd();\n i0.ɵɵtemplate(4, LinkComponent_div_4_Template, 20, 18, \"div\", 1);\n }\n if (rf & 2) {\n i0.ɵɵclassProp(\"NgxEditor__MenuItem--Active\", ctx.isActive || ctx.showPopup)(\"NgxEditor--Disabled\", !ctx.canExecute);\n i0.ɵɵproperty(\"disabled\", !ctx.canExecute)(\"innerHTML\", i0.ɵɵpipeBind1(1, 10, ctx.icon), i0.ɵɵsanitizeHtml)(\"title\", i0.ɵɵpipeBind1(2, 12, ctx.title))(\"ariaLabel\", i0.ɵɵpipeBind1(3, 14, ctx.title))(\"ariaExpanded\", ctx.showPopup);\n i0.ɵɵadvance(4);\n i0.ɵɵproperty(\"ngIf\", ctx.showPopup);\n }\n },\n dependencies: [i3.NgIf, i4.ɵNgNoValidate, i4.DefaultValueAccessor, i4.CheckboxControlValueAccessor, i4.NgControlStatus, i4.NgControlStatusGroup, i4.FormGroupDirective, i4.FormControlName, i3.AsyncPipe, SanitizeHtmlPipe]\n });\n }\n }\n return LinkComponent;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet DropdownComponent = /*#__PURE__*/(() => {\n class DropdownComponent {\n constructor(ngxeService, menuService, el) {\n this.ngxeService = ngxeService;\n this.menuService = menuService;\n this.el = el;\n this.isDropdownOpen = false;\n this.disabledItems = [];\n this.update = view => {\n const {\n state\n } = view;\n this.disabledItems = [];\n const activeItems = [];\n this.items.forEach(item => {\n const command = ToggleCommands[item];\n const isActive = command.isActive(state);\n if (isActive) {\n activeItems.push(item);\n }\n if (!command.canExecute(state)) {\n this.disabledItems.push(item);\n }\n });\n if (activeItems.length === 1) {\n [this.activeItem] = activeItems;\n } else {\n this.activeItem = null;\n }\n };\n }\n get isSelected() {\n return Boolean(this.activeItem || this.isDropdownOpen);\n }\n get isDropdownDisabled() {\n return this.disabledItems.length === this.items.length;\n }\n onDocumentClick(target) {\n if (!this.el.nativeElement.contains(target) && this.isDropdownOpen) {\n this.isDropdownOpen = false;\n }\n }\n getName(key) {\n return this.ngxeService.locals.get(key);\n }\n getIsDropdownActive(item) {\n return this.activeItem === item;\n }\n toggleDropdown() {\n this.isDropdownOpen = !this.isDropdownOpen;\n }\n onToggleDropdownMouseClick(e) {\n e.preventDefault();\n if (e.button !== 0) {\n return;\n }\n this.toggleDropdown();\n }\n onToggleDropdownKeydown() {\n this.toggleDropdown();\n }\n trackByIndex(index) {\n return index;\n }\n selectItem(item) {\n const command = ToggleCommands[item];\n const {\n state,\n dispatch\n } = this.editorView;\n command.toggle()(state, dispatch);\n this.isDropdownOpen = false;\n }\n onDropdownItemMouseClick(e, item) {\n e.preventDefault();\n // consider only left click\n if (e.button !== 0) {\n return;\n }\n this.selectItem(item);\n }\n onDropdownItemKeydown(event, item) {\n const e = event;\n e.preventDefault();\n this.selectItem(item);\n }\n ngOnInit() {\n this.editorView = this.menuService.editor.view;\n this.updateSubscription = this.menuService.editor.update.subscribe(view => {\n this.update(view);\n });\n }\n ngOnDestroy() {\n this.updateSubscription.unsubscribe();\n }\n static {\n this.ɵfac = function DropdownComponent_Factory(t) {\n return new (t || DropdownComponent)(i0.ɵɵdirectiveInject(NgxEditorService), i0.ɵɵdirectiveInject(MenuService), i0.ɵɵdirectiveInject(i0.ElementRef));\n };\n }\n static {\n this.ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: DropdownComponent,\n selectors: [[\"ngx-dropdown\"]],\n hostBindings: function DropdownComponent_HostBindings(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵlistener(\"mousedown\", function DropdownComponent_mousedown_HostBindingHandler($event) {\n return ctx.onDocumentClick($event.target);\n }, false, i0.ɵɵresolveDocument);\n }\n },\n inputs: {\n group: \"group\",\n items: \"items\"\n },\n decls: 5,\n vars: 13,\n consts: [[\"type\", \"button\", \"aria-haspopup\", \"listbox\", 1, \"NgxEditor__Dropdown--Text\", 3, \"mousedown\", \"keydown.enter\", \"keydown.space\", \"disabled\", \"ariaLabel\", \"ariaExpanded\"], [\"class\", \"NgxEditor__Dropdown--DropdownMenu\", \"role\", \"listbox\", 4, \"ngIf\"], [\"role\", \"listbox\", 1, \"NgxEditor__Dropdown--DropdownMenu\"], [\"type\", \"button\", \"class\", \"NgxEditor__Dropdown--Item\", \"role\", \"option\", 3, \"ngClass\", \"ariaLabel\", \"mousedown\", \"keydown.enter\", \"keydown.space\", 4, \"ngFor\", \"ngForOf\", \"ngForTrackBy\"], [\"type\", \"button\", \"role\", \"option\", 1, \"NgxEditor__Dropdown--Item\", 3, \"mousedown\", \"keydown.enter\", \"keydown.space\", \"ngClass\", \"ariaLabel\"]],\n template: function DropdownComponent_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"button\", 0);\n i0.ɵɵpipe(1, \"async\");\n i0.ɵɵlistener(\"mousedown\", function DropdownComponent_Template_button_mousedown_0_listener($event) {\n return ctx.onToggleDropdownMouseClick($event);\n })(\"keydown.enter\", function DropdownComponent_Template_button_keydown_enter_0_listener() {\n return ctx.onToggleDropdownKeydown();\n })(\"keydown.space\", function DropdownComponent_Template_button_keydown_space_0_listener() {\n return ctx.onToggleDropdownKeydown();\n });\n i0.ɵɵtext(2);\n i0.ɵɵpipe(3, \"async\");\n i0.ɵɵelementEnd();\n i0.ɵɵtemplate(4, DropdownComponent_div_4_Template, 2, 2, \"div\", 1);\n }\n if (rf & 2) {\n i0.ɵɵclassProp(\"NgxEditor__Dropdown--Selected\", ctx.isSelected)(\"NgxEditor--Disabled\", ctx.isDropdownDisabled);\n i0.ɵɵproperty(\"disabled\", ctx.isDropdownDisabled)(\"ariaLabel\", i0.ɵɵpipeBind1(1, 9, ctx.getName(ctx.activeItem || ctx.group)))(\"ariaExpanded\", ctx.isDropdownOpen);\n i0.ɵɵadvance(2);\n i0.ɵɵtextInterpolate1(\" \", i0.ɵɵpipeBind1(3, 11, ctx.getName(ctx.activeItem || ctx.group)), \"\\n\");\n i0.ɵɵadvance(2);\n i0.ɵɵproperty(\"ngIf\", ctx.isDropdownOpen);\n }\n },\n dependencies: [i3.NgClass, i3.NgForOf, i3.NgIf, i3.AsyncPipe]\n });\n }\n }\n return DropdownComponent;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet ImageComponent = /*#__PURE__*/(() => {\n class ImageComponent {\n constructor(el, ngxeService, menuService) {\n this.el = el;\n this.ngxeService = ngxeService;\n this.menuService = menuService;\n this.showPopup = false;\n this.isActive = false;\n this.componentId = uniq();\n this.form = new FormGroup({\n src: new FormControl('', [Validators$1.required, Validators$1.pattern('(https?://)?([\\\\da-z.-]+)\\\\.([a-z.]{2,6})[/\\\\w .-]*/??([^#\\n\\r]*)?#?([^\\n\\r]*)')]),\n alt: new FormControl(''),\n title: new FormControl('')\n });\n this.update = view => {\n const {\n state\n } = view;\n this.isActive = Image.isActive(state);\n };\n }\n get icon() {\n return this.ngxeService.getIcon('image');\n }\n get src() {\n return this.form.get('src');\n }\n onDocumentClick(e) {\n if (!this.el.nativeElement.contains(e.target) && this.showPopup) {\n this.hideForm();\n }\n }\n getId(name) {\n return `${name}-${this.componentId}`;\n }\n getLabel(key) {\n return this.ngxeService.locals.get(key);\n }\n hideForm() {\n this.showPopup = false;\n this.form.reset({\n src: '',\n alt: '',\n title: ''\n });\n }\n togglePopup() {\n this.showPopup = !this.showPopup;\n if (this.showPopup) {\n this.fillForm();\n }\n }\n onTogglePopupMouseClick(e) {\n if (e.button !== 0) {\n return;\n }\n this.togglePopup();\n }\n onTogglePopupKeydown() {\n this.togglePopup();\n }\n fillForm() {\n const {\n state\n } = this.editorView;\n const {\n selection\n } = state;\n if (selection instanceof NodeSelection && this.isActive) {\n const {\n src,\n alt = '',\n title = ''\n } = selection.node.attrs;\n this.form.setValue({\n src,\n alt,\n title\n });\n }\n }\n insertLink(e) {\n e.preventDefault();\n const {\n src,\n alt,\n title\n } = this.form.getRawValue();\n const {\n dispatch,\n state\n } = this.editorView;\n const attrs = {\n alt,\n title\n };\n Image.insert(src, attrs)(state, dispatch);\n this.editorView.focus();\n this.hideForm();\n }\n ngOnInit() {\n this.editorView = this.menuService.editor.view;\n this.updateSubscription = this.menuService.editor.update.subscribe(view => {\n this.update(view);\n });\n }\n ngOnDestroy() {\n this.updateSubscription.unsubscribe();\n }\n static {\n this.ɵfac = function ImageComponent_Factory(t) {\n return new (t || ImageComponent)(i0.ɵɵdirectiveInject(i0.ElementRef), i0.ɵɵdirectiveInject(NgxEditorService), i0.ɵɵdirectiveInject(MenuService));\n };\n }\n static {\n this.ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: ImageComponent,\n selectors: [[\"ngx-image\"]],\n hostBindings: function ImageComponent_HostBindings(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵlistener(\"mousedown\", function ImageComponent_mousedown_HostBindingHandler($event) {\n return ctx.onDocumentClick($event);\n }, false, i0.ɵɵresolveDocument);\n }\n },\n decls: 5,\n vars: 13,\n consts: [[\"type\", \"button\", \"aria-haspopup\", \"dialog\", 1, \"NgxEditor__MenuItem--Icon\", 3, \"mousedown\", \"keydown.enter\", \"keydown.space\", \"innerHTML\", \"title\", \"ariaLabel\", \"ariaExpanded\"], [\"class\", \"NgxEditor__Popup\", 4, \"ngIf\"], [1, \"NgxEditor__Popup\"], [1, \"NgxEditor__Popup--Form\", 3, \"ngSubmit\", \"formGroup\"], [1, \"NgxEditor__Popup--FormGroup\"], [1, \"NgxEditor__Popup--Col\"], [1, \"NgxEditor__Popup--Label\", 3, \"htmlFor\"], [\"type\", \"href\", \"formControlName\", \"src\", \"autocomplete\", \"off\", 3, \"id\"], [\"class\", \"NgxEditor__HelpText NgxEditor__HelpText--Error\", 4, \"ngIf\"], [\"type\", \"text\", \"formControlName\", \"alt\", \"autocomplete\", \"off\", 3, \"id\"], [\"type\", \"text\", \"formControlName\", \"title\", \"autocomplete\", \"off\", 3, \"id\"], [\"type\", \"submit\", 3, \"disabled\"], [1, \"NgxEditor__HelpText\", \"NgxEditor__HelpText--Error\"]],\n template: function ImageComponent_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"button\", 0);\n i0.ɵɵpipe(1, \"sanitizeHtml\");\n i0.ɵɵpipe(2, \"async\");\n i0.ɵɵpipe(3, \"async\");\n i0.ɵɵlistener(\"mousedown\", function ImageComponent_Template_button_mousedown_0_listener($event) {\n return ctx.onTogglePopupMouseClick($event);\n })(\"keydown.enter\", function ImageComponent_Template_button_keydown_enter_0_listener() {\n return ctx.onTogglePopupKeydown();\n })(\"keydown.space\", function ImageComponent_Template_button_keydown_space_0_listener() {\n return ctx.onTogglePopupKeydown();\n });\n i0.ɵɵelementEnd();\n i0.ɵɵtemplate(4, ImageComponent_div_4_Template, 24, 21, \"div\", 1);\n }\n if (rf & 2) {\n i0.ɵɵclassProp(\"NgxEditor__MenuItem--Active\", ctx.isActive || ctx.showPopup);\n i0.ɵɵproperty(\"innerHTML\", i0.ɵɵpipeBind1(1, 7, ctx.icon), i0.ɵɵsanitizeHtml)(\"title\", i0.ɵɵpipeBind1(2, 9, ctx.getLabel(\"insertImage\")))(\"ariaLabel\", i0.ɵɵpipeBind1(3, 11, ctx.getLabel(\"insertImage\")))(\"ariaExpanded\", ctx.showPopup);\n i0.ɵɵadvance(4);\n i0.ɵɵproperty(\"ngIf\", ctx.showPopup);\n }\n },\n dependencies: [i3.NgIf, i4.ɵNgNoValidate, i4.DefaultValueAccessor, i4.NgControlStatus, i4.NgControlStatusGroup, i4.FormGroupDirective, i4.FormControlName, i3.AsyncPipe, SanitizeHtmlPipe]\n });\n }\n }\n return ImageComponent;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet ColorPickerComponent = /*#__PURE__*/(() => {\n class ColorPickerComponent {\n constructor(el, menuService, ngxeService) {\n this.el = el;\n this.menuService = menuService;\n this.ngxeService = ngxeService;\n this.showPopup = false;\n this.isActive = false;\n this.activeColors = [];\n this.canExecute = true;\n this.update = view => {\n const {\n state\n } = view;\n this.canExecute = this.command.canExecute(state);\n this.isActive = this.command.isActive(state);\n this.activeColors = [];\n if (this.isActive) {\n this.activeColors = this.command.getActiveColors(state);\n }\n };\n }\n get title() {\n return this.getLabel(this.type === 'text_color' ? 'text_color' : 'background_color');\n }\n get icon() {\n return this.ngxeService.getIcon(this.type === 'text_color' ? 'text_color' : 'color_fill');\n }\n get command() {\n return this.type === 'text_color' ? TextColor : TextBackgroundColor;\n }\n getContrastYIQ(hexcolor) {\n const color = hexcolor.replace('#', '');\n const r = parseInt(color.substring(0, 2), 16);\n const g = parseInt(color.substring(2, 4), 16);\n const b = parseInt(color.substring(4, 6), 16);\n const yiq = (r * 299 + g * 587 + b * 114) / 1000;\n return yiq >= 128 ? 'black' : 'white';\n }\n onDocumentClick(e) {\n if (!this.el.nativeElement.contains(e.target) && this.showPopup) {\n this.hidePopup();\n }\n }\n hidePopup() {\n this.showPopup = false;\n }\n togglePopup() {\n this.showPopup = !this.showPopup;\n }\n onTogglePopupMouseClick(e) {\n e.preventDefault();\n if (e.button !== 0) {\n return;\n }\n this.togglePopup();\n }\n onTogglePopupKeydown() {\n this.togglePopup();\n }\n remove() {\n const {\n state,\n dispatch\n } = this.editorView;\n this.command.remove()(state, dispatch);\n this.hidePopup();\n }\n onRemoveMouseClick(e) {\n e.preventDefault();\n if (e.button !== 0) {\n return;\n }\n e.preventDefault();\n this.remove();\n }\n onRemoveKeydown() {\n this.remove();\n }\n trackByIndex(index) {\n return index;\n }\n selectColor(color) {\n const {\n state,\n dispatch\n } = this.editorView;\n if (this.type === 'text_color') {\n const attrs = {\n color\n };\n this.command.apply(attrs)(state, dispatch);\n } else {\n const attrs = {\n backgroundColor: color\n };\n this.command.apply(attrs)(state, dispatch);\n }\n if (!this.editorView.hasFocus()) {\n this.editorView.focus();\n }\n this.hidePopup();\n }\n onColorSelectMouseClick(e, color) {\n e.preventDefault();\n if (e.button !== 0) {\n return;\n }\n this.selectColor(color);\n }\n onColorSelectKeydown(color) {\n this.selectColor(color);\n }\n getLabel(key) {\n return this.ngxeService.locals.get(key);\n }\n ngOnInit() {\n this.editorView = this.menuService.editor.view;\n this.updateSubscription = this.menuService.editor.update.subscribe(view => {\n this.update(view);\n });\n }\n ngOnDestroy() {\n this.updateSubscription.unsubscribe();\n }\n static {\n this.ɵfac = function ColorPickerComponent_Factory(t) {\n return new (t || ColorPickerComponent)(i0.ɵɵdirectiveInject(i0.ElementRef), i0.ɵɵdirectiveInject(MenuService), i0.ɵɵdirectiveInject(NgxEditorService));\n };\n }\n static {\n this.ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: ColorPickerComponent,\n selectors: [[\"ngx-color-picker\"]],\n hostBindings: function ColorPickerComponent_HostBindings(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵlistener(\"mousedown\", function ColorPickerComponent_mousedown_HostBindingHandler($event) {\n return ctx.onDocumentClick($event);\n }, false, i0.ɵɵresolveDocument);\n }\n },\n inputs: {\n presets: \"presets\",\n type: \"type\"\n },\n decls: 5,\n vars: 15,\n consts: [[\"type\", \"button\", 1, \"NgxEditor__MenuItem--Icon\", 3, \"mousedown\", \"keydown.enter\", \"keydown.space\", \"disabled\", \"innerHTML\", \"title\", \"ariaLabel\"], [\"class\", \"NgxEditor__Popup\", 4, \"ngIf\"], [1, \"NgxEditor__Popup\"], [\"class\", \"NgxEditor__ColorContainer\", 4, \"ngFor\", \"ngForOf\", \"ngForTrackBy\"], [1, \"NgxEditor__MenuItem--Button\", 3, \"mousedown\", \"keydown.enter\", \"keydown.space\", \"disabled\"], [1, \"NgxEditor__ColorContainer\"], [\"class\", \"NgxEditor__Color\", 3, \"ngStyle\", \"title\", \"ngClass\", \"mousedown\", \"keydown.enter\", \"keydown.space\", 4, \"ngFor\", \"ngForOf\", \"ngForTrackBy\"], [1, \"NgxEditor__Color\", 3, \"mousedown\", \"keydown.enter\", \"keydown.space\", \"ngStyle\", \"title\", \"ngClass\"]],\n template: function ColorPickerComponent_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"button\", 0);\n i0.ɵɵpipe(1, \"sanitizeHtml\");\n i0.ɵɵpipe(2, \"async\");\n i0.ɵɵpipe(3, \"async\");\n i0.ɵɵlistener(\"mousedown\", function ColorPickerComponent_Template_button_mousedown_0_listener($event) {\n return ctx.onTogglePopupMouseClick($event);\n })(\"keydown.enter\", function ColorPickerComponent_Template_button_keydown_enter_0_listener() {\n return ctx.onTogglePopupKeydown();\n })(\"keydown.space\", function ColorPickerComponent_Template_button_keydown_space_0_listener() {\n return ctx.onTogglePopupKeydown();\n });\n i0.ɵɵelementEnd();\n i0.ɵɵtemplate(4, ColorPickerComponent_div_4_Template, 5, 6, \"div\", 1);\n }\n if (rf & 2) {\n i0.ɵɵclassProp(\"NgxEditor__MenuItem--Active\", ctx.isActive || ctx.showPopup)(\"NgxEditor--Disabled\", !ctx.canExecute);\n i0.ɵɵproperty(\"disabled\", !ctx.canExecute)(\"innerHTML\", i0.ɵɵpipeBind1(1, 9, ctx.icon), i0.ɵɵsanitizeHtml)(\"title\", i0.ɵɵpipeBind1(2, 11, ctx.title))(\"ariaLabel\", i0.ɵɵpipeBind1(3, 13, ctx.title));\n i0.ɵɵadvance(4);\n i0.ɵɵproperty(\"ngIf\", ctx.showPopup);\n }\n },\n dependencies: [i3.NgClass, i3.NgForOf, i3.NgIf, i3.NgStyle, i3.AsyncPipe, SanitizeHtmlPipe],\n styles: [\"@charset \\\"UTF-8\\\";.NgxEditor__Popup[_ngcontent-%COMP%]{width:230px}.NgxEditor__ColorContainer[_ngcontent-%COMP%]{display:flex;justify-content:space-between}.NgxEditor__ColorContainer[_ngcontent-%COMP%] + .NgxEditor__ColorContainer[_ngcontent-%COMP%]{margin-top:5px}.NgxEditor__Color[_ngcontent-%COMP%]{border:none;outline:none;border-radius:6px;width:24px;height:24px;flex-shrink:0}.NgxEditor__Color[_ngcontent-%COMP%]:focus-visible{outline:1px solid var(--ngx-editor-focus-ring-color);outline-offset:1px}.NgxEditor__Color--Active[_ngcontent-%COMP%]:after{content:\\\"\\\\2714\\\";font-size:90%}.NgxEditor__MenuItem--Button[_ngcontent-%COMP%]{margin-top:5px}\"]\n });\n }\n }\n return ColorPickerComponent;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nconst DEFAULT_TOOLBAR = [['bold', 'italic'], ['code', 'blockquote'], ['underline', 'strike'], ['ordered_list', 'bullet_list'], [{\n heading: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']\n}], ['link', 'image'], ['text_color', 'background_color'], ['align_left', 'align_center', 'align_right', 'align_justify'], ['format_clear']];\nconst TOOLBAR_MINIMAL = [['bold', 'italic'], [{\n heading: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']\n}], ['link', 'image'], ['text_color', 'background_color']];\nconst TOOLBAR_FULL = [['bold', 'italic'], ['code', 'blockquote'], ['underline', 'strike'], ['ordered_list', 'bullet_list'], [{\n heading: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']\n}], ['link', 'image'], ['text_color', 'background_color'], ['align_left', 'align_center', 'align_right', 'align_justify'], ['horizontal_rule', 'format_clear', 'indent', 'outdent'], ['superscript', 'subscript'], ['undo', 'redo']];\nconst DEFAULT_COLOR_PRESETS = ['#b60205', '#d93f0b', '#fbca04', '#0e8a16', '#006b75', '#1d76db', '#0052cc', '#5319e7', '#e99695', '#f9d0c4', '#fef2c0', '#c2e0c6', '#bfdadc', '#c5def5', '#bfd4f2', '#d4c5f9'];\nlet MenuComponent = /*#__PURE__*/(() => {\n class MenuComponent {\n constructor(menuService) {\n this.menuService = menuService;\n this.toolbar = TOOLBAR_MINIMAL;\n this.colorPresets = DEFAULT_COLOR_PRESETS;\n this.disabled = false;\n this.customMenuRef = null;\n this.dropdownPlacement = 'bottom';\n this.toggleCommands = ['bold', 'italic', 'underline', 'strike', 'code', 'blockquote', 'ordered_list', 'bullet_list', 'align_left', 'align_center', 'align_right', 'align_justify', 'superscript', 'subscript'];\n this.insertCommands = ['horizontal_rule', 'format_clear', 'indent', 'outdent', 'undo', 'redo'];\n this.iconContainerClass = ['NgxEditor__MenuItem', 'NgxEditor__MenuItem--IconContainer'];\n this.dropdownContainerClass = ['NgxEditor__Dropdown'];\n this.seperatorClass = ['NgxEditor__Seperator'];\n }\n get presets() {\n const col = 8;\n const colors = [];\n this.colorPresets.forEach((color, index) => {\n const row = Math.floor(index / col);\n if (!colors[row]) {\n colors.push([]);\n }\n colors[row].push(color);\n });\n return colors;\n }\n trackByIndex(index) {\n return index;\n }\n isDropDown(item) {\n if (item?.heading) {\n return true;\n }\n return false;\n }\n getDropdownItems(item) {\n return item;\n }\n isLinkItem(item) {\n if (item === 'link') {\n return true;\n }\n // NOTE: it is not sufficient to check for a `link` property\n // as String.prototype.link is a valid (although deprecated) method\n return typeof item === 'object' && typeof item?.link === 'object';\n }\n isLinkWithOptions(item) {\n // NOTE: it is not sufficient to check for a `link` property\n // as String.prototype.link is a valid (although deprecated) method\n return typeof item === 'object' && typeof item?.link === 'object';\n }\n getLinkOptions(item) {\n return item?.link;\n }\n ngOnInit() {\n if (!this.editor) {\n throw new NgxEditorError('Required editor instance to initialize menu component');\n }\n this.menuService.editor = this.editor;\n }\n static {\n this.ɵfac = function MenuComponent_Factory(t) {\n return new (t || MenuComponent)(i0.ɵɵdirectiveInject(MenuService));\n };\n }\n static {\n this.ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: MenuComponent,\n selectors: [[\"ngx-editor-menu\"]],\n inputs: {\n toolbar: \"toolbar\",\n colorPresets: \"colorPresets\",\n disabled: \"disabled\",\n editor: \"editor\",\n customMenuRef: \"customMenuRef\",\n dropdownPlacement: \"dropdownPlacement\"\n },\n features: [i0.ɵɵProvidersFeature([MenuService])],\n decls: 3,\n vars: 7,\n consts: [[1, \"NgxEditor__MenuBar\", 3, \"ngClass\"], [4, \"ngFor\", \"ngForOf\", \"ngForTrackBy\"], [4, \"ngIf\"], [3, \"toolbarItem\", \"class\", 4, \"ngIf\"], [3, \"class\", 4, \"ngIf\"], [\"type\", \"text_color\", 3, \"class\", \"presets\", 4, \"ngIf\"], [\"type\", \"background_color\", 3, \"class\", \"presets\", 4, \"ngIf\"], [3, \"toolbarItem\"], [3, \"options\"], [3, \"class\", \"group\", \"items\", 4, \"ngFor\", \"ngForOf\", \"ngForTrackBy\"], [3, \"group\", \"items\"], [\"type\", \"text_color\", 3, \"presets\"], [\"type\", \"background_color\", 3, \"presets\"], [3, \"ngTemplateOutlet\"]],\n template: function MenuComponent_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵelementStart(0, \"div\", 0);\n i0.ɵɵtemplate(1, MenuComponent_ng_container_1_Template, 2, 2, \"ng-container\", 1)(2, MenuComponent_ng_container_2_Template, 2, 1, \"ng-container\", 2);\n i0.ɵɵelementEnd();\n }\n if (rf & 2) {\n i0.ɵɵproperty(\"ngClass\", i0.ɵɵpureFunction2(4, _c7, ctx.disabled, ctx.dropdownPlacement === \"top\"));\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngForOf\", ctx.toolbar)(\"ngForTrackBy\", ctx.trackByIndex);\n i0.ɵɵadvance();\n i0.ɵɵproperty(\"ngIf\", ctx.customMenuRef);\n }\n },\n dependencies: [i3.NgClass, i3.NgForOf, i3.NgIf, i3.NgTemplateOutlet, ToggleCommandComponent, InsertCommandComponent, LinkComponent, DropdownComponent, ImageComponent, ColorPickerComponent, i3.KeyValuePipe]\n });\n }\n }\n return MenuComponent;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet BubbleComponent = /*#__PURE__*/(() => {\n class BubbleComponent {\n constructor(sanitizeHTML, ngxeService) {\n this.sanitizeHTML = sanitizeHTML;\n this.ngxeService = ngxeService;\n this.execulableItems = [];\n this.activeItems = [];\n this.toolbar = [['bold', 'italic', 'underline', 'strike'], ['ordered_list', 'bullet_list', 'blockquote', 'code'], ['align_left', 'align_center', 'align_right', 'align_justify']];\n this.toggleCommands = ['bold', 'italic', 'underline', 'strike', 'ordered_list', 'bullet_list', 'blockquote', 'code', 'align_left', 'align_center', 'align_right', 'align_justify'];\n }\n get view() {\n return this.editor.view;\n }\n getIcon(name) {\n return this.sanitizeHTML.transform(this.ngxeService.getIcon(name));\n }\n getTitle(name) {\n return this.ngxeService.locals.get(name);\n }\n trackByIndex(index) {\n return index;\n }\n onClick(e, commandName) {\n e.preventDefault();\n e.stopPropagation();\n if (e.button !== 0) {\n return;\n }\n const {\n state,\n dispatch\n } = this.view;\n const command = ToggleCommands[commandName];\n command.toggle()(state, dispatch);\n }\n update(view) {\n this.activeItems = [];\n this.execulableItems = [];\n const {\n state\n } = view;\n this.toggleCommands.forEach(toolbarItem => {\n const command = ToggleCommands[toolbarItem];\n const isActive = command.isActive(state);\n if (isActive) {\n this.activeItems.push(toolbarItem);\n }\n const canExecute = command.canExecute(state);\n if (canExecute) {\n this.execulableItems.push(toolbarItem);\n }\n });\n }\n ngOnInit() {\n this.updateSubscription = this.editor.update.subscribe(view => {\n this.update(view);\n });\n }\n ngOnDestroy() {\n this.updateSubscription.unsubscribe();\n }\n static {\n this.ɵfac = function BubbleComponent_Factory(t) {\n return new (t || BubbleComponent)(i0.ɵɵdirectiveInject(SanitizeHtmlPipe), i0.ɵɵdirectiveInject(NgxEditorService));\n };\n }\n static {\n this.ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: BubbleComponent,\n selectors: [[\"ngx-bubble\"]],\n inputs: {\n editor: \"editor\"\n },\n decls: 1,\n vars: 2,\n consts: [[4, \"ngFor\", \"ngForOf\", \"ngForTrackBy\"], [\"type\", \"button\", \"class\", \"NgxBubbleMenu__Icon\", 3, \"ngClass\", \"title\", \"innerHTML\", \"mousedown\", 4, \"ngIf\"], [\"class\", \"NgxBubbleMenu__Seperator\", 4, \"ngIf\"], [\"type\", \"button\", 1, \"NgxBubbleMenu__Icon\", 3, \"mousedown\", \"ngClass\", \"title\", \"innerHTML\"], [1, \"NgxBubbleMenu__Seperator\"]],\n template: function BubbleComponent_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵtemplate(0, BubbleComponent_ng_container_0_Template, 2, 2, \"ng-container\", 0);\n }\n if (rf & 2) {\n i0.ɵɵproperty(\"ngForOf\", ctx.toolbar)(\"ngForTrackBy\", ctx.trackByIndex);\n }\n },\n dependencies: [i3.NgClass, i3.NgForOf, i3.NgIf, i3.AsyncPipe],\n styles: [\"*[_ngcontent-%COMP%], *[_ngcontent-%COMP%]:before, *[_ngcontent-%COMP%]:after{box-sizing:border-box}[_nghost-%COMP%]{display:flex;flex-wrap:wrap;background-color:var(--ngx-editor-bubble-bg-color);color:var(--ngx-editor-bubble-text-color);padding:5px;border-radius:4px}.NgxBubbleMenu__Icon[_ngcontent-%COMP%]{all:unset;appearance:none;height:var(--ngx-editor-icon-size);width:var(--ngx-editor-icon-size);transition:.2s ease-in-out;border-radius:var(--ngx-editor-menu-item-border-radius);display:flex;align-items:center;justify-content:center;color:#fff}.NgxBubbleMenu__Icon[_ngcontent-%COMP%]:hover{background-color:var(--ngx-editor-bubble-item-hover-color)}.NgxBubbleMenu__Icon[_ngcontent-%COMP%] + .NgxBubbleMenu__Icon[_ngcontent-%COMP%]{margin-left:5px}.NgxBubbleMenu__Icon.NgxBubbleMenu__Icon--Active[_ngcontent-%COMP%]{background-color:var(--ngx-editor-bubble-text-color);color:var(--ngx-editor-bubble-bg-color)}.NgxBubbleMenu__Seperator[_ngcontent-%COMP%]{border-left:1px solid var(--ngx-editor-seperator-color);margin:0 5px}\"]\n });\n }\n }\n return BubbleComponent;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet FloatingMenuComponent = /*#__PURE__*/(() => {\n class FloatingMenuComponent {\n constructor(el) {\n this.el = el;\n this.autoPlace = false;\n this.posLeft = 0;\n this.posTop = 0;\n this.showMenu = false;\n this.dragging = false;\n }\n get display() {\n return {\n visibility: this.showMenu ? 'visible' : 'hidden',\n opacity: this.showMenu ? '1' : '0',\n top: `${this.posTop}px`,\n left: `${this.posLeft}px`\n };\n }\n get view() {\n return this.editor.view;\n }\n onMouseDown(e) {\n const target = e.target;\n if (this.el.nativeElement.contains(target) && target.nodeName !== 'INPUT') {\n e.preventDefault();\n return;\n }\n this.dragging = true;\n }\n onKeyDown(e) {\n const target = e.target;\n if (target.nodeName === 'INPUT') {\n return;\n }\n this.dragging = true;\n this.hide();\n }\n onMouseUp(e) {\n const target = e.target;\n if (this.el.nativeElement.contains(target) || target.nodeName === 'INPUT') {\n e.preventDefault();\n return;\n }\n this.dragging = false;\n this.useUpdate();\n }\n onKeyUp(e) {\n const target = e.target;\n if (target.nodeName === 'INPUT') {\n return;\n }\n this.dragging = false;\n this.useUpdate();\n }\n useUpdate() {\n if (!this.view) {\n return;\n }\n this.update(this.view);\n }\n hide() {\n this.showMenu = false;\n }\n show() {\n this.showMenu = true;\n }\n async calculateBubblePosition(view) {\n const {\n state: {\n selection\n }\n } = view;\n const {\n from,\n to\n } = selection;\n const start = view.coordsAtPos(from);\n const end = view.coordsAtPos(to);\n const selectionElement = {\n getBoundingClientRect() {\n if (selection instanceof NodeSelection) {\n const node = view.nodeDOM(from);\n return node.getBoundingClientRect();\n }\n const {\n top,\n left\n } = start;\n const {\n bottom,\n right\n } = end;\n return {\n x: left,\n y: top,\n top,\n bottom,\n left,\n right,\n width: right - left,\n height: bottom - top\n };\n }\n };\n // the floating bubble itself\n const bubbleEl = this.el.nativeElement;\n const {\n x: left,\n y: top\n } = await computePosition(selectionElement, bubbleEl, {\n placement: 'top',\n middleware: [offset(5), this.autoPlace && autoPlacement({\n boundary: view.dom,\n padding: 5,\n allowedPlacements: ['top', 'bottom']\n }), {\n // prevent overflow on right and left side\n // since only top and bottom placements are allowed\n // autoplacement can't handle overflows on the right and left\n name: 'overflowMiddleware',\n async fn(middlewareArgs) {\n const overflow = await detectOverflow(middlewareArgs, {\n boundary: view.dom,\n padding: 5\n });\n // overflows left\n if (overflow.left > 0) {\n return {\n x: middlewareArgs.x + overflow.left\n };\n }\n // overflows right\n if (overflow.right > 0) {\n return {\n x: middlewareArgs.x - overflow.right\n };\n }\n return {};\n }\n }].filter(Boolean)\n });\n return {\n left,\n top\n };\n }\n canShowMenu(view) {\n const {\n state\n } = view;\n const {\n selection\n } = state;\n const {\n empty\n } = selection;\n if (selection instanceof NodeSelection) {\n if (selection.node.type.name === 'image') {\n return false;\n }\n }\n const hasFocus = this.view.hasFocus();\n if (!hasFocus || empty || this.dragging) {\n this.hide();\n return false;\n }\n return true;\n }\n update(view) {\n const canShowMenu = this.canShowMenu(view);\n if (!canShowMenu) {\n this.hide();\n return;\n }\n this.calculateBubblePosition(this.view).then(({\n top,\n left\n }) => {\n if (!this.canShowMenu) {\n this.hide();\n return;\n }\n this.posLeft = left;\n this.posTop = top;\n this.show();\n });\n }\n ngOnInit() {\n if (!this.editor) {\n throw new NgxEditorError('Required editor instance to initialize floating menu component');\n }\n this.updateSubscription = this.editor.update.subscribe(view => {\n this.update(view);\n });\n this.resizeSubscription = fromEvent(window, 'resize').pipe(throttleTime(500, asyncScheduler, {\n leading: true,\n trailing: true\n })).subscribe(() => {\n this.useUpdate();\n });\n }\n ngOnDestroy() {\n this.updateSubscription.unsubscribe();\n this.resizeSubscription.unsubscribe();\n }\n static {\n this.ɵfac = function FloatingMenuComponent_Factory(t) {\n return new (t || FloatingMenuComponent)(i0.ɵɵdirectiveInject(i0.ElementRef));\n };\n }\n static {\n this.ɵcmp = /* @__PURE__ */i0.ɵɵdefineComponent({\n type: FloatingMenuComponent,\n selectors: [[\"ngx-editor-floating-menu\"]],\n hostVars: 2,\n hostBindings: function FloatingMenuComponent_HostBindings(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵlistener(\"mousedown\", function FloatingMenuComponent_mousedown_HostBindingHandler($event) {\n return ctx.onMouseDown($event);\n }, false, i0.ɵɵresolveDocument)(\"keydown\", function FloatingMenuComponent_keydown_HostBindingHandler($event) {\n return ctx.onKeyDown($event);\n }, false, i0.ɵɵresolveDocument)(\"mouseup\", function FloatingMenuComponent_mouseup_HostBindingHandler($event) {\n return ctx.onMouseUp($event);\n }, false, i0.ɵɵresolveDocument)(\"keyup\", function FloatingMenuComponent_keyup_HostBindingHandler($event) {\n return ctx.onKeyUp($event);\n }, false, i0.ɵɵresolveDocument);\n }\n if (rf & 2) {\n i0.ɵɵstyleMap(ctx.display);\n }\n },\n inputs: {\n editor: \"editor\",\n autoPlace: \"autoPlace\"\n },\n ngContentSelectors: _c3,\n decls: 4,\n vars: 1,\n consts: [[\"ref\", \"\"], [4, \"ngIf\"], [3, \"editor\"]],\n template: function FloatingMenuComponent_Template(rf, ctx) {\n if (rf & 1) {\n i0.ɵɵprojectionDef();\n i0.ɵɵelementStart(0, \"div\", null, 0);\n i0.ɵɵprojection(2);\n i0.ɵɵelementEnd();\n i0.ɵɵtemplate(3, FloatingMenuComponent_ng_container_3_Template, 2, 1, \"ng-container\", 1);\n }\n if (rf & 2) {\n const ref_r2 = i0.ɵɵreference(1);\n i0.ɵɵadvance(3);\n i0.ɵɵproperty(\"ngIf\", ref_r2.children.length === 0);\n }\n },\n dependencies: [i3.NgIf, BubbleComponent],\n styles: [\"*[_ngcontent-%COMP%], *[_ngcontent-%COMP%]:before, *[_ngcontent-%COMP%]:after{box-sizing:border-box}[_nghost-%COMP%]{position:absolute;z-index:20;margin-bottom:5px;visibility:hidden;opacity:0}\"]\n });\n }\n }\n return FloatingMenuComponent;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nlet MenuModule = /*#__PURE__*/(() => {\n class MenuModule {\n static {\n this.ɵfac = function MenuModule_Factory(t) {\n return new (t || MenuModule)();\n };\n }\n static {\n this.ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: MenuModule\n });\n }\n static {\n this.ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({\n providers: [SanitizeHtmlPipe],\n imports: [CommonModule, ReactiveFormsModule]\n });\n }\n }\n return MenuModule;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nconst NGX_EDITOR_CONFIG_TOKEN = new InjectionToken('NgxEditorConfig');\nconst defaultConfig = {\n locals: defaults,\n icons\n};\nlet NgxEditorModule = /*#__PURE__*/(() => {\n class NgxEditorModule {\n static forRoot(config = defaultConfig) {\n return {\n ngModule: NgxEditorModule,\n providers: [{\n provide: NGX_EDITOR_CONFIG_TOKEN,\n useValue: config\n }, {\n provide: NgxEditorServiceConfig,\n useFactory: provideMyServiceOptions,\n deps: [NGX_EDITOR_CONFIG_TOKEN]\n }]\n };\n }\n static forChild(config = defaultConfig) {\n return {\n ngModule: NgxEditorModule,\n providers: [{\n provide: NGX_EDITOR_CONFIG_TOKEN,\n useValue: config\n }, {\n provide: NgxEditorServiceConfig,\n useFactory: provideMyServiceOptions,\n deps: [NGX_EDITOR_CONFIG_TOKEN]\n }, NgxEditorService]\n };\n }\n static {\n this.ɵfac = function NgxEditorModule_Factory(t) {\n return new (t || NgxEditorModule)();\n };\n }\n static {\n this.ɵmod = /* @__PURE__ */i0.ɵɵdefineNgModule({\n type: NgxEditorModule\n });\n }\n static {\n this.ɵinj = /* @__PURE__ */i0.ɵɵdefineInjector({\n imports: [CommonModule, MenuModule]\n });\n }\n }\n return NgxEditorModule;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nconst isEmptyInputValue = value => {\n // we don't check for string here so it also works with arrays\n return value === null || value.length === 0;\n};\nconst hasValidLength = value => {\n // non-strict comparison is intentional, to check for both `null` and `undefined` values\n return value !== null && typeof value.length === 'number';\n};\nconst isDocEmpty = doc => {\n if (!doc) {\n return true;\n }\n const {\n childCount,\n firstChild\n } = doc;\n return Boolean(childCount === 1 && firstChild?.isTextblock && firstChild.content.size === 0);\n};\n// @dynamic\nclass Validators {\n static required(userSchema) {\n return control => {\n const schema$1 = userSchema || schema;\n const doc = parseContent(control.value, schema$1);\n const isEmpty = isDocEmpty(doc);\n if (!isEmpty) {\n return null;\n }\n return {\n required: true\n };\n };\n }\n static maxLength(maxLength, userSchema) {\n return control => {\n const schema$1 = userSchema || schema;\n const doc = parseContent(control.value, schema$1);\n const value = doc.textContent;\n if (hasValidLength(value) && value.length > maxLength) {\n return {\n maxlength: {\n requiredLength: maxLength,\n actualLength: value.length\n }\n };\n }\n return null;\n };\n }\n static minLength(minLength, userSchema) {\n return control => {\n const schema$1 = userSchema || schema;\n const doc = parseContent(control.value, schema$1);\n const value = doc.textContent;\n if (isEmptyInputValue(value) || !hasValidLength(value)) {\n // don't validate empty values to allow optional controls\n // don't validate values without `length` property\n return null;\n }\n if (value.length < minLength) {\n return {\n minlength: {\n requiredLength: minLength,\n actualLength: value.length\n }\n };\n }\n return null;\n };\n }\n}\nconst execMark = (name, toggle = false) => {\n return (state, dispatch) => {\n const command = new Mark(name);\n if (!toggle) {\n return command.apply()(state, dispatch);\n }\n return command.toggle()(state, dispatch);\n };\n};\nclass EditorCommands {\n constructor(view) {\n this.applyTrx = tr => {\n this.state = this.state.apply(tr ?? this.tr);\n this.tr = this.state.tr;\n this.tr.setMeta('APPLIED_TRX', true);\n };\n this.dispatch = tr => {\n this.applyTrx(tr);\n };\n if (!view) {\n throw new NgxEditorError('Required view to initialize commands.');\n }\n this.view = view;\n this.state = view.state;\n this.tr = this.view.state.tr;\n }\n exec() {\n // No changes applied\n if (!this.tr.getMeta('APPLIED_TRX')) {\n return false;\n }\n const forceEmit = !this.view.state.doc.eq(this.state.doc);\n this.view.updateState(this.state);\n const tr = this.tr.setMeta('FORCE_EMIT', forceEmit);\n this.view.dispatch(tr);\n return true;\n }\n focus(position = 'end') {\n const selection = position === 'start' ? Selection.atStart(this.state.doc) : Selection.atEnd(this.state.doc);\n this.tr.setSelection(selection);\n this.applyTrx();\n this.view.focus();\n return this;\n }\n scrollIntoView() {\n this.tr.scrollIntoView();\n this.applyTrx();\n return this;\n }\n insertText(text) {\n this.tr.insertText(text);\n this.applyTrx();\n return this;\n }\n insertNewLine() {\n const newLineCommands = [newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock];\n chainCommands(...newLineCommands)(this.state, this.dispatch);\n return this;\n }\n applyMark(name) {\n execMark(name, false)(this.state, this.dispatch);\n return this;\n }\n toggleMark(name) {\n execMark(name, true)(this.state, this.dispatch);\n return this;\n }\n bold() {\n execMark('strong')(this.state, this.dispatch);\n return this;\n }\n toggleBold() {\n execMark('strong', true)(this.state, this.dispatch);\n return this;\n }\n italics() {\n execMark('em')(this.state, this.dispatch);\n return this;\n }\n toggleItalics() {\n execMark('em', true)(this.state, this.dispatch);\n return this;\n }\n underline() {\n execMark('u')(this.state, this.dispatch);\n return this;\n }\n toggleUnderline() {\n execMark('u', true)(this.state, this.dispatch);\n return this;\n }\n strike() {\n execMark('s')(this.state, this.dispatch);\n return this;\n }\n toggleStrike() {\n execMark('s', true)(this.state, this.dispatch);\n return this;\n }\n code() {\n execMark('code')(this.state, this.dispatch);\n return this;\n }\n toggleCode() {\n execMark('code', true)(this.state, this.dispatch);\n return this;\n }\n superscript() {\n execMark('sup')(this.state, this.dispatch);\n return this;\n }\n subscript() {\n execMark('sub')(this.state, this.dispatch);\n return this;\n }\n toggleOrderedList() {\n const command = new ListItem(false);\n command.toggle()(this.state, this.dispatch);\n return this;\n }\n toggleBulletList() {\n const command = new ListItem(true);\n command.toggle()(this.state, this.dispatch);\n return this;\n }\n toggleHeading(level) {\n const command = new Heading(level);\n command.toggle()(this.state, this.dispatch);\n return this;\n }\n insertLink(text, attrs) {\n const command = new Link$1();\n command.insert(text, attrs)(this.state, this.dispatch);\n return this;\n }\n updateLink(attrs) {\n const command = new Link$1();\n command.update(attrs)(this.state, this.dispatch);\n return this;\n }\n insertImage(src, attrs = {}) {\n const command = new Image$1();\n command.insert(src, attrs)(this.state, this.dispatch);\n return this;\n }\n textColor(color) {\n const command = new TextColor$1('text_color');\n command.apply({\n color\n })(this.state, this.dispatch);\n return this;\n }\n backgroundColor(color) {\n const command = new TextColor$1('text_background_color');\n command.apply({\n backgroundColor: color\n })(this.state, this.dispatch);\n return this;\n }\n removeTextColor() {\n const command = new TextColor$1('text_color');\n command.remove()(this.state, this.dispatch);\n return this;\n }\n removeBackgroundColor() {\n const command = new TextColor$1('text_background_color');\n command.remove()(this.state, this.dispatch);\n return this;\n }\n align(p) {\n const command = new TextAlign(p);\n command.toggle()(this.state, this.dispatch);\n return this;\n }\n insertHTML(html) {\n const {\n selection,\n schema,\n tr\n } = this.state;\n const {\n from,\n to\n } = selection;\n const element = document.createElement('div');\n element.innerHTML = isString(html) ? html.trim() : html;\n const slice = DOMParser.fromSchema(schema).parseSlice(element);\n const transaction = tr.replaceRange(from, to, slice);\n this.applyTrx(transaction);\n return this;\n }\n indent() {\n const command = new Indent('increase');\n command.insert()(this.state, this.dispatch);\n return this;\n }\n outdent() {\n const command = new Indent('decrease');\n command.insert()(this.state, this.dispatch);\n return this;\n }\n}\nconst isMacOs = typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false;\n// Input rules ref: https://github.com/ProseMirror/prosemirror-example-setup/\n// : (NodeType) → InputRule\n// Given a blockquote node type, returns an input rule that turns `\"> \"`\n// at the start of a textblock into a blockquote.\nconst blockQuoteRule = nodeType => {\n return wrappingInputRule(/^\\s*>\\s$/, nodeType);\n};\n// : (NodeType) → InputRule\n// Given a list node type, returns an input rule that turns a number\n// followed by a dot at the start of a textblock into an ordered list.\nconst orderedListRule = nodeType => {\n return wrappingInputRule(/^(?:\\d+)\\.\\s$/, nodeType, match => ({\n order: Number(match[1])\n }), (match, node) => node.childCount + node.attrs['order'] === Number(match[1]));\n};\n// : (NodeType) → InputRule\n// Given a list node type, returns an input rule that turns a bullet\n// (dash, plush, or asterisk) at the start of a textblock into a\n// bullet list.\nconst bulletListRule = nodeType => {\n return wrappingInputRule(/^\\s*(?:[-+*])\\s$/, nodeType);\n};\n// : (NodeType) → InputRule\n// Given a code block node type, returns an input rule that turns a\n// textblock starting with three backticks into a code block.\nconst codeBlockRule = nodeType => {\n return textblockTypeInputRule(/^```$/, nodeType);\n};\n// : (NodeType, number) → InputRule\n// Given a node type and a maximum level, creates an input rule that\n// turns up to that number of `#` characters followed by a space at\n// the start of a textblock into a heading whose level corresponds to\n// the number of `#` signs.\nconst headingRule = (nodeType, maxLevel) => {\n return textblockTypeInputRule(new RegExp(`^(#{1,${maxLevel}})\\\\s$`), nodeType, match => ({\n level: match[1].length\n }));\n};\n// : (MarkType) → InputRule\n// Wraps matching text with bold mark\nconst boldRule = markType => {\n // eslint-disable-next-line prefer-named-capture-group\n return markInputRule(/(?:^|\\s)(?:(\\*\\*|__)(?:([^*_]+))(\\*\\*|__))$/, markType);\n};\n// : (MarkType) → InputRule\n// Wraps matching text with em mark\nconst emRule = markType => {\n // eslint-disable-next-line prefer-named-capture-group\n return markInputRule(/(?:^|\\s)(?:(\\*|_)(?:([^*_]+))(\\*|_))$/, markType);\n};\n// : (Schema) → Plugin\n// A set of input rules for creating the basic block quotes, lists,\n// code blocks, and heading.\nconst buildInputRules = schema => {\n const rules = smartQuotes.concat(ellipsis, emDash);\n rules.push(boldRule(schema.marks['strong']));\n rules.push(emRule(schema.marks['em']));\n rules.push(blockQuoteRule(schema.nodes['blockquote']));\n rules.push(orderedListRule(schema.nodes['ordered_list']));\n rules.push(bulletListRule(schema.nodes['bullet_list']));\n rules.push(codeBlockRule(schema.nodes['code_block']));\n rules.push(headingRule(schema.nodes['heading'], 6));\n return inputRules({\n rules\n });\n};\nconst getKeyboardShortcuts = (schema, options) => {\n const historyKeyMap = {};\n historyKeyMap['Mod-z'] = undo$1;\n if (isMacOs) {\n historyKeyMap['Shift-Mod-z'] = redo$1;\n } else {\n historyKeyMap['Mod-y'] = redo$1;\n }\n const plugins = [keymap({\n 'Mod-b': toggleMark(schema.marks['strong']),\n 'Mod-i': toggleMark(schema.marks['em']),\n 'Mod-u': toggleMark(schema.marks['u']),\n 'Mod-`': toggleMark(schema.marks['code'])\n }), keymap({\n 'Enter': splitListItem(schema.nodes['list_item']),\n 'Shift-Enter': chainCommands(exitCode, (state, dispatch) => {\n const {\n tr\n } = state;\n const br = schema.nodes['hard_break'];\n dispatch(tr.replaceSelectionWith(br.create()).scrollIntoView());\n return true;\n }),\n 'Mod-[': liftListItem(schema.nodes['list_item']),\n 'Mod-]': sinkListItem(schema.nodes['list_item']),\n 'Tab': sinkListItem(schema.nodes['list_item'])\n }), keymap(baseKeymap)];\n if (options.history) {\n plugins.push(keymap(historyKeyMap));\n }\n return plugins;\n};\nconst getDefaultPlugins = (schema, options) => {\n const plugins = [];\n if (options.keyboardShortcuts) {\n plugins.push(...getKeyboardShortcuts(schema, {\n history: options.history\n }));\n }\n if (options.history) {\n plugins.push(history());\n }\n if (options.inputRules) {\n plugins.push(buildInputRules(schema));\n }\n return plugins;\n};\nconst defaultFeatures = {\n linkOnPaste: true,\n resizeImage: true\n};\nconst DEFAULT_OPTIONS = {\n content: null,\n history: true,\n keyboardShortcuts: true,\n inputRules: true,\n schema: schema,\n plugins: [],\n nodeViews: {},\n attributes: {},\n features: defaultFeatures,\n handleScrollToSelection: null,\n linkValidationPattern: '(https?://)?([\\\\da-z.-]+)\\\\.([a-z.]{2,6})[/\\\\w .-]*/??([^#\\n\\r]*)?#?([^\\n\\r]*)|(mailto:.*[@].*)'\n};\nclass Editor {\n constructor(options = DEFAULT_OPTIONS) {\n this.valueChangesSubject = new Subject();\n this.updateSubject = new Subject();\n this.options = {\n ...DEFAULT_OPTIONS,\n ...options\n };\n this.createEditor();\n }\n get valueChanges() {\n return this.valueChangesSubject.asObservable();\n }\n get update() {\n return this.updateSubject.asObservable();\n }\n get schema() {\n return this.options.schema || schema;\n }\n get linkValidationPattern() {\n return this.options.linkValidationPattern;\n }\n get commands() {\n return new EditorCommands(this.view);\n }\n get features() {\n return {\n ...defaultFeatures,\n ...this.options.features\n };\n }\n handleTransactions(tr) {\n const state = this.view.state.apply(tr);\n this.view.updateState(state);\n this.updateSubject.next(this.view);\n if (!tr.docChanged && !tr.getMeta('FORCE_EMIT')) {\n return;\n }\n const json = state.doc.toJSON();\n this.valueChangesSubject.next(json);\n }\n createEditor() {\n const {\n options,\n schema\n } = this;\n const {\n content = null,\n nodeViews\n } = options;\n const {\n history = true,\n keyboardShortcuts = true,\n inputRules = true\n } = options;\n const doc = parseContent(content, schema, options.parseOptions);\n const plugins = options.plugins ?? [];\n const attributes = options.attributes ?? {};\n const defaultPlugins = getDefaultPlugins(schema, {\n history,\n keyboardShortcuts,\n inputRules\n });\n this.view = new EditorView(null, {\n state: EditorState.create({\n doc,\n schema,\n plugins: [...defaultPlugins, ...plugins]\n }),\n nodeViews,\n dispatchTransaction: this.handleTransactions.bind(this),\n attributes,\n handleScrollToSelection: options.handleScrollToSelection\n });\n }\n setContent(content) {\n if (isNil(content)) {\n return;\n }\n const {\n state\n } = this.view;\n const {\n tr,\n doc\n } = state;\n const newDoc = parseContent(content, this.schema, this.options.parseOptions);\n tr.replaceWith(0, state.doc.content.size, newDoc);\n // don't emit if both content is same\n if (doc.eq(tr.doc)) {\n return;\n }\n if (!tr.docChanged) {\n return;\n }\n this.view.dispatch(tr);\n }\n registerPlugin(plugin) {\n const {\n state\n } = this.view;\n const plugins = [...state.plugins, plugin];\n const newState = state.reconfigure({\n plugins\n });\n this.view.updateState(newState);\n }\n destroy() {\n this.view.destroy();\n }\n}\n\n/*\n * Public API Surface of ngx-editor\n */\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { DEFAULT_TOOLBAR, Editor, FloatingMenuComponent, ImageViewComponent, MenuComponent, NGX_EDITOR_CONFIG_TOKEN, NgxEditorComponent, NgxEditorModule, NgxEditorService, TOOLBAR_FULL, TOOLBAR_MINIMAL, Validators, emptyDoc, getKeyboardShortcuts, parseContent, provideMyServiceOptions, toDoc, toHTML };\n","const isNil = val => {\n return typeof val === 'undefined' || val === null;\n};\nconst camelToDashed = str => {\n return str.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`);\n};\nconst cleanObject = obj => {\n const cleanObj = {};\n Object.keys(obj).forEach(prop => {\n if (obj[prop]) {\n cleanObj[prop] = obj[prop];\n }\n });\n return cleanObj;\n};\nconst toStyleString = obj => {\n const styles = cleanObject(obj);\n return Object.entries(styles).map(([k, v]) => `${camelToDashed(k)}:${v}`).join(';');\n};\nclass NgxEditorError extends Error {\n constructor(message) {\n super(message);\n this.name = this.constructor.name;\n }\n}\nconst uniq = () => {\n const timeStamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 7);\n return `${timeStamp}${random}`;\n};\nconst clamp = (value, min, max) => {\n return Math.min(Math.max(value, min), max);\n};\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { NgxEditorError, clamp, isNil, toStyleString, uniq };\n","import { Slice, Fragment, Mark, Node } from 'prosemirror-model';\nimport { ReplaceStep, ReplaceAroundStep, Transform } from 'prosemirror-transform';\nconst classesById = Object.create(null);\n/**\nSuperclass for editor selections. Every selection type should\nextend this. Should not be instantiated directly.\n*/\nclass Selection {\n /**\n Initialize a selection with the head and anchor and ranges. If no\n ranges are given, constructs a single range across `$anchor` and\n `$head`.\n */\n constructor(\n /**\n The resolved anchor of the selection (the side that stays in\n place when the selection is modified).\n */\n $anchor,\n /**\n The resolved head of the selection (the side that moves when\n the selection is modified).\n */\n $head, ranges) {\n this.$anchor = $anchor;\n this.$head = $head;\n this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];\n }\n /**\n The selection's anchor, as an unresolved position.\n */\n get anchor() {\n return this.$anchor.pos;\n }\n /**\n The selection's head.\n */\n get head() {\n return this.$head.pos;\n }\n /**\n The lower bound of the selection's main range.\n */\n get from() {\n return this.$from.pos;\n }\n /**\n The upper bound of the selection's main range.\n */\n get to() {\n return this.$to.pos;\n }\n /**\n The resolved lower bound of the selection's main range.\n */\n get $from() {\n return this.ranges[0].$from;\n }\n /**\n The resolved upper bound of the selection's main range.\n */\n get $to() {\n return this.ranges[0].$to;\n }\n /**\n Indicates whether the selection contains any content.\n */\n get empty() {\n let ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) if (ranges[i].$from.pos != ranges[i].$to.pos) return false;\n return true;\n }\n /**\n Get the content of this selection as a slice.\n */\n content() {\n return this.$from.doc.slice(this.from, this.to, true);\n }\n /**\n Replace the selection with a slice or, if no slice is given,\n delete the selection. Will append to the given transaction.\n */\n replace(tr, content = Slice.empty) {\n // Put the new selection at the position after the inserted\n // content. When that ended in an inline node, search backwards,\n // to get the position after that node. If not, search forward.\n let lastNode = content.content.lastChild,\n lastParent = null;\n for (let i = 0; i < content.openEnd; i++) {\n lastParent = lastNode;\n lastNode = lastNode.lastChild;\n }\n let mapFrom = tr.steps.length,\n ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let {\n $from,\n $to\n } = ranges[i],\n mapping = tr.mapping.slice(mapFrom);\n tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);\n if (i == 0) selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);\n }\n }\n /**\n Replace the selection with the given node, appending the changes\n to the given transaction.\n */\n replaceWith(tr, node) {\n let mapFrom = tr.steps.length,\n ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let {\n $from,\n $to\n } = ranges[i],\n mapping = tr.mapping.slice(mapFrom);\n let from = mapping.map($from.pos),\n to = mapping.map($to.pos);\n if (i) {\n tr.deleteRange(from, to);\n } else {\n tr.replaceRangeWith(from, to, node);\n selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);\n }\n }\n }\n /**\n Find a valid cursor or leaf node selection starting at the given\n position and searching back if `dir` is negative, and forward if\n positive. When `textOnly` is true, only consider cursor\n selections. Will return null when no valid selection position is\n found.\n */\n static findFrom($pos, dir, textOnly = false) {\n let inner = $pos.parent.inlineContent ? new TextSelection($pos) : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);\n if (inner) return inner;\n for (let depth = $pos.depth - 1; depth >= 0; depth--) {\n let found = dir < 0 ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly) : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);\n if (found) return found;\n }\n return null;\n }\n /**\n Find a valid cursor or leaf node selection near the given\n position. Searches forward first by default, but if `bias` is\n negative, it will search backwards first.\n */\n static near($pos, bias = 1) {\n return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));\n }\n /**\n Find the cursor or leaf node selection closest to the start of\n the given document. Will return an\n [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position\n exists.\n */\n static atStart(doc) {\n return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc);\n }\n /**\n Find the cursor or leaf node selection closest to the end of the\n given document.\n */\n static atEnd(doc) {\n return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc);\n }\n /**\n Deserialize the JSON representation of a selection. Must be\n implemented for custom classes (as a static class method).\n */\n static fromJSON(doc, json) {\n if (!json || !json.type) throw new RangeError(\"Invalid input for Selection.fromJSON\");\n let cls = classesById[json.type];\n if (!cls) throw new RangeError(`No selection type ${json.type} defined`);\n return cls.fromJSON(doc, json);\n }\n /**\n To be able to deserialize selections from JSON, custom selection\n classes must register themselves with an ID string, so that they\n can be disambiguated. Try to pick something that's unlikely to\n clash with classes from other modules.\n */\n static jsonID(id, selectionClass) {\n if (id in classesById) throw new RangeError(\"Duplicate use of selection JSON ID \" + id);\n classesById[id] = selectionClass;\n selectionClass.prototype.jsonID = id;\n return selectionClass;\n }\n /**\n Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,\n which is a value that can be mapped without having access to a\n current document, and later resolved to a real selection for a\n given document again. (This is used mostly by the history to\n track and restore old selections.) The default implementation of\n this method just converts the selection to a text selection and\n returns the bookmark for that.\n */\n getBookmark() {\n return TextSelection.between(this.$anchor, this.$head).getBookmark();\n }\n}\nSelection.prototype.visible = true;\n/**\nRepresents a selected range in a document.\n*/\nclass SelectionRange {\n /**\n Create a range.\n */\n constructor(\n /**\n The lower bound of the range.\n */\n $from,\n /**\n The upper bound of the range.\n */\n $to) {\n this.$from = $from;\n this.$to = $to;\n }\n}\nlet warnedAboutTextSelection = false;\nfunction checkTextSelection($pos) {\n if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {\n warnedAboutTextSelection = true;\n console[\"warn\"](\"TextSelection endpoint not pointing into a node with inline content (\" + $pos.parent.type.name + \")\");\n }\n}\n/**\nA text selection represents a classical editor selection, with a\nhead (the moving side) and anchor (immobile side), both of which\npoint into textblock nodes. It can be empty (a regular cursor\nposition).\n*/\nclass TextSelection extends Selection {\n /**\n Construct a text selection between the given points.\n */\n constructor($anchor, $head = $anchor) {\n checkTextSelection($anchor);\n checkTextSelection($head);\n super($anchor, $head);\n }\n /**\n Returns a resolved position if this is a cursor selection (an\n empty text selection), and null otherwise.\n */\n get $cursor() {\n return this.$anchor.pos == this.$head.pos ? this.$head : null;\n }\n map(doc, mapping) {\n let $head = doc.resolve(mapping.map(this.head));\n if (!$head.parent.inlineContent) return Selection.near($head);\n let $anchor = doc.resolve(mapping.map(this.anchor));\n return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);\n }\n replace(tr, content = Slice.empty) {\n super.replace(tr, content);\n if (content == Slice.empty) {\n let marks = this.$from.marksAcross(this.$to);\n if (marks) tr.ensureMarks(marks);\n }\n }\n eq(other) {\n return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;\n }\n getBookmark() {\n return new TextBookmark(this.anchor, this.head);\n }\n toJSON() {\n return {\n type: \"text\",\n anchor: this.anchor,\n head: this.head\n };\n }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\" || typeof json.head != \"number\") throw new RangeError(\"Invalid input for TextSelection.fromJSON\");\n return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head));\n }\n /**\n Create a text selection from non-resolved positions.\n */\n static create(doc, anchor, head = anchor) {\n let $anchor = doc.resolve(anchor);\n return new this($anchor, head == anchor ? $anchor : doc.resolve(head));\n }\n /**\n Return a text selection that spans the given positions or, if\n they aren't text positions, find a text selection near them.\n `bias` determines whether the method searches forward (default)\n or backwards (negative number) first. Will fall back to calling\n [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document\n doesn't contain a valid text position.\n */\n static between($anchor, $head, bias) {\n let dPos = $anchor.pos - $head.pos;\n if (!bias || dPos) bias = dPos >= 0 ? 1 : -1;\n if (!$head.parent.inlineContent) {\n let found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);\n if (found) $head = found.$head;else return Selection.near($head, bias);\n }\n if (!$anchor.parent.inlineContent) {\n if (dPos == 0) {\n $anchor = $head;\n } else {\n $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;\n if ($anchor.pos < $head.pos != dPos < 0) $anchor = $head;\n }\n }\n return new TextSelection($anchor, $head);\n }\n}\nSelection.jsonID(\"text\", TextSelection);\nclass TextBookmark {\n constructor(anchor, head) {\n this.anchor = anchor;\n this.head = head;\n }\n map(mapping) {\n return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));\n }\n resolve(doc) {\n return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head));\n }\n}\n/**\nA node selection is a selection that points at a single node. All\nnodes marked [selectable](https://prosemirror.net/docs/ref/#model.NodeSpec.selectable) can be the\ntarget of a node selection. In such a selection, `from` and `to`\npoint directly before and after the selected node, `anchor` equals\n`from`, and `head` equals `to`..\n*/\nclass NodeSelection extends Selection {\n /**\n Create a node selection. Does not verify the validity of its\n argument.\n */\n constructor($pos) {\n let node = $pos.nodeAfter;\n let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);\n super($pos, $end);\n this.node = node;\n }\n map(doc, mapping) {\n let {\n deleted,\n pos\n } = mapping.mapResult(this.anchor);\n let $pos = doc.resolve(pos);\n if (deleted) return Selection.near($pos);\n return new NodeSelection($pos);\n }\n content() {\n return new Slice(Fragment.from(this.node), 0, 0);\n }\n eq(other) {\n return other instanceof NodeSelection && other.anchor == this.anchor;\n }\n toJSON() {\n return {\n type: \"node\",\n anchor: this.anchor\n };\n }\n getBookmark() {\n return new NodeBookmark(this.anchor);\n }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\") throw new RangeError(\"Invalid input for NodeSelection.fromJSON\");\n return new NodeSelection(doc.resolve(json.anchor));\n }\n /**\n Create a node selection from non-resolved positions.\n */\n static create(doc, from) {\n return new NodeSelection(doc.resolve(from));\n }\n /**\n Determines whether the given node may be selected as a node\n selection.\n */\n static isSelectable(node) {\n return !node.isText && node.type.spec.selectable !== false;\n }\n}\nNodeSelection.prototype.visible = false;\nSelection.jsonID(\"node\", NodeSelection);\nclass NodeBookmark {\n constructor(anchor) {\n this.anchor = anchor;\n }\n map(mapping) {\n let {\n deleted,\n pos\n } = mapping.mapResult(this.anchor);\n return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);\n }\n resolve(doc) {\n let $pos = doc.resolve(this.anchor),\n node = $pos.nodeAfter;\n if (node && NodeSelection.isSelectable(node)) return new NodeSelection($pos);\n return Selection.near($pos);\n }\n}\n/**\nA selection type that represents selecting the whole document\n(which can not necessarily be expressed with a text selection, when\nthere are for example leaf block nodes at the start or end of the\ndocument).\n*/\nclass AllSelection extends Selection {\n /**\n Create an all-selection over the given document.\n */\n constructor(doc) {\n super(doc.resolve(0), doc.resolve(doc.content.size));\n }\n replace(tr, content = Slice.empty) {\n if (content == Slice.empty) {\n tr.delete(0, tr.doc.content.size);\n let sel = Selection.atStart(tr.doc);\n if (!sel.eq(tr.selection)) tr.setSelection(sel);\n } else {\n super.replace(tr, content);\n }\n }\n toJSON() {\n return {\n type: \"all\"\n };\n }\n /**\n @internal\n */\n static fromJSON(doc) {\n return new AllSelection(doc);\n }\n map(doc) {\n return new AllSelection(doc);\n }\n eq(other) {\n return other instanceof AllSelection;\n }\n getBookmark() {\n return AllBookmark;\n }\n}\nSelection.jsonID(\"all\", AllSelection);\nconst AllBookmark = {\n map() {\n return this;\n },\n resolve(doc) {\n return new AllSelection(doc);\n }\n};\n// FIXME we'll need some awareness of text direction when scanning for selections\n// Try to find a selection inside the given node. `pos` points at the\n// position where the search starts. When `text` is true, only return\n// text selections.\nfunction findSelectionIn(doc, node, pos, index, dir, text = false) {\n if (node.inlineContent) return TextSelection.create(doc, pos);\n for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n let child = node.child(i);\n if (!child.isAtom) {\n let inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n if (inner) return inner;\n } else if (!text && NodeSelection.isSelectable(child)) {\n return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0));\n }\n pos += child.nodeSize * dir;\n }\n return null;\n}\nfunction selectionToInsertionEnd(tr, startLen, bias) {\n let last = tr.steps.length - 1;\n if (last < startLen) return;\n let step = tr.steps[last];\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) return;\n let map = tr.mapping.maps[last],\n end;\n map.forEach((_from, _to, _newFrom, newTo) => {\n if (end == null) end = newTo;\n });\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias));\n}\nconst UPDATED_SEL = 1,\n UPDATED_MARKS = 2,\n UPDATED_SCROLL = 4;\n/**\nAn editor state transaction, which can be applied to a state to\ncreate an updated state. Use\n[`EditorState.tr`](https://prosemirror.net/docs/ref/#state.EditorState.tr) to create an instance.\n\nTransactions track changes to the document (they are a subclass of\n[`Transform`](https://prosemirror.net/docs/ref/#transform.Transform)), but also other state changes,\nlike selection updates and adjustments of the set of [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks). In addition, you can store\nmetadata properties in a transaction, which are extra pieces of\ninformation that client code or plugins can use to describe what a\ntransaction represents, so that they can update their [own\nstate](https://prosemirror.net/docs/ref/#state.StateField) accordingly.\n\nThe [editor view](https://prosemirror.net/docs/ref/#view.EditorView) uses a few metadata\nproperties: it will attach a property `\"pointer\"` with the value\n`true` to selection transactions directly caused by mouse or touch\ninput, a `\"composition\"` property holding an ID identifying the\ncomposition that caused it to transactions caused by composed DOM\ninput, and a `\"uiEvent\"` property of that may be `\"paste\"`,\n`\"cut\"`, or `\"drop\"`.\n*/\nclass Transaction extends Transform {\n /**\n @internal\n */\n constructor(state) {\n super(state.doc);\n // The step count for which the current selection is valid.\n this.curSelectionFor = 0;\n // Bitfield to track which aspects of the state were updated by\n // this transaction.\n this.updated = 0;\n // Object used to store metadata properties for the transaction.\n this.meta = Object.create(null);\n this.time = Date.now();\n this.curSelection = state.selection;\n this.storedMarks = state.storedMarks;\n }\n /**\n The transaction's current selection. This defaults to the editor\n selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the\n transaction, but can be overwritten with\n [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).\n */\n get selection() {\n if (this.curSelectionFor < this.steps.length) {\n this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));\n this.curSelectionFor = this.steps.length;\n }\n return this.curSelection;\n }\n /**\n Update the transaction's current selection. Will determine the\n selection that the editor gets when the transaction is applied.\n */\n setSelection(selection) {\n if (selection.$from.doc != this.doc) throw new RangeError(\"Selection passed to setSelection must point at the current document\");\n this.curSelection = selection;\n this.curSelectionFor = this.steps.length;\n this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;\n this.storedMarks = null;\n return this;\n }\n /**\n Whether the selection was explicitly updated by this transaction.\n */\n get selectionSet() {\n return (this.updated & UPDATED_SEL) > 0;\n }\n /**\n Set the current stored marks.\n */\n setStoredMarks(marks) {\n this.storedMarks = marks;\n this.updated |= UPDATED_MARKS;\n return this;\n }\n /**\n Make sure the current stored marks or, if that is null, the marks\n at the selection, match the given set of marks. Does nothing if\n this is already the case.\n */\n ensureMarks(marks) {\n if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks)) this.setStoredMarks(marks);\n return this;\n }\n /**\n Add a mark to the set of stored marks.\n */\n addStoredMark(mark) {\n return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Remove a mark or mark type from the set of stored marks.\n */\n removeStoredMark(mark) {\n return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Whether the stored marks were explicitly set for this transaction.\n */\n get storedMarksSet() {\n return (this.updated & UPDATED_MARKS) > 0;\n }\n /**\n @internal\n */\n addStep(step, doc) {\n super.addStep(step, doc);\n this.updated = this.updated & ~UPDATED_MARKS;\n this.storedMarks = null;\n }\n /**\n Update the timestamp for the transaction.\n */\n setTime(time) {\n this.time = time;\n return this;\n }\n /**\n Replace the current selection with the given slice.\n */\n replaceSelection(slice) {\n this.selection.replace(this, slice);\n return this;\n }\n /**\n Replace the selection with the given node. When `inheritMarks` is\n true and the content is inline, it inherits the marks from the\n place where it is inserted.\n */\n replaceSelectionWith(node, inheritMarks = true) {\n let selection = this.selection;\n if (inheritMarks) node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : selection.$from.marksAcross(selection.$to) || Mark.none));\n selection.replaceWith(this, node);\n return this;\n }\n /**\n Delete the selection.\n */\n deleteSelection() {\n this.selection.replace(this);\n return this;\n }\n /**\n Replace the given range, or the selection if no range is given,\n with a text node containing the given string.\n */\n insertText(text, from, to) {\n let schema = this.doc.type.schema;\n if (from == null) {\n if (!text) return this.deleteSelection();\n return this.replaceSelectionWith(schema.text(text), true);\n } else {\n if (to == null) to = from;\n to = to == null ? from : to;\n if (!text) return this.deleteRange(from, to);\n let marks = this.storedMarks;\n if (!marks) {\n let $from = this.doc.resolve(from);\n marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));\n }\n this.replaceRangeWith(from, to, schema.text(text, marks));\n if (!this.selection.empty) this.setSelection(Selection.near(this.selection.$to));\n return this;\n }\n }\n /**\n Store a metadata property in this transaction, keyed either by\n name or by plugin.\n */\n setMeta(key, value) {\n this.meta[typeof key == \"string\" ? key : key.key] = value;\n return this;\n }\n /**\n Retrieve a metadata property for a given name or plugin.\n */\n getMeta(key) {\n return this.meta[typeof key == \"string\" ? key : key.key];\n }\n /**\n Returns true if this transaction doesn't contain any metadata,\n and can thus safely be extended.\n */\n get isGeneric() {\n for (let _ in this.meta) return false;\n return true;\n }\n /**\n Indicate that the editor should scroll the selection into view\n when updated to the state produced by this transaction.\n */\n scrollIntoView() {\n this.updated |= UPDATED_SCROLL;\n return this;\n }\n /**\n True when this transaction has had `scrollIntoView` called on it.\n */\n get scrolledIntoView() {\n return (this.updated & UPDATED_SCROLL) > 0;\n }\n}\nfunction bind(f, self) {\n return !self || !f ? f : f.bind(self);\n}\nclass FieldDesc {\n constructor(name, desc, self) {\n this.name = name;\n this.init = bind(desc.init, self);\n this.apply = bind(desc.apply, self);\n }\n}\nconst baseFields = [new FieldDesc(\"doc\", {\n init(config) {\n return config.doc || config.schema.topNodeType.createAndFill();\n },\n apply(tr) {\n return tr.doc;\n }\n}), new FieldDesc(\"selection\", {\n init(config, instance) {\n return config.selection || Selection.atStart(instance.doc);\n },\n apply(tr) {\n return tr.selection;\n }\n}), new FieldDesc(\"storedMarks\", {\n init(config) {\n return config.storedMarks || null;\n },\n apply(tr, _marks, _old, state) {\n return state.selection.$cursor ? tr.storedMarks : null;\n }\n}), new FieldDesc(\"scrollToSelection\", {\n init() {\n return 0;\n },\n apply(tr, prev) {\n return tr.scrolledIntoView ? prev + 1 : prev;\n }\n})];\n// Object wrapping the part of a state object that stays the same\n// across transactions. Stored in the state's `config` property.\nclass Configuration {\n constructor(schema, plugins) {\n this.schema = schema;\n this.plugins = [];\n this.pluginsByKey = Object.create(null);\n this.fields = baseFields.slice();\n if (plugins) plugins.forEach(plugin => {\n if (this.pluginsByKey[plugin.key]) throw new RangeError(\"Adding different instances of a keyed plugin (\" + plugin.key + \")\");\n this.plugins.push(plugin);\n this.pluginsByKey[plugin.key] = plugin;\n if (plugin.spec.state) this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));\n });\n }\n}\n/**\nThe state of a ProseMirror editor is represented by an object of\nthis type. A state is a persistent data structure—it isn't\nupdated, but rather a new state value is computed from an old one\nusing the [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) method.\n\nA state holds a number of built-in fields, and plugins can\n[define](https://prosemirror.net/docs/ref/#state.PluginSpec.state) additional fields.\n*/\nclass EditorState {\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n config) {\n this.config = config;\n }\n /**\n The schema of the state's document.\n */\n get schema() {\n return this.config.schema;\n }\n /**\n The plugins that are active in this state.\n */\n get plugins() {\n return this.config.plugins;\n }\n /**\n Apply the given transaction to produce a new state.\n */\n apply(tr) {\n return this.applyTransaction(tr).state;\n }\n /**\n @internal\n */\n filterTransaction(tr, ignore = -1) {\n for (let i = 0; i < this.config.plugins.length; i++) if (i != ignore) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this)) return false;\n }\n return true;\n }\n /**\n Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that\n returns the precise transactions that were applied (which might\n be influenced by the [transaction\n hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of\n plugins) along with the new state.\n */\n applyTransaction(rootTr) {\n if (!this.filterTransaction(rootTr)) return {\n state: this,\n transactions: []\n };\n let trs = [rootTr],\n newState = this.applyInner(rootTr),\n seen = null;\n // This loop repeatedly gives plugins a chance to respond to\n // transactions as new transactions are added, making sure to only\n // pass the transactions the plugin did not see before.\n for (;;) {\n let haveNew = false;\n for (let i = 0; i < this.config.plugins.length; i++) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.appendTransaction) {\n let n = seen ? seen[i].n : 0,\n oldState = seen ? seen[i].state : this;\n let tr = n < trs.length && plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);\n if (tr && newState.filterTransaction(tr, i)) {\n tr.setMeta(\"appendedTransaction\", rootTr);\n if (!seen) {\n seen = [];\n for (let j = 0; j < this.config.plugins.length; j++) seen.push(j < i ? {\n state: newState,\n n: trs.length\n } : {\n state: this,\n n: 0\n });\n }\n trs.push(tr);\n newState = newState.applyInner(tr);\n haveNew = true;\n }\n if (seen) seen[i] = {\n state: newState,\n n: trs.length\n };\n }\n }\n if (!haveNew) return {\n state: newState,\n transactions: trs\n };\n }\n }\n /**\n @internal\n */\n applyInner(tr) {\n if (!tr.before.eq(this.doc)) throw new RangeError(\"Applying a mismatched transaction\");\n let newInstance = new EditorState(this.config),\n fields = this.config.fields;\n for (let i = 0; i < fields.length; i++) {\n let field = fields[i];\n newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);\n }\n return newInstance;\n }\n /**\n Start a [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.\n */\n get tr() {\n return new Transaction(this);\n }\n /**\n Create a new state.\n */\n static create(config) {\n let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);\n let instance = new EditorState($config);\n for (let i = 0; i < $config.fields.length; i++) instance[$config.fields[i].name] = $config.fields[i].init(config, instance);\n return instance;\n }\n /**\n Create a new state based on this one, but with an adjusted set\n of active plugins. State fields that exist in both sets of\n plugins are kept unchanged. Those that no longer exist are\n dropped, and those that are new are initialized using their\n [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new\n configuration object..\n */\n reconfigure(config) {\n let $config = new Configuration(this.schema, config.plugins);\n let fields = $config.fields,\n instance = new EditorState($config);\n for (let i = 0; i < fields.length; i++) {\n let name = fields[i].name;\n instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);\n }\n return instance;\n }\n /**\n Serialize this state to JSON. If you want to serialize the state\n of plugins, pass an object mapping property names to use in the\n resulting JSON object to plugin objects. The argument may also be\n a string or number, in which case it is ignored, to support the\n way `JSON.stringify` calls `toString` methods.\n */\n toJSON(pluginFields) {\n let result = {\n doc: this.doc.toJSON(),\n selection: this.selection.toJSON()\n };\n if (this.storedMarks) result.storedMarks = this.storedMarks.map(m => m.toJSON());\n if (pluginFields && typeof pluginFields == 'object') for (let prop in pluginFields) {\n if (prop == \"doc\" || prop == \"selection\") throw new RangeError(\"The JSON fields `doc` and `selection` are reserved\");\n let plugin = pluginFields[prop],\n state = plugin.spec.state;\n if (state && state.toJSON) result[prop] = state.toJSON.call(plugin, this[plugin.key]);\n }\n return result;\n }\n /**\n Deserialize a JSON representation of a state. `config` should\n have at least a `schema` field, and should contain array of\n plugins to initialize the state with. `pluginFields` can be used\n to deserialize the state of plugins, by associating plugin\n instances with the property names they use in the JSON object.\n */\n static fromJSON(config, json, pluginFields) {\n if (!json) throw new RangeError(\"Invalid input for EditorState.fromJSON\");\n if (!config.schema) throw new RangeError(\"Required config field 'schema' missing\");\n let $config = new Configuration(config.schema, config.plugins);\n let instance = new EditorState($config);\n $config.fields.forEach(field => {\n if (field.name == \"doc\") {\n instance.doc = Node.fromJSON(config.schema, json.doc);\n } else if (field.name == \"selection\") {\n instance.selection = Selection.fromJSON(instance.doc, json.selection);\n } else if (field.name == \"storedMarks\") {\n if (json.storedMarks) instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);\n } else {\n if (pluginFields) for (let prop in pluginFields) {\n let plugin = pluginFields[prop],\n state = plugin.spec.state;\n if (plugin.key == field.name && state && state.fromJSON && Object.prototype.hasOwnProperty.call(json, prop)) {\n instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);\n return;\n }\n }\n instance[field.name] = field.init(config, instance);\n }\n });\n return instance;\n }\n}\nfunction bindProps(obj, self, target) {\n for (let prop in obj) {\n let val = obj[prop];\n if (val instanceof Function) val = val.bind(self);else if (prop == \"handleDOMEvents\") val = bindProps(val, self, {});\n target[prop] = val;\n }\n return target;\n}\n/**\nPlugins bundle functionality that can be added to an editor.\nThey are part of the [editor state](https://prosemirror.net/docs/ref/#state.EditorState) and\nmay influence that state and the view that contains it.\n*/\nclass Plugin {\n /**\n Create a plugin.\n */\n constructor(\n /**\n The plugin's [spec object](https://prosemirror.net/docs/ref/#state.PluginSpec).\n */\n spec) {\n this.spec = spec;\n /**\n The [props](https://prosemirror.net/docs/ref/#view.EditorProps) exported by this plugin.\n */\n this.props = {};\n if (spec.props) bindProps(spec.props, this, this.props);\n this.key = spec.key ? spec.key.key : createKey(\"plugin\");\n }\n /**\n Extract the plugin's state field from an editor state.\n */\n getState(state) {\n return state[this.key];\n }\n}\nconst keys = Object.create(null);\nfunction createKey(name) {\n if (name in keys) return name + \"$\" + ++keys[name];\n keys[name] = 0;\n return name + \"$\";\n}\n/**\nA key is used to [tag](https://prosemirror.net/docs/ref/#state.PluginSpec.key) plugins in a way\nthat makes it possible to find them, given an editor state.\nAssigning a key does mean only one plugin of that type can be\nactive in a state.\n*/\nclass PluginKey {\n /**\n Create a plugin key.\n */\n constructor(name = \"key\") {\n this.key = createKey(name);\n }\n /**\n Get the active plugin with this key, if any, from an editor\n state.\n */\n get(state) {\n return state.config.pluginsByKey[this.key];\n }\n /**\n Get the plugin's state from an editor state.\n */\n getState(state) {\n return state[this.key];\n }\n}\nexport { AllSelection, EditorState, NodeSelection, Plugin, PluginKey, Selection, SelectionRange, TextSelection, Transaction };","import OrderedMap from 'orderedmap';\nfunction findDiffStart(a, b, pos) {\n for (let i = 0;; i++) {\n if (i == a.childCount || i == b.childCount) return a.childCount == b.childCount ? null : pos;\n let childA = a.child(i),\n childB = b.child(i);\n if (childA == childB) {\n pos += childA.nodeSize;\n continue;\n }\n if (!childA.sameMarkup(childB)) return pos;\n if (childA.isText && childA.text != childB.text) {\n for (let j = 0; childA.text[j] == childB.text[j]; j++) pos++;\n return pos;\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffStart(childA.content, childB.content, pos + 1);\n if (inner != null) return inner;\n }\n pos += childA.nodeSize;\n }\n}\nfunction findDiffEnd(a, b, posA, posB) {\n for (let iA = a.childCount, iB = b.childCount;;) {\n if (iA == 0 || iB == 0) return iA == iB ? null : {\n a: posA,\n b: posB\n };\n let childA = a.child(--iA),\n childB = b.child(--iB),\n size = childA.nodeSize;\n if (childA == childB) {\n posA -= size;\n posB -= size;\n continue;\n }\n if (!childA.sameMarkup(childB)) return {\n a: posA,\n b: posB\n };\n if (childA.isText && childA.text != childB.text) {\n let same = 0,\n minSize = Math.min(childA.text.length, childB.text.length);\n while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {\n same++;\n posA--;\n posB--;\n }\n return {\n a: posA,\n b: posB\n };\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);\n if (inner) return inner;\n }\n posA -= size;\n posB -= size;\n }\n}\n\n/**\nA fragment represents a node's collection of child nodes.\n\nLike nodes, fragments are persistent data structures, and you\nshould not mutate them or their content. Rather, you create new\ninstances whenever needed. The API tries to make this easy.\n*/\nclass Fragment {\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n content, size) {\n this.content = content;\n this.size = size || 0;\n if (size == null) for (let i = 0; i < content.length; i++) this.size += content[i].nodeSize;\n }\n /**\n Invoke a callback for all descendant nodes between the given two\n positions (relative to start of this fragment). Doesn't descend\n into a node when the callback returns `false`.\n */\n nodesBetween(from, to, f, nodeStart = 0, parent) {\n for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i],\n end = pos + child.nodeSize;\n if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {\n let start = pos + 1;\n child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);\n }\n pos = end;\n }\n }\n /**\n Call the given callback for every descendant node. `pos` will be\n relative to the start of the fragment. The callback may return\n `false` to prevent traversal of a given node's children.\n */\n descendants(f) {\n this.nodesBetween(0, this.size, f);\n }\n /**\n Extract the text between `from` and `to`. See the same method on\n [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).\n */\n textBetween(from, to, blockSeparator, leafText) {\n let text = \"\",\n first = true;\n this.nodesBetween(from, to, (node, pos) => {\n let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos) : !node.isLeaf ? \"\" : leafText ? typeof leafText === \"function\" ? leafText(node) : leafText : node.type.spec.leafText ? node.type.spec.leafText(node) : \"\";\n if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {\n if (first) first = false;else text += blockSeparator;\n }\n text += nodeText;\n }, 0);\n return text;\n }\n /**\n Create a new fragment containing the combined content of this\n fragment and the other.\n */\n append(other) {\n if (!other.size) return this;\n if (!this.size) return other;\n let last = this.lastChild,\n first = other.firstChild,\n content = this.content.slice(),\n i = 0;\n if (last.isText && last.sameMarkup(first)) {\n content[content.length - 1] = last.withText(last.text + first.text);\n i = 1;\n }\n for (; i < other.content.length; i++) content.push(other.content[i]);\n return new Fragment(content, this.size + other.size);\n }\n /**\n Cut out the sub-fragment between the two given positions.\n */\n cut(from, to = this.size) {\n if (from == 0 && to == this.size) return this;\n let result = [],\n size = 0;\n if (to > from) for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i],\n end = pos + child.nodeSize;\n if (end > from) {\n if (pos < from || end > to) {\n if (child.isText) child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));else child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));\n }\n result.push(child);\n size += child.nodeSize;\n }\n pos = end;\n }\n return new Fragment(result, size);\n }\n /**\n @internal\n */\n cutByIndex(from, to) {\n if (from == to) return Fragment.empty;\n if (from == 0 && to == this.content.length) return this;\n return new Fragment(this.content.slice(from, to));\n }\n /**\n Create a new fragment in which the node at the given index is\n replaced by the given node.\n */\n replaceChild(index, node) {\n let current = this.content[index];\n if (current == node) return this;\n let copy = this.content.slice();\n let size = this.size + node.nodeSize - current.nodeSize;\n copy[index] = node;\n return new Fragment(copy, size);\n }\n /**\n Create a new fragment by prepending the given node to this\n fragment.\n */\n addToStart(node) {\n return new Fragment([node].concat(this.content), this.size + node.nodeSize);\n }\n /**\n Create a new fragment by appending the given node to this\n fragment.\n */\n addToEnd(node) {\n return new Fragment(this.content.concat(node), this.size + node.nodeSize);\n }\n /**\n Compare this fragment to another one.\n */\n eq(other) {\n if (this.content.length != other.content.length) return false;\n for (let i = 0; i < this.content.length; i++) if (!this.content[i].eq(other.content[i])) return false;\n return true;\n }\n /**\n The first child of the fragment, or `null` if it is empty.\n */\n get firstChild() {\n return this.content.length ? this.content[0] : null;\n }\n /**\n The last child of the fragment, or `null` if it is empty.\n */\n get lastChild() {\n return this.content.length ? this.content[this.content.length - 1] : null;\n }\n /**\n The number of child nodes in this fragment.\n */\n get childCount() {\n return this.content.length;\n }\n /**\n Get the child node at the given index. Raise an error when the\n index is out of range.\n */\n child(index) {\n let found = this.content[index];\n if (!found) throw new RangeError(\"Index \" + index + \" out of range for \" + this);\n return found;\n }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) {\n return this.content[index] || null;\n }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) {\n for (let i = 0, p = 0; i < this.content.length; i++) {\n let child = this.content[i];\n f(child, p, i);\n p += child.nodeSize;\n }\n }\n /**\n Find the first position at which this fragment and another\n fragment differ, or `null` if they are the same.\n */\n findDiffStart(other, pos = 0) {\n return findDiffStart(this, other, pos);\n }\n /**\n Find the first position, searching from the end, at which this\n fragment and the given fragment differ, or `null` if they are\n the same. Since this position will not be the same in both\n nodes, an object with two separate positions is returned.\n */\n findDiffEnd(other, pos = this.size, otherPos = other.size) {\n return findDiffEnd(this, other, pos, otherPos);\n }\n /**\n Find the index and inner offset corresponding to a given relative\n position in this fragment. The result object will be reused\n (overwritten) the next time the function is called. @internal\n */\n findIndex(pos, round = -1) {\n if (pos == 0) return retIndex(0, pos);\n if (pos == this.size) return retIndex(this.content.length, pos);\n if (pos > this.size || pos < 0) throw new RangeError(`Position ${pos} outside of fragment (${this})`);\n for (let i = 0, curPos = 0;; i++) {\n let cur = this.child(i),\n end = curPos + cur.nodeSize;\n if (end >= pos) {\n if (end == pos || round > 0) return retIndex(i + 1, end);\n return retIndex(i, curPos);\n }\n curPos = end;\n }\n }\n /**\n Return a debugging string that describes this fragment.\n */\n toString() {\n return \"<\" + this.toStringInner() + \">\";\n }\n /**\n @internal\n */\n toStringInner() {\n return this.content.join(\", \");\n }\n /**\n Create a JSON-serializeable representation of this fragment.\n */\n toJSON() {\n return this.content.length ? this.content.map(n => n.toJSON()) : null;\n }\n /**\n Deserialize a fragment from its JSON representation.\n */\n static fromJSON(schema, value) {\n if (!value) return Fragment.empty;\n if (!Array.isArray(value)) throw new RangeError(\"Invalid input for Fragment.fromJSON\");\n return new Fragment(value.map(schema.nodeFromJSON));\n }\n /**\n Build a fragment from an array of nodes. Ensures that adjacent\n text nodes with the same marks are joined together.\n */\n static fromArray(array) {\n if (!array.length) return Fragment.empty;\n let joined,\n size = 0;\n for (let i = 0; i < array.length; i++) {\n let node = array[i];\n size += node.nodeSize;\n if (i && node.isText && array[i - 1].sameMarkup(node)) {\n if (!joined) joined = array.slice(0, i);\n joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text);\n } else if (joined) {\n joined.push(node);\n }\n }\n return new Fragment(joined || array, size);\n }\n /**\n Create a fragment from something that can be interpreted as a\n set of nodes. For `null`, it returns the empty fragment. For a\n fragment, the fragment itself. For a node or array of nodes, a\n fragment containing those nodes.\n */\n static from(nodes) {\n if (!nodes) return Fragment.empty;\n if (nodes instanceof Fragment) return nodes;\n if (Array.isArray(nodes)) return this.fromArray(nodes);\n if (nodes.attrs) return new Fragment([nodes], nodes.nodeSize);\n throw new RangeError(\"Can not convert \" + nodes + \" to a Fragment\" + (nodes.nodesBetween ? \" (looks like multiple versions of prosemirror-model were loaded)\" : \"\"));\n }\n}\n/**\nAn empty fragment. Intended to be reused whenever a node doesn't\ncontain anything (rather than allocating a new empty fragment for\neach leaf node).\n*/\nFragment.empty = new Fragment([], 0);\nconst found = {\n index: 0,\n offset: 0\n};\nfunction retIndex(index, offset) {\n found.index = index;\n found.offset = offset;\n return found;\n}\nfunction compareDeep(a, b) {\n if (a === b) return true;\n if (!(a && typeof a == \"object\") || !(b && typeof b == \"object\")) return false;\n let array = Array.isArray(a);\n if (Array.isArray(b) != array) return false;\n if (array) {\n if (a.length != b.length) return false;\n for (let i = 0; i < a.length; i++) if (!compareDeep(a[i], b[i])) return false;\n } else {\n for (let p in a) if (!(p in b) || !compareDeep(a[p], b[p])) return false;\n for (let p in b) if (!(p in a)) return false;\n }\n return true;\n}\n\n/**\nA mark is a piece of information that can be attached to a node,\nsuch as it being emphasized, in code font, or a link. It has a\ntype and optionally a set of attributes that provide further\ninformation (such as the target of the link). Marks are created\nthrough a `Schema`, which controls which types exist and which\nattributes they have.\n*/\nlet Mark = /*#__PURE__*/(() => {\n class Mark {\n /**\n @internal\n */\n constructor(\n /**\n The type of this mark.\n */\n type,\n /**\n The attributes associated with this mark.\n */\n attrs) {\n this.type = type;\n this.attrs = attrs;\n }\n /**\n Given a set of marks, create a new set which contains this one as\n well, in the right position. If this mark is already in the set,\n the set itself is returned. If any marks that are set to be\n [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,\n those are replaced by this one.\n */\n addToSet(set) {\n let copy,\n placed = false;\n for (let i = 0; i < set.length; i++) {\n let other = set[i];\n if (this.eq(other)) return set;\n if (this.type.excludes(other.type)) {\n if (!copy) copy = set.slice(0, i);\n } else if (other.type.excludes(this.type)) {\n return set;\n } else {\n if (!placed && other.type.rank > this.type.rank) {\n if (!copy) copy = set.slice(0, i);\n copy.push(this);\n placed = true;\n }\n if (copy) copy.push(other);\n }\n }\n if (!copy) copy = set.slice();\n if (!placed) copy.push(this);\n return copy;\n }\n /**\n Remove this mark from the given set, returning a new set. If this\n mark is not in the set, the set itself is returned.\n */\n removeFromSet(set) {\n for (let i = 0; i < set.length; i++) if (this.eq(set[i])) return set.slice(0, i).concat(set.slice(i + 1));\n return set;\n }\n /**\n Test whether this mark is in the given set of marks.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++) if (this.eq(set[i])) return true;\n return false;\n }\n /**\n Test whether this mark has the same type and attributes as\n another mark.\n */\n eq(other) {\n return this == other || this.type == other.type && compareDeep(this.attrs, other.attrs);\n }\n /**\n Convert this mark to a JSON-serializeable representation.\n */\n toJSON() {\n let obj = {\n type: this.type.name\n };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n return obj;\n }\n /**\n Deserialize a mark from JSON.\n */\n static fromJSON(schema, json) {\n if (!json) throw new RangeError(\"Invalid input for Mark.fromJSON\");\n let type = schema.marks[json.type];\n if (!type) throw new RangeError(`There is no mark type ${json.type} in this schema`);\n let mark = type.create(json.attrs);\n type.checkAttrs(mark.attrs);\n return mark;\n }\n /**\n Test whether two sets of marks are identical.\n */\n static sameSet(a, b) {\n if (a == b) return true;\n if (a.length != b.length) return false;\n for (let i = 0; i < a.length; i++) if (!a[i].eq(b[i])) return false;\n return true;\n }\n /**\n Create a properly sorted mark set from null, a single mark, or an\n unsorted array of marks.\n */\n static setFrom(marks) {\n if (!marks || Array.isArray(marks) && marks.length == 0) return Mark.none;\n if (marks instanceof Mark) return [marks];\n let copy = marks.slice();\n copy.sort((a, b) => a.type.rank - b.type.rank);\n return copy;\n }\n }\n /**\n The empty set of marks.\n */\n Mark.none = [];\n\n /**\n Error type raised by [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) when\n given an invalid replacement.\n */\n return Mark;\n})();\nclass ReplaceError extends Error {}\n/*\nReplaceError = function(this: any, message: string) {\n let err = Error.call(this, message)\n ;(err as any).__proto__ = ReplaceError.prototype\n return err\n} as any\n\nReplaceError.prototype = Object.create(Error.prototype)\nReplaceError.prototype.constructor = ReplaceError\nReplaceError.prototype.name = \"ReplaceError\"\n*/\n/**\nA slice represents a piece cut out of a larger document. It\nstores not only a fragment, but also the depth up to which nodes on\nboth side are ‘open’ (cut through).\n*/\nclass Slice {\n /**\n Create a slice. When specifying a non-zero open depth, you must\n make sure that there are nodes of at least that depth at the\n appropriate side of the fragment—i.e. if the fragment is an\n empty paragraph node, `openStart` and `openEnd` can't be greater\n than 1.\n \n It is not necessary for the content of open nodes to conform to\n the schema's content constraints, though it should be a valid\n start/end/middle for such a node, depending on which sides are\n open.\n */\n constructor(\n /**\n The slice's content.\n */\n content,\n /**\n The open depth at the start of the fragment.\n */\n openStart,\n /**\n The open depth at the end.\n */\n openEnd) {\n this.content = content;\n this.openStart = openStart;\n this.openEnd = openEnd;\n }\n /**\n The size this slice would add when inserted into a document.\n */\n get size() {\n return this.content.size - this.openStart - this.openEnd;\n }\n /**\n @internal\n */\n insertAt(pos, fragment) {\n let content = insertInto(this.content, pos + this.openStart, fragment);\n return content && new Slice(content, this.openStart, this.openEnd);\n }\n /**\n @internal\n */\n removeBetween(from, to) {\n return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);\n }\n /**\n Tests whether this slice is equal to another slice.\n */\n eq(other) {\n return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;\n }\n /**\n @internal\n */\n toString() {\n return this.content + \"(\" + this.openStart + \",\" + this.openEnd + \")\";\n }\n /**\n Convert a slice to a JSON-serializable representation.\n */\n toJSON() {\n if (!this.content.size) return null;\n let json = {\n content: this.content.toJSON()\n };\n if (this.openStart > 0) json.openStart = this.openStart;\n if (this.openEnd > 0) json.openEnd = this.openEnd;\n return json;\n }\n /**\n Deserialize a slice from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json) return Slice.empty;\n let openStart = json.openStart || 0,\n openEnd = json.openEnd || 0;\n if (typeof openStart != \"number\" || typeof openEnd != \"number\") throw new RangeError(\"Invalid input for Slice.fromJSON\");\n return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);\n }\n /**\n Create a slice from a fragment by taking the maximum possible\n open value on both side of the fragment.\n */\n static maxOpen(fragment, openIsolating = true) {\n let openStart = 0,\n openEnd = 0;\n for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild) openStart++;\n for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild) openEnd++;\n return new Slice(fragment, openStart, openEnd);\n }\n}\n/**\nThe empty slice.\n*/\nSlice.empty = new Slice(Fragment.empty, 0, 0);\nfunction removeRange(content, from, to) {\n let {\n index,\n offset\n } = content.findIndex(from),\n child = content.maybeChild(index);\n let {\n index: indexTo,\n offset: offsetTo\n } = content.findIndex(to);\n if (offset == from || child.isText) {\n if (offsetTo != to && !content.child(indexTo).isText) throw new RangeError(\"Removing non-flat range\");\n return content.cut(0, from).append(content.cut(to));\n }\n if (index != indexTo) throw new RangeError(\"Removing non-flat range\");\n return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));\n}\nfunction insertInto(content, dist, insert, parent) {\n let {\n index,\n offset\n } = content.findIndex(dist),\n child = content.maybeChild(index);\n if (offset == dist || child.isText) {\n if (parent && !parent.canReplace(index, index, insert)) return null;\n return content.cut(0, dist).append(insert).append(content.cut(dist));\n }\n let inner = insertInto(child.content, dist - offset - 1, insert);\n return inner && content.replaceChild(index, child.copy(inner));\n}\nfunction replace($from, $to, slice) {\n if (slice.openStart > $from.depth) throw new ReplaceError(\"Inserted content deeper than insertion position\");\n if ($from.depth - slice.openStart != $to.depth - slice.openEnd) throw new ReplaceError(\"Inconsistent open depths\");\n return replaceOuter($from, $to, slice, 0);\n}\nfunction replaceOuter($from, $to, slice, depth) {\n let index = $from.index(depth),\n node = $from.node(depth);\n if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {\n let inner = replaceOuter($from, $to, slice, depth + 1);\n return node.copy(node.content.replaceChild(index, inner));\n } else if (!slice.content.size) {\n return close(node, replaceTwoWay($from, $to, depth));\n } else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) {\n // Simple, flat case\n let parent = $from.parent,\n content = parent.content;\n return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));\n } else {\n let {\n start,\n end\n } = prepareSliceForReplace(slice, $from);\n return close(node, replaceThreeWay($from, start, end, $to, depth));\n }\n}\nfunction checkJoin(main, sub) {\n if (!sub.type.compatibleContent(main.type)) throw new ReplaceError(\"Cannot join \" + sub.type.name + \" onto \" + main.type.name);\n}\nfunction joinable($before, $after, depth) {\n let node = $before.node(depth);\n checkJoin(node, $after.node(depth));\n return node;\n}\nfunction addNode(child, target) {\n let last = target.length - 1;\n if (last >= 0 && child.isText && child.sameMarkup(target[last])) target[last] = child.withText(target[last].text + child.text);else target.push(child);\n}\nfunction addRange($start, $end, depth, target) {\n let node = ($end || $start).node(depth);\n let startIndex = 0,\n endIndex = $end ? $end.index(depth) : node.childCount;\n if ($start) {\n startIndex = $start.index(depth);\n if ($start.depth > depth) {\n startIndex++;\n } else if ($start.textOffset) {\n addNode($start.nodeAfter, target);\n startIndex++;\n }\n }\n for (let i = startIndex; i < endIndex; i++) addNode(node.child(i), target);\n if ($end && $end.depth == depth && $end.textOffset) addNode($end.nodeBefore, target);\n}\nfunction close(node, content) {\n node.type.checkContent(content);\n return node.copy(content);\n}\nfunction replaceThreeWay($from, $start, $end, $to, depth) {\n let openStart = $from.depth > depth && joinable($from, $start, depth + 1);\n let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);\n let content = [];\n addRange(null, $from, depth, content);\n if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {\n checkJoin(openStart, openEnd);\n addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);\n } else {\n if (openStart) addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);\n addRange($start, $end, depth, content);\n if (openEnd) addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content);\n}\nfunction replaceTwoWay($from, $to, depth) {\n let content = [];\n addRange(null, $from, depth, content);\n if ($from.depth > depth) {\n let type = joinable($from, $to, depth + 1);\n addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content);\n}\nfunction prepareSliceForReplace(slice, $along) {\n let extra = $along.depth - slice.openStart,\n parent = $along.node(extra);\n let node = parent.copy(slice.content);\n for (let i = extra - 1; i >= 0; i--) node = $along.node(i).copy(Fragment.from(node));\n return {\n start: node.resolveNoCache(slice.openStart + extra),\n end: node.resolveNoCache(node.content.size - slice.openEnd - extra)\n };\n}\n\n/**\nYou can [_resolve_](https://prosemirror.net/docs/ref/#model.Node.resolve) a position to get more\ninformation about it. Objects of this class represent such a\nresolved position, providing various pieces of context\ninformation, and some helper methods.\n\nThroughout this interface, methods that take an optional `depth`\nparameter will interpret undefined as `this.depth` and negative\nnumbers as `this.depth + value`.\n*/\nclass ResolvedPos {\n /**\n @internal\n */\n constructor(\n /**\n The position that was resolved.\n */\n pos,\n /**\n @internal\n */\n path,\n /**\n The offset this position has into its parent node.\n */\n parentOffset) {\n this.pos = pos;\n this.path = path;\n this.parentOffset = parentOffset;\n this.depth = path.length / 3 - 1;\n }\n /**\n @internal\n */\n resolveDepth(val) {\n if (val == null) return this.depth;\n if (val < 0) return this.depth + val;\n return val;\n }\n /**\n The parent node that the position points into. Note that even if\n a position points into a text node, that node is not considered\n the parent—text nodes are ‘flat’ in this model, and have no content.\n */\n get parent() {\n return this.node(this.depth);\n }\n /**\n The root node in which the position was resolved.\n */\n get doc() {\n return this.node(0);\n }\n /**\n The ancestor node at the given level. `p.node(p.depth)` is the\n same as `p.parent`.\n */\n node(depth) {\n return this.path[this.resolveDepth(depth) * 3];\n }\n /**\n The index into the ancestor at the given level. If this points\n at the 3rd node in the 2nd paragraph on the top level, for\n example, `p.index(0)` is 1 and `p.index(1)` is 2.\n */\n index(depth) {\n return this.path[this.resolveDepth(depth) * 3 + 1];\n }\n /**\n The index pointing after this position into the ancestor at the\n given level.\n */\n indexAfter(depth) {\n depth = this.resolveDepth(depth);\n return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);\n }\n /**\n The (absolute) position at the start of the node at the given\n level.\n */\n start(depth) {\n depth = this.resolveDepth(depth);\n return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n }\n /**\n The (absolute) position at the end of the node at the given\n level.\n */\n end(depth) {\n depth = this.resolveDepth(depth);\n return this.start(depth) + this.node(depth).content.size;\n }\n /**\n The (absolute) position directly before the wrapping node at the\n given level, or, when `depth` is `this.depth + 1`, the original\n position.\n */\n before(depth) {\n depth = this.resolveDepth(depth);\n if (!depth) throw new RangeError(\"There is no position before the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];\n }\n /**\n The (absolute) position directly after the wrapping node at the\n given level, or the original position when `depth` is `this.depth + 1`.\n */\n after(depth) {\n depth = this.resolveDepth(depth);\n if (!depth) throw new RangeError(\"There is no position after the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;\n }\n /**\n When this position points into a text node, this returns the\n distance between the position and the start of the text node.\n Will be zero for positions that point between nodes.\n */\n get textOffset() {\n return this.pos - this.path[this.path.length - 1];\n }\n /**\n Get the node directly after the position, if any. If the position\n points into a text node, only the part of that node after the\n position is returned.\n */\n get nodeAfter() {\n let parent = this.parent,\n index = this.index(this.depth);\n if (index == parent.childCount) return null;\n let dOff = this.pos - this.path[this.path.length - 1],\n child = parent.child(index);\n return dOff ? parent.child(index).cut(dOff) : child;\n }\n /**\n Get the node directly before the position, if any. If the\n position points into a text node, only the part of that node\n before the position is returned.\n */\n get nodeBefore() {\n let index = this.index(this.depth);\n let dOff = this.pos - this.path[this.path.length - 1];\n if (dOff) return this.parent.child(index).cut(0, dOff);\n return index == 0 ? null : this.parent.child(index - 1);\n }\n /**\n Get the position at the given index in the parent node at the\n given depth (which defaults to `this.depth`).\n */\n posAtIndex(index, depth) {\n depth = this.resolveDepth(depth);\n let node = this.path[depth * 3],\n pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n for (let i = 0; i < index; i++) pos += node.child(i).nodeSize;\n return pos;\n }\n /**\n Get the marks at this position, factoring in the surrounding\n marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the\n position is at the start of a non-empty node, the marks of the\n node after it (if any) are returned.\n */\n marks() {\n let parent = this.parent,\n index = this.index();\n // In an empty parent, return the empty array\n if (parent.content.size == 0) return Mark.none;\n // When inside a text node, just return the text node's marks\n if (this.textOffset) return parent.child(index).marks;\n let main = parent.maybeChild(index - 1),\n other = parent.maybeChild(index);\n // If the `after` flag is true of there is no node before, make\n // the node after this position the main reference.\n if (!main) {\n let tmp = main;\n main = other;\n other = tmp;\n }\n // Use all marks in the main node, except those that have\n // `inclusive` set to false and are not present in the other node.\n let marks = main.marks;\n for (var i = 0; i < marks.length; i++) if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks))) marks = marks[i--].removeFromSet(marks);\n return marks;\n }\n /**\n Get the marks after the current position, if any, except those\n that are non-inclusive and not present at position `$end`. This\n is mostly useful for getting the set of marks to preserve after a\n deletion. Will return `null` if this position is at the end of\n its parent node or its parent node isn't a textblock (in which\n case no marks should be preserved).\n */\n marksAcross($end) {\n let after = this.parent.maybeChild(this.index());\n if (!after || !after.isInline) return null;\n let marks = after.marks,\n next = $end.parent.maybeChild($end.index());\n for (var i = 0; i < marks.length; i++) if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks))) marks = marks[i--].removeFromSet(marks);\n return marks;\n }\n /**\n The depth up to which this position and the given (non-resolved)\n position share the same parent nodes.\n */\n sharedDepth(pos) {\n for (let depth = this.depth; depth > 0; depth--) if (this.start(depth) <= pos && this.end(depth) >= pos) return depth;\n return 0;\n }\n /**\n Returns a range based on the place where this position and the\n given position diverge around block content. If both point into\n the same textblock, for example, a range around that textblock\n will be returned. If they point into different blocks, the range\n around those blocks in their shared ancestor is returned. You can\n pass in an optional predicate that will be called with a parent\n node to see if a range into that parent is acceptable.\n */\n blockRange(other = this, pred) {\n if (other.pos < this.pos) return other.blockRange(this);\n for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--) if (other.pos <= this.end(d) && (!pred || pred(this.node(d)))) return new NodeRange(this, other, d);\n return null;\n }\n /**\n Query whether the given position shares the same parent node.\n */\n sameParent(other) {\n return this.pos - this.parentOffset == other.pos - other.parentOffset;\n }\n /**\n Return the greater of this and the given position.\n */\n max(other) {\n return other.pos > this.pos ? other : this;\n }\n /**\n Return the smaller of this and the given position.\n */\n min(other) {\n return other.pos < this.pos ? other : this;\n }\n /**\n @internal\n */\n toString() {\n let str = \"\";\n for (let i = 1; i <= this.depth; i++) str += (str ? \"/\" : \"\") + this.node(i).type.name + \"_\" + this.index(i - 1);\n return str + \":\" + this.parentOffset;\n }\n /**\n @internal\n */\n static resolve(doc, pos) {\n if (!(pos >= 0 && pos <= doc.content.size)) throw new RangeError(\"Position \" + pos + \" out of range\");\n let path = [];\n let start = 0,\n parentOffset = pos;\n for (let node = doc;;) {\n let {\n index,\n offset\n } = node.content.findIndex(parentOffset);\n let rem = parentOffset - offset;\n path.push(node, index, start + offset);\n if (!rem) break;\n node = node.child(index);\n if (node.isText) break;\n parentOffset = rem - 1;\n start += offset + 1;\n }\n return new ResolvedPos(pos, path, parentOffset);\n }\n /**\n @internal\n */\n static resolveCached(doc, pos) {\n let cache = resolveCache.get(doc);\n if (cache) {\n for (let i = 0; i < cache.elts.length; i++) {\n let elt = cache.elts[i];\n if (elt.pos == pos) return elt;\n }\n } else {\n resolveCache.set(doc, cache = new ResolveCache());\n }\n let result = cache.elts[cache.i] = ResolvedPos.resolve(doc, pos);\n cache.i = (cache.i + 1) % resolveCacheSize;\n return result;\n }\n}\nclass ResolveCache {\n constructor() {\n this.elts = [];\n this.i = 0;\n }\n}\nconst resolveCacheSize = 12,\n resolveCache = new WeakMap();\n/**\nRepresents a flat range of content, i.e. one that starts and\nends in the same node.\n*/\nclass NodeRange {\n /**\n Construct a node range. `$from` and `$to` should point into the\n same node until at least the given `depth`, since a node range\n denotes an adjacent set of nodes in a single parent node.\n */\n constructor(\n /**\n A resolved position along the start of the content. May have a\n `depth` greater than this object's `depth` property, since\n these are the positions that were used to compute the range,\n not re-resolved positions directly at its boundaries.\n */\n $from,\n /**\n A position along the end of the content. See\n caveat for [`$from`](https://prosemirror.net/docs/ref/#model.NodeRange.$from).\n */\n $to,\n /**\n The depth of the node that this range points into.\n */\n depth) {\n this.$from = $from;\n this.$to = $to;\n this.depth = depth;\n }\n /**\n The position at the start of the range.\n */\n get start() {\n return this.$from.before(this.depth + 1);\n }\n /**\n The position at the end of the range.\n */\n get end() {\n return this.$to.after(this.depth + 1);\n }\n /**\n The parent node that the range points into.\n */\n get parent() {\n return this.$from.node(this.depth);\n }\n /**\n The start index of the range in the parent node.\n */\n get startIndex() {\n return this.$from.index(this.depth);\n }\n /**\n The end index of the range in the parent node.\n */\n get endIndex() {\n return this.$to.indexAfter(this.depth);\n }\n}\nconst emptyAttrs = Object.create(null);\n/**\nThis class represents a node in the tree that makes up a\nProseMirror document. So a document is an instance of `Node`, with\nchildren that are also instances of `Node`.\n\nNodes are persistent data structures. Instead of changing them, you\ncreate new ones with the content you want. Old ones keep pointing\nat the old document shape. This is made cheaper by sharing\nstructure between the old and new data as much as possible, which a\ntree shape like this (without back pointers) makes easy.\n\n**Do not** directly mutate the properties of a `Node` object. See\n[the guide](/docs/guide/#doc) for more information.\n*/\nclass Node {\n /**\n @internal\n */\n constructor(\n /**\n The type of node that this is.\n */\n type,\n /**\n An object mapping attribute names to values. The kind of\n attributes allowed and required are\n [determined](https://prosemirror.net/docs/ref/#model.NodeSpec.attrs) by the node type.\n */\n attrs,\n // A fragment holding the node's children.\n content,\n /**\n The marks (things like whether it is emphasized or part of a\n link) applied to this node.\n */\n marks = Mark.none) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.content = content || Fragment.empty;\n }\n /**\n The size of this node, as defined by the integer-based [indexing\n scheme](/docs/guide/#doc.indexing). For text nodes, this is the\n amount of characters. For other leaf nodes, it is one. For\n non-leaf nodes, it is the size of the content plus two (the\n start and end token).\n */\n get nodeSize() {\n return this.isLeaf ? 1 : 2 + this.content.size;\n }\n /**\n The number of children that the node has.\n */\n get childCount() {\n return this.content.childCount;\n }\n /**\n Get the child node at the given index. Raises an error when the\n index is out of range.\n */\n child(index) {\n return this.content.child(index);\n }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) {\n return this.content.maybeChild(index);\n }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) {\n this.content.forEach(f);\n }\n /**\n Invoke a callback for all descendant nodes recursively between\n the given two positions that are relative to start of this\n node's content. The callback is invoked with the node, its\n position relative to the original node (method receiver),\n its parent node, and its child index. When the callback returns\n false for a given node, that node's children will not be\n recursed over. The last parameter can be used to specify a\n starting position to count from.\n */\n nodesBetween(from, to, f, startPos = 0) {\n this.content.nodesBetween(from, to, f, startPos, this);\n }\n /**\n Call the given callback for every descendant node. Doesn't\n descend into a node when the callback returns `false`.\n */\n descendants(f) {\n this.nodesBetween(0, this.content.size, f);\n }\n /**\n Concatenates all the text nodes found in this fragment and its\n children.\n */\n get textContent() {\n return this.isLeaf && this.type.spec.leafText ? this.type.spec.leafText(this) : this.textBetween(0, this.content.size, \"\");\n }\n /**\n Get all text between positions `from` and `to`. When\n `blockSeparator` is given, it will be inserted to separate text\n from different block nodes. If `leafText` is given, it'll be\n inserted for every non-text leaf node encountered, otherwise\n [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec^leafText) will be used.\n */\n textBetween(from, to, blockSeparator, leafText) {\n return this.content.textBetween(from, to, blockSeparator, leafText);\n }\n /**\n Returns this node's first child, or `null` if there are no\n children.\n */\n get firstChild() {\n return this.content.firstChild;\n }\n /**\n Returns this node's last child, or `null` if there are no\n children.\n */\n get lastChild() {\n return this.content.lastChild;\n }\n /**\n Test whether two nodes represent the same piece of document.\n */\n eq(other) {\n return this == other || this.sameMarkup(other) && this.content.eq(other.content);\n }\n /**\n Compare the markup (type, attributes, and marks) of this node to\n those of another. Returns `true` if both have the same markup.\n */\n sameMarkup(other) {\n return this.hasMarkup(other.type, other.attrs, other.marks);\n }\n /**\n Check whether this node's markup correspond to the given type,\n attributes, and marks.\n */\n hasMarkup(type, attrs, marks) {\n return this.type == type && compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && Mark.sameSet(this.marks, marks || Mark.none);\n }\n /**\n Create a new node with the same markup as this node, containing\n the given content (or empty, if no content is given).\n */\n copy(content = null) {\n if (content == this.content) return this;\n return new Node(this.type, this.attrs, content, this.marks);\n }\n /**\n Create a copy of this node, with the given set of marks instead\n of the node's own marks.\n */\n mark(marks) {\n return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks);\n }\n /**\n Create a copy of this node with only the content between the\n given positions. If `to` is not given, it defaults to the end of\n the node.\n */\n cut(from, to = this.content.size) {\n if (from == 0 && to == this.content.size) return this;\n return this.copy(this.content.cut(from, to));\n }\n /**\n Cut out the part of the document between the given positions, and\n return it as a `Slice` object.\n */\n slice(from, to = this.content.size, includeParents = false) {\n if (from == to) return Slice.empty;\n let $from = this.resolve(from),\n $to = this.resolve(to);\n let depth = includeParents ? 0 : $from.sharedDepth(to);\n let start = $from.start(depth),\n node = $from.node(depth);\n let content = node.content.cut($from.pos - start, $to.pos - start);\n return new Slice(content, $from.depth - depth, $to.depth - depth);\n }\n /**\n Replace the part of the document between the given positions with\n the given slice. The slice must 'fit', meaning its open sides\n must be able to connect to the surrounding content, and its\n content nodes must be valid children for the node they are placed\n into. If any of this is violated, an error of type\n [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.\n */\n replace(from, to, slice) {\n return replace(this.resolve(from), this.resolve(to), slice);\n }\n /**\n Find the node directly after the given position.\n */\n nodeAt(pos) {\n for (let node = this;;) {\n let {\n index,\n offset\n } = node.content.findIndex(pos);\n node = node.maybeChild(index);\n if (!node) return null;\n if (offset == pos || node.isText) return node;\n pos -= offset + 1;\n }\n }\n /**\n Find the (direct) child node after the given offset, if any,\n and return it along with its index and offset relative to this\n node.\n */\n childAfter(pos) {\n let {\n index,\n offset\n } = this.content.findIndex(pos);\n return {\n node: this.content.maybeChild(index),\n index,\n offset\n };\n }\n /**\n Find the (direct) child node before the given offset, if any,\n and return it along with its index and offset relative to this\n node.\n */\n childBefore(pos) {\n if (pos == 0) return {\n node: null,\n index: 0,\n offset: 0\n };\n let {\n index,\n offset\n } = this.content.findIndex(pos);\n if (offset < pos) return {\n node: this.content.child(index),\n index,\n offset\n };\n let node = this.content.child(index - 1);\n return {\n node,\n index: index - 1,\n offset: offset - node.nodeSize\n };\n }\n /**\n Resolve the given position in the document, returning an\n [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.\n */\n resolve(pos) {\n return ResolvedPos.resolveCached(this, pos);\n }\n /**\n @internal\n */\n resolveNoCache(pos) {\n return ResolvedPos.resolve(this, pos);\n }\n /**\n Test whether a given mark or mark type occurs in this document\n between the two given positions.\n */\n rangeHasMark(from, to, type) {\n let found = false;\n if (to > from) this.nodesBetween(from, to, node => {\n if (type.isInSet(node.marks)) found = true;\n return !found;\n });\n return found;\n }\n /**\n True when this is a block (non-inline node)\n */\n get isBlock() {\n return this.type.isBlock;\n }\n /**\n True when this is a textblock node, a block node with inline\n content.\n */\n get isTextblock() {\n return this.type.isTextblock;\n }\n /**\n True when this node allows inline content.\n */\n get inlineContent() {\n return this.type.inlineContent;\n }\n /**\n True when this is an inline node (a text node or a node that can\n appear among text).\n */\n get isInline() {\n return this.type.isInline;\n }\n /**\n True when this is a text node.\n */\n get isText() {\n return this.type.isText;\n }\n /**\n True when this is a leaf node.\n */\n get isLeaf() {\n return this.type.isLeaf;\n }\n /**\n True when this is an atom, i.e. when it does not have directly\n editable content. This is usually the same as `isLeaf`, but can\n be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)\n on a node's spec (typically used when the node is displayed as\n an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).\n */\n get isAtom() {\n return this.type.isAtom;\n }\n /**\n Return a string representation of this node for debugging\n purposes.\n */\n toString() {\n if (this.type.spec.toDebugString) return this.type.spec.toDebugString(this);\n let name = this.type.name;\n if (this.content.size) name += \"(\" + this.content.toStringInner() + \")\";\n return wrapMarks(this.marks, name);\n }\n /**\n Get the content match in this node at the given index.\n */\n contentMatchAt(index) {\n let match = this.type.contentMatch.matchFragment(this.content, 0, index);\n if (!match) throw new Error(\"Called contentMatchAt on a node with invalid content\");\n return match;\n }\n /**\n Test whether replacing the range between `from` and `to` (by\n child index) with the given replacement fragment (which defaults\n to the empty fragment) would leave the node's content valid. You\n can optionally pass `start` and `end` indices into the\n replacement fragment.\n */\n canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {\n let one = this.contentMatchAt(from).matchFragment(replacement, start, end);\n let two = one && one.matchFragment(this.content, to);\n if (!two || !two.validEnd) return false;\n for (let i = start; i < end; i++) if (!this.type.allowsMarks(replacement.child(i).marks)) return false;\n return true;\n }\n /**\n Test whether replacing the range `from` to `to` (by index) with\n a node of the given type would leave the node's content valid.\n */\n canReplaceWith(from, to, type, marks) {\n if (marks && !this.type.allowsMarks(marks)) return false;\n let start = this.contentMatchAt(from).matchType(type);\n let end = start && start.matchFragment(this.content, to);\n return end ? end.validEnd : false;\n }\n /**\n Test whether the given node's content could be appended to this\n node. If that node is empty, this will only return true if there\n is at least one node type that can appear in both nodes (to avoid\n merging completely incompatible nodes).\n */\n canAppend(other) {\n if (other.content.size) return this.canReplace(this.childCount, this.childCount, other.content);else return this.type.compatibleContent(other.type);\n }\n /**\n Check whether this node and its descendants conform to the\n schema, and raise an exception when they do not.\n */\n check() {\n this.type.checkContent(this.content);\n this.type.checkAttrs(this.attrs);\n let copy = Mark.none;\n for (let i = 0; i < this.marks.length; i++) {\n let mark = this.marks[i];\n mark.type.checkAttrs(mark.attrs);\n copy = mark.addToSet(copy);\n }\n if (!Mark.sameSet(copy, this.marks)) throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(m => m.type.name)}`);\n this.content.forEach(node => node.check());\n }\n /**\n Return a JSON-serializeable representation of this node.\n */\n toJSON() {\n let obj = {\n type: this.type.name\n };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n if (this.content.size) obj.content = this.content.toJSON();\n if (this.marks.length) obj.marks = this.marks.map(n => n.toJSON());\n return obj;\n }\n /**\n Deserialize a node from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json) throw new RangeError(\"Invalid input for Node.fromJSON\");\n let marks = undefined;\n if (json.marks) {\n if (!Array.isArray(json.marks)) throw new RangeError(\"Invalid mark data for Node.fromJSON\");\n marks = json.marks.map(schema.markFromJSON);\n }\n if (json.type == \"text\") {\n if (typeof json.text != \"string\") throw new RangeError(\"Invalid text node in JSON\");\n return schema.text(json.text, marks);\n }\n let content = Fragment.fromJSON(schema, json.content);\n let node = schema.nodeType(json.type).create(json.attrs, content, marks);\n node.type.checkAttrs(node.attrs);\n return node;\n }\n}\nNode.prototype.text = undefined;\nclass TextNode extends Node {\n /**\n @internal\n */\n constructor(type, attrs, content, marks) {\n super(type, attrs, null, marks);\n if (!content) throw new RangeError(\"Empty text nodes are not allowed\");\n this.text = content;\n }\n toString() {\n if (this.type.spec.toDebugString) return this.type.spec.toDebugString(this);\n return wrapMarks(this.marks, JSON.stringify(this.text));\n }\n get textContent() {\n return this.text;\n }\n textBetween(from, to) {\n return this.text.slice(from, to);\n }\n get nodeSize() {\n return this.text.length;\n }\n mark(marks) {\n return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);\n }\n withText(text) {\n if (text == this.text) return this;\n return new TextNode(this.type, this.attrs, text, this.marks);\n }\n cut(from = 0, to = this.text.length) {\n if (from == 0 && to == this.text.length) return this;\n return this.withText(this.text.slice(from, to));\n }\n eq(other) {\n return this.sameMarkup(other) && this.text == other.text;\n }\n toJSON() {\n let base = super.toJSON();\n base.text = this.text;\n return base;\n }\n}\nfunction wrapMarks(marks, str) {\n for (let i = marks.length - 1; i >= 0; i--) str = marks[i].type.name + \"(\" + str + \")\";\n return str;\n}\n\n/**\nInstances of this class represent a match state of a node type's\n[content expression](https://prosemirror.net/docs/ref/#model.NodeSpec.content), and can be used to\nfind out whether further content matches here, and whether a given\nposition is a valid end of the node.\n*/\nclass ContentMatch {\n /**\n @internal\n */\n constructor(\n /**\n True when this match state represents a valid end of the node.\n */\n validEnd) {\n this.validEnd = validEnd;\n /**\n @internal\n */\n this.next = [];\n /**\n @internal\n */\n this.wrapCache = [];\n }\n /**\n @internal\n */\n static parse(string, nodeTypes) {\n let stream = new TokenStream(string, nodeTypes);\n if (stream.next == null) return ContentMatch.empty;\n let expr = parseExpr(stream);\n if (stream.next) stream.err(\"Unexpected trailing text\");\n let match = dfa(nfa(expr));\n checkForDeadEnds(match, stream);\n return match;\n }\n /**\n Match a node type, returning a match after that node if\n successful.\n */\n matchType(type) {\n for (let i = 0; i < this.next.length; i++) if (this.next[i].type == type) return this.next[i].next;\n return null;\n }\n /**\n Try to match a fragment. Returns the resulting match when\n successful.\n */\n matchFragment(frag, start = 0, end = frag.childCount) {\n let cur = this;\n for (let i = start; cur && i < end; i++) cur = cur.matchType(frag.child(i).type);\n return cur;\n }\n /**\n @internal\n */\n get inlineContent() {\n return this.next.length != 0 && this.next[0].type.isInline;\n }\n /**\n Get the first matching node type at this match position that can\n be generated.\n */\n get defaultType() {\n for (let i = 0; i < this.next.length; i++) {\n let {\n type\n } = this.next[i];\n if (!(type.isText || type.hasRequiredAttrs())) return type;\n }\n return null;\n }\n /**\n @internal\n */\n compatible(other) {\n for (let i = 0; i < this.next.length; i++) for (let j = 0; j < other.next.length; j++) if (this.next[i].type == other.next[j].type) return true;\n return false;\n }\n /**\n Try to match the given fragment, and if that fails, see if it can\n be made to match by inserting nodes in front of it. When\n successful, return a fragment of inserted nodes (which may be\n empty if nothing had to be inserted). When `toEnd` is true, only\n return a fragment if the resulting match goes to the end of the\n content expression.\n */\n fillBefore(after, toEnd = false, startIndex = 0) {\n let seen = [this];\n function search(match, types) {\n let finished = match.matchFragment(after, startIndex);\n if (finished && (!toEnd || finished.validEnd)) return Fragment.from(types.map(tp => tp.createAndFill()));\n for (let i = 0; i < match.next.length; i++) {\n let {\n type,\n next\n } = match.next[i];\n if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {\n seen.push(next);\n let found = search(next, types.concat(type));\n if (found) return found;\n }\n }\n return null;\n }\n return search(this, []);\n }\n /**\n Find a set of wrapping node types that would allow a node of the\n given type to appear at this position. The result may be empty\n (when it fits directly) and will be null when no such wrapping\n exists.\n */\n findWrapping(target) {\n for (let i = 0; i < this.wrapCache.length; i += 2) if (this.wrapCache[i] == target) return this.wrapCache[i + 1];\n let computed = this.computeWrapping(target);\n this.wrapCache.push(target, computed);\n return computed;\n }\n /**\n @internal\n */\n computeWrapping(target) {\n let seen = Object.create(null),\n active = [{\n match: this,\n type: null,\n via: null\n }];\n while (active.length) {\n let current = active.shift(),\n match = current.match;\n if (match.matchType(target)) {\n let result = [];\n for (let obj = current; obj.type; obj = obj.via) result.push(obj.type);\n return result.reverse();\n }\n for (let i = 0; i < match.next.length; i++) {\n let {\n type,\n next\n } = match.next[i];\n if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {\n active.push({\n match: type.contentMatch,\n type,\n via: current\n });\n seen[type.name] = true;\n }\n }\n }\n return null;\n }\n /**\n The number of outgoing edges this node has in the finite\n automaton that describes the content expression.\n */\n get edgeCount() {\n return this.next.length;\n }\n /**\n Get the _n_​th outgoing edge from this node in the finite\n automaton that describes the content expression.\n */\n edge(n) {\n if (n >= this.next.length) throw new RangeError(`There's no ${n}th edge in this content match`);\n return this.next[n];\n }\n /**\n @internal\n */\n toString() {\n let seen = [];\n function scan(m) {\n seen.push(m);\n for (let i = 0; i < m.next.length; i++) if (seen.indexOf(m.next[i].next) == -1) scan(m.next[i].next);\n }\n scan(this);\n return seen.map((m, i) => {\n let out = i + (m.validEnd ? \"*\" : \" \") + \" \";\n for (let i = 0; i < m.next.length; i++) out += (i ? \", \" : \"\") + m.next[i].type.name + \"->\" + seen.indexOf(m.next[i].next);\n return out;\n }).join(\"\\n\");\n }\n}\n/**\n@internal\n*/\nContentMatch.empty = new ContentMatch(true);\nclass TokenStream {\n constructor(string, nodeTypes) {\n this.string = string;\n this.nodeTypes = nodeTypes;\n this.inline = null;\n this.pos = 0;\n this.tokens = string.split(/\\s*(?=\\b|\\W|$)/);\n if (this.tokens[this.tokens.length - 1] == \"\") this.tokens.pop();\n if (this.tokens[0] == \"\") this.tokens.shift();\n }\n get next() {\n return this.tokens[this.pos];\n }\n eat(tok) {\n return this.next == tok && (this.pos++ || true);\n }\n err(str) {\n throw new SyntaxError(str + \" (in content expression '\" + this.string + \"')\");\n }\n}\nfunction parseExpr(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSeq(stream));\n } while (stream.eat(\"|\"));\n return exprs.length == 1 ? exprs[0] : {\n type: \"choice\",\n exprs\n };\n}\nfunction parseExprSeq(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSubscript(stream));\n } while (stream.next && stream.next != \")\" && stream.next != \"|\");\n return exprs.length == 1 ? exprs[0] : {\n type: \"seq\",\n exprs\n };\n}\nfunction parseExprSubscript(stream) {\n let expr = parseExprAtom(stream);\n for (;;) {\n if (stream.eat(\"+\")) expr = {\n type: \"plus\",\n expr\n };else if (stream.eat(\"*\")) expr = {\n type: \"star\",\n expr\n };else if (stream.eat(\"?\")) expr = {\n type: \"opt\",\n expr\n };else if (stream.eat(\"{\")) expr = parseExprRange(stream, expr);else break;\n }\n return expr;\n}\nfunction parseNum(stream) {\n if (/\\D/.test(stream.next)) stream.err(\"Expected number, got '\" + stream.next + \"'\");\n let result = Number(stream.next);\n stream.pos++;\n return result;\n}\nfunction parseExprRange(stream, expr) {\n let min = parseNum(stream),\n max = min;\n if (stream.eat(\",\")) {\n if (stream.next != \"}\") max = parseNum(stream);else max = -1;\n }\n if (!stream.eat(\"}\")) stream.err(\"Unclosed braced range\");\n return {\n type: \"range\",\n min,\n max,\n expr\n };\n}\nfunction resolveName(stream, name) {\n let types = stream.nodeTypes,\n type = types[name];\n if (type) return [type];\n let result = [];\n for (let typeName in types) {\n let type = types[typeName];\n if (type.groups.indexOf(name) > -1) result.push(type);\n }\n if (result.length == 0) stream.err(\"No node type or group '\" + name + \"' found\");\n return result;\n}\nfunction parseExprAtom(stream) {\n if (stream.eat(\"(\")) {\n let expr = parseExpr(stream);\n if (!stream.eat(\")\")) stream.err(\"Missing closing paren\");\n return expr;\n } else if (!/\\W/.test(stream.next)) {\n let exprs = resolveName(stream, stream.next).map(type => {\n if (stream.inline == null) stream.inline = type.isInline;else if (stream.inline != type.isInline) stream.err(\"Mixing inline and block content\");\n return {\n type: \"name\",\n value: type\n };\n });\n stream.pos++;\n return exprs.length == 1 ? exprs[0] : {\n type: \"choice\",\n exprs\n };\n } else {\n stream.err(\"Unexpected token '\" + stream.next + \"'\");\n }\n}\n/**\nConstruct an NFA from an expression as returned by the parser. The\nNFA is represented as an array of states, which are themselves\narrays of edges, which are `{term, to}` objects. The first state is\nthe entry state and the last node is the success state.\n\nNote that unlike typical NFAs, the edge ordering in this one is\nsignificant, in that it is used to contruct filler content when\nnecessary.\n*/\nfunction nfa(expr) {\n let nfa = [[]];\n connect(compile(expr, 0), node());\n return nfa;\n function node() {\n return nfa.push([]) - 1;\n }\n function edge(from, to, term) {\n let edge = {\n term,\n to\n };\n nfa[from].push(edge);\n return edge;\n }\n function connect(edges, to) {\n edges.forEach(edge => edge.to = to);\n }\n function compile(expr, from) {\n if (expr.type == \"choice\") {\n return expr.exprs.reduce((out, expr) => out.concat(compile(expr, from)), []);\n } else if (expr.type == \"seq\") {\n for (let i = 0;; i++) {\n let next = compile(expr.exprs[i], from);\n if (i == expr.exprs.length - 1) return next;\n connect(next, from = node());\n }\n } else if (expr.type == \"star\") {\n let loop = node();\n edge(from, loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n } else if (expr.type == \"plus\") {\n let loop = node();\n connect(compile(expr.expr, from), loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n } else if (expr.type == \"opt\") {\n return [edge(from)].concat(compile(expr.expr, from));\n } else if (expr.type == \"range\") {\n let cur = from;\n for (let i = 0; i < expr.min; i++) {\n let next = node();\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n if (expr.max == -1) {\n connect(compile(expr.expr, cur), cur);\n } else {\n for (let i = expr.min; i < expr.max; i++) {\n let next = node();\n edge(cur, next);\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n }\n return [edge(cur)];\n } else if (expr.type == \"name\") {\n return [edge(from, undefined, expr.value)];\n } else {\n throw new Error(\"Unknown expr type\");\n }\n }\n}\nfunction cmp(a, b) {\n return b - a;\n}\n// Get the set of nodes reachable by null edges from `node`. Omit\n// nodes with only a single null-out-edge, since they may lead to\n// needless duplicated nodes.\nfunction nullFrom(nfa, node) {\n let result = [];\n scan(node);\n return result.sort(cmp);\n function scan(node) {\n let edges = nfa[node];\n if (edges.length == 1 && !edges[0].term) return scan(edges[0].to);\n result.push(node);\n for (let i = 0; i < edges.length; i++) {\n let {\n term,\n to\n } = edges[i];\n if (!term && result.indexOf(to) == -1) scan(to);\n }\n }\n}\n// Compiles an NFA as produced by `nfa` into a DFA, modeled as a set\n// of state objects (`ContentMatch` instances) with transitions\n// between them.\nfunction dfa(nfa) {\n let labeled = Object.create(null);\n return explore(nullFrom(nfa, 0));\n function explore(states) {\n let out = [];\n states.forEach(node => {\n nfa[node].forEach(({\n term,\n to\n }) => {\n if (!term) return;\n let set;\n for (let i = 0; i < out.length; i++) if (out[i][0] == term) set = out[i][1];\n nullFrom(nfa, to).forEach(node => {\n if (!set) out.push([term, set = []]);\n if (set.indexOf(node) == -1) set.push(node);\n });\n });\n });\n let state = labeled[states.join(\",\")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);\n for (let i = 0; i < out.length; i++) {\n let states = out[i][1].sort(cmp);\n state.next.push({\n type: out[i][0],\n next: labeled[states.join(\",\")] || explore(states)\n });\n }\n return state;\n }\n}\nfunction checkForDeadEnds(match, stream) {\n for (let i = 0, work = [match]; i < work.length; i++) {\n let state = work[i],\n dead = !state.validEnd,\n nodes = [];\n for (let j = 0; j < state.next.length; j++) {\n let {\n type,\n next\n } = state.next[j];\n nodes.push(type.name);\n if (dead && !(type.isText || type.hasRequiredAttrs())) dead = false;\n if (work.indexOf(next) == -1) work.push(next);\n }\n if (dead) stream.err(\"Only non-generatable nodes (\" + nodes.join(\", \") + \") in a required position (see https://prosemirror.net/docs/guide/#generatable)\");\n }\n}\n\n// For node types where all attrs have a default value (or which don't\n// have any attributes), build up a single reusable default attribute\n// object, and use it for all nodes that don't specify specific\n// attributes.\nfunction defaultAttrs(attrs) {\n let defaults = Object.create(null);\n for (let attrName in attrs) {\n let attr = attrs[attrName];\n if (!attr.hasDefault) return null;\n defaults[attrName] = attr.default;\n }\n return defaults;\n}\nfunction computeAttrs(attrs, value) {\n let built = Object.create(null);\n for (let name in attrs) {\n let given = value && value[name];\n if (given === undefined) {\n let attr = attrs[name];\n if (attr.hasDefault) given = attr.default;else throw new RangeError(\"No value supplied for attribute \" + name);\n }\n built[name] = given;\n }\n return built;\n}\nfunction checkAttrs(attrs, values, type, name) {\n for (let name in values) if (!(name in attrs)) throw new RangeError(`Unsupported attribute ${name} for ${type} of type ${name}`);\n for (let name in attrs) {\n let attr = attrs[name];\n if (attr.validate) attr.validate(values[name]);\n }\n}\nfunction initAttrs(typeName, attrs) {\n let result = Object.create(null);\n if (attrs) for (let name in attrs) result[name] = new Attribute(typeName, name, attrs[name]);\n return result;\n}\n/**\nNode types are objects allocated once per `Schema` and used to\n[tag](https://prosemirror.net/docs/ref/#model.Node.type) `Node` instances. They contain information\nabout the node type, such as its name and what kind of node it\nrepresents.\n*/\nclass NodeType {\n /**\n @internal\n */\n constructor(\n /**\n The name the node type has in this schema.\n */\n name,\n /**\n A link back to the `Schema` the node type belongs to.\n */\n schema,\n /**\n The spec that this type is based on\n */\n spec) {\n this.name = name;\n this.schema = schema;\n this.spec = spec;\n /**\n The set of marks allowed in this node. `null` means all marks\n are allowed.\n */\n this.markSet = null;\n this.groups = spec.group ? spec.group.split(\" \") : [];\n this.attrs = initAttrs(name, spec.attrs);\n this.defaultAttrs = defaultAttrs(this.attrs);\n this.contentMatch = null;\n this.inlineContent = null;\n this.isBlock = !(spec.inline || name == \"text\");\n this.isText = name == \"text\";\n }\n /**\n True if this is an inline type.\n */\n get isInline() {\n return !this.isBlock;\n }\n /**\n True if this is a textblock type, a block that contains inline\n content.\n */\n get isTextblock() {\n return this.isBlock && this.inlineContent;\n }\n /**\n True for node types that allow no content.\n */\n get isLeaf() {\n return this.contentMatch == ContentMatch.empty;\n }\n /**\n True when this node is an atom, i.e. when it does not have\n directly editable content.\n */\n get isAtom() {\n return this.isLeaf || !!this.spec.atom;\n }\n /**\n The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.\n */\n get whitespace() {\n return this.spec.whitespace || (this.spec.code ? \"pre\" : \"normal\");\n }\n /**\n Tells you whether this node type has any required attributes.\n */\n hasRequiredAttrs() {\n for (let n in this.attrs) if (this.attrs[n].isRequired) return true;\n return false;\n }\n /**\n Indicates whether this node allows some of the same content as\n the given node type.\n */\n compatibleContent(other) {\n return this == other || this.contentMatch.compatible(other.contentMatch);\n }\n /**\n @internal\n */\n computeAttrs(attrs) {\n if (!attrs && this.defaultAttrs) return this.defaultAttrs;else return computeAttrs(this.attrs, attrs);\n }\n /**\n Create a `Node` of this type. The given attributes are\n checked and defaulted (you can pass `null` to use the type's\n defaults entirely, if no required attributes exist). `content`\n may be a `Fragment`, a node, an array of nodes, or\n `null`. Similarly `marks` may be `null` to default to the empty\n set of marks.\n */\n create(attrs = null, content, marks) {\n if (this.isText) throw new Error(\"NodeType.create can't construct text nodes\");\n return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content\n against the node type's content restrictions, and throw an error\n if it doesn't match.\n */\n createChecked(attrs = null, content, marks) {\n content = Fragment.from(content);\n this.checkContent(content);\n return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is\n necessary to add nodes to the start or end of the given fragment\n to make it fit the node. If no fitting wrapping can be found,\n return null. Note that, due to the fact that required nodes can\n always be created, this will always succeed if you pass null or\n `Fragment.empty` as content.\n */\n createAndFill(attrs = null, content, marks) {\n attrs = this.computeAttrs(attrs);\n content = Fragment.from(content);\n if (content.size) {\n let before = this.contentMatch.fillBefore(content);\n if (!before) return null;\n content = before.append(content);\n }\n let matched = this.contentMatch.matchFragment(content);\n let after = matched && matched.fillBefore(Fragment.empty, true);\n if (!after) return null;\n return new Node(this, attrs, content.append(after), Mark.setFrom(marks));\n }\n /**\n Returns true if the given fragment is valid content for this node\n type.\n */\n validContent(content) {\n let result = this.contentMatch.matchFragment(content);\n if (!result || !result.validEnd) return false;\n for (let i = 0; i < content.childCount; i++) if (!this.allowsMarks(content.child(i).marks)) return false;\n return true;\n }\n /**\n Throws a RangeError if the given fragment is not valid content for this\n node type.\n @internal\n */\n checkContent(content) {\n if (!this.validContent(content)) throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);\n }\n /**\n @internal\n */\n checkAttrs(attrs) {\n checkAttrs(this.attrs, attrs, \"node\", this.name);\n }\n /**\n Check whether the given mark type is allowed in this node.\n */\n allowsMarkType(markType) {\n return this.markSet == null || this.markSet.indexOf(markType) > -1;\n }\n /**\n Test whether the given set of marks are allowed in this node.\n */\n allowsMarks(marks) {\n if (this.markSet == null) return true;\n for (let i = 0; i < marks.length; i++) if (!this.allowsMarkType(marks[i].type)) return false;\n return true;\n }\n /**\n Removes the marks that are not allowed in this node from the given set.\n */\n allowedMarks(marks) {\n if (this.markSet == null) return marks;\n let copy;\n for (let i = 0; i < marks.length; i++) {\n if (!this.allowsMarkType(marks[i].type)) {\n if (!copy) copy = marks.slice(0, i);\n } else if (copy) {\n copy.push(marks[i]);\n }\n }\n return !copy ? marks : copy.length ? copy : Mark.none;\n }\n /**\n @internal\n */\n static compile(nodes, schema) {\n let result = Object.create(null);\n nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec));\n let topType = schema.spec.topNode || \"doc\";\n if (!result[topType]) throw new RangeError(\"Schema is missing its top node type ('\" + topType + \"')\");\n if (!result.text) throw new RangeError(\"Every schema needs a 'text' type\");\n for (let _ in result.text.attrs) throw new RangeError(\"The text node type should not have attributes\");\n return result;\n }\n}\nfunction validateType(typeName, attrName, type) {\n let types = type.split(\"|\");\n return value => {\n let name = value === null ? \"null\" : typeof value;\n if (types.indexOf(name) < 0) throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);\n };\n}\n// Attribute descriptors\nclass Attribute {\n constructor(typeName, attrName, options) {\n this.hasDefault = Object.prototype.hasOwnProperty.call(options, \"default\");\n this.default = options.default;\n this.validate = typeof options.validate == \"string\" ? validateType(typeName, attrName, options.validate) : options.validate;\n }\n get isRequired() {\n return !this.hasDefault;\n }\n}\n// Marks\n/**\nLike nodes, marks (which are associated with nodes to signify\nthings like emphasis or being part of a link) are\n[tagged](https://prosemirror.net/docs/ref/#model.Mark.type) with type objects, which are\ninstantiated once per `Schema`.\n*/\nclass MarkType {\n /**\n @internal\n */\n constructor(\n /**\n The name of the mark type.\n */\n name,\n /**\n @internal\n */\n rank,\n /**\n The schema that this mark type instance is part of.\n */\n schema,\n /**\n The spec on which the type is based.\n */\n spec) {\n this.name = name;\n this.rank = rank;\n this.schema = schema;\n this.spec = spec;\n this.attrs = initAttrs(name, spec.attrs);\n this.excluded = null;\n let defaults = defaultAttrs(this.attrs);\n this.instance = defaults ? new Mark(this, defaults) : null;\n }\n /**\n Create a mark of this type. `attrs` may be `null` or an object\n containing only some of the mark's attributes. The others, if\n they have defaults, will be added.\n */\n create(attrs = null) {\n if (!attrs && this.instance) return this.instance;\n return new Mark(this, computeAttrs(this.attrs, attrs));\n }\n /**\n @internal\n */\n static compile(marks, schema) {\n let result = Object.create(null),\n rank = 0;\n marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec));\n return result;\n }\n /**\n When there is a mark of this type in the given set, a new set\n without it is returned. Otherwise, the input set is returned.\n */\n removeFromSet(set) {\n for (var i = 0; i < set.length; i++) if (set[i].type == this) {\n set = set.slice(0, i).concat(set.slice(i + 1));\n i--;\n }\n return set;\n }\n /**\n Tests whether there is a mark of this type in the given set.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++) if (set[i].type == this) return set[i];\n }\n /**\n @internal\n */\n checkAttrs(attrs) {\n checkAttrs(this.attrs, attrs, \"mark\", this.name);\n }\n /**\n Queries whether a given mark type is\n [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.\n */\n excludes(other) {\n return this.excluded.indexOf(other) > -1;\n }\n}\n/**\nA document schema. Holds [node](https://prosemirror.net/docs/ref/#model.NodeType) and [mark\ntype](https://prosemirror.net/docs/ref/#model.MarkType) objects for the nodes and marks that may\noccur in conforming documents, and provides functionality for\ncreating and deserializing such documents.\n\nWhen given, the type parameters provide the names of the nodes and\nmarks in this schema.\n*/\nclass Schema {\n /**\n Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).\n */\n constructor(spec) {\n /**\n The [linebreak\n replacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement) node defined\n in this schema, if any.\n */\n this.linebreakReplacement = null;\n /**\n An object for storing whatever values modules may want to\n compute and cache per schema. (If you want to store something\n in it, try to use property names unlikely to clash.)\n */\n this.cached = Object.create(null);\n let instanceSpec = this.spec = {};\n for (let prop in spec) instanceSpec[prop] = spec[prop];\n instanceSpec.nodes = OrderedMap.from(spec.nodes), instanceSpec.marks = OrderedMap.from(spec.marks || {}), this.nodes = NodeType.compile(this.spec.nodes, this);\n this.marks = MarkType.compile(this.spec.marks, this);\n let contentExprCache = Object.create(null);\n for (let prop in this.nodes) {\n if (prop in this.marks) throw new RangeError(prop + \" can not be both a node and a mark\");\n let type = this.nodes[prop],\n contentExpr = type.spec.content || \"\",\n markExpr = type.spec.marks;\n type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));\n type.inlineContent = type.contentMatch.inlineContent;\n if (type.spec.linebreakReplacement) {\n if (this.linebreakReplacement) throw new RangeError(\"Multiple linebreak nodes defined\");\n if (!type.isInline || !type.isLeaf) throw new RangeError(\"Linebreak replacement nodes must be inline leaf nodes\");\n this.linebreakReplacement = type;\n }\n type.markSet = markExpr == \"_\" ? null : markExpr ? gatherMarks(this, markExpr.split(\" \")) : markExpr == \"\" || !type.inlineContent ? [] : null;\n }\n for (let prop in this.marks) {\n let type = this.marks[prop],\n excl = type.spec.excludes;\n type.excluded = excl == null ? [type] : excl == \"\" ? [] : gatherMarks(this, excl.split(\" \"));\n }\n this.nodeFromJSON = this.nodeFromJSON.bind(this);\n this.markFromJSON = this.markFromJSON.bind(this);\n this.topNodeType = this.nodes[this.spec.topNode || \"doc\"];\n this.cached.wrappings = Object.create(null);\n }\n /**\n Create a node in this schema. The `type` may be a string or a\n `NodeType` instance. Attributes will be extended with defaults,\n `content` may be a `Fragment`, `null`, a `Node`, or an array of\n nodes.\n */\n node(type, attrs = null, content, marks) {\n if (typeof type == \"string\") type = this.nodeType(type);else if (!(type instanceof NodeType)) throw new RangeError(\"Invalid node type: \" + type);else if (type.schema != this) throw new RangeError(\"Node type from different schema used (\" + type.name + \")\");\n return type.createChecked(attrs, content, marks);\n }\n /**\n Create a text node in the schema. Empty text nodes are not\n allowed.\n */\n text(text, marks) {\n let type = this.nodes.text;\n return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks));\n }\n /**\n Create a mark with the given type and attributes.\n */\n mark(type, attrs) {\n if (typeof type == \"string\") type = this.marks[type];\n return type.create(attrs);\n }\n /**\n Deserialize a node from its JSON representation. This method is\n bound.\n */\n nodeFromJSON(json) {\n return Node.fromJSON(this, json);\n }\n /**\n Deserialize a mark from its JSON representation. This method is\n bound.\n */\n markFromJSON(json) {\n return Mark.fromJSON(this, json);\n }\n /**\n @internal\n */\n nodeType(name) {\n let found = this.nodes[name];\n if (!found) throw new RangeError(\"Unknown node type: \" + name);\n return found;\n }\n}\nfunction gatherMarks(schema, marks) {\n let found = [];\n for (let i = 0; i < marks.length; i++) {\n let name = marks[i],\n mark = schema.marks[name],\n ok = mark;\n if (mark) {\n found.push(mark);\n } else {\n for (let prop in schema.marks) {\n let mark = schema.marks[prop];\n if (name == \"_\" || mark.spec.group && mark.spec.group.split(\" \").indexOf(name) > -1) found.push(ok = mark);\n }\n }\n if (!ok) throw new SyntaxError(\"Unknown mark type: '\" + marks[i] + \"'\");\n }\n return found;\n}\nfunction isTagRule(rule) {\n return rule.tag != null;\n}\nfunction isStyleRule(rule) {\n return rule.style != null;\n}\n/**\nA DOM parser represents a strategy for parsing DOM content into a\nProseMirror document conforming to a given schema. Its behavior is\ndefined by an array of [rules](https://prosemirror.net/docs/ref/#model.ParseRule).\n*/\nclass DOMParser {\n /**\n Create a parser that targets the given schema, using the given\n parsing rules.\n */\n constructor(\n /**\n The schema into which the parser parses.\n */\n schema,\n /**\n The set of [parse rules](https://prosemirror.net/docs/ref/#model.ParseRule) that the parser\n uses, in order of precedence.\n */\n rules) {\n this.schema = schema;\n this.rules = rules;\n /**\n @internal\n */\n this.tags = [];\n /**\n @internal\n */\n this.styles = [];\n let matchedStyles = this.matchedStyles = [];\n rules.forEach(rule => {\n if (isTagRule(rule)) {\n this.tags.push(rule);\n } else if (isStyleRule(rule)) {\n let prop = /[^=]*/.exec(rule.style)[0];\n if (matchedStyles.indexOf(prop) < 0) matchedStyles.push(prop);\n this.styles.push(rule);\n }\n });\n // Only normalize list elements when lists in the schema can't directly contain themselves\n this.normalizeLists = !this.tags.some(r => {\n if (!/^(ul|ol)\\b/.test(r.tag) || !r.node) return false;\n let node = schema.nodes[r.node];\n return node.contentMatch.matchType(node);\n });\n }\n /**\n Parse a document from the content of a DOM node.\n */\n parse(dom, options = {}) {\n let context = new ParseContext(this, options, false);\n context.addAll(dom, options.from, options.to);\n return context.finish();\n }\n /**\n Parses the content of the given DOM node, like\n [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of\n options. But unlike that method, which produces a whole node,\n this one returns a slice that is open at the sides, meaning that\n the schema constraints aren't applied to the start of nodes to\n the left of the input and the end of nodes at the end.\n */\n parseSlice(dom, options = {}) {\n let context = new ParseContext(this, options, true);\n context.addAll(dom, options.from, options.to);\n return Slice.maxOpen(context.finish());\n }\n /**\n @internal\n */\n matchTag(dom, context, after) {\n for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) {\n let rule = this.tags[i];\n if (matches(dom, rule.tag) && (rule.namespace === undefined || dom.namespaceURI == rule.namespace) && (!rule.context || context.matchesContext(rule.context))) {\n if (rule.getAttrs) {\n let result = rule.getAttrs(dom);\n if (result === false) continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n }\n /**\n @internal\n */\n matchStyle(prop, value, context, after) {\n for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) {\n let rule = this.styles[i],\n style = rule.style;\n if (style.indexOf(prop) != 0 || rule.context && !context.matchesContext(rule.context) ||\n // Test that the style string either precisely matches the prop,\n // or has an '=' sign after the prop, followed by the given\n // value.\n style.length > prop.length && (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value)) continue;\n if (rule.getAttrs) {\n let result = rule.getAttrs(value);\n if (result === false) continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n /**\n @internal\n */\n static schemaRules(schema) {\n let result = [];\n function insert(rule) {\n let priority = rule.priority == null ? 50 : rule.priority,\n i = 0;\n for (; i < result.length; i++) {\n let next = result[i],\n nextPriority = next.priority == null ? 50 : next.priority;\n if (nextPriority < priority) break;\n }\n result.splice(i, 0, rule);\n }\n for (let name in schema.marks) {\n let rules = schema.marks[name].spec.parseDOM;\n if (rules) rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.mark || rule.ignore || rule.clearMark)) rule.mark = name;\n });\n }\n for (let name in schema.nodes) {\n let rules = schema.nodes[name].spec.parseDOM;\n if (rules) rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.node || rule.ignore || rule.mark)) rule.node = name;\n });\n }\n return result;\n }\n /**\n Construct a DOM parser using the parsing rules listed in a\n schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by\n [priority](https://prosemirror.net/docs/ref/#model.ParseRule.priority).\n */\n static fromSchema(schema) {\n return schema.cached.domParser || (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)));\n }\n}\nconst blockTags = {\n address: true,\n article: true,\n aside: true,\n blockquote: true,\n canvas: true,\n dd: true,\n div: true,\n dl: true,\n fieldset: true,\n figcaption: true,\n figure: true,\n footer: true,\n form: true,\n h1: true,\n h2: true,\n h3: true,\n h4: true,\n h5: true,\n h6: true,\n header: true,\n hgroup: true,\n hr: true,\n li: true,\n noscript: true,\n ol: true,\n output: true,\n p: true,\n pre: true,\n section: true,\n table: true,\n tfoot: true,\n ul: true\n};\nconst ignoreTags = {\n head: true,\n noscript: true,\n object: true,\n script: true,\n style: true,\n title: true\n};\nconst listTags = {\n ol: true,\n ul: true\n};\n// Using a bitfield for node context options\nconst OPT_PRESERVE_WS = 1,\n OPT_PRESERVE_WS_FULL = 2,\n OPT_OPEN_LEFT = 4;\nfunction wsOptionsFor(type, preserveWhitespace, base) {\n if (preserveWhitespace != null) return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === \"full\" ? OPT_PRESERVE_WS_FULL : 0);\n return type && type.whitespace == \"pre\" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base & ~OPT_OPEN_LEFT;\n}\nclass NodeContext {\n constructor(type, attrs,\n // Marks applied to this node itself\n marks,\n // Marks that can't apply here, but will be used in children if possible\n pendingMarks, solid, match, options) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.pendingMarks = pendingMarks;\n this.solid = solid;\n this.options = options;\n this.content = [];\n // Marks applied to the node's children\n this.activeMarks = Mark.none;\n // Nested Marks with same type\n this.stashMarks = [];\n this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);\n }\n findWrapping(node) {\n if (!this.match) {\n if (!this.type) return [];\n let fill = this.type.contentMatch.fillBefore(Fragment.from(node));\n if (fill) {\n this.match = this.type.contentMatch.matchFragment(fill);\n } else {\n let start = this.type.contentMatch,\n wrap;\n if (wrap = start.findWrapping(node.type)) {\n this.match = start;\n return wrap;\n } else {\n return null;\n }\n }\n }\n return this.match.findWrapping(node.type);\n }\n finish(openEnd) {\n if (!(this.options & OPT_PRESERVE_WS)) {\n // Strip trailing whitespace\n let last = this.content[this.content.length - 1],\n m;\n if (last && last.isText && (m = /[ \\t\\r\\n\\u000c]+$/.exec(last.text))) {\n let text = last;\n if (last.text.length == m[0].length) this.content.pop();else this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length));\n }\n }\n let content = Fragment.from(this.content);\n if (!openEnd && this.match) content = content.append(this.match.fillBefore(Fragment.empty, true));\n return this.type ? this.type.create(this.attrs, content, this.marks) : content;\n }\n popFromStashMark(mark) {\n for (let i = this.stashMarks.length - 1; i >= 0; i--) if (mark.eq(this.stashMarks[i])) return this.stashMarks.splice(i, 1)[0];\n }\n applyPending(nextType) {\n for (let i = 0, pending = this.pendingMarks; i < pending.length; i++) {\n let mark = pending[i];\n if ((this.type ? this.type.allowsMarkType(mark.type) : markMayApply(mark.type, nextType)) && !mark.isInSet(this.activeMarks)) {\n this.activeMarks = mark.addToSet(this.activeMarks);\n this.pendingMarks = mark.removeFromSet(this.pendingMarks);\n }\n }\n }\n inlineContext(node) {\n if (this.type) return this.type.inlineContent;\n if (this.content.length) return this.content[0].isInline;\n return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());\n }\n}\nclass ParseContext {\n constructor(\n // The parser we are using.\n parser,\n // The options passed to this parse.\n options, isOpen) {\n this.parser = parser;\n this.options = options;\n this.isOpen = isOpen;\n this.open = 0;\n let topNode = options.topNode,\n topContext;\n let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);\n if (topNode) topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);else if (isOpen) topContext = new NodeContext(null, null, Mark.none, Mark.none, true, null, topOptions);else topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, Mark.none, true, null, topOptions);\n this.nodes = [topContext];\n this.find = options.findPositions;\n this.needsBlock = false;\n }\n get top() {\n return this.nodes[this.open];\n }\n // Add a DOM node to the content. Text is inserted as text node,\n // otherwise, the node is passed to `addElement` or, if it has a\n // `style` attribute, `addElementWithStyles`.\n addDOM(dom) {\n if (dom.nodeType == 3) this.addTextNode(dom);else if (dom.nodeType == 1) this.addElement(dom);\n }\n withStyleRules(dom, f) {\n let style = dom.style;\n if (!style || !style.length) return f();\n let marks = this.readStyles(dom.style);\n if (!marks) return; // A style with ignore: true\n let [addMarks, removeMarks] = marks,\n top = this.top;\n for (let i = 0; i < removeMarks.length; i++) this.removePendingMark(removeMarks[i], top);\n for (let i = 0; i < addMarks.length; i++) this.addPendingMark(addMarks[i]);\n f();\n for (let i = 0; i < addMarks.length; i++) this.removePendingMark(addMarks[i], top);\n for (let i = 0; i < removeMarks.length; i++) this.addPendingMark(removeMarks[i]);\n }\n addTextNode(dom) {\n let value = dom.nodeValue;\n let top = this.top;\n if (top.options & OPT_PRESERVE_WS_FULL || top.inlineContext(dom) || /[^ \\t\\r\\n\\u000c]/.test(value)) {\n if (!(top.options & OPT_PRESERVE_WS)) {\n value = value.replace(/[ \\t\\r\\n\\u000c]+/g, \" \");\n // If this starts with whitespace, and there is no node before it, or\n // a hard break, or a text node that ends with whitespace, strip the\n // leading space.\n if (/^[ \\t\\r\\n\\u000c]/.test(value) && this.open == this.nodes.length - 1) {\n let nodeBefore = top.content[top.content.length - 1];\n let domNodeBefore = dom.previousSibling;\n if (!nodeBefore || domNodeBefore && domNodeBefore.nodeName == 'BR' || nodeBefore.isText && /[ \\t\\r\\n\\u000c]$/.test(nodeBefore.text)) value = value.slice(1);\n }\n } else if (!(top.options & OPT_PRESERVE_WS_FULL)) {\n value = value.replace(/\\r?\\n|\\r/g, \" \");\n } else {\n value = value.replace(/\\r\\n?/g, \"\\n\");\n }\n if (value) this.insertNode(this.parser.schema.text(value));\n this.findInText(dom);\n } else {\n this.findInside(dom);\n }\n }\n // Try to find a handler for the given tag and use that to parse. If\n // none is found, the element's content nodes are added directly.\n addElement(dom, matchAfter) {\n let name = dom.nodeName.toLowerCase(),\n ruleID;\n if (listTags.hasOwnProperty(name) && this.parser.normalizeLists) normalizeList(dom);\n let rule = this.options.ruleFromNode && this.options.ruleFromNode(dom) || (ruleID = this.parser.matchTag(dom, this, matchAfter));\n if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {\n this.findInside(dom);\n this.ignoreFallback(dom);\n } else if (!rule || rule.skip || rule.closeParent) {\n if (rule && rule.closeParent) this.open = Math.max(0, this.open - 1);else if (rule && rule.skip.nodeType) dom = rule.skip;\n let sync,\n top = this.top,\n oldNeedsBlock = this.needsBlock;\n if (blockTags.hasOwnProperty(name)) {\n if (top.content.length && top.content[0].isInline && this.open) {\n this.open--;\n top = this.top;\n }\n sync = true;\n if (!top.type) this.needsBlock = true;\n } else if (!dom.firstChild) {\n this.leafFallback(dom);\n return;\n }\n if (rule && rule.skip) this.addAll(dom);else this.withStyleRules(dom, () => this.addAll(dom));\n if (sync) this.sync(top);\n this.needsBlock = oldNeedsBlock;\n } else {\n this.withStyleRules(dom, () => {\n this.addElementByRule(dom, rule, rule.consuming === false ? ruleID : undefined);\n });\n }\n }\n // Called for leaf DOM nodes that would otherwise be ignored\n leafFallback(dom) {\n if (dom.nodeName == \"BR\" && this.top.type && this.top.type.inlineContent) this.addTextNode(dom.ownerDocument.createTextNode(\"\\n\"));\n }\n // Called for ignored nodes\n ignoreFallback(dom) {\n // Ignored BR nodes should at least create an inline context\n if (dom.nodeName == \"BR\" && (!this.top.type || !this.top.type.inlineContent)) this.findPlace(this.parser.schema.text(\"-\"));\n }\n // Run any style parser associated with the node's styles. Either\n // return an array of marks, or null to indicate some of the styles\n // had a rule with `ignore` set.\n readStyles(styles) {\n let add = Mark.none,\n remove = Mark.none;\n // Because many properties will only show up in 'normalized' form\n // in `style.item` (i.e. text-decoration becomes\n // text-decoration-line, text-decoration-color, etc), we directly\n // query the styles mentioned in our rules instead of iterating\n // over the items.\n if (styles.length) for (let i = 0; i < this.parser.matchedStyles.length; i++) {\n let name = this.parser.matchedStyles[i],\n value = styles.getPropertyValue(name);\n if (value) for (let after = undefined;;) {\n let rule = this.parser.matchStyle(name, value, this, after);\n if (!rule) break;\n if (rule.ignore) return null;\n if (rule.clearMark) {\n this.top.pendingMarks.concat(this.top.activeMarks).forEach(m => {\n if (rule.clearMark(m)) remove = m.addToSet(remove);\n });\n } else {\n add = this.parser.schema.marks[rule.mark].create(rule.attrs).addToSet(add);\n }\n if (rule.consuming === false) after = rule;else break;\n }\n }\n return [add, remove];\n }\n // Look up a handler for the given node. If none are found, return\n // false. Otherwise, apply it, use its return value to drive the way\n // the node's content is wrapped, and return true.\n addElementByRule(dom, rule, continueAfter) {\n let sync, nodeType, mark;\n if (rule.node) {\n nodeType = this.parser.schema.nodes[rule.node];\n if (!nodeType.isLeaf) {\n sync = this.enter(nodeType, rule.attrs || null, rule.preserveWhitespace);\n } else if (!this.insertNode(nodeType.create(rule.attrs))) {\n this.leafFallback(dom);\n }\n } else {\n let markType = this.parser.schema.marks[rule.mark];\n mark = markType.create(rule.attrs);\n this.addPendingMark(mark);\n }\n let startIn = this.top;\n if (nodeType && nodeType.isLeaf) {\n this.findInside(dom);\n } else if (continueAfter) {\n this.addElement(dom, continueAfter);\n } else if (rule.getContent) {\n this.findInside(dom);\n rule.getContent(dom, this.parser.schema).forEach(node => this.insertNode(node));\n } else {\n let contentDOM = dom;\n if (typeof rule.contentElement == \"string\") contentDOM = dom.querySelector(rule.contentElement);else if (typeof rule.contentElement == \"function\") contentDOM = rule.contentElement(dom);else if (rule.contentElement) contentDOM = rule.contentElement;\n this.findAround(dom, contentDOM, true);\n this.addAll(contentDOM);\n }\n if (sync && this.sync(startIn)) this.open--;\n if (mark) this.removePendingMark(mark, startIn);\n }\n // Add all child nodes between `startIndex` and `endIndex` (or the\n // whole node, if not given). If `sync` is passed, use it to\n // synchronize after every block element.\n addAll(parent, startIndex, endIndex) {\n let index = startIndex || 0;\n for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {\n this.findAtPoint(parent, index);\n this.addDOM(dom);\n }\n this.findAtPoint(parent, index);\n }\n // Try to find a way to fit the given node type into the current\n // context. May add intermediate wrappers and/or leave non-solid\n // nodes that we're in.\n findPlace(node) {\n let route, sync;\n for (let depth = this.open; depth >= 0; depth--) {\n let cx = this.nodes[depth];\n let found = cx.findWrapping(node);\n if (found && (!route || route.length > found.length)) {\n route = found;\n sync = cx;\n if (!found.length) break;\n }\n if (cx.solid) break;\n }\n if (!route) return false;\n this.sync(sync);\n for (let i = 0; i < route.length; i++) this.enterInner(route[i], null, false);\n return true;\n }\n // Try to insert the given node, adjusting the context when needed.\n insertNode(node) {\n if (node.isInline && this.needsBlock && !this.top.type) {\n let block = this.textblockFromContext();\n if (block) this.enterInner(block);\n }\n if (this.findPlace(node)) {\n this.closeExtra();\n let top = this.top;\n top.applyPending(node.type);\n if (top.match) top.match = top.match.matchType(node.type);\n let marks = top.activeMarks;\n for (let i = 0; i < node.marks.length; i++) if (!top.type || top.type.allowsMarkType(node.marks[i].type)) marks = node.marks[i].addToSet(marks);\n top.content.push(node.mark(marks));\n return true;\n }\n return false;\n }\n // Try to start a node of the given type, adjusting the context when\n // necessary.\n enter(type, attrs, preserveWS) {\n let ok = this.findPlace(type.create(attrs));\n if (ok) this.enterInner(type, attrs, true, preserveWS);\n return ok;\n }\n // Open a node of the given type\n enterInner(type, attrs = null, solid = false, preserveWS) {\n this.closeExtra();\n let top = this.top;\n top.applyPending(type);\n top.match = top.match && top.match.matchType(type);\n let options = wsOptionsFor(type, preserveWS, top.options);\n if (top.options & OPT_OPEN_LEFT && top.content.length == 0) options |= OPT_OPEN_LEFT;\n this.nodes.push(new NodeContext(type, attrs, top.activeMarks, top.pendingMarks, solid, null, options));\n this.open++;\n }\n // Make sure all nodes above this.open are finished and added to\n // their parents\n closeExtra(openEnd = false) {\n let i = this.nodes.length - 1;\n if (i > this.open) {\n for (; i > this.open; i--) this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));\n this.nodes.length = this.open + 1;\n }\n }\n finish() {\n this.open = 0;\n this.closeExtra(this.isOpen);\n return this.nodes[0].finish(this.isOpen || this.options.topOpen);\n }\n sync(to) {\n for (let i = this.open; i >= 0; i--) if (this.nodes[i] == to) {\n this.open = i;\n return true;\n }\n return false;\n }\n get currentPos() {\n this.closeExtra();\n let pos = 0;\n for (let i = this.open; i >= 0; i--) {\n let content = this.nodes[i].content;\n for (let j = content.length - 1; j >= 0; j--) pos += content[j].nodeSize;\n if (i) pos++;\n }\n return pos;\n }\n findAtPoint(parent, offset) {\n if (this.find) for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].node == parent && this.find[i].offset == offset) this.find[i].pos = this.currentPos;\n }\n }\n findInside(parent) {\n if (this.find) for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) this.find[i].pos = this.currentPos;\n }\n }\n findAround(parent, content, before) {\n if (parent != content && this.find) for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {\n let pos = content.compareDocumentPosition(this.find[i].node);\n if (pos & (before ? 2 : 4)) this.find[i].pos = this.currentPos;\n }\n }\n }\n findInText(textNode) {\n if (this.find) for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].node == textNode) this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);\n }\n }\n // Determines whether the given context string matches this context.\n matchesContext(context) {\n if (context.indexOf(\"|\") > -1) return context.split(/\\s*\\|\\s*/).some(this.matchesContext, this);\n let parts = context.split(\"/\");\n let option = this.options.context;\n let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);\n let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);\n let match = (i, depth) => {\n for (; i >= 0; i--) {\n let part = parts[i];\n if (part == \"\") {\n if (i == parts.length - 1 || i == 0) continue;\n for (; depth >= minDepth; depth--) if (match(i - 1, depth)) return true;\n return false;\n } else {\n let next = depth > 0 || depth == 0 && useRoot ? this.nodes[depth].type : option && depth >= minDepth ? option.node(depth - minDepth).type : null;\n if (!next || next.name != part && next.groups.indexOf(part) == -1) return false;\n depth--;\n }\n }\n return true;\n };\n return match(parts.length - 1, this.open);\n }\n textblockFromContext() {\n let $context = this.options.context;\n if ($context) for (let d = $context.depth; d >= 0; d--) {\n let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;\n if (deflt && deflt.isTextblock && deflt.defaultAttrs) return deflt;\n }\n for (let name in this.parser.schema.nodes) {\n let type = this.parser.schema.nodes[name];\n if (type.isTextblock && type.defaultAttrs) return type;\n }\n }\n addPendingMark(mark) {\n let found = findSameMarkInSet(mark, this.top.pendingMarks);\n if (found) this.top.stashMarks.push(found);\n this.top.pendingMarks = mark.addToSet(this.top.pendingMarks);\n }\n removePendingMark(mark, upto) {\n for (let depth = this.open; depth >= 0; depth--) {\n let level = this.nodes[depth];\n let found = level.pendingMarks.lastIndexOf(mark);\n if (found > -1) {\n level.pendingMarks = mark.removeFromSet(level.pendingMarks);\n } else {\n level.activeMarks = mark.removeFromSet(level.activeMarks);\n let stashMark = level.popFromStashMark(mark);\n if (stashMark && level.type && level.type.allowsMarkType(stashMark.type)) level.activeMarks = stashMark.addToSet(level.activeMarks);\n }\n if (level == upto) break;\n }\n }\n}\n// Kludge to work around directly nested list nodes produced by some\n// tools and allowed by browsers to mean that the nested list is\n// actually part of the list item above it.\nfunction normalizeList(dom) {\n for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {\n let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;\n if (name && listTags.hasOwnProperty(name) && prevItem) {\n prevItem.appendChild(child);\n child = prevItem;\n } else if (name == \"li\") {\n prevItem = child;\n } else if (name) {\n prevItem = null;\n }\n }\n}\n// Apply a CSS selector.\nfunction matches(dom, selector) {\n return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);\n}\nfunction copy(obj) {\n let copy = {};\n for (let prop in obj) copy[prop] = obj[prop];\n return copy;\n}\n// Used when finding a mark at the top level of a fragment parse.\n// Checks whether it would be reasonable to apply a given mark type to\n// a given node, by looking at the way the mark occurs in the schema.\nfunction markMayApply(markType, nodeType) {\n let nodes = nodeType.schema.nodes;\n for (let name in nodes) {\n let parent = nodes[name];\n if (!parent.allowsMarkType(markType)) continue;\n let seen = [],\n scan = match => {\n seen.push(match);\n for (let i = 0; i < match.edgeCount; i++) {\n let {\n type,\n next\n } = match.edge(i);\n if (type == nodeType) return true;\n if (seen.indexOf(next) < 0 && scan(next)) return true;\n }\n };\n if (scan(parent.contentMatch)) return true;\n }\n}\nfunction findSameMarkInSet(mark, set) {\n for (let i = 0; i < set.length; i++) {\n if (mark.eq(set[i])) return set[i];\n }\n}\n\n/**\nA DOM serializer knows how to convert ProseMirror nodes and\nmarks of various types to DOM nodes.\n*/\nclass DOMSerializer {\n /**\n Create a serializer. `nodes` should map node names to functions\n that take a node and return a description of the corresponding\n DOM. `marks` does the same for mark names, but also gets an\n argument that tells it whether the mark's content is block or\n inline content (for typical use, it'll always be inline). A mark\n serializer may be `null` to indicate that marks of that type\n should not be serialized.\n */\n constructor(\n /**\n The node serialization functions.\n */\n nodes,\n /**\n The mark serialization functions.\n */\n marks) {\n this.nodes = nodes;\n this.marks = marks;\n }\n /**\n Serialize the content of this fragment to a DOM fragment. When\n not in the browser, the `document` option, containing a DOM\n document, should be passed so that the serializer can create\n nodes.\n */\n serializeFragment(fragment, options = {}, target) {\n if (!target) target = doc(options).createDocumentFragment();\n let top = target,\n active = [];\n fragment.forEach(node => {\n if (active.length || node.marks.length) {\n let keep = 0,\n rendered = 0;\n while (keep < active.length && rendered < node.marks.length) {\n let next = node.marks[rendered];\n if (!this.marks[next.type.name]) {\n rendered++;\n continue;\n }\n if (!next.eq(active[keep][0]) || next.type.spec.spanning === false) break;\n keep++;\n rendered++;\n }\n while (keep < active.length) top = active.pop()[1];\n while (rendered < node.marks.length) {\n let add = node.marks[rendered++];\n let markDOM = this.serializeMark(add, node.isInline, options);\n if (markDOM) {\n active.push([add, top]);\n top.appendChild(markDOM.dom);\n top = markDOM.contentDOM || markDOM.dom;\n }\n }\n }\n top.appendChild(this.serializeNodeInner(node, options));\n });\n return target;\n }\n /**\n @internal\n */\n serializeNodeInner(node, options) {\n let {\n dom,\n contentDOM\n } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);\n if (contentDOM) {\n if (node.isLeaf) throw new RangeError(\"Content hole not allowed in a leaf node spec\");\n this.serializeFragment(node.content, options, contentDOM);\n }\n return dom;\n }\n /**\n Serialize this node to a DOM node. This can be useful when you\n need to serialize a part of a document, as opposed to the whole\n document. To serialize a whole document, use\n [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on\n its [content](https://prosemirror.net/docs/ref/#model.Node.content).\n */\n serializeNode(node, options = {}) {\n let dom = this.serializeNodeInner(node, options);\n for (let i = node.marks.length - 1; i >= 0; i--) {\n let wrap = this.serializeMark(node.marks[i], node.isInline, options);\n if (wrap) {\n (wrap.contentDOM || wrap.dom).appendChild(dom);\n dom = wrap.dom;\n }\n }\n return dom;\n }\n /**\n @internal\n */\n serializeMark(mark, inline, options = {}) {\n let toDOM = this.marks[mark.type.name];\n return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs);\n }\n static renderSpec(doc, structure, xmlNS = null, blockArraysIn) {\n return renderSpec(doc, structure, xmlNS, blockArraysIn);\n }\n /**\n Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)\n properties in a schema's node and mark specs.\n */\n static fromSchema(schema) {\n return schema.cached.domSerializer || (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));\n }\n /**\n Gather the serializers in a schema's node specs into an object.\n This can be useful as a base to build a custom serializer from.\n */\n static nodesFromSchema(schema) {\n let result = gatherToDOM(schema.nodes);\n if (!result.text) result.text = node => node.text;\n return result;\n }\n /**\n Gather the serializers in a schema's mark specs into an object.\n */\n static marksFromSchema(schema) {\n return gatherToDOM(schema.marks);\n }\n}\nfunction gatherToDOM(obj) {\n let result = {};\n for (let name in obj) {\n let toDOM = obj[name].spec.toDOM;\n if (toDOM) result[name] = toDOM;\n }\n return result;\n}\nfunction doc(options) {\n return options.document || window.document;\n}\nconst suspiciousAttributeCache = new WeakMap();\nfunction suspiciousAttributes(attrs) {\n let value = suspiciousAttributeCache.get(attrs);\n if (value === undefined) suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));\n return value;\n}\nfunction suspiciousAttributesInner(attrs) {\n let result = null;\n function scan(value) {\n if (value && typeof value == \"object\") {\n if (Array.isArray(value)) {\n if (typeof value[0] == \"string\") {\n if (!result) result = [];\n result.push(value);\n } else {\n for (let i = 0; i < value.length; i++) scan(value[i]);\n }\n } else {\n for (let prop in value) scan(value[prop]);\n }\n }\n }\n scan(attrs);\n return result;\n}\nfunction renderSpec(doc, structure, xmlNS, blockArraysIn) {\n if (typeof structure == \"string\") return {\n dom: doc.createTextNode(structure)\n };\n if (structure.nodeType != null) return {\n dom: structure\n };\n if (structure.dom && structure.dom.nodeType != null) return structure;\n let tagName = structure[0],\n suspicious;\n if (typeof tagName != \"string\") throw new RangeError(\"Invalid array passed to renderSpec\");\n if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) && suspicious.indexOf(structure) > -1) throw new RangeError(\"Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.\");\n let space = tagName.indexOf(\" \");\n if (space > 0) {\n xmlNS = tagName.slice(0, space);\n tagName = tagName.slice(space + 1);\n }\n let contentDOM;\n let dom = xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName);\n let attrs = structure[1],\n start = 1;\n if (attrs && typeof attrs == \"object\" && attrs.nodeType == null && !Array.isArray(attrs)) {\n start = 2;\n for (let name in attrs) if (attrs[name] != null) {\n let space = name.indexOf(\" \");\n if (space > 0) dom.setAttributeNS(name.slice(0, space), name.slice(space + 1), attrs[name]);else dom.setAttribute(name, attrs[name]);\n }\n }\n for (let i = start; i < structure.length; i++) {\n let child = structure[i];\n if (child === 0) {\n if (i < structure.length - 1 || i > start) throw new RangeError(\"Content hole must be the only child of its parent node\");\n return {\n dom,\n contentDOM: dom\n };\n } else {\n let {\n dom: inner,\n contentDOM: innerContent\n } = renderSpec(doc, child, xmlNS, blockArraysIn);\n dom.appendChild(inner);\n if (innerContent) {\n if (contentDOM) throw new RangeError(\"Multiple content holes\");\n contentDOM = innerContent;\n }\n }\n }\n return {\n dom,\n contentDOM\n };\n}\nexport { ContentMatch, DOMParser, DOMSerializer, Fragment, Mark, MarkType, Node, NodeRange, NodeType, ReplaceError, ResolvedPos, Schema, Slice };","import { ReplaceError, Slice, Fragment, MarkType, Mark } from 'prosemirror-model';\n\n// Recovery values encode a range index and an offset. They are\n// represented as numbers, because tons of them will be created when\n// mapping, for example, a large number of decorations. The number's\n// lower 16 bits provide the index, the remaining bits the offset.\n//\n// Note: We intentionally don't use bit shift operators to en- and\n// decode these, since those clip to 32 bits, which we might in rare\n// cases want to overflow. A 64-bit float can represent 48-bit\n// integers precisely.\nconst lower16 = 0xffff;\nconst factor16 = Math.pow(2, 16);\nfunction makeRecover(index, offset) {\n return index + offset * factor16;\n}\nfunction recoverIndex(value) {\n return value & lower16;\n}\nfunction recoverOffset(value) {\n return (value - (value & lower16)) / factor16;\n}\nconst DEL_BEFORE = 1,\n DEL_AFTER = 2,\n DEL_ACROSS = 4,\n DEL_SIDE = 8;\n/**\nAn object representing a mapped position with extra\ninformation.\n*/\nclass MapResult {\n /**\n @internal\n */\n constructor(\n /**\n The mapped version of the position.\n */\n pos,\n /**\n @internal\n */\n delInfo,\n /**\n @internal\n */\n recover) {\n this.pos = pos;\n this.delInfo = delInfo;\n this.recover = recover;\n }\n /**\n Tells you whether the position was deleted, that is, whether the\n step removed the token on the side queried (via the `assoc`)\n argument from the document.\n */\n get deleted() {\n return (this.delInfo & DEL_SIDE) > 0;\n }\n /**\n Tells you whether the token before the mapped position was deleted.\n */\n get deletedBefore() {\n return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0;\n }\n /**\n True when the token after the mapped position was deleted.\n */\n get deletedAfter() {\n return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0;\n }\n /**\n Tells whether any of the steps mapped through deletes across the\n position (including both the token before and after the\n position).\n */\n get deletedAcross() {\n return (this.delInfo & DEL_ACROSS) > 0;\n }\n}\n/**\nA map describing the deletions and insertions made by a step, which\ncan be used to find the correspondence between positions in the\npre-step version of a document and the same position in the\npost-step version.\n*/\nclass StepMap {\n /**\n Create a position map. The modifications to the document are\n represented as an array of numbers, in which each group of three\n represents a modified chunk as `[start, oldSize, newSize]`.\n */\n constructor(\n /**\n @internal\n */\n ranges,\n /**\n @internal\n */\n inverted = false) {\n this.ranges = ranges;\n this.inverted = inverted;\n if (!ranges.length && StepMap.empty) return StepMap.empty;\n }\n /**\n @internal\n */\n recover(value) {\n let diff = 0,\n index = recoverIndex(value);\n if (!this.inverted) for (let i = 0; i < index; i++) diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];\n return this.ranges[index * 3] + diff + recoverOffset(value);\n }\n mapResult(pos, assoc = 1) {\n return this._map(pos, assoc, false);\n }\n map(pos, assoc = 1) {\n return this._map(pos, assoc, true);\n }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let diff = 0,\n oldIndex = this.inverted ? 2 : 1,\n newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos) break;\n let oldSize = this.ranges[i + oldIndex],\n newSize = this.ranges[i + newIndex],\n end = start + oldSize;\n if (pos <= end) {\n let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;\n let result = start + diff + (side < 0 ? 0 : newSize);\n if (simple) return result;\n let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);\n let del = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;\n if (assoc < 0 ? pos != start : pos != end) del |= DEL_SIDE;\n return new MapResult(result, del, recover);\n }\n diff += newSize - oldSize;\n }\n return simple ? pos + diff : new MapResult(pos + diff, 0, null);\n }\n /**\n @internal\n */\n touches(pos, recover) {\n let diff = 0,\n index = recoverIndex(recover);\n let oldIndex = this.inverted ? 2 : 1,\n newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos) break;\n let oldSize = this.ranges[i + oldIndex],\n end = start + oldSize;\n if (pos <= end && i == index * 3) return true;\n diff += this.ranges[i + newIndex] - oldSize;\n }\n return false;\n }\n /**\n Calls the given function on each of the changed ranges included in\n this map.\n */\n forEach(f) {\n let oldIndex = this.inverted ? 2 : 1,\n newIndex = this.inverted ? 1 : 2;\n for (let i = 0, diff = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i],\n oldStart = start - (this.inverted ? diff : 0),\n newStart = start + (this.inverted ? 0 : diff);\n let oldSize = this.ranges[i + oldIndex],\n newSize = this.ranges[i + newIndex];\n f(oldStart, oldStart + oldSize, newStart, newStart + newSize);\n diff += newSize - oldSize;\n }\n }\n /**\n Create an inverted version of this map. The result can be used to\n map positions in the post-step document to the pre-step document.\n */\n invert() {\n return new StepMap(this.ranges, !this.inverted);\n }\n /**\n @internal\n */\n toString() {\n return (this.inverted ? \"-\" : \"\") + JSON.stringify(this.ranges);\n }\n /**\n Create a map that moves all positions by offset `n` (which may be\n negative). This can be useful when applying steps meant for a\n sub-document to a larger document, or vice-versa.\n */\n static offset(n) {\n return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);\n }\n}\n/**\nA StepMap that contains no changed ranges.\n*/\nStepMap.empty = new StepMap([]);\n/**\nA mapping represents a pipeline of zero or more [step\nmaps](https://prosemirror.net/docs/ref/#transform.StepMap). It has special provisions for losslessly\nhandling mapping positions through a series of steps in which some\nsteps are inverted versions of earlier steps. (This comes up when\n‘[rebasing](/docs/guide/#transform.rebasing)’ steps for\ncollaboration or history management.)\n*/\nclass Mapping {\n /**\n Create a new mapping with the given position maps.\n */\n constructor(\n /**\n The step maps in this mapping.\n */\n maps = [],\n /**\n @internal\n */\n mirror,\n /**\n The starting position in the `maps` array, used when `map` or\n `mapResult` is called.\n */\n from = 0,\n /**\n The end position in the `maps` array.\n */\n to = maps.length) {\n this.maps = maps;\n this.mirror = mirror;\n this.from = from;\n this.to = to;\n }\n /**\n Create a mapping that maps only through a part of this one.\n */\n slice(from = 0, to = this.maps.length) {\n return new Mapping(this.maps, this.mirror, from, to);\n }\n /**\n @internal\n */\n copy() {\n return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.to);\n }\n /**\n Add a step map to the end of this mapping. If `mirrors` is\n given, it should be the index of the step map that is the mirror\n image of this one.\n */\n appendMap(map, mirrors) {\n this.to = this.maps.push(map);\n if (mirrors != null) this.setMirror(this.maps.length - 1, mirrors);\n }\n /**\n Add all the step maps in a given mapping to this one (preserving\n mirroring information).\n */\n appendMapping(mapping) {\n for (let i = 0, startSize = this.maps.length; i < mapping.maps.length; i++) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping.maps[i], mirr != null && mirr < i ? startSize + mirr : undefined);\n }\n }\n /**\n Finds the offset of the step map that mirrors the map at the\n given offset, in this mapping (as per the second argument to\n `appendMap`).\n */\n getMirror(n) {\n if (this.mirror) for (let i = 0; i < this.mirror.length; i++) if (this.mirror[i] == n) return this.mirror[i + (i % 2 ? -1 : 1)];\n }\n /**\n @internal\n */\n setMirror(n, m) {\n if (!this.mirror) this.mirror = [];\n this.mirror.push(n, m);\n }\n /**\n Append the inverse of the given mapping to this one.\n */\n appendMappingInverted(mapping) {\n for (let i = mapping.maps.length - 1, totalSize = this.maps.length + mapping.maps.length; i >= 0; i--) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping.maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : undefined);\n }\n }\n /**\n Create an inverted version of this mapping.\n */\n invert() {\n let inverse = new Mapping();\n inverse.appendMappingInverted(this);\n return inverse;\n }\n /**\n Map a position through this mapping.\n */\n map(pos, assoc = 1) {\n if (this.mirror) return this._map(pos, assoc, true);\n for (let i = this.from; i < this.to; i++) pos = this.maps[i].map(pos, assoc);\n return pos;\n }\n /**\n Map a position through this mapping, returning a mapping\n result.\n */\n mapResult(pos, assoc = 1) {\n return this._map(pos, assoc, false);\n }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let delInfo = 0;\n for (let i = this.from; i < this.to; i++) {\n let map = this.maps[i],\n result = map.mapResult(pos, assoc);\n if (result.recover != null) {\n let corr = this.getMirror(i);\n if (corr != null && corr > i && corr < this.to) {\n i = corr;\n pos = this.maps[corr].recover(result.recover);\n continue;\n }\n }\n delInfo |= result.delInfo;\n pos = result.pos;\n }\n return simple ? pos : new MapResult(pos, delInfo, null);\n }\n}\nconst stepsByID = Object.create(null);\n/**\nA step object represents an atomic change. It generally applies\nonly to the document it was created for, since the positions\nstored in it will only make sense for that document.\n\nNew steps are defined by creating classes that extend `Step`,\noverriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`\nmethods, and registering your class with a unique\nJSON-serialization identifier using\n[`Step.jsonID`](https://prosemirror.net/docs/ref/#transform.Step^jsonID).\n*/\nclass Step {\n /**\n Get the step map that represents the changes made by this step,\n and which can be used to transform between positions in the old\n and the new document.\n */\n getMap() {\n return StepMap.empty;\n }\n /**\n Try to merge this step with another one, to be applied directly\n after it. Returns the merged step when possible, null if the\n steps can't be merged.\n */\n merge(other) {\n return null;\n }\n /**\n Deserialize a step from its JSON representation. Will call\n through to the step class' own implementation of this method.\n */\n static fromJSON(schema, json) {\n if (!json || !json.stepType) throw new RangeError(\"Invalid input for Step.fromJSON\");\n let type = stepsByID[json.stepType];\n if (!type) throw new RangeError(`No step type ${json.stepType} defined`);\n return type.fromJSON(schema, json);\n }\n /**\n To be able to serialize steps to JSON, each step needs a string\n ID to attach to its JSON representation. Use this method to\n register an ID for your step classes. Try to pick something\n that's unlikely to clash with steps from other modules.\n */\n static jsonID(id, stepClass) {\n if (id in stepsByID) throw new RangeError(\"Duplicate use of step JSON ID \" + id);\n stepsByID[id] = stepClass;\n stepClass.prototype.jsonID = id;\n return stepClass;\n }\n}\n/**\nThe result of [applying](https://prosemirror.net/docs/ref/#transform.Step.apply) a step. Contains either a\nnew document or a failure value.\n*/\nclass StepResult {\n /**\n @internal\n */\n constructor(\n /**\n The transformed document, if successful.\n */\n doc,\n /**\n The failure message, if unsuccessful.\n */\n failed) {\n this.doc = doc;\n this.failed = failed;\n }\n /**\n Create a successful step result.\n */\n static ok(doc) {\n return new StepResult(doc, null);\n }\n /**\n Create a failed step result.\n */\n static fail(message) {\n return new StepResult(null, message);\n }\n /**\n Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given\n arguments. Create a successful result if it succeeds, and a\n failed one if it throws a `ReplaceError`.\n */\n static fromReplace(doc, from, to, slice) {\n try {\n return StepResult.ok(doc.replace(from, to, slice));\n } catch (e) {\n if (e instanceof ReplaceError) return StepResult.fail(e.message);\n throw e;\n }\n }\n}\nfunction mapFragment(fragment, f, parent) {\n let mapped = [];\n for (let i = 0; i < fragment.childCount; i++) {\n let child = fragment.child(i);\n if (child.content.size) child = child.copy(mapFragment(child.content, f, child));\n if (child.isInline) child = f(child, parent, i);\n mapped.push(child);\n }\n return Fragment.fromArray(mapped);\n}\n/**\nAdd a mark to all inline content between two positions.\n*/\nclass AddMarkStep extends Step {\n /**\n Create a mark step.\n */\n constructor(\n /**\n The start of the marked range.\n */\n from,\n /**\n The end of the marked range.\n */\n to,\n /**\n The mark to add.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to),\n $from = doc.resolve(this.from);\n let parent = $from.node($from.sharedDepth(this.to));\n let slice = new Slice(mapFragment(oldSlice.content, (node, parent) => {\n if (!node.isAtom || !parent.type.allowsMarkType(this.mark.type)) return node;\n return node.mark(this.mark.addToSet(node.marks));\n }, parent), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert() {\n return new RemoveMarkStep(this.from, this.to, this.mark);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1),\n to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos) return null;\n return new AddMarkStep(from.pos, to.pos, this.mark);\n }\n merge(other) {\n if (other instanceof AddMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from) return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return {\n stepType: \"addMark\",\n mark: this.mark.toJSON(),\n from: this.from,\n to: this.to\n };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\") throw new RangeError(\"Invalid input for AddMarkStep.fromJSON\");\n return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addMark\", AddMarkStep);\n/**\nRemove a mark from all inline content between two positions.\n*/\nclass RemoveMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The start of the unmarked range.\n */\n from,\n /**\n The end of the unmarked range.\n */\n to,\n /**\n The mark to remove.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to);\n let slice = new Slice(mapFragment(oldSlice.content, node => {\n return node.mark(this.mark.removeFromSet(node.marks));\n }, doc), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert() {\n return new AddMarkStep(this.from, this.to, this.mark);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1),\n to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos) return null;\n return new RemoveMarkStep(from.pos, to.pos, this.mark);\n }\n merge(other) {\n if (other instanceof RemoveMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from) return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return {\n stepType: \"removeMark\",\n mark: this.mark.toJSON(),\n from: this.from,\n to: this.to\n };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\") throw new RangeError(\"Invalid input for RemoveMarkStep.fromJSON\");\n return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeMark\", RemoveMarkStep);\n/**\nAdd a mark to a specific node.\n*/\nclass AddNodeMarkStep extends Step {\n /**\n Create a node mark step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos,\n /**\n The mark to add.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node) return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (node) {\n let newSet = this.mark.addToSet(node.marks);\n if (newSet.length == node.marks.length) {\n for (let i = 0; i < node.marks.length; i++) if (!node.marks[i].isInSet(newSet)) return new AddNodeMarkStep(this.pos, node.marks[i]);\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n }\n return new RemoveNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return {\n stepType: \"addNodeMark\",\n pos: this.pos,\n mark: this.mark.toJSON()\n };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\") throw new RangeError(\"Invalid input for AddNodeMarkStep.fromJSON\");\n return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addNodeMark\", AddNodeMarkStep);\n/**\nRemove a mark from a specific node.\n*/\nclass RemoveNodeMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos,\n /**\n The mark to remove.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node) return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node || !this.mark.isInSet(node.marks)) return this;\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return {\n stepType: \"removeNodeMark\",\n pos: this.pos,\n mark: this.mark.toJSON()\n };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\") throw new RangeError(\"Invalid input for RemoveNodeMarkStep.fromJSON\");\n return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeNodeMark\", RemoveNodeMarkStep);\n\n/**\nReplace a part of the document with a slice of new content.\n*/\nclass ReplaceStep extends Step {\n /**\n The given `slice` should fit the 'gap' between `from` and\n `to`—the depths must line up, and the surrounding nodes must be\n able to be joined with the open sides of the slice. When\n `structure` is true, the step will fail if the content between\n from and to is not just a sequence of closing and then opening\n tokens (this is to guard against rebased replace steps\n overwriting something they weren't supposed to).\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from,\n /**\n The end position of the replaced range.\n */\n to,\n /**\n The slice to insert.\n */\n slice,\n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.slice = slice;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && contentBetween(doc, this.from, this.to)) return StepResult.fail(\"Structure replace would overwrite content\");\n return StepResult.fromReplace(doc, this.from, this.to, this.slice);\n }\n getMap() {\n return new StepMap([this.from, this.to - this.from, this.slice.size]);\n }\n invert(doc) {\n return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to));\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1),\n to = mapping.mapResult(this.to, -1);\n if (from.deletedAcross && to.deletedAcross) return null;\n return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice);\n }\n merge(other) {\n if (!(other instanceof ReplaceStep) || other.structure || this.structure) return null;\n if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);\n return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure);\n } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);\n return new ReplaceStep(other.from, this.to, slice, this.structure);\n } else {\n return null;\n }\n }\n toJSON() {\n let json = {\n stepType: \"replace\",\n from: this.from,\n to: this.to\n };\n if (this.slice.size) json.slice = this.slice.toJSON();\n if (this.structure) json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\") throw new RangeError(\"Invalid input for ReplaceStep.fromJSON\");\n return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);\n }\n}\nStep.jsonID(\"replace\", ReplaceStep);\n/**\nReplace a part of the document with a slice of content, but\npreserve a range of the replaced content by moving it into the\nslice.\n*/\nclass ReplaceAroundStep extends Step {\n /**\n Create a replace-around step with the given range and gap.\n `insert` should be the point in the slice into which the content\n of the gap should be moved. `structure` has the same meaning as\n it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from,\n /**\n The end position of the replaced range.\n */\n to,\n /**\n The start of preserved range.\n */\n gapFrom,\n /**\n The end of preserved range.\n */\n gapTo,\n /**\n The slice to insert.\n */\n slice,\n /**\n The position in the slice where the preserved range should be\n inserted.\n */\n insert,\n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.gapFrom = gapFrom;\n this.gapTo = gapTo;\n this.slice = slice;\n this.insert = insert;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && (contentBetween(doc, this.from, this.gapFrom) || contentBetween(doc, this.gapTo, this.to))) return StepResult.fail(\"Structure gap-replace would overwrite content\");\n let gap = doc.slice(this.gapFrom, this.gapTo);\n if (gap.openStart || gap.openEnd) return StepResult.fail(\"Gap is not a flat range\");\n let inserted = this.slice.insertAt(this.insert, gap.content);\n if (!inserted) return StepResult.fail(\"Content does not fit in gap\");\n return StepResult.fromReplace(doc, this.from, this.to, inserted);\n }\n getMap() {\n return new StepMap([this.from, this.gapFrom - this.from, this.insert, this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]);\n }\n invert(doc) {\n let gap = this.gapTo - this.gapFrom;\n return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1),\n to = mapping.mapResult(this.to, -1);\n let gapFrom = this.from == this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1);\n let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);\n if (from.deletedAcross && to.deletedAcross || gapFrom < from.pos || gapTo > to.pos) return null;\n return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);\n }\n toJSON() {\n let json = {\n stepType: \"replaceAround\",\n from: this.from,\n to: this.to,\n gapFrom: this.gapFrom,\n gapTo: this.gapTo,\n insert: this.insert\n };\n if (this.slice.size) json.slice = this.slice.toJSON();\n if (this.structure) json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\" || typeof json.gapFrom != \"number\" || typeof json.gapTo != \"number\" || typeof json.insert != \"number\") throw new RangeError(\"Invalid input for ReplaceAroundStep.fromJSON\");\n return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);\n }\n}\nStep.jsonID(\"replaceAround\", ReplaceAroundStep);\nfunction contentBetween(doc, from, to) {\n let $from = doc.resolve(from),\n dist = to - from,\n depth = $from.depth;\n while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {\n depth--;\n dist--;\n }\n if (dist > 0) {\n let next = $from.node(depth).maybeChild($from.indexAfter(depth));\n while (dist > 0) {\n if (!next || next.isLeaf) return true;\n next = next.firstChild;\n dist--;\n }\n }\n return false;\n}\nfunction addMark(tr, from, to, mark) {\n let removed = [],\n added = [];\n let removing, adding;\n tr.doc.nodesBetween(from, to, (node, pos, parent) => {\n if (!node.isInline) return;\n let marks = node.marks;\n if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {\n let start = Math.max(pos, from),\n end = Math.min(pos + node.nodeSize, to);\n let newSet = mark.addToSet(marks);\n for (let i = 0; i < marks.length; i++) {\n if (!marks[i].isInSet(newSet)) {\n if (removing && removing.to == start && removing.mark.eq(marks[i])) removing.to = end;else removed.push(removing = new RemoveMarkStep(start, end, marks[i]));\n }\n }\n if (adding && adding.to == start) adding.to = end;else added.push(adding = new AddMarkStep(start, end, mark));\n }\n });\n removed.forEach(s => tr.step(s));\n added.forEach(s => tr.step(s));\n}\nfunction removeMark(tr, from, to, mark) {\n let matched = [],\n step = 0;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isInline) return;\n step++;\n let toRemove = null;\n if (mark instanceof MarkType) {\n let set = node.marks,\n found;\n while (found = mark.isInSet(set)) {\n (toRemove || (toRemove = [])).push(found);\n set = found.removeFromSet(set);\n }\n } else if (mark) {\n if (mark.isInSet(node.marks)) toRemove = [mark];\n } else {\n toRemove = node.marks;\n }\n if (toRemove && toRemove.length) {\n let end = Math.min(pos + node.nodeSize, to);\n for (let i = 0; i < toRemove.length; i++) {\n let style = toRemove[i],\n found;\n for (let j = 0; j < matched.length; j++) {\n let m = matched[j];\n if (m.step == step - 1 && style.eq(matched[j].style)) found = m;\n }\n if (found) {\n found.to = end;\n found.step = step;\n } else {\n matched.push({\n style,\n from: Math.max(pos, from),\n to: end,\n step\n });\n }\n }\n }\n });\n matched.forEach(m => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));\n}\nfunction clearIncompatible(tr, pos, parentType, match = parentType.contentMatch, clearNewlines = true) {\n let node = tr.doc.nodeAt(pos);\n let replSteps = [],\n cur = pos + 1;\n for (let i = 0; i < node.childCount; i++) {\n let child = node.child(i),\n end = cur + child.nodeSize;\n let allowed = match.matchType(child.type);\n if (!allowed) {\n replSteps.push(new ReplaceStep(cur, end, Slice.empty));\n } else {\n match = allowed;\n for (let j = 0; j < child.marks.length; j++) if (!parentType.allowsMarkType(child.marks[j].type)) tr.step(new RemoveMarkStep(cur, end, child.marks[j]));\n if (clearNewlines && child.isText && parentType.whitespace != \"pre\") {\n let m,\n newline = /\\r?\\n|\\r/g,\n slice;\n while (m = newline.exec(child.text)) {\n if (!slice) slice = new Slice(Fragment.from(parentType.schema.text(\" \", parentType.allowedMarks(child.marks))), 0, 0);\n replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice));\n }\n }\n }\n cur = end;\n }\n if (!match.validEnd) {\n let fill = match.fillBefore(Fragment.empty, true);\n tr.replace(cur, cur, new Slice(fill, 0, 0));\n }\n for (let i = replSteps.length - 1; i >= 0; i--) tr.step(replSteps[i]);\n}\nfunction canCut(node, start, end) {\n return (start == 0 || node.canReplace(start, node.childCount)) && (end == node.childCount || node.canReplace(0, end));\n}\n/**\nTry to find a target depth to which the content in the given range\ncan be lifted. Will not go across\n[isolating](https://prosemirror.net/docs/ref/#model.NodeSpec.isolating) parent nodes.\n*/\nfunction liftTarget(range) {\n let parent = range.parent;\n let content = parent.content.cutByIndex(range.startIndex, range.endIndex);\n for (let depth = range.depth;; --depth) {\n let node = range.$from.node(depth);\n let index = range.$from.index(depth),\n endIndex = range.$to.indexAfter(depth);\n if (depth < range.depth && node.canReplace(index, endIndex, content)) return depth;\n if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex)) break;\n }\n return null;\n}\nfunction lift(tr, range, target) {\n let {\n $from,\n $to,\n depth\n } = range;\n let gapStart = $from.before(depth + 1),\n gapEnd = $to.after(depth + 1);\n let start = gapStart,\n end = gapEnd;\n let before = Fragment.empty,\n openStart = 0;\n for (let d = depth, splitting = false; d > target; d--) if (splitting || $from.index(d) > 0) {\n splitting = true;\n before = Fragment.from($from.node(d).copy(before));\n openStart++;\n } else {\n start--;\n }\n let after = Fragment.empty,\n openEnd = 0;\n for (let d = depth, splitting = false; d > target; d--) if (splitting || $to.after(d + 1) < $to.end(d)) {\n splitting = true;\n after = Fragment.from($to.node(d).copy(after));\n openEnd++;\n } else {\n end++;\n }\n tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));\n}\n/**\nTry to find a valid way to wrap the content in the given range in a\nnode of the given type. May introduce extra nodes around and inside\nthe wrapper node, if necessary. Returns null if no valid wrapping\ncould be found. When `innerRange` is given, that range's content is\nused as the content to fit into the wrapping, instead of the\ncontent of `range`.\n*/\nfunction findWrapping(range, nodeType, attrs = null, innerRange = range) {\n let around = findWrappingOutside(range, nodeType);\n let inner = around && findWrappingInside(innerRange, nodeType);\n if (!inner) return null;\n return around.map(withAttrs).concat({\n type: nodeType,\n attrs\n }).concat(inner.map(withAttrs));\n}\nfunction withAttrs(type) {\n return {\n type,\n attrs: null\n };\n}\nfunction findWrappingOutside(range, type) {\n let {\n parent,\n startIndex,\n endIndex\n } = range;\n let around = parent.contentMatchAt(startIndex).findWrapping(type);\n if (!around) return null;\n let outer = around.length ? around[0] : type;\n return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;\n}\nfunction findWrappingInside(range, type) {\n let {\n parent,\n startIndex,\n endIndex\n } = range;\n let inner = parent.child(startIndex);\n let inside = type.contentMatch.findWrapping(inner.type);\n if (!inside) return null;\n let lastType = inside.length ? inside[inside.length - 1] : type;\n let innerMatch = lastType.contentMatch;\n for (let i = startIndex; innerMatch && i < endIndex; i++) innerMatch = innerMatch.matchType(parent.child(i).type);\n if (!innerMatch || !innerMatch.validEnd) return null;\n return inside;\n}\nfunction wrap(tr, range, wrappers) {\n let content = Fragment.empty;\n for (let i = wrappers.length - 1; i >= 0; i--) {\n if (content.size) {\n let match = wrappers[i].type.contentMatch.matchFragment(content);\n if (!match || !match.validEnd) throw new RangeError(\"Wrapper type given to Transform.wrap does not form valid content of its parent wrapper\");\n }\n content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n }\n let start = range.start,\n end = range.end;\n tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));\n}\nfunction setBlockType(tr, from, to, type, attrs) {\n if (!type.isTextblock) throw new RangeError(\"Type given to setBlockType should be a textblock\");\n let mapFrom = tr.steps.length;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n if (node.isTextblock && !node.hasMarkup(type, attrs) && canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {\n let convertNewlines = null;\n if (type.schema.linebreakReplacement) {\n let pre = type.whitespace == \"pre\",\n supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);\n if (pre && !supportLinebreak) convertNewlines = false;else if (!pre && supportLinebreak) convertNewlines = true;\n }\n // Ensure all markup that isn't allowed in the new node type is cleared\n if (convertNewlines === false) replaceLinebreaks(tr, node, pos, mapFrom);\n clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type, undefined, convertNewlines === null);\n let mapping = tr.mapping.slice(mapFrom);\n let startM = mapping.map(pos, 1),\n endM = mapping.map(pos + node.nodeSize, 1);\n tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrs, null, node.marks)), 0, 0), 1, true));\n if (convertNewlines === true) replaceNewlines(tr, node, pos, mapFrom);\n return false;\n }\n });\n}\nfunction replaceNewlines(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.isText) {\n let m,\n newline = /\\r?\\n|\\r/g;\n while (m = newline.exec(child.text)) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset + m.index);\n tr.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create());\n }\n }\n });\n}\nfunction replaceLinebreaks(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.type == child.type.schema.linebreakReplacement) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset);\n tr.replaceWith(start, start + 1, node.type.schema.text(\"\\n\"));\n }\n });\n}\nfunction canChangeType(doc, pos, type) {\n let $pos = doc.resolve(pos),\n index = $pos.index();\n return $pos.parent.canReplaceWith(index, index + 1, type);\n}\n/**\nChange the type, attributes, and/or marks of the node at `pos`.\nWhen `type` isn't given, the existing node type is preserved,\n*/\nfunction setNodeMarkup(tr, pos, type, attrs, marks) {\n let node = tr.doc.nodeAt(pos);\n if (!node) throw new RangeError(\"No node at given position\");\n if (!type) type = node.type;\n let newNode = type.create(attrs, null, marks || node.marks);\n if (node.isLeaf) return tr.replaceWith(pos, pos + node.nodeSize, newNode);\n if (!type.validContent(node.content)) throw new RangeError(\"Invalid content for node type \" + type.name);\n tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));\n}\n/**\nCheck whether splitting at the given position is allowed.\n*/\nfunction canSplit(doc, pos, depth = 1, typesAfter) {\n let $pos = doc.resolve(pos),\n base = $pos.depth - depth;\n let innerType = typesAfter && typesAfter[typesAfter.length - 1] || $pos.parent;\n if (base < 0 || $pos.parent.type.spec.isolating || !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) || !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount))) return false;\n for (let d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {\n let node = $pos.node(d),\n index = $pos.index(d);\n if (node.type.spec.isolating) return false;\n let rest = node.content.cutByIndex(index, node.childCount);\n let overrideChild = typesAfter && typesAfter[i + 1];\n if (overrideChild) rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));\n let after = typesAfter && typesAfter[i] || node;\n if (!node.canReplace(index + 1, node.childCount) || !after.type.validContent(rest)) return false;\n }\n let index = $pos.indexAfter(base);\n let baseType = typesAfter && typesAfter[0];\n return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type);\n}\nfunction split(tr, pos, depth = 1, typesAfter) {\n let $pos = tr.doc.resolve(pos),\n before = Fragment.empty,\n after = Fragment.empty;\n for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {\n before = Fragment.from($pos.node(d).copy(before));\n let typeAfter = typesAfter && typesAfter[i];\n after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));\n }\n tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));\n}\n/**\nTest whether the blocks before and after a given position can be\njoined.\n*/\nfunction canJoin(doc, pos) {\n let $pos = doc.resolve(pos),\n index = $pos.index();\n return joinable($pos.nodeBefore, $pos.nodeAfter) && $pos.parent.canReplace(index, index + 1);\n}\nfunction joinable(a, b) {\n return !!(a && b && !a.isLeaf && a.canAppend(b));\n}\n/**\nFind an ancestor of the given position that can be joined to the\nblock before (or after if `dir` is positive). Returns the joinable\npoint, if any.\n*/\nfunction joinPoint(doc, pos, dir = -1) {\n let $pos = doc.resolve(pos);\n for (let d = $pos.depth;; d--) {\n let before,\n after,\n index = $pos.index(d);\n if (d == $pos.depth) {\n before = $pos.nodeBefore;\n after = $pos.nodeAfter;\n } else if (dir > 0) {\n before = $pos.node(d + 1);\n index++;\n after = $pos.node(d).maybeChild(index);\n } else {\n before = $pos.node(d).maybeChild(index - 1);\n after = $pos.node(d + 1);\n }\n if (before && !before.isTextblock && joinable(before, after) && $pos.node(d).canReplace(index, index + 1)) return pos;\n if (d == 0) break;\n pos = dir < 0 ? $pos.before(d) : $pos.after(d);\n }\n}\nfunction join(tr, pos, depth) {\n let step = new ReplaceStep(pos - depth, pos + depth, Slice.empty, true);\n tr.step(step);\n}\n/**\nTry to find a point where a node of the given type can be inserted\nnear `pos`, by searching up the node hierarchy when `pos` itself\nisn't a valid place but is at the start or end of a node. Return\nnull if no position was found.\n*/\nfunction insertPoint(doc, pos, nodeType) {\n let $pos = doc.resolve(pos);\n if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType)) return pos;\n if ($pos.parentOffset == 0) for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.index(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType)) return $pos.before(d + 1);\n if (index > 0) return null;\n }\n if ($pos.parentOffset == $pos.parent.content.size) for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.indexAfter(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType)) return $pos.after(d + 1);\n if (index < $pos.node(d).childCount) return null;\n }\n return null;\n}\n/**\nFinds a position at or around the given position where the given\nslice can be inserted. Will look at parent nodes' nearest boundary\nand try there, even if the original position wasn't directly at the\nstart or end of that node. Returns null when no position was found.\n*/\nfunction dropPoint(doc, pos, slice) {\n let $pos = doc.resolve(pos);\n if (!slice.content.size) return pos;\n let content = slice.content;\n for (let i = 0; i < slice.openStart; i++) content = content.firstChild.content;\n for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {\n for (let d = $pos.depth; d >= 0; d--) {\n let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;\n let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);\n let parent = $pos.node(d),\n fits = false;\n if (pass == 1) {\n fits = parent.canReplace(insertPos, insertPos, content);\n } else {\n let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);\n fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);\n }\n if (fits) return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);\n }\n }\n return null;\n}\n\n/**\n‘Fit’ a slice into a given position in the document, producing a\n[step](https://prosemirror.net/docs/ref/#transform.Step) that inserts it. Will return null if\nthere's no meaningful way to insert the slice here, or inserting it\nwould be a no-op (an empty slice over an empty range).\n*/\nfunction replaceStep(doc, from, to = from, slice = Slice.empty) {\n if (from == to && !slice.size) return null;\n let $from = doc.resolve(from),\n $to = doc.resolve(to);\n // Optimization -- avoid work if it's obvious that it's not needed.\n if (fitsTrivially($from, $to, slice)) return new ReplaceStep(from, to, slice);\n return new Fitter($from, $to, slice).fit();\n}\nfunction fitsTrivially($from, $to, slice) {\n return !slice.openStart && !slice.openEnd && $from.start() == $to.start() && $from.parent.canReplace($from.index(), $to.index(), slice.content);\n}\n// Algorithm for 'placing' the elements of a slice into a gap:\n//\n// We consider the content of each node that is open to the left to be\n// independently placeable. I.e. in , when the\n// paragraph on the left is open, \"foo\" can be placed (somewhere on\n// the left side of the replacement gap) independently from p(\"bar\").\n//\n// This class tracks the state of the placement progress in the\n// following properties:\n//\n// - `frontier` holds a stack of `{type, match}` objects that\n// represent the open side of the replacement. It starts at\n// `$from`, then moves forward as content is placed, and is finally\n// reconciled with `$to`.\n//\n// - `unplaced` is a slice that represents the content that hasn't\n// been placed yet.\n//\n// - `placed` is a fragment of placed content. Its open-start value\n// is implicit in `$from`, and its open-end value in `frontier`.\nclass Fitter {\n constructor($from, $to, unplaced) {\n this.$from = $from;\n this.$to = $to;\n this.unplaced = unplaced;\n this.frontier = [];\n this.placed = Fragment.empty;\n for (let i = 0; i <= $from.depth; i++) {\n let node = $from.node(i);\n this.frontier.push({\n type: node.type,\n match: node.contentMatchAt($from.indexAfter(i))\n });\n }\n for (let i = $from.depth; i > 0; i--) this.placed = Fragment.from($from.node(i).copy(this.placed));\n }\n get depth() {\n return this.frontier.length - 1;\n }\n fit() {\n // As long as there's unplaced content, try to place some of it.\n // If that fails, either increase the open score of the unplaced\n // slice, or drop nodes from it, and then try again.\n while (this.unplaced.size) {\n let fit = this.findFittable();\n if (fit) this.placeNodes(fit);else this.openMore() || this.dropNode();\n }\n // When there's inline content directly after the frontier _and_\n // directly after `this.$to`, we must generate a `ReplaceAround`\n // step that pulls that content into the node after the frontier.\n // That means the fitting must be done to the end of the textblock\n // node after `this.$to`, not `this.$to` itself.\n let moveInline = this.mustMoveInline(),\n placedSize = this.placed.size - this.depth - this.$from.depth;\n let $from = this.$from,\n $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));\n if (!$to) return null;\n // If closing to `$to` succeeded, create a step\n let content = this.placed,\n openStart = $from.depth,\n openEnd = $to.depth;\n while (openStart && openEnd && content.childCount == 1) {\n // Normalize by dropping open parent nodes\n content = content.firstChild.content;\n openStart--;\n openEnd--;\n }\n let slice = new Slice(content, openStart, openEnd);\n if (moveInline > -1) return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize);\n if (slice.size || $from.pos != this.$to.pos)\n // Don't generate no-op steps\n return new ReplaceStep($from.pos, $to.pos, slice);\n return null;\n }\n // Find a position on the start spine of `this.unplaced` that has\n // content that can be moved somewhere on the frontier. Returns two\n // depths, one for the slice and one for the frontier.\n findFittable() {\n let startDepth = this.unplaced.openStart;\n for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {\n let node = cur.firstChild;\n if (cur.childCount > 1) openEnd = 0;\n if (node.type.spec.isolating && openEnd <= d) {\n startDepth = d;\n break;\n }\n cur = node.content;\n }\n // Only try wrapping nodes (pass 2) after finding a place without\n // wrapping failed.\n for (let pass = 1; pass <= 2; pass++) {\n for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {\n let fragment,\n parent = null;\n if (sliceDepth) {\n parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;\n fragment = parent.content;\n } else {\n fragment = this.unplaced.content;\n }\n let first = fragment.firstChild;\n for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {\n let {\n type,\n match\n } = this.frontier[frontierDepth],\n wrap,\n inject = null;\n // In pass 1, if the next node matches, or there is no next\n // node but the parents look compatible, we've found a\n // place.\n if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false)) : parent && type.compatibleContent(parent.type))) return {\n sliceDepth,\n frontierDepth,\n parent,\n inject\n };\n // In pass 2, look for a set of wrapping nodes that make\n // `first` fit here.\n else if (pass == 2 && first && (wrap = match.findWrapping(first.type))) return {\n sliceDepth,\n frontierDepth,\n parent,\n wrap\n };\n // Don't continue looking further up if the parent node\n // would fit here.\n if (parent && match.matchType(parent.type)) break;\n }\n }\n }\n }\n openMore() {\n let {\n content,\n openStart,\n openEnd\n } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (!inner.childCount || inner.firstChild.isLeaf) return false;\n this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));\n return true;\n }\n dropNode() {\n let {\n content,\n openStart,\n openEnd\n } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (inner.childCount <= 1 && openStart > 0) {\n let openAtEnd = content.size - openStart <= openStart + inner.size;\n this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);\n } else {\n this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);\n }\n }\n // Move content from the unplaced slice at `sliceDepth` to the\n // frontier node at `frontierDepth`. Close that frontier node when\n // applicable.\n placeNodes({\n sliceDepth,\n frontierDepth,\n parent,\n inject,\n wrap\n }) {\n while (this.depth > frontierDepth) this.closeFrontierNode();\n if (wrap) for (let i = 0; i < wrap.length; i++) this.openFrontierNode(wrap[i]);\n let slice = this.unplaced,\n fragment = parent ? parent.content : slice.content;\n let openStart = slice.openStart - sliceDepth;\n let taken = 0,\n add = [];\n let {\n match,\n type\n } = this.frontier[frontierDepth];\n if (inject) {\n for (let i = 0; i < inject.childCount; i++) add.push(inject.child(i));\n match = match.matchFragment(inject);\n }\n // Computes the amount of (end) open nodes at the end of the\n // fragment. When 0, the parent is open, but no more. When\n // negative, nothing is open.\n let openEndCount = fragment.size + sliceDepth - (slice.content.size - slice.openEnd);\n // Scan over the fragment, fitting as many child nodes as\n // possible.\n while (taken < fragment.childCount) {\n let next = fragment.child(taken),\n matches = match.matchType(next.type);\n if (!matches) break;\n taken++;\n if (taken > 1 || openStart == 0 || next.content.size) {\n // Drop empty open nodes\n match = matches;\n add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));\n }\n }\n let toEnd = taken == fragment.childCount;\n if (!toEnd) openEndCount = -1;\n this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));\n this.frontier[frontierDepth].match = match;\n // If the parent types match, and the entire node was moved, and\n // it's not open, close this frontier node right away.\n if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1) this.closeFrontierNode();\n // Add new frontier nodes for any open nodes at the end.\n for (let i = 0, cur = fragment; i < openEndCount; i++) {\n let node = cur.lastChild;\n this.frontier.push({\n type: node.type,\n match: node.contentMatchAt(node.childCount)\n });\n cur = node.content;\n }\n // Update `this.unplaced`. Drop the entire node from which we\n // placed it we got to its end, otherwise just drop the placed\n // nodes.\n this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd) : sliceDepth == 0 ? Slice.empty : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);\n }\n mustMoveInline() {\n if (!this.$to.parent.isTextblock) return -1;\n let top = this.frontier[this.depth],\n level;\n if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) || this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth) return -1;\n let {\n depth\n } = this.$to,\n after = this.$to.after(depth);\n while (depth > 1 && after == this.$to.end(--depth)) ++after;\n return after;\n }\n findCloseLevel($to) {\n scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {\n let {\n match,\n type\n } = this.frontier[i];\n let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));\n let fit = contentAfterFits($to, i, type, match, dropInner);\n if (!fit) continue;\n for (let d = i - 1; d >= 0; d--) {\n let {\n match,\n type\n } = this.frontier[d];\n let matches = contentAfterFits($to, d, type, match, true);\n if (!matches || matches.childCount) continue scan;\n }\n return {\n depth: i,\n fit,\n move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to\n };\n }\n }\n close($to) {\n let close = this.findCloseLevel($to);\n if (!close) return null;\n while (this.depth > close.depth) this.closeFrontierNode();\n if (close.fit.childCount) this.placed = addToFragment(this.placed, close.depth, close.fit);\n $to = close.move;\n for (let d = close.depth + 1; d <= $to.depth; d++) {\n let node = $to.node(d),\n add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));\n this.openFrontierNode(node.type, node.attrs, add);\n }\n return $to;\n }\n openFrontierNode(type, attrs = null, content) {\n let top = this.frontier[this.depth];\n top.match = top.match.matchType(type);\n this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));\n this.frontier.push({\n type,\n match: type.contentMatch\n });\n }\n closeFrontierNode() {\n let open = this.frontier.pop();\n let add = open.match.fillBefore(Fragment.empty, true);\n if (add.childCount) this.placed = addToFragment(this.placed, this.frontier.length, add);\n }\n}\nfunction dropFromFragment(fragment, depth, count) {\n if (depth == 0) return fragment.cutByIndex(count, fragment.childCount);\n return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));\n}\nfunction addToFragment(fragment, depth, content) {\n if (depth == 0) return fragment.append(content);\n return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));\n}\nfunction contentAt(fragment, depth) {\n for (let i = 0; i < depth; i++) fragment = fragment.firstChild.content;\n return fragment;\n}\nfunction closeNodeStart(node, openStart, openEnd) {\n if (openStart <= 0) return node;\n let frag = node.content;\n if (openStart > 1) frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));\n if (openStart > 0) {\n frag = node.type.contentMatch.fillBefore(frag).append(frag);\n if (openEnd <= 0) frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));\n }\n return node.copy(frag);\n}\nfunction contentAfterFits($to, depth, type, match, open) {\n let node = $to.node(depth),\n index = open ? $to.indexAfter(depth) : $to.index(depth);\n if (index == node.childCount && !type.compatibleContent(node.type)) return null;\n let fit = match.fillBefore(node.content, true, index);\n return fit && !invalidMarks(type, node.content, index) ? fit : null;\n}\nfunction invalidMarks(type, fragment, start) {\n for (let i = start; i < fragment.childCount; i++) if (!type.allowsMarks(fragment.child(i).marks)) return true;\n return false;\n}\nfunction definesContent(type) {\n return type.spec.defining || type.spec.definingForContent;\n}\nfunction replaceRange(tr, from, to, slice) {\n if (!slice.size) return tr.deleteRange(from, to);\n let $from = tr.doc.resolve(from),\n $to = tr.doc.resolve(to);\n if (fitsTrivially($from, $to, slice)) return tr.step(new ReplaceStep(from, to, slice));\n let targetDepths = coveredDepths($from, tr.doc.resolve(to));\n // Can't replace the whole document, so remove 0 if it's present\n if (targetDepths[targetDepths.length - 1] == 0) targetDepths.pop();\n // Negative numbers represent not expansion over the whole node at\n // that depth, but replacing from $from.before(-D) to $to.pos.\n let preferredTarget = -($from.depth + 1);\n targetDepths.unshift(preferredTarget);\n // This loop picks a preferred target depth, if one of the covering\n // depths is not outside of a defining node, and adds negative\n // depths for any depth that has $from at its start and does not\n // cross a defining node.\n for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {\n let spec = $from.node(d).type.spec;\n if (spec.defining || spec.definingAsContext || spec.isolating) break;\n if (targetDepths.indexOf(d) > -1) preferredTarget = d;else if ($from.before(d) == pos) targetDepths.splice(1, 0, -d);\n }\n // Try to fit each possible depth of the slice into each possible\n // target depth, starting with the preferred depths.\n let preferredTargetIndex = targetDepths.indexOf(preferredTarget);\n let leftNodes = [],\n preferredDepth = slice.openStart;\n for (let content = slice.content, i = 0;; i++) {\n let node = content.firstChild;\n leftNodes.push(node);\n if (i == slice.openStart) break;\n content = node.content;\n }\n // Back up preferredDepth to cover defining textblocks directly\n // above it, possibly skipping a non-defining textblock.\n for (let d = preferredDepth - 1; d >= 0; d--) {\n let leftNode = leftNodes[d],\n def = definesContent(leftNode.type);\n if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1))) preferredDepth = d;else if (def || !leftNode.type.isTextblock) break;\n }\n for (let j = slice.openStart; j >= 0; j--) {\n let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);\n let insert = leftNodes[openDepth];\n if (!insert) continue;\n for (let i = 0; i < targetDepths.length; i++) {\n // Loop over possible expansion levels, starting with the\n // preferred one\n let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length],\n expand = true;\n if (targetDepth < 0) {\n expand = false;\n targetDepth = -targetDepth;\n }\n let parent = $from.node(targetDepth - 1),\n index = $from.index(targetDepth - 1);\n if (parent.canReplaceWith(index, index, insert.type, insert.marks)) return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd));\n }\n }\n let startSteps = tr.steps.length;\n for (let i = targetDepths.length - 1; i >= 0; i--) {\n tr.replace(from, to, slice);\n if (tr.steps.length > startSteps) break;\n let depth = targetDepths[i];\n if (depth < 0) continue;\n from = $from.before(depth);\n to = $to.after(depth);\n }\n}\nfunction closeFragment(fragment, depth, oldOpen, newOpen, parent) {\n if (depth < oldOpen) {\n let first = fragment.firstChild;\n fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));\n }\n if (depth > newOpen) {\n let match = parent.contentMatchAt(0);\n let start = match.fillBefore(fragment).append(fragment);\n fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));\n }\n return fragment;\n}\nfunction replaceRangeWith(tr, from, to, node) {\n if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) {\n let point = insertPoint(tr.doc, from, node.type);\n if (point != null) from = to = point;\n }\n tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0));\n}\nfunction deleteRange(tr, from, to) {\n let $from = tr.doc.resolve(from),\n $to = tr.doc.resolve(to);\n let covered = coveredDepths($from, $to);\n for (let i = 0; i < covered.length; i++) {\n let depth = covered[i],\n last = i == covered.length - 1;\n if (last && depth == 0 || $from.node(depth).type.contentMatch.validEnd) return tr.delete($from.start(depth), $to.end(depth));\n if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1)))) return tr.delete($from.before(depth), $to.after(depth));\n }\n for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {\n if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d) return tr.delete($from.before(d), to);\n }\n tr.delete(from, to);\n}\n// Returns an array of all depths for which $from - $to spans the\n// whole content of the nodes at that depth.\nfunction coveredDepths($from, $to) {\n let result = [],\n minDepth = Math.min($from.depth, $to.depth);\n for (let d = minDepth; d >= 0; d--) {\n let start = $from.start(d);\n if (start < $from.pos - ($from.depth - d) || $to.end(d) > $to.pos + ($to.depth - d) || $from.node(d).type.spec.isolating || $to.node(d).type.spec.isolating) break;\n if (start == $to.start(d) || d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent && d && $to.start(d - 1) == start - 1) result.push(d);\n }\n return result;\n}\n\n/**\nUpdate an attribute in a specific node.\n*/\nclass AttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos,\n /**\n The attribute to set.\n */\n attr,\n // The attribute's new value.\n value) {\n super();\n this.pos = pos;\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node) return StepResult.fail(\"No node at attribute step's position\");\n let attrs = Object.create(null);\n for (let name in node.attrs) attrs[name] = node.attrs[name];\n attrs[this.attr] = this.value;\n let updated = node.type.create(attrs, null, node.marks);\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new AttrStep(this.pos, this.attr, doc.nodeAt(this.pos).attrs[this.attr]);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);\n }\n toJSON() {\n return {\n stepType: \"attr\",\n pos: this.pos,\n attr: this.attr,\n value: this.value\n };\n }\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\" || typeof json.attr != \"string\") throw new RangeError(\"Invalid input for AttrStep.fromJSON\");\n return new AttrStep(json.pos, json.attr, json.value);\n }\n}\nStep.jsonID(\"attr\", AttrStep);\n/**\nUpdate an attribute in the doc node.\n*/\nclass DocAttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The attribute to set.\n */\n attr,\n // The attribute's new value.\n value) {\n super();\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let attrs = Object.create(null);\n for (let name in doc.attrs) attrs[name] = doc.attrs[name];\n attrs[this.attr] = this.value;\n let updated = doc.type.create(attrs, doc.content, doc.marks);\n return StepResult.ok(updated);\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new DocAttrStep(this.attr, doc.attrs[this.attr]);\n }\n map(mapping) {\n return this;\n }\n toJSON() {\n return {\n stepType: \"docAttr\",\n attr: this.attr,\n value: this.value\n };\n }\n static fromJSON(schema, json) {\n if (typeof json.attr != \"string\") throw new RangeError(\"Invalid input for DocAttrStep.fromJSON\");\n return new DocAttrStep(json.attr, json.value);\n }\n}\nStep.jsonID(\"docAttr\", DocAttrStep);\n\n/**\n@internal\n*/\nlet TransformError = class extends Error {};\nTransformError = function TransformError(message) {\n let err = Error.call(this, message);\n err.__proto__ = TransformError.prototype;\n return err;\n};\nTransformError.prototype = Object.create(Error.prototype);\nTransformError.prototype.constructor = TransformError;\nTransformError.prototype.name = \"TransformError\";\n/**\nAbstraction to build up and track an array of\n[steps](https://prosemirror.net/docs/ref/#transform.Step) representing a document transformation.\n\nMost transforming methods return the `Transform` object itself, so\nthat they can be chained.\n*/\nclass Transform {\n /**\n Create a transform that starts with the given document.\n */\n constructor(\n /**\n The current document (the result of applying the steps in the\n transform).\n */\n doc) {\n this.doc = doc;\n /**\n The steps in this transform.\n */\n this.steps = [];\n /**\n The documents before each of the steps.\n */\n this.docs = [];\n /**\n A mapping with the maps for each of the steps in this transform.\n */\n this.mapping = new Mapping();\n }\n /**\n The starting document.\n */\n get before() {\n return this.docs.length ? this.docs[0] : this.doc;\n }\n /**\n Apply a new step in this transform, saving the result. Throws an\n error when the step fails.\n */\n step(step) {\n let result = this.maybeStep(step);\n if (result.failed) throw new TransformError(result.failed);\n return this;\n }\n /**\n Try to apply a step in this transformation, ignoring it if it\n fails. Returns the step result.\n */\n maybeStep(step) {\n let result = step.apply(this.doc);\n if (!result.failed) this.addStep(step, result.doc);\n return result;\n }\n /**\n True when the document has been changed (when there are any\n steps).\n */\n get docChanged() {\n return this.steps.length > 0;\n }\n /**\n @internal\n */\n addStep(step, doc) {\n this.docs.push(this.doc);\n this.steps.push(step);\n this.mapping.appendMap(step.getMap());\n this.doc = doc;\n }\n /**\n Replace the part of the document between `from` and `to` with the\n given `slice`.\n */\n replace(from, to = from, slice = Slice.empty) {\n let step = replaceStep(this.doc, from, to, slice);\n if (step) this.step(step);\n return this;\n }\n /**\n Replace the given range with the given content, which may be a\n fragment, node, or array of nodes.\n */\n replaceWith(from, to, content) {\n return this.replace(from, to, new Slice(Fragment.from(content), 0, 0));\n }\n /**\n Delete the content between the given positions.\n */\n delete(from, to) {\n return this.replace(from, to, Slice.empty);\n }\n /**\n Insert the given content at the given position.\n */\n insert(pos, content) {\n return this.replaceWith(pos, pos, content);\n }\n /**\n Replace a range of the document with a given slice, using\n `from`, `to`, and the slice's\n [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather\n than fixed start and end points. This method may grow the\n replaced area or close open nodes in the slice in order to get a\n fit that is more in line with WYSIWYG expectations, by dropping\n fully covered parent nodes of the replaced region when they are\n marked [non-defining as\n context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an\n open parent node from the slice that _is_ marked as [defining\n its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n \n This is the method, for example, to handle paste. The similar\n [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more\n primitive tool which will _not_ move the start and end of its given\n range, and is useful in situations where you need more precise\n control over what happens.\n */\n replaceRange(from, to, slice) {\n replaceRange(this, from, to, slice);\n return this;\n }\n /**\n Replace the given range with a node, but use `from` and `to` as\n hints, rather than precise positions. When from and to are the same\n and are at the start or end of a parent node in which the given\n node doesn't fit, this method may _move_ them out towards a parent\n that does allow the given node to be placed. When the given range\n completely covers a parent node, this method may completely replace\n that parent node.\n */\n replaceRangeWith(from, to, node) {\n replaceRangeWith(this, from, to, node);\n return this;\n }\n /**\n Delete the given range, expanding it to cover fully covered\n parent nodes until a valid replace is found.\n */\n deleteRange(from, to) {\n deleteRange(this, from, to);\n return this;\n }\n /**\n Split the content in the given range off from its parent, if there\n is sibling content before or after it, and move it up the tree to\n the depth specified by `target`. You'll probably want to use\n [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make\n sure the lift is valid.\n */\n lift(range, target) {\n lift(this, range, target);\n return this;\n }\n /**\n Join the blocks around the given position. If depth is 2, their\n last and first siblings are also joined, and so on.\n */\n join(pos, depth = 1) {\n join(this, pos, depth);\n return this;\n }\n /**\n Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.\n The wrappers are assumed to be valid in this position, and should\n probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).\n */\n wrap(range, wrappers) {\n wrap(this, range, wrappers);\n return this;\n }\n /**\n Set the type of all textblocks (partly) between `from` and `to` to\n the given node type with the given attributes.\n */\n setBlockType(from, to = from, type, attrs = null) {\n setBlockType(this, from, to, type, attrs);\n return this;\n }\n /**\n Change the type, attributes, and/or marks of the node at `pos`.\n When `type` isn't given, the existing node type is preserved,\n */\n setNodeMarkup(pos, type, attrs = null, marks) {\n setNodeMarkup(this, pos, type, attrs, marks);\n return this;\n }\n /**\n Set a single attribute on a given node to a new value.\n The `pos` addresses the document content. Use `setDocAttribute`\n to set attributes on the document itself.\n */\n setNodeAttribute(pos, attr, value) {\n this.step(new AttrStep(pos, attr, value));\n return this;\n }\n /**\n Set a single attribute on the document to a new value.\n */\n setDocAttribute(attr, value) {\n this.step(new DocAttrStep(attr, value));\n return this;\n }\n /**\n Add a mark to the node at position `pos`.\n */\n addNodeMark(pos, mark) {\n this.step(new AddNodeMarkStep(pos, mark));\n return this;\n }\n /**\n Remove a mark (or a mark of the given type) from the node at\n position `pos`.\n */\n removeNodeMark(pos, mark) {\n if (!(mark instanceof Mark)) {\n let node = this.doc.nodeAt(pos);\n if (!node) throw new RangeError(\"No node at position \" + pos);\n mark = mark.isInSet(node.marks);\n if (!mark) return this;\n }\n this.step(new RemoveNodeMarkStep(pos, mark));\n return this;\n }\n /**\n Split the node at the given position, and optionally, if `depth` is\n greater than one, any number of nodes above that. By default, the\n parts split off will inherit the node type of the original node.\n This can be changed by passing an array of types and attributes to\n use after the split.\n */\n split(pos, depth = 1, typesAfter) {\n split(this, pos, depth, typesAfter);\n return this;\n }\n /**\n Add the given mark to the inline content between `from` and `to`.\n */\n addMark(from, to, mark) {\n addMark(this, from, to, mark);\n return this;\n }\n /**\n Remove marks from inline nodes between `from` and `to`. When\n `mark` is a single mark, remove precisely that mark. When it is\n a mark type, remove all marks of that type. When it is null,\n remove all marks of any type.\n */\n removeMark(from, to, mark) {\n removeMark(this, from, to, mark);\n return this;\n }\n /**\n Removes all marks and nodes from the content of the node at\n `pos` that don't match the given new parent node type. Accepts\n an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as\n third argument.\n */\n clearIncompatible(pos, parentType, match) {\n clearIncompatible(this, pos, parentType, match);\n return this;\n }\n}\nexport { AddMarkStep, AddNodeMarkStep, AttrStep, DocAttrStep, MapResult, Mapping, RemoveMarkStep, RemoveNodeMarkStep, ReplaceAroundStep, ReplaceStep, Step, StepMap, StepResult, Transform, TransformError, canJoin, canSplit, dropPoint, findWrapping, insertPoint, joinPoint, liftTarget, replaceStep };","import { findWrapping, ReplaceAroundStep, canSplit, liftTarget, canJoin } from 'prosemirror-transform';\nimport { NodeRange, Fragment, Slice } from 'prosemirror-model';\nimport { Selection } from 'prosemirror-state';\nconst olDOM = [\"ol\", 0],\n ulDOM = [\"ul\", 0],\n liDOM = [\"li\", 0];\n/**\nAn ordered list [node spec](https://prosemirror.net/docs/ref/#model.NodeSpec). Has a single\nattribute, `order`, which determines the number at which the list\nstarts counting, and defaults to 1. Represented as an `
    `\nelement.\n*/\nconst orderedList = {\n attrs: {\n order: {\n default: 1,\n validate: \"number\"\n }\n },\n parseDOM: [{\n tag: \"ol\",\n getAttrs(dom) {\n return {\n order: dom.hasAttribute(\"start\") ? +dom.getAttribute(\"start\") : 1\n };\n }\n }],\n toDOM(node) {\n return node.attrs.order == 1 ? olDOM : [\"ol\", {\n start: node.attrs.order\n }, 0];\n }\n};\n/**\nA bullet list node spec, represented in the DOM as `
      `.\n*/\nconst bulletList = {\n parseDOM: [{\n tag: \"ul\"\n }],\n toDOM() {\n return ulDOM;\n }\n};\n/**\nA list item (`
    • `) spec.\n*/\nconst listItem = {\n parseDOM: [{\n tag: \"li\"\n }],\n toDOM() {\n return liDOM;\n },\n defining: true\n};\nfunction add(obj, props) {\n let copy = {};\n for (let prop in obj) copy[prop] = obj[prop];\n for (let prop in props) copy[prop] = props[prop];\n return copy;\n}\n/**\nConvenience function for adding list-related node types to a map\nspecifying the nodes for a schema. Adds\n[`orderedList`](https://prosemirror.net/docs/ref/#schema-list.orderedList) as `\"ordered_list\"`,\n[`bulletList`](https://prosemirror.net/docs/ref/#schema-list.bulletList) as `\"bullet_list\"`, and\n[`listItem`](https://prosemirror.net/docs/ref/#schema-list.listItem) as `\"list_item\"`.\n\n`itemContent` determines the content expression for the list items.\nIf you want the commands defined in this module to apply to your\nlist structure, it should have a shape like `\"paragraph block*\"` or\n`\"paragraph (ordered_list | bullet_list)*\"`. `listGroup` can be\ngiven to assign a group name to the list node types, for example\n`\"block\"`.\n*/\nfunction addListNodes(nodes, itemContent, listGroup) {\n return nodes.append({\n ordered_list: add(orderedList, {\n content: \"list_item+\",\n group: listGroup\n }),\n bullet_list: add(bulletList, {\n content: \"list_item+\",\n group: listGroup\n }),\n list_item: add(listItem, {\n content: itemContent\n })\n });\n}\n/**\nReturns a command function that wraps the selection in a list with\nthe given type an attributes. If `dispatch` is null, only return a\nvalue to indicate whether this is possible, but don't actually\nperform the change.\n*/\nfunction wrapInList(listType, attrs = null) {\n return function (state, dispatch) {\n let {\n $from,\n $to\n } = state.selection;\n let range = $from.blockRange($to),\n doJoin = false,\n outerRange = range;\n if (!range) return false;\n // This is at the top of an existing list item\n if (range.depth >= 2 && $from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) {\n // Don't do anything if this is the top of the list\n if ($from.index(range.depth - 1) == 0) return false;\n let $insert = state.doc.resolve(range.start - 2);\n outerRange = new NodeRange($insert, $insert, range.depth);\n if (range.endIndex < range.parent.childCount) range = new NodeRange($from, state.doc.resolve($to.end(range.depth)), range.depth);\n doJoin = true;\n }\n let wrap = findWrapping(outerRange, listType, attrs, range);\n if (!wrap) return false;\n if (dispatch) dispatch(doWrapInList(state.tr, range, wrap, doJoin, listType).scrollIntoView());\n return true;\n };\n}\nfunction doWrapInList(tr, range, wrappers, joinBefore, listType) {\n let content = Fragment.empty;\n for (let i = wrappers.length - 1; i >= 0; i--) content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n tr.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true));\n let found = 0;\n for (let i = 0; i < wrappers.length; i++) if (wrappers[i].type == listType) found = i + 1;\n let splitDepth = wrappers.length - found;\n let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0),\n parent = range.parent;\n for (let i = range.startIndex, e = range.endIndex, first = true; i < e; i++, first = false) {\n if (!first && canSplit(tr.doc, splitPos, splitDepth)) {\n tr.split(splitPos, splitDepth);\n splitPos += 2 * splitDepth;\n }\n splitPos += parent.child(i).nodeSize;\n }\n return tr;\n}\n/**\nBuild a command that splits a non-empty textblock at the top level\nof a list item by also splitting that list item.\n*/\nfunction splitListItem(itemType, itemAttrs) {\n return function (state, dispatch) {\n let {\n $from,\n $to,\n node\n } = state.selection;\n if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to)) return false;\n let grandParent = $from.node(-1);\n if (grandParent.type != itemType) return false;\n if ($from.parent.content.size == 0 && $from.node(-1).childCount == $from.indexAfter(-1)) {\n // In an empty block. If this is a nested list, the wrapping\n // list item should be split. Otherwise, bail out and let next\n // command handle lifting.\n if ($from.depth == 3 || $from.node(-3).type != itemType || $from.index(-2) != $from.node(-2).childCount - 1) return false;\n if (dispatch) {\n let wrap = Fragment.empty;\n let depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;\n // Build a fragment containing empty versions of the structure\n // from the outer list item to the parent node of the cursor\n for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d--) wrap = Fragment.from($from.node(d).copy(wrap));\n let depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3;\n // Add a second list item with an empty default start node\n wrap = wrap.append(Fragment.from(itemType.createAndFill()));\n let start = $from.before($from.depth - (depthBefore - 1));\n let tr = state.tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0));\n let sel = -1;\n tr.doc.nodesBetween(start, tr.doc.content.size, (node, pos) => {\n if (sel > -1) return false;\n if (node.isTextblock && node.content.size == 0) sel = pos + 1;\n });\n if (sel > -1) tr.setSelection(Selection.near(tr.doc.resolve(sel)));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n let nextType = $to.pos == $from.end() ? grandParent.contentMatchAt(0).defaultType : null;\n let tr = state.tr.delete($from.pos, $to.pos);\n let types = nextType ? [itemAttrs ? {\n type: itemType,\n attrs: itemAttrs\n } : null, {\n type: nextType\n }] : undefined;\n if (!canSplit(tr.doc, $from.pos, 2, types)) return false;\n if (dispatch) dispatch(tr.split($from.pos, 2, types).scrollIntoView());\n return true;\n };\n}\n/**\nActs like [`splitListItem`](https://prosemirror.net/docs/ref/#schema-list.splitListItem), but\nwithout resetting the set of active marks at the cursor.\n*/\nfunction splitListItemKeepMarks(itemType, itemAttrs) {\n let split = splitListItem(itemType, itemAttrs);\n return (state, dispatch) => {\n return split(state, dispatch && (tr => {\n let marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks();\n if (marks) tr.ensureMarks(marks);\n dispatch(tr);\n }));\n };\n}\n/**\nCreate a command to lift the list item around the selection up into\na wrapping list.\n*/\nfunction liftListItem(itemType) {\n return function (state, dispatch) {\n let {\n $from,\n $to\n } = state.selection;\n let range = $from.blockRange($to, node => node.childCount > 0 && node.firstChild.type == itemType);\n if (!range) return false;\n if (!dispatch) return true;\n if ($from.node(range.depth - 1).type == itemType)\n // Inside a parent list\n return liftToOuterList(state, dispatch, itemType, range);else\n // Outer list node\n return liftOutOfList(state, dispatch, range);\n };\n}\nfunction liftToOuterList(state, dispatch, itemType, range) {\n let tr = state.tr,\n end = range.end,\n endOfList = range.$to.end(range.depth);\n if (end < endOfList) {\n // There are siblings after the lifted items, which must become\n // children of the last item\n tr.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true));\n range = new NodeRange(tr.doc.resolve(range.$from.pos), tr.doc.resolve(endOfList), range.depth);\n }\n const target = liftTarget(range);\n if (target == null) return false;\n tr.lift(range, target);\n let after = tr.mapping.map(end, -1) - 1;\n if (canJoin(tr.doc, after)) tr.join(after);\n dispatch(tr.scrollIntoView());\n return true;\n}\nfunction liftOutOfList(state, dispatch, range) {\n let tr = state.tr,\n list = range.parent;\n // Merge the list items into a single big item\n for (let pos = range.end, i = range.endIndex - 1, e = range.startIndex; i > e; i--) {\n pos -= list.child(i).nodeSize;\n tr.delete(pos - 1, pos + 1);\n }\n let $start = tr.doc.resolve(range.start),\n item = $start.nodeAfter;\n if (tr.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize) return false;\n let atStart = range.startIndex == 0,\n atEnd = range.endIndex == list.childCount;\n let parent = $start.node(-1),\n indexBefore = $start.index(-1);\n if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list)))) return false;\n let start = $start.pos,\n end = start + item.nodeSize;\n // Strip off the surrounding list. At the sides where we're not at\n // the end of the list, the existing list is closed. At sides where\n // this is the end, it is overwritten to its end.\n tr.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));\n dispatch(tr.scrollIntoView());\n return true;\n}\n/**\nCreate a command to sink the list item around the selection down\ninto an inner list.\n*/\nfunction sinkListItem(itemType) {\n return function (state, dispatch) {\n let {\n $from,\n $to\n } = state.selection;\n let range = $from.blockRange($to, node => node.childCount > 0 && node.firstChild.type == itemType);\n if (!range) return false;\n let startIndex = range.startIndex;\n if (startIndex == 0) return false;\n let parent = range.parent,\n nodeBefore = parent.child(startIndex - 1);\n if (nodeBefore.type != itemType) return false;\n if (dispatch) {\n let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type;\n let inner = Fragment.from(nestedBefore ? itemType.create() : null);\n let slice = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0);\n let before = range.start,\n after = range.end;\n dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice, 1, true)).scrollIntoView());\n }\n return true;\n };\n}\nexport { addListNodes, bulletList, liftListItem, listItem, orderedList, sinkListItem, splitListItem, splitListItemKeepMarks, wrapInList };","import { liftTarget, replaceStep, ReplaceStep, canJoin, joinPoint, canSplit, ReplaceAroundStep, findWrapping } from 'prosemirror-transform';\nimport { Slice, Fragment } from 'prosemirror-model';\nimport { NodeSelection, Selection, TextSelection, AllSelection } from 'prosemirror-state';\n\n/**\nDelete the selection, if there is one.\n*/\nconst deleteSelection = (state, dispatch) => {\n if (state.selection.empty) return false;\n if (dispatch) dispatch(state.tr.deleteSelection().scrollIntoView());\n return true;\n};\nfunction atBlockStart(state, view) {\n let {\n $cursor\n } = state.selection;\n if (!$cursor || (view ? !view.endOfTextblock(\"backward\", state) : $cursor.parentOffset > 0)) return null;\n return $cursor;\n}\n/**\nIf the selection is empty and at the start of a textblock, try to\nreduce the distance between that block and the one before it—if\nthere's a block directly before it that can be joined, join them.\nIf not, try to move the selected block closer to the next one in\nthe document structure by lifting it out of its parent or moving it\ninto a parent of the previous block. Will use the view for accurate\n(bidi-aware) start-of-textblock detection if given.\n*/\nconst joinBackward = (state, dispatch, view) => {\n let $cursor = atBlockStart(state, view);\n if (!$cursor) return false;\n let $cut = findCutBefore($cursor);\n // If there is no node before this, try to lift\n if (!$cut) {\n let range = $cursor.blockRange(),\n target = range && liftTarget(range);\n if (target == null) return false;\n if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n }\n let before = $cut.nodeBefore;\n // Apply the joining algorithm\n if (!before.type.spec.isolating && deleteBarrier(state, $cut, dispatch)) return true;\n // If the node below has no content and the node above is\n // selectable, delete the node below and select the one above.\n if ($cursor.parent.content.size == 0 && (textblockAt(before, \"end\") || NodeSelection.isSelectable(before))) {\n let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);\n if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n if (dispatch) {\n let tr = state.tr.step(delStep);\n tr.setSelection(textblockAt(before, \"end\") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1) : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n }\n // If the node before is an atom, delete it\n if (before.isAtom && $cut.depth == $cursor.depth - 1) {\n if (dispatch) dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());\n return true;\n }\n return false;\n};\n/**\nA more limited form of [`joinBackward`]($commands.joinBackward)\nthat only tries to join the current textblock to the one before\nit, if the cursor is at the start of a textblock.\n*/\nconst joinTextblockBackward = (state, dispatch, view) => {\n let $cursor = atBlockStart(state, view);\n if (!$cursor) return false;\n let $cut = findCutBefore($cursor);\n return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\n/**\nA more limited form of [`joinForward`]($commands.joinForward)\nthat only tries to join the current textblock to the one after\nit, if the cursor is at the end of a textblock.\n*/\nconst joinTextblockForward = (state, dispatch, view) => {\n let $cursor = atBlockEnd(state, view);\n if (!$cursor) return false;\n let $cut = findCutAfter($cursor);\n return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\nfunction joinTextblocksAround(state, $cut, dispatch) {\n let before = $cut.nodeBefore,\n beforeText = before,\n beforePos = $cut.pos - 1;\n for (; !beforeText.isTextblock; beforePos--) {\n if (beforeText.type.spec.isolating) return false;\n let child = beforeText.lastChild;\n if (!child) return false;\n beforeText = child;\n }\n let after = $cut.nodeAfter,\n afterText = after,\n afterPos = $cut.pos + 1;\n for (; !afterText.isTextblock; afterPos++) {\n if (afterText.type.spec.isolating) return false;\n let child = afterText.firstChild;\n if (!child) return false;\n afterText = child;\n }\n let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty);\n if (!step || step.from != beforePos || step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos) return false;\n if (dispatch) {\n let tr = state.tr.step(step);\n tr.setSelection(TextSelection.create(tr.doc, beforePos));\n dispatch(tr.scrollIntoView());\n }\n return true;\n}\nfunction textblockAt(node, side, only = false) {\n for (let scan = node; scan; scan = side == \"start\" ? scan.firstChild : scan.lastChild) {\n if (scan.isTextblock) return true;\n if (only && scan.childCount != 1) return false;\n }\n return false;\n}\n/**\nWhen the selection is empty and at the start of a textblock, select\nthe node before that textblock, if possible. This is intended to be\nbound to keys like backspace, after\n[`joinBackward`](https://prosemirror.net/docs/ref/#commands.joinBackward) or other deleting\ncommands, as a fall-back behavior when the schema doesn't allow\ndeletion at the selected point.\n*/\nconst selectNodeBackward = (state, dispatch, view) => {\n let {\n $head,\n empty\n } = state.selection,\n $cut = $head;\n if (!empty) return false;\n if ($head.parent.isTextblock) {\n if (view ? !view.endOfTextblock(\"backward\", state) : $head.parentOffset > 0) return false;\n $cut = findCutBefore($head);\n }\n let node = $cut && $cut.nodeBefore;\n if (!node || !NodeSelection.isSelectable(node)) return false;\n if (dispatch) dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());\n return true;\n};\nfunction findCutBefore($pos) {\n if (!$pos.parent.type.spec.isolating) for (let i = $pos.depth - 1; i >= 0; i--) {\n if ($pos.index(i) > 0) return $pos.doc.resolve($pos.before(i + 1));\n if ($pos.node(i).type.spec.isolating) break;\n }\n return null;\n}\nfunction atBlockEnd(state, view) {\n let {\n $cursor\n } = state.selection;\n if (!$cursor || (view ? !view.endOfTextblock(\"forward\", state) : $cursor.parentOffset < $cursor.parent.content.size)) return null;\n return $cursor;\n}\n/**\nIf the selection is empty and the cursor is at the end of a\ntextblock, try to reduce or remove the boundary between that block\nand the one after it, either by joining them or by moving the other\nblock closer to this one in the tree structure. Will use the view\nfor accurate start-of-textblock detection if given.\n*/\nconst joinForward = (state, dispatch, view) => {\n let $cursor = atBlockEnd(state, view);\n if (!$cursor) return false;\n let $cut = findCutAfter($cursor);\n // If there is no node after this, there's nothing to do\n if (!$cut) return false;\n let after = $cut.nodeAfter;\n // Try the joining algorithm\n if (deleteBarrier(state, $cut, dispatch)) return true;\n // If the node above has no content and the node below is\n // selectable, delete the node above and select the one below.\n if ($cursor.parent.content.size == 0 && (textblockAt(after, \"start\") || NodeSelection.isSelectable(after))) {\n let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);\n if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n if (dispatch) {\n let tr = state.tr.step(delStep);\n tr.setSelection(textblockAt(after, \"start\") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1) : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n }\n // If the next node is an atom, delete it\n if (after.isAtom && $cut.depth == $cursor.depth - 1) {\n if (dispatch) dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());\n return true;\n }\n return false;\n};\n/**\nWhen the selection is empty and at the end of a textblock, select\nthe node coming after that textblock, if possible. This is intended\nto be bound to keys like delete, after\n[`joinForward`](https://prosemirror.net/docs/ref/#commands.joinForward) and similar deleting\ncommands, to provide a fall-back behavior when the schema doesn't\nallow deletion at the selected point.\n*/\nconst selectNodeForward = (state, dispatch, view) => {\n let {\n $head,\n empty\n } = state.selection,\n $cut = $head;\n if (!empty) return false;\n if ($head.parent.isTextblock) {\n if (view ? !view.endOfTextblock(\"forward\", state) : $head.parentOffset < $head.parent.content.size) return false;\n $cut = findCutAfter($head);\n }\n let node = $cut && $cut.nodeAfter;\n if (!node || !NodeSelection.isSelectable(node)) return false;\n if (dispatch) dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());\n return true;\n};\nfunction findCutAfter($pos) {\n if (!$pos.parent.type.spec.isolating) for (let i = $pos.depth - 1; i >= 0; i--) {\n let parent = $pos.node(i);\n if ($pos.index(i) + 1 < parent.childCount) return $pos.doc.resolve($pos.after(i + 1));\n if (parent.type.spec.isolating) break;\n }\n return null;\n}\n/**\nJoin the selected block or, if there is a text selection, the\nclosest ancestor block of the selection that can be joined, with\nthe sibling above it.\n*/\nconst joinUp = (state, dispatch) => {\n let sel = state.selection,\n nodeSel = sel instanceof NodeSelection,\n point;\n if (nodeSel) {\n if (sel.node.isTextblock || !canJoin(state.doc, sel.from)) return false;\n point = sel.from;\n } else {\n point = joinPoint(state.doc, sel.from, -1);\n if (point == null) return false;\n }\n if (dispatch) {\n let tr = state.tr.join(point);\n if (nodeSel) tr.setSelection(NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nJoin the selected block, or the closest ancestor of the selection\nthat can be joined, with the sibling after it.\n*/\nconst joinDown = (state, dispatch) => {\n let sel = state.selection,\n point;\n if (sel instanceof NodeSelection) {\n if (sel.node.isTextblock || !canJoin(state.doc, sel.to)) return false;\n point = sel.to;\n } else {\n point = joinPoint(state.doc, sel.to, 1);\n if (point == null) return false;\n }\n if (dispatch) dispatch(state.tr.join(point).scrollIntoView());\n return true;\n};\n/**\nLift the selected block, or the closest ancestor block of the\nselection that can be lifted, out of its parent node.\n*/\nconst lift = (state, dispatch) => {\n let {\n $from,\n $to\n } = state.selection;\n let range = $from.blockRange($to),\n target = range && liftTarget(range);\n if (target == null) return false;\n if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n};\n/**\nIf the selection is in a node whose type has a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, replace the\nselection with a newline character.\n*/\nconst newlineInCode = (state, dispatch) => {\n let {\n $head,\n $anchor\n } = state.selection;\n if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) return false;\n if (dispatch) dispatch(state.tr.insertText(\"\\n\").scrollIntoView());\n return true;\n};\nfunction defaultBlockAt(match) {\n for (let i = 0; i < match.edgeCount; i++) {\n let {\n type\n } = match.edge(i);\n if (type.isTextblock && !type.hasRequiredAttrs()) return type;\n }\n return null;\n}\n/**\nWhen the selection is in a node with a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, create a\ndefault block after the code block, and move the cursor there.\n*/\nconst exitCode = (state, dispatch) => {\n let {\n $head,\n $anchor\n } = state.selection;\n if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) return false;\n let above = $head.node(-1),\n after = $head.indexAfter(-1),\n type = defaultBlockAt(above.contentMatchAt(after));\n if (!type || !above.canReplaceWith(after, after, type)) return false;\n if (dispatch) {\n let pos = $head.after(),\n tr = state.tr.replaceWith(pos, pos, type.createAndFill());\n tr.setSelection(Selection.near(tr.doc.resolve(pos), 1));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nIf a block node is selected, create an empty paragraph before (if\nit is its parent's first child) or after it.\n*/\nconst createParagraphNear = (state, dispatch) => {\n let sel = state.selection,\n {\n $from,\n $to\n } = sel;\n if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent) return false;\n let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));\n if (!type || !type.isTextblock) return false;\n if (dispatch) {\n let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;\n let tr = state.tr.insert(side, type.createAndFill());\n tr.setSelection(TextSelection.create(tr.doc, side + 1));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nIf the cursor is in an empty textblock that can be lifted, lift the\nblock.\n*/\nconst liftEmptyBlock = (state, dispatch) => {\n let {\n $cursor\n } = state.selection;\n if (!$cursor || $cursor.parent.content.size) return false;\n if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {\n let before = $cursor.before();\n if (canSplit(state.doc, before)) {\n if (dispatch) dispatch(state.tr.split(before).scrollIntoView());\n return true;\n }\n }\n let range = $cursor.blockRange(),\n target = range && liftTarget(range);\n if (target == null) return false;\n if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n};\n/**\nCreate a variant of [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock) that uses\na custom function to determine the type of the newly split off block.\n*/\nfunction splitBlockAs(splitNode) {\n return (state, dispatch) => {\n let {\n $from,\n $to\n } = state.selection;\n if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {\n if (!$from.parentOffset || !canSplit(state.doc, $from.pos)) return false;\n if (dispatch) dispatch(state.tr.split($from.pos).scrollIntoView());\n return true;\n }\n if (!$from.parent.isBlock) return false;\n if (dispatch) {\n let atEnd = $to.parentOffset == $to.parent.content.size;\n let tr = state.tr;\n if (state.selection instanceof TextSelection || state.selection instanceof AllSelection) tr.deleteSelection();\n let deflt = $from.depth == 0 ? null : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)));\n let splitType = splitNode && splitNode($to.parent, atEnd);\n let types = splitType ? [splitType] : atEnd && deflt ? [{\n type: deflt\n }] : undefined;\n let can = canSplit(tr.doc, tr.mapping.map($from.pos), 1, types);\n if (!types && !can && canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt ? [{\n type: deflt\n }] : undefined)) {\n if (deflt) types = [{\n type: deflt\n }];\n can = true;\n }\n if (can) {\n tr.split(tr.mapping.map($from.pos), 1, types);\n if (!atEnd && !$from.parentOffset && $from.parent.type != deflt) {\n let first = tr.mapping.map($from.before()),\n $first = tr.doc.resolve(first);\n if (deflt && $from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) tr.setNodeMarkup(tr.mapping.map($from.before()), deflt);\n }\n }\n dispatch(tr.scrollIntoView());\n }\n return true;\n };\n}\n/**\nSplit the parent block of the selection. If the selection is a text\nselection, also delete its content.\n*/\nconst splitBlock = splitBlockAs();\n/**\nActs like [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock), but without\nresetting the set of active marks at the cursor.\n*/\nconst splitBlockKeepMarks = (state, dispatch) => {\n return splitBlock(state, dispatch && (tr => {\n let marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks();\n if (marks) tr.ensureMarks(marks);\n dispatch(tr);\n }));\n};\n/**\nMove the selection to the node wrapping the current selection, if\nany. (Will not select the document node.)\n*/\nconst selectParentNode = (state, dispatch) => {\n let {\n $from,\n to\n } = state.selection,\n pos;\n let same = $from.sharedDepth(to);\n if (same == 0) return false;\n pos = $from.before(same);\n if (dispatch) dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)));\n return true;\n};\n/**\nSelect the whole document.\n*/\nconst selectAll = (state, dispatch) => {\n if (dispatch) dispatch(state.tr.setSelection(new AllSelection(state.doc)));\n return true;\n};\nfunction joinMaybeClear(state, $pos, dispatch) {\n let before = $pos.nodeBefore,\n after = $pos.nodeAfter,\n index = $pos.index();\n if (!before || !after || !before.type.compatibleContent(after.type)) return false;\n if (!before.content.size && $pos.parent.canReplace(index - 1, index)) {\n if (dispatch) dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());\n return true;\n }\n if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos))) return false;\n if (dispatch) dispatch(state.tr.clearIncompatible($pos.pos, before.type, before.contentMatchAt(before.childCount)).join($pos.pos).scrollIntoView());\n return true;\n}\nfunction deleteBarrier(state, $cut, dispatch) {\n let before = $cut.nodeBefore,\n after = $cut.nodeAfter,\n conn,\n match;\n if (before.type.spec.isolating || after.type.spec.isolating) return false;\n if (joinMaybeClear(state, $cut, dispatch)) return true;\n let canDelAfter = $cut.parent.canReplace($cut.index(), $cut.index() + 1);\n if (canDelAfter && (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && match.matchType(conn[0] || after.type).validEnd) {\n if (dispatch) {\n let end = $cut.pos + after.nodeSize,\n wrap = Fragment.empty;\n for (let i = conn.length - 1; i >= 0; i--) wrap = Fragment.from(conn[i].create(null, wrap));\n wrap = Fragment.from(before.copy(wrap));\n let tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap, 1, 0), conn.length, true));\n let joinAt = end + 2 * conn.length;\n if (canJoin(tr.doc, joinAt)) tr.join(joinAt);\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n let selAfter = Selection.findFrom($cut, 1);\n let range = selAfter && selAfter.$from.blockRange(selAfter.$to),\n target = range && liftTarget(range);\n if (target != null && target >= $cut.depth) {\n if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n }\n if (canDelAfter && textblockAt(after, \"start\", true) && textblockAt(before, \"end\")) {\n let at = before,\n wrap = [];\n for (;;) {\n wrap.push(at);\n if (at.isTextblock) break;\n at = at.lastChild;\n }\n let afterText = after,\n afterDepth = 1;\n for (; !afterText.isTextblock; afterText = afterText.firstChild) afterDepth++;\n if (at.canReplace(at.childCount, at.childCount, afterText.content)) {\n if (dispatch) {\n let end = Fragment.empty;\n for (let i = wrap.length - 1; i >= 0; i--) end = Fragment.from(wrap[i].copy(end));\n let tr = state.tr.step(new ReplaceAroundStep($cut.pos - wrap.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap.length, 0), 0, true));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n }\n return false;\n}\nfunction selectTextblockSide(side) {\n return function (state, dispatch) {\n let sel = state.selection,\n $pos = side < 0 ? sel.$from : sel.$to;\n let depth = $pos.depth;\n while ($pos.node(depth).isInline) {\n if (!depth) return false;\n depth--;\n }\n if (!$pos.node(depth).isTextblock) return false;\n if (dispatch) dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));\n return true;\n };\n}\n/**\nMoves the cursor to the start of current text block.\n*/\nconst selectTextblockStart = selectTextblockSide(-1);\n/**\nMoves the cursor to the end of current text block.\n*/\nconst selectTextblockEnd = selectTextblockSide(1);\n// Parameterized commands\n/**\nWrap the selection in a node of the given type with the given\nattributes.\n*/\nfunction wrapIn(nodeType, attrs = null) {\n return function (state, dispatch) {\n let {\n $from,\n $to\n } = state.selection;\n let range = $from.blockRange($to),\n wrapping = range && findWrapping(range, nodeType, attrs);\n if (!wrapping) return false;\n if (dispatch) dispatch(state.tr.wrap(range, wrapping).scrollIntoView());\n return true;\n };\n}\n/**\nReturns a command that tries to set the selected textblocks to the\ngiven node type with the given attributes.\n*/\nfunction setBlockType(nodeType, attrs = null) {\n return function (state, dispatch) {\n let applicable = false;\n for (let i = 0; i < state.selection.ranges.length && !applicable; i++) {\n let {\n $from: {\n pos: from\n },\n $to: {\n pos: to\n }\n } = state.selection.ranges[i];\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (applicable) return false;\n if (!node.isTextblock || node.hasMarkup(nodeType, attrs)) return;\n if (node.type == nodeType) {\n applicable = true;\n } else {\n let $pos = state.doc.resolve(pos),\n index = $pos.index();\n applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);\n }\n });\n }\n if (!applicable) return false;\n if (dispatch) {\n let tr = state.tr;\n for (let i = 0; i < state.selection.ranges.length; i++) {\n let {\n $from: {\n pos: from\n },\n $to: {\n pos: to\n }\n } = state.selection.ranges[i];\n tr.setBlockType(from, to, nodeType, attrs);\n }\n dispatch(tr.scrollIntoView());\n }\n return true;\n };\n}\nfunction markApplies(doc, ranges, type) {\n for (let i = 0; i < ranges.length; i++) {\n let {\n $from,\n $to\n } = ranges[i];\n let can = $from.depth == 0 ? doc.inlineContent && doc.type.allowsMarkType(type) : false;\n doc.nodesBetween($from.pos, $to.pos, node => {\n if (can) return false;\n can = node.inlineContent && node.type.allowsMarkType(type);\n });\n if (can) return true;\n }\n return false;\n}\n/**\nCreate a command function that toggles the given mark with the\ngiven attributes. Will return `false` when the current selection\ndoesn't support that mark. This will remove the mark if any marks\nof that type exist in the selection, or add it otherwise. If the\nselection is empty, this applies to the [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks) instead of a range of the\ndocument.\n*/\nfunction toggleMark(markType, attrs = null) {\n return function (state, dispatch) {\n let {\n empty,\n $cursor,\n ranges\n } = state.selection;\n if (empty && !$cursor || !markApplies(state.doc, ranges, markType)) return false;\n if (dispatch) {\n if ($cursor) {\n if (markType.isInSet(state.storedMarks || $cursor.marks())) dispatch(state.tr.removeStoredMark(markType));else dispatch(state.tr.addStoredMark(markType.create(attrs)));\n } else {\n let has = false,\n tr = state.tr;\n for (let i = 0; !has && i < ranges.length; i++) {\n let {\n $from,\n $to\n } = ranges[i];\n has = state.doc.rangeHasMark($from.pos, $to.pos, markType);\n }\n for (let i = 0; i < ranges.length; i++) {\n let {\n $from,\n $to\n } = ranges[i];\n if (has) {\n tr.removeMark($from.pos, $to.pos, markType);\n } else {\n let from = $from.pos,\n to = $to.pos,\n start = $from.nodeAfter,\n end = $to.nodeBefore;\n let spaceStart = start && start.isText ? /^\\s*/.exec(start.text)[0].length : 0;\n let spaceEnd = end && end.isText ? /\\s*$/.exec(end.text)[0].length : 0;\n if (from + spaceStart < to) {\n from += spaceStart;\n to -= spaceEnd;\n }\n tr.addMark(from, to, markType.create(attrs));\n }\n }\n dispatch(tr.scrollIntoView());\n }\n }\n return true;\n };\n}\nfunction wrapDispatchForJoin(dispatch, isJoinable) {\n return tr => {\n if (!tr.isGeneric) return dispatch(tr);\n let ranges = [];\n for (let i = 0; i < tr.mapping.maps.length; i++) {\n let map = tr.mapping.maps[i];\n for (let j = 0; j < ranges.length; j++) ranges[j] = map.map(ranges[j]);\n map.forEach((_s, _e, from, to) => ranges.push(from, to));\n }\n // Figure out which joinable points exist inside those ranges,\n // by checking all node boundaries in their parent nodes.\n let joinable = [];\n for (let i = 0; i < ranges.length; i += 2) {\n let from = ranges[i],\n to = ranges[i + 1];\n let $from = tr.doc.resolve(from),\n depth = $from.sharedDepth(to),\n parent = $from.node(depth);\n for (let index = $from.indexAfter(depth), pos = $from.after(depth + 1); pos <= to; ++index) {\n let after = parent.maybeChild(index);\n if (!after) break;\n if (index && joinable.indexOf(pos) == -1) {\n let before = parent.child(index - 1);\n if (before.type == after.type && isJoinable(before, after)) joinable.push(pos);\n }\n pos += after.nodeSize;\n }\n }\n // Join the joinable points\n joinable.sort((a, b) => a - b);\n for (let i = joinable.length - 1; i >= 0; i--) {\n if (canJoin(tr.doc, joinable[i])) tr.join(joinable[i]);\n }\n dispatch(tr);\n };\n}\n/**\nWrap a command so that, when it produces a transform that causes\ntwo joinable nodes to end up next to each other, those are joined.\nNodes are considered joinable when they are of the same type and\nwhen the `isJoinable` predicate returns true for them or, if an\narray of strings was passed, if their node type name is in that\narray.\n*/\nfunction autoJoin(command, isJoinable) {\n let canJoin = Array.isArray(isJoinable) ? node => isJoinable.indexOf(node.type.name) > -1 : isJoinable;\n return (state, dispatch, view) => command(state, dispatch && wrapDispatchForJoin(dispatch, canJoin), view);\n}\n/**\nCombine a number of command functions into a single function (which\ncalls them one by one until one returns true).\n*/\nfunction chainCommands(...commands) {\n return function (state, dispatch, view) {\n for (let i = 0; i < commands.length; i++) if (commands[i](state, dispatch, view)) return true;\n return false;\n };\n}\nlet backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);\nlet del = chainCommands(deleteSelection, joinForward, selectNodeForward);\n/**\nA basic keymap containing bindings not specific to any schema.\nBinds the following keys (when multiple commands are listed, they\nare chained with [`chainCommands`](https://prosemirror.net/docs/ref/#commands.chainCommands)):\n\n* **Enter** to `newlineInCode`, `createParagraphNear`, `liftEmptyBlock`, `splitBlock`\n* **Mod-Enter** to `exitCode`\n* **Backspace** and **Mod-Backspace** to `deleteSelection`, `joinBackward`, `selectNodeBackward`\n* **Delete** and **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-a** to `selectAll`\n*/\nconst pcBaseKeymap = {\n \"Enter\": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),\n \"Mod-Enter\": exitCode,\n \"Backspace\": backspace,\n \"Mod-Backspace\": backspace,\n \"Shift-Backspace\": backspace,\n \"Delete\": del,\n \"Mod-Delete\": del,\n \"Mod-a\": selectAll\n};\n/**\nA copy of `pcBaseKeymap` that also binds **Ctrl-h** like Backspace,\n**Ctrl-d** like Delete, **Alt-Backspace** like Ctrl-Backspace, and\n**Ctrl-Alt-Backspace**, **Alt-Delete**, and **Alt-d** like\nCtrl-Delete.\n*/\nconst macBaseKeymap = {\n \"Ctrl-h\": pcBaseKeymap[\"Backspace\"],\n \"Alt-Backspace\": pcBaseKeymap[\"Mod-Backspace\"],\n \"Ctrl-d\": pcBaseKeymap[\"Delete\"],\n \"Ctrl-Alt-Backspace\": pcBaseKeymap[\"Mod-Delete\"],\n \"Alt-Delete\": pcBaseKeymap[\"Mod-Delete\"],\n \"Alt-d\": pcBaseKeymap[\"Mod-Delete\"],\n \"Ctrl-a\": selectTextblockStart,\n \"Ctrl-e\": selectTextblockEnd\n};\nfor (let key in pcBaseKeymap) macBaseKeymap[key] = pcBaseKeymap[key];\nconst mac = typeof navigator != \"undefined\" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform)\n// @ts-ignore\n: typeof os != \"undefined\" && os.platform ? os.platform() == \"darwin\" : false;\n/**\nDepending on the detected platform, this will hold\n[`pcBasekeymap`](https://prosemirror.net/docs/ref/#commands.pcBaseKeymap) or\n[`macBaseKeymap`](https://prosemirror.net/docs/ref/#commands.macBaseKeymap).\n*/\nconst baseKeymap = mac ? macBaseKeymap : pcBaseKeymap;\nexport { autoJoin, baseKeymap, chainCommands, createParagraphNear, deleteSelection, exitCode, joinBackward, joinDown, joinForward, joinTextblockBackward, joinTextblockForward, joinUp, lift, liftEmptyBlock, macBaseKeymap, newlineInCode, pcBaseKeymap, selectAll, selectNodeBackward, selectNodeForward, selectParentNode, selectTextblockEnd, selectTextblockStart, setBlockType, splitBlock, splitBlockAs, splitBlockKeepMarks, toggleMark, wrapIn };","import { TextSelection } from 'prosemirror-state';\nimport { markApplies } from 'ngx-editor/helpers';\nconst removeLink = () => {\n return (state, dispatch) => {\n const {\n doc,\n selection,\n tr,\n schema\n } = state;\n const {\n $head: {\n pos\n },\n from,\n to\n } = selection;\n const linkMark = schema.marks['link'];\n // if the cursor is on the link without any selection\n if (from === to) {\n const $pos = doc.resolve(pos);\n const linkStart = pos - $pos.textOffset;\n const linkEnd = linkStart + $pos.parent.child($pos.index()).nodeSize;\n tr.removeMark(linkStart, linkEnd, linkMark);\n } else {\n tr.removeMark(from, to, linkMark);\n }\n if (!tr.docChanged) {\n return false;\n }\n dispatch?.(tr);\n return true;\n };\n};\n\n// Ref: https://github.com/ProseMirror/prosemirror-commands/blob/master/src/commands.js\nconst applyMark = (type, attrs = {}) => {\n return (state, dispatch) => {\n const {\n tr,\n selection\n } = state;\n const {\n empty,\n ranges,\n $from,\n $to\n } = selection;\n if (empty && selection instanceof TextSelection) {\n const {\n $cursor\n } = selection;\n if (!$cursor || !markApplies(state.doc, ranges, type)) {\n return false;\n }\n tr.addStoredMark(type.create(attrs));\n if (!tr.storedMarksSet) {\n return false;\n }\n dispatch?.(tr);\n } else {\n tr.addMark($from.pos, $to.pos, type.create(attrs));\n if (!tr.docChanged) {\n return false;\n }\n dispatch?.(tr.scrollIntoView());\n }\n return true;\n };\n};\nconst removeMark = type => {\n return (state, dispatch) => {\n const {\n tr,\n selection,\n storedMarks,\n doc\n } = state;\n const {\n empty,\n ranges\n } = selection;\n if (empty && selection instanceof TextSelection) {\n const {\n $cursor\n } = selection;\n if (!$cursor || !markApplies(state.doc, ranges, type)) {\n return false;\n }\n if (type.isInSet(storedMarks || $cursor.marks())) {\n tr.removeStoredMark(type);\n dispatch?.(tr);\n return true;\n }\n } else {\n for (const range of ranges) {\n const {\n $from,\n $to\n } = range;\n const hasMark = doc.rangeHasMark($from.pos, $to.pos, type);\n if (hasMark) {\n tr.removeMark($from.pos, $to.pos, type);\n }\n }\n if (!tr.docChanged) {\n return false;\n }\n dispatch?.(tr.scrollIntoView());\n }\n return false;\n };\n};\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { applyMark, removeLink, removeMark };\n","import { InputRule } from 'prosemirror-inputrules';\nconst isMarkActive = (state, type) => {\n const {\n from,\n $from,\n to,\n empty\n } = state.selection;\n if (empty) {\n return Boolean(type.isInSet(state.storedMarks || $from.marks()));\n }\n return state.doc.rangeHasMark(from, to, type);\n};\nconst findNodeType = (type, $from) => {\n for (let i = $from.depth; i > 0; i -= 1) {\n if ($from.node(i).type === type) {\n return $from.node(i).type;\n }\n }\n return null;\n};\nconst isNodeActive = (state, type, attrs = {}) => {\n const {\n selection\n } = state;\n const {\n $from,\n to\n } = selection;\n const node = findNodeType(type, $from);\n if (!Object.entries(attrs).length || !node) {\n return Boolean(node);\n }\n return to <= $from.end() && $from.parent.hasMarkup(type, attrs);\n};\nconst getSelectionMarks = state => {\n let marks = [];\n const {\n selection,\n storedMarks\n } = state;\n const {\n from,\n to,\n empty,\n $from\n } = selection;\n if (empty) {\n marks = storedMarks || $from.marks();\n } else {\n state.doc.nodesBetween(from, to, node => {\n marks = [...marks, ...node.marks];\n });\n }\n return marks;\n};\nconst getSelectionNodes = state => {\n const nodes = [];\n const {\n selection: {\n from,\n to\n }\n } = state;\n state.doc.nodesBetween(from, to, node => {\n nodes.push(node);\n });\n return nodes;\n};\n\n// Ref: https://github.com/ProseMirror/prosemirror-commands/blob/master/src/commands.js\nconst markApplies = (doc, ranges, type) => {\n for (const range of ranges) {\n const {\n $from,\n $to\n } = range;\n let canApply = $from.depth === 0 ? doc.type.allowsMarkType(type) : false;\n doc.nodesBetween($from.pos, $to.pos, node => {\n if (canApply) {\n return false;\n }\n canApply = node.inlineContent && node.type.allowsMarkType(type);\n return true;\n });\n if (canApply) {\n return true;\n }\n }\n return false;\n};\nconst markInputRule = (regexp, markType, attrs) => {\n return new InputRule(regexp, (state, match, start, end) => {\n const {\n tr\n } = state;\n const from = start;\n let to = end;\n const [fullMatch,, content] = match;\n const noOfStartSpaces = fullMatch.search(/\\S/);\n if (content) {\n const textStart = start + fullMatch.indexOf(content);\n const textEnd = textStart + content.length;\n if (textEnd < end) {\n tr.delete(textEnd, end);\n }\n if (textStart > start) {\n tr.delete(start + noOfStartSpaces, textStart);\n }\n to = start + content.length + noOfStartSpaces;\n }\n tr.addMark(from, to, markType.create(attrs));\n tr.removeStoredMark(markType);\n return tr;\n });\n};\nconst canInsert = (state, nodeType) => {\n const {\n $from\n } = state.selection;\n for (let d = $from.depth; d >= 0; d -= 1) {\n const index = $from.index(d);\n if ($from.node(d).canReplaceWith(index, index, nodeType)) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { canInsert, getSelectionMarks, getSelectionNodes, isMarkActive, isNodeActive, markApplies, markInputRule };\n","import RopeSequence from 'rope-sequence';\nimport { Mapping } from 'prosemirror-transform';\nimport { PluginKey, Plugin } from 'prosemirror-state';\n\n// ProseMirror's history isn't simply a way to roll back to a previous\n// state, because ProseMirror supports applying changes without adding\n// them to the history (for example during collaboration).\n//\n// To this end, each 'Branch' (one for the undo history and one for\n// the redo history) keeps an array of 'Items', which can optionally\n// hold a step (an actual undoable change), and always hold a position\n// map (which is needed to move changes below them to apply to the\n// current document).\n//\n// An item that has both a step and a selection bookmark is the start\n// of an 'event' — a group of changes that will be undone or redone at\n// once. (It stores only the bookmark, since that way we don't have to\n// provide a document until the selection is actually applied, which\n// is useful when compressing.)\n// Used to schedule history compression\nconst max_empty_items = 500;\nclass Branch {\n constructor(items, eventCount) {\n this.items = items;\n this.eventCount = eventCount;\n }\n // Pop the latest event off the branch's history and apply it\n // to a document transform.\n popEvent(state, preserveItems) {\n if (this.eventCount == 0) return null;\n let end = this.items.length;\n for (;; end--) {\n let next = this.items.get(end - 1);\n if (next.selection) {\n --end;\n break;\n }\n }\n let remap, mapFrom;\n if (preserveItems) {\n remap = this.remapping(end, this.items.length);\n mapFrom = remap.maps.length;\n }\n let transform = state.tr;\n let selection, remaining;\n let addAfter = [],\n addBefore = [];\n this.items.forEach((item, i) => {\n if (!item.step) {\n if (!remap) {\n remap = this.remapping(end, i + 1);\n mapFrom = remap.maps.length;\n }\n mapFrom--;\n addBefore.push(item);\n return;\n }\n if (remap) {\n addBefore.push(new Item(item.map));\n let step = item.step.map(remap.slice(mapFrom)),\n map;\n if (step && transform.maybeStep(step).doc) {\n map = transform.mapping.maps[transform.mapping.maps.length - 1];\n addAfter.push(new Item(map, undefined, undefined, addAfter.length + addBefore.length));\n }\n mapFrom--;\n if (map) remap.appendMap(map, mapFrom);\n } else {\n transform.maybeStep(item.step);\n }\n if (item.selection) {\n selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;\n remaining = new Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1);\n return false;\n }\n }, this.items.length, 0);\n return {\n remaining: remaining,\n transform,\n selection: selection\n };\n }\n // Create a new branch with the given transform added.\n addTransform(transform, selection, histOptions, preserveItems) {\n let newItems = [],\n eventCount = this.eventCount;\n let oldItems = this.items,\n lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;\n for (let i = 0; i < transform.steps.length; i++) {\n let step = transform.steps[i].invert(transform.docs[i]);\n let item = new Item(transform.mapping.maps[i], step, selection),\n merged;\n if (merged = lastItem && lastItem.merge(item)) {\n item = merged;\n if (i) newItems.pop();else oldItems = oldItems.slice(0, oldItems.length - 1);\n }\n newItems.push(item);\n if (selection) {\n eventCount++;\n selection = undefined;\n }\n if (!preserveItems) lastItem = item;\n }\n let overflow = eventCount - histOptions.depth;\n if (overflow > DEPTH_OVERFLOW) {\n oldItems = cutOffEvents(oldItems, overflow);\n eventCount -= overflow;\n }\n return new Branch(oldItems.append(newItems), eventCount);\n }\n remapping(from, to) {\n let maps = new Mapping();\n this.items.forEach((item, i) => {\n let mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from ? maps.maps.length - item.mirrorOffset : undefined;\n maps.appendMap(item.map, mirrorPos);\n }, from, to);\n return maps;\n }\n addMaps(array) {\n if (this.eventCount == 0) return this;\n return new Branch(this.items.append(array.map(map => new Item(map))), this.eventCount);\n }\n // When the collab module receives remote changes, the history has\n // to know about those, so that it can adjust the steps that were\n // rebased on top of the remote changes, and include the position\n // maps for the remote changes in its array of items.\n rebased(rebasedTransform, rebasedCount) {\n if (!this.eventCount) return this;\n let rebasedItems = [],\n start = Math.max(0, this.items.length - rebasedCount);\n let mapping = rebasedTransform.mapping;\n let newUntil = rebasedTransform.steps.length;\n let eventCount = this.eventCount;\n this.items.forEach(item => {\n if (item.selection) eventCount--;\n }, start);\n let iRebased = rebasedCount;\n this.items.forEach(item => {\n let pos = mapping.getMirror(--iRebased);\n if (pos == null) return;\n newUntil = Math.min(newUntil, pos);\n let map = mapping.maps[pos];\n if (item.step) {\n let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);\n let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));\n if (selection) eventCount++;\n rebasedItems.push(new Item(map, step, selection));\n } else {\n rebasedItems.push(new Item(map));\n }\n }, start);\n let newMaps = [];\n for (let i = rebasedCount; i < newUntil; i++) newMaps.push(new Item(mapping.maps[i]));\n let items = this.items.slice(0, start).append(newMaps).append(rebasedItems);\n let branch = new Branch(items, eventCount);\n if (branch.emptyItemCount() > max_empty_items) branch = branch.compress(this.items.length - rebasedItems.length);\n return branch;\n }\n emptyItemCount() {\n let count = 0;\n this.items.forEach(item => {\n if (!item.step) count++;\n });\n return count;\n }\n // Compressing a branch means rewriting it to push the air (map-only\n // items) out. During collaboration, these naturally accumulate\n // because each remote change adds one. The `upto` argument is used\n // to ensure that only the items below a given level are compressed,\n // because `rebased` relies on a clean, untouched set of items in\n // order to associate old items with rebased steps.\n compress(upto = this.items.length) {\n let remap = this.remapping(0, upto),\n mapFrom = remap.maps.length;\n let items = [],\n events = 0;\n this.items.forEach((item, i) => {\n if (i >= upto) {\n items.push(item);\n if (item.selection) events++;\n } else if (item.step) {\n let step = item.step.map(remap.slice(mapFrom)),\n map = step && step.getMap();\n mapFrom--;\n if (map) remap.appendMap(map, mapFrom);\n if (step) {\n let selection = item.selection && item.selection.map(remap.slice(mapFrom));\n if (selection) events++;\n let newItem = new Item(map.invert(), step, selection),\n merged,\n last = items.length - 1;\n if (merged = items.length && items[last].merge(newItem)) items[last] = merged;else items.push(newItem);\n }\n } else if (item.map) {\n mapFrom--;\n }\n }, this.items.length, 0);\n return new Branch(RopeSequence.from(items.reverse()), events);\n }\n}\nBranch.empty = new Branch(RopeSequence.empty, 0);\nfunction cutOffEvents(items, n) {\n let cutPoint;\n items.forEach((item, i) => {\n if (item.selection && n-- == 0) {\n cutPoint = i;\n return false;\n }\n });\n return items.slice(cutPoint);\n}\nclass Item {\n constructor(\n // The (forward) step map for this item.\n map,\n // The inverted step\n step,\n // If this is non-null, this item is the start of a group, and\n // this selection is the starting selection for the group (the one\n // that was active before the first step was applied)\n selection,\n // If this item is the inverse of a previous mapping on the stack,\n // this points at the inverse's offset\n mirrorOffset) {\n this.map = map;\n this.step = step;\n this.selection = selection;\n this.mirrorOffset = mirrorOffset;\n }\n merge(other) {\n if (this.step && other.step && !other.selection) {\n let step = other.step.merge(this.step);\n if (step) return new Item(step.getMap().invert(), step, this.selection);\n }\n }\n}\n// The value of the state field that tracks undo/redo history for that\n// state. Will be stored in the plugin state when the history plugin\n// is active.\nclass HistoryState {\n constructor(done, undone, prevRanges, prevTime, prevComposition) {\n this.done = done;\n this.undone = undone;\n this.prevRanges = prevRanges;\n this.prevTime = prevTime;\n this.prevComposition = prevComposition;\n }\n}\nconst DEPTH_OVERFLOW = 20;\n// Record a transformation in undo history.\nfunction applyTransaction(history, state, tr, options) {\n let historyTr = tr.getMeta(historyKey),\n rebased;\n if (historyTr) return historyTr.historyState;\n if (tr.getMeta(closeHistoryKey)) history = new HistoryState(history.done, history.undone, null, 0, -1);\n let appended = tr.getMeta(\"appendedTransaction\");\n if (tr.steps.length == 0) {\n return history;\n } else if (appended && appended.getMeta(historyKey)) {\n if (appended.getMeta(historyKey).redo) return new HistoryState(history.done.addTransform(tr, undefined, options, mustPreserveItems(state)), history.undone, rangesFor(tr.mapping.maps), history.prevTime, history.prevComposition);else return new HistoryState(history.done, history.undone.addTransform(tr, undefined, options, mustPreserveItems(state)), null, history.prevTime, history.prevComposition);\n } else if (tr.getMeta(\"addToHistory\") !== false && !(appended && appended.getMeta(\"addToHistory\") === false)) {\n // Group transforms that occur in quick succession into one event.\n let composition = tr.getMeta(\"composition\");\n let newGroup = history.prevTime == 0 || !appended && history.prevComposition != composition && (history.prevTime < (tr.time || 0) - options.newGroupDelay || !isAdjacentTo(tr, history.prevRanges));\n let prevRanges = appended ? mapRanges(history.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps);\n return new HistoryState(history.done.addTransform(tr, newGroup ? state.selection.getBookmark() : undefined, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr.time, composition == null ? history.prevComposition : composition);\n } else if (rebased = tr.getMeta(\"rebased\")) {\n // Used by the collab module to tell the history that some of its\n // content has been rebased.\n return new HistoryState(history.done.rebased(tr, rebased), history.undone.rebased(tr, rebased), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);\n } else {\n return new HistoryState(history.done.addMaps(tr.mapping.maps), history.undone.addMaps(tr.mapping.maps), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);\n }\n}\nfunction isAdjacentTo(transform, prevRanges) {\n if (!prevRanges) return false;\n if (!transform.docChanged) return true;\n let adjacent = false;\n transform.mapping.maps[0].forEach((start, end) => {\n for (let i = 0; i < prevRanges.length; i += 2) if (start <= prevRanges[i + 1] && end >= prevRanges[i]) adjacent = true;\n });\n return adjacent;\n}\nfunction rangesFor(maps) {\n let result = [];\n for (let i = maps.length - 1; i >= 0 && result.length == 0; i--) maps[i].forEach((_from, _to, from, to) => result.push(from, to));\n return result;\n}\nfunction mapRanges(ranges, mapping) {\n if (!ranges) return null;\n let result = [];\n for (let i = 0; i < ranges.length; i += 2) {\n let from = mapping.map(ranges[i], 1),\n to = mapping.map(ranges[i + 1], -1);\n if (from <= to) result.push(from, to);\n }\n return result;\n}\n// Apply the latest event from one branch to the document and shift the event\n// onto the other branch.\nfunction histTransaction(history, state, redo) {\n let preserveItems = mustPreserveItems(state);\n let histOptions = historyKey.get(state).spec.config;\n let pop = (redo ? history.undone : history.done).popEvent(state, preserveItems);\n if (!pop) return null;\n let selection = pop.selection.resolve(pop.transform.doc);\n let added = (redo ? history.done : history.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems);\n let newHist = new HistoryState(redo ? added : pop.remaining, redo ? pop.remaining : added, null, 0, -1);\n return pop.transform.setSelection(selection).setMeta(historyKey, {\n redo,\n historyState: newHist\n });\n}\nlet cachedPreserveItems = false,\n cachedPreserveItemsPlugins = null;\n// Check whether any plugin in the given state has a\n// `historyPreserveItems` property in its spec, in which case we must\n// preserve steps exactly as they came in, so that they can be\n// rebased.\nfunction mustPreserveItems(state) {\n let plugins = state.plugins;\n if (cachedPreserveItemsPlugins != plugins) {\n cachedPreserveItems = false;\n cachedPreserveItemsPlugins = plugins;\n for (let i = 0; i < plugins.length; i++) if (plugins[i].spec.historyPreserveItems) {\n cachedPreserveItems = true;\n break;\n }\n }\n return cachedPreserveItems;\n}\n/**\nSet a flag on the given transaction that will prevent further steps\nfrom being appended to an existing history event (so that they\nrequire a separate undo command to undo).\n*/\nfunction closeHistory(tr) {\n return tr.setMeta(closeHistoryKey, true);\n}\nconst historyKey = new PluginKey(\"history\");\nconst closeHistoryKey = new PluginKey(\"closeHistory\");\n/**\nReturns a plugin that enables the undo history for an editor. The\nplugin will track undo and redo stacks, which can be used with the\n[`undo`](https://prosemirror.net/docs/ref/#history.undo) and [`redo`](https://prosemirror.net/docs/ref/#history.redo) commands.\n\nYou can set an `\"addToHistory\"` [metadata\nproperty](https://prosemirror.net/docs/ref/#state.Transaction.setMeta) of `false` on a transaction\nto prevent it from being rolled back by undo.\n*/\nfunction history(config = {}) {\n config = {\n depth: config.depth || 100,\n newGroupDelay: config.newGroupDelay || 500\n };\n return new Plugin({\n key: historyKey,\n state: {\n init() {\n return new HistoryState(Branch.empty, Branch.empty, null, 0, -1);\n },\n apply(tr, hist, state) {\n return applyTransaction(hist, state, tr, config);\n }\n },\n config,\n props: {\n handleDOMEvents: {\n beforeinput(view, e) {\n let inputType = e.inputType;\n let command = inputType == \"historyUndo\" ? undo : inputType == \"historyRedo\" ? redo : null;\n if (!command) return false;\n e.preventDefault();\n return command(view.state, view.dispatch);\n }\n }\n }\n });\n}\nfunction buildCommand(redo, scroll) {\n return (state, dispatch) => {\n let hist = historyKey.getState(state);\n if (!hist || (redo ? hist.undone : hist.done).eventCount == 0) return false;\n if (dispatch) {\n let tr = histTransaction(hist, state, redo);\n if (tr) dispatch(scroll ? tr.scrollIntoView() : tr);\n }\n return true;\n };\n}\n/**\nA command function that undoes the last change, if any.\n*/\nconst undo = buildCommand(false, true);\n/**\nA command function that redoes the last undone change, if any.\n*/\nconst redo = buildCommand(true, true);\n/**\nA command function that undoes the last change. Don't scroll the\nselection into view.\n*/\nconst undoNoScroll = buildCommand(false, false);\n/**\nA command function that redoes the last undone change. Don't\nscroll the selection into view.\n*/\nconst redoNoScroll = buildCommand(true, false);\n/**\nThe amount of undoable events available in a given state.\n*/\nfunction undoDepth(state) {\n let hist = historyKey.getState(state);\n return hist ? hist.done.eventCount : 0;\n}\n/**\nThe amount of redoable events available in a given editor state.\n*/\nfunction redoDepth(state) {\n let hist = historyKey.getState(state);\n return hist ? hist.undone.eventCount : 0;\n}\nexport { closeHistory, history, redo, redoDepth, redoNoScroll, undo, undoDepth, undoNoScroll };","var GOOD_LEAF_SIZE = 200;\n\n// :: class A rope sequence is a persistent sequence data structure\n// that supports appending, prepending, and slicing without doing a\n// full copy. It is represented as a mostly-balanced tree.\nvar RopeSequence = function RopeSequence() {};\nRopeSequence.prototype.append = function append(other) {\n if (!other.length) {\n return this;\n }\n other = RopeSequence.from(other);\n return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other);\n};\n\n// :: (union<[T], RopeSequence>) → RopeSequence\n// Prepend an array or other rope to this one, returning a new rope.\nRopeSequence.prototype.prepend = function prepend(other) {\n if (!other.length) {\n return this;\n }\n return RopeSequence.from(other).append(this);\n};\nRopeSequence.prototype.appendInner = function appendInner(other) {\n return new Append(this, other);\n};\n\n// :: (?number, ?number) → RopeSequence\n// Create a rope repesenting a sub-sequence of this rope.\nRopeSequence.prototype.slice = function slice(from, to) {\n if (from === void 0) from = 0;\n if (to === void 0) to = this.length;\n if (from >= to) {\n return RopeSequence.empty;\n }\n return this.sliceInner(Math.max(0, from), Math.min(this.length, to));\n};\n\n// :: (number) → T\n// Retrieve the element at the given position from this rope.\nRopeSequence.prototype.get = function get(i) {\n if (i < 0 || i >= this.length) {\n return undefined;\n }\n return this.getInner(i);\n};\n\n// :: ((element: T, index: number) → ?bool, ?number, ?number)\n// Call the given function for each element between the given\n// indices. This tends to be more efficient than looping over the\n// indices and calling `get`, because it doesn't have to descend the\n// tree for every element.\nRopeSequence.prototype.forEach = function forEach(f, from, to) {\n if (from === void 0) from = 0;\n if (to === void 0) to = this.length;\n if (from <= to) {\n this.forEachInner(f, from, to, 0);\n } else {\n this.forEachInvertedInner(f, from, to, 0);\n }\n};\n\n// :: ((element: T, index: number) → U, ?number, ?number) → [U]\n// Map the given functions over the elements of the rope, producing\n// a flat array.\nRopeSequence.prototype.map = function map(f, from, to) {\n if (from === void 0) from = 0;\n if (to === void 0) to = this.length;\n var result = [];\n this.forEach(function (elt, i) {\n return result.push(f(elt, i));\n }, from, to);\n return result;\n};\n\n// :: (?union<[T], RopeSequence>) → RopeSequence\n// Create a rope representing the given array, or return the rope\n// itself if a rope was given.\nRopeSequence.from = function from(values) {\n if (values instanceof RopeSequence) {\n return values;\n }\n return values && values.length ? new Leaf(values) : RopeSequence.empty;\n};\nvar Leaf = /*@__PURE__*/function (RopeSequence) {\n function Leaf(values) {\n RopeSequence.call(this);\n this.values = values;\n }\n if (RopeSequence) Leaf.__proto__ = RopeSequence;\n Leaf.prototype = Object.create(RopeSequence && RopeSequence.prototype);\n Leaf.prototype.constructor = Leaf;\n var prototypeAccessors = {\n length: {\n configurable: true\n },\n depth: {\n configurable: true\n }\n };\n Leaf.prototype.flatten = function flatten() {\n return this.values;\n };\n Leaf.prototype.sliceInner = function sliceInner(from, to) {\n if (from == 0 && to == this.length) {\n return this;\n }\n return new Leaf(this.values.slice(from, to));\n };\n Leaf.prototype.getInner = function getInner(i) {\n return this.values[i];\n };\n Leaf.prototype.forEachInner = function forEachInner(f, from, to, start) {\n for (var i = from; i < to; i++) {\n if (f(this.values[i], start + i) === false) {\n return false;\n }\n }\n };\n Leaf.prototype.forEachInvertedInner = function forEachInvertedInner(f, from, to, start) {\n for (var i = from - 1; i >= to; i--) {\n if (f(this.values[i], start + i) === false) {\n return false;\n }\n }\n };\n Leaf.prototype.leafAppend = function leafAppend(other) {\n if (this.length + other.length <= GOOD_LEAF_SIZE) {\n return new Leaf(this.values.concat(other.flatten()));\n }\n };\n Leaf.prototype.leafPrepend = function leafPrepend(other) {\n if (this.length + other.length <= GOOD_LEAF_SIZE) {\n return new Leaf(other.flatten().concat(this.values));\n }\n };\n prototypeAccessors.length.get = function () {\n return this.values.length;\n };\n prototypeAccessors.depth.get = function () {\n return 0;\n };\n Object.defineProperties(Leaf.prototype, prototypeAccessors);\n return Leaf;\n}(RopeSequence);\n\n// :: RopeSequence\n// The empty rope sequence.\nRopeSequence.empty = new Leaf([]);\nvar Append = /*@__PURE__*/function (RopeSequence) {\n function Append(left, right) {\n RopeSequence.call(this);\n this.left = left;\n this.right = right;\n this.length = left.length + right.length;\n this.depth = Math.max(left.depth, right.depth) + 1;\n }\n if (RopeSequence) Append.__proto__ = RopeSequence;\n Append.prototype = Object.create(RopeSequence && RopeSequence.prototype);\n Append.prototype.constructor = Append;\n Append.prototype.flatten = function flatten() {\n return this.left.flatten().concat(this.right.flatten());\n };\n Append.prototype.getInner = function getInner(i) {\n return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length);\n };\n Append.prototype.forEachInner = function forEachInner(f, from, to, start) {\n var leftLen = this.left.length;\n if (from < leftLen && this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false) {\n return false;\n }\n if (to > leftLen && this.right.forEachInner(f, Math.max(from - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false) {\n return false;\n }\n };\n Append.prototype.forEachInvertedInner = function forEachInvertedInner(f, from, to, start) {\n var leftLen = this.left.length;\n if (from > leftLen && this.right.forEachInvertedInner(f, from - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false) {\n return false;\n }\n if (to < leftLen && this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false) {\n return false;\n }\n };\n Append.prototype.sliceInner = function sliceInner(from, to) {\n if (from == 0 && to == this.length) {\n return this;\n }\n var leftLen = this.left.length;\n if (to <= leftLen) {\n return this.left.slice(from, to);\n }\n if (from >= leftLen) {\n return this.right.slice(from - leftLen, to - leftLen);\n }\n return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen));\n };\n Append.prototype.leafAppend = function leafAppend(other) {\n var inner = this.right.leafAppend(other);\n if (inner) {\n return new Append(this.left, inner);\n }\n };\n Append.prototype.leafPrepend = function leafPrepend(other) {\n var inner = this.left.leafPrepend(other);\n if (inner) {\n return new Append(inner, this.right);\n }\n };\n Append.prototype.appendInner = function appendInner(other) {\n if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1) {\n return new Append(this.left, new Append(this.right, other));\n }\n return new Append(this, other);\n };\n return Append;\n}(RopeSequence);\nexport default RopeSequence;","import { inject } from '@angular/core';\nimport { CanActivateFn, ParamMap, Router, Routes } from '@angular/router';\nimport { from } from 'rxjs';\n\nimport { authGuard } from './auth.guard';\nimport uiKitRoutes from './pages/ui-kit-page/ui-kit.routes';\n\nexport const redirectTo =\n (redirectToUrl: (params: ParamMap) => string): CanActivateFn =>\n (route) =>\n from(inject(Router).navigateByUrl(redirectToUrl(route.queryParamMap)));\n\nexport const routes: Routes = [\n uiKitRoutes,\n {\n path: '',\n loadComponent: () => import('./pages/main-page/main-page.component'),\n canActivate: [authGuard],\n children: [\n {\n path: '',\n canActivate: [redirectTo(() => 'applications?sortField=originDate&sortOrder=-1')],\n children: [],\n pathMatch: 'full',\n },\n {\n path: 'account',\n loadComponent: () => import('./pages/settings-page/account-page/account-page.component'),\n },\n {\n path: 'dashboard',\n loadComponent: () => import('./pages/dashboard-page/dashboard-page.component'),\n canActivate: [authGuard],\n children: [\n {\n path: 'overview-dashboard',\n loadComponent: () =>\n import('./pages/dashboard-page/overview-dashboard-page/overview-dashboard-page.component'),\n },\n {\n path: 'activity',\n loadComponent: () => import('./pages/dashboard-page/activity-page/activity-page.component'),\n },\n {\n path: 'deadlines',\n loadComponent: () => import('./pages/dashboard-page/deadlines-page/deadlines-page.component'),\n },\n {\n path: '**',\n redirectTo: 'overview-dashboard',\n pathMatch: 'full',\n },\n ],\n },\n {\n path: 'lead',\n loadComponent: () => import('./pages/lead-page/lead-page.component'),\n canActivate: [authGuard],\n },\n {\n path: 'lead/:id',\n loadComponent: () => import('./pages/lead-details-page/lead-details-page.component'),\n canActivate: [authGuard],\n children: [\n {\n path: 'related-contacts',\n loadComponent: () => import('./pages/related-contacts-page/related-contacts-page.component'),\n },\n ],\n },\n {\n path: 'students',\n loadComponent: () => import('./pages/students-page/students-page.component'),\n canActivate: [authGuard],\n },\n {\n path: 'students/:id',\n loadComponent: () => import('./pages/student-details-page/student-details-page.component'),\n canActivate: [authGuard],\n children: [\n {\n path: 'overview-students',\n loadComponent: () => import('./pages/student-details-page/overview-students/overview-students.component'),\n },\n {\n path: 'registry',\n loadComponent: () => import('./pages/student-details-page/registry/registry.component'),\n },\n {\n path: 'family',\n loadComponent: () => import('./pages/student-details-page/family/family.component'),\n },\n {\n path: 'health',\n loadComponent: () => import('./pages/student-details-page/health/health.component'),\n },\n {\n path: 'education',\n loadComponent: () => import('./pages/student-details-page/education/education.component'),\n },\n {\n path: 'isee',\n loadComponent: () => import('./pages/student-details-page/isee/isee.component'),\n },\n {\n path: 'documents-students',\n loadComponent: () => import('./pages/student-details-page/documents-students/documents-students.component'),\n },\n {\n path: 'historical',\n loadComponent: () => import('./pages/student-details-page/historical/historical.component'),\n },\n {\n path: 'contacts',\n loadComponent: () => import('./pages/student-details-page/historical/historical.component'),\n },\n {\n path: 'related-contacts',\n loadComponent: () => import('./pages/related-contacts-page/related-contacts-page.component'),\n },\n {\n path: '**',\n redirectTo: 'overview-students',\n pathMatch: 'full',\n },\n ],\n },\n {\n path: 'parents',\n loadComponent: () => import('./pages/parents-page/parents-page.component'),\n canActivate: [authGuard],\n },\n {\n path: 'parents/:id',\n loadComponent: () => import('./pages/parents-details-page/parents-details-page.component'),\n canActivate: [authGuard],\n children: [\n {\n path: 'overview-parents',\n loadComponent: () => import('./pages/parents-details-page/overview-parents/overview-parents.component'),\n },\n {\n path: 'profile',\n loadComponent: () => import('./pages/parents-details-page/profile/profile.component'),\n },\n {\n path: 'documents-parents',\n loadComponent: () => import('./pages/parents-details-page/documents-parents/documents-parents.component'),\n },\n {\n path: 'related-contacts',\n loadComponent: () => import('./pages/related-contacts-page/related-contacts-page.component'),\n },\n {\n path: '**',\n redirectTo: 'overview-parents',\n pathMatch: 'full',\n },\n ],\n },\n {\n path: 'applications',\n loadComponent: () => import('./pages/applications-page/applications-page.component'),\n canActivate: [authGuard],\n },\n {\n path: 'applications/:id',\n loadComponent: () => import('./pages/application-details-page/application-details-page.component'),\n canActivate: [authGuard],\n },\n {\n path: 'programs',\n loadComponent: () => import('./pages/programs-page/programs-page.component'),\n canActivate: [authGuard],\n },\n {\n path: 'communications',\n loadComponent: () => import('./pages/communications-page/communications-page.component'),\n canActivate: [authGuard],\n children: [\n {\n path: ':threadId',\n loadComponent: () => import('./pages/communication-details-page/communication-details-page.component'),\n },\n ],\n },\n {\n path: 'settings',\n loadComponent: () => import('./pages/settings-page/settings-page.component'),\n canActivate: [authGuard],\n children: [\n {\n path: 'users',\n loadComponent: () => import('./pages/settings-page/widget/users/users.component'),\n },\n {\n path: 'procedure',\n loadComponent: () => import('./pages/settings-page/procedures-page/procedures-page.component'),\n },\n {\n path: 'contests',\n loadComponent: () => import('./pages/settings-page/contests-page/contests-page.component'),\n children: [\n {\n path: ':contestId',\n loadComponent: () =>\n import('./pages/settings-page/contests-page/contest-details/contest-details.component'),\n },\n ],\n },\n {\n path: '',\n redirectTo: 'users',\n pathMatch: 'full',\n },\n ],\n },\n ],\n },\n {\n path: '**',\n redirectTo: '',\n pathMatch: 'full',\n },\n];\n","import { inject } from '@angular/core';\nimport { CanActivateFn } from '@angular/router';\nimport { firstValueFrom } from 'rxjs';\n\nimport { AuthenticationService } from './services/authentication.service';\nimport { environment } from '../environments/environment';\n\nexport const authGuard: CanActivateFn = async ({ url }) => {\n const authenticationService = inject(AuthenticationService);\n\n try {\n authenticationService.currentUser = await firstValueFrom(authenticationService.getMe());\n return true;\n } catch (e) {\n if (environment.production) {\n window.location.href = `${environment.loginFlowPath}?redirectUri=${url}`;\n } else {\n window.location.href = `${environment.internalLoginFlowPath}?redirectUri=${url}`;\n }\n return false;\n }\n};\n","import { Route } from '@angular/router';\n\nconst uiKitRoutes: Route = {\n path: 'ui-kit',\n redirectTo: '/',\n};\n\nexport default uiKitRoutes;\n","/* eslint-disable import/no-unresolved */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { ApplicationConfig, inject } from '@angular/core';\nimport { ApolloClientOptions, ApolloLink, InMemoryCache } from '@apollo/client/core';\nimport { Apollo, APOLLO_OPTIONS } from 'apollo-angular';\nimport { HttpLink } from 'apollo-angular/http';\nimport { Body } from 'apollo-angular/http/types';\nimport extractFiles from 'extract-files/extractFiles.mjs';\nimport isExtractableFile from 'extract-files/isExtractableFile.mjs';\n\nimport { toLocaleDate, toYearMonthDate } from './utils/date';\nimport { environment } from '../environments/environment';\n\nconst INSTANT_DATE_OPERATIONS = [\n 'GetDashboard',\n 'CreateTask',\n 'UpdateTask',\n 'CreateRequest',\n 'UpdateRequest',\n 'CreateView',\n 'UpdateView',\n];\n\nconst DOCUMENT_OPERATIONS = ['UploadDocument'];\n\nconst YEAR_MONTH_OPERATIONS = ['UpdateInternationalApplication'];\n\nconst NOT_LOCALE_DATE_OPERATIONS = [...INSTANT_DATE_OPERATIONS, ...DOCUMENT_OPERATIONS, ...YEAR_MONTH_OPERATIONS];\n\nfunction transformDatesToLocaleDate(obj: any): any {\n if (obj === null || obj === undefined) return obj;\n\n if (obj instanceof Date) {\n // Convert Date to local date string format\n return toLocaleDate(obj);\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => transformDatesToLocaleDate(item));\n }\n\n if (typeof obj === 'object') {\n return Object.keys(obj).reduce((acc, key) => {\n acc[key] = transformDatesToLocaleDate(obj[key]);\n return acc;\n }, {} as any);\n }\n\n return obj;\n}\n\nfunction transformDatesToYearMonth(obj: any): any {\n if (obj === null || obj === undefined) return obj;\n\n if (obj instanceof Date) {\n // Convert Date to local date string format\n return toYearMonthDate(obj);\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => transformDatesToYearMonth(item));\n }\n\n if (typeof obj === 'object') {\n return Object.keys(obj).reduce((acc, key) => {\n acc[key] = transformDatesToYearMonth(obj[key]);\n return acc;\n }, {} as any);\n }\n\n return obj;\n}\n\nexport function apolloOptionsFactory(): ApolloClientOptions {\n const httpLink = inject(HttpLink);\n\n const dateMiddleware = new ApolloLink((operation, forward) => {\n if (!NOT_LOCALE_DATE_OPERATIONS.includes(operation.operationName)) {\n operation.variables = transformDatesToLocaleDate(operation.variables);\n }\n\n if (YEAR_MONTH_OPERATIONS.includes(operation.operationName)) {\n operation.variables = transformDatesToYearMonth(operation.variables);\n }\n\n return forward(operation);\n });\n\n return {\n link: ApolloLink.from([\n dateMiddleware,\n httpLink.create({\n uri: environment.apiGraphQlPath,\n extractFiles: (body) =>\n extractFiles(body, isExtractableFile) as {\n clone: Body;\n files: Map;\n },\n }),\n ]),\n cache: new InMemoryCache(),\n };\n}\n\nexport const graphqlProvider: ApplicationConfig['providers'] = [\n Apollo,\n {\n provide: APOLLO_OPTIONS,\n useFactory: apolloOptionsFactory,\n },\n];\n","import { print } from 'graphql';\nimport * as i0 from '@angular/core';\nimport { Injectable } from '@angular/core';\nimport { ApolloLink, Observable as Observable$1 } from '@apollo/client/core';\nimport { Observable } from 'rxjs';\nimport * as i1 from '@angular/common/http';\nimport { HttpHeaders } from '@angular/common/http';\nimport { BatchLink } from '@apollo/client/link/batch';\nconst fetch = (req, httpClient, extractFiles) => {\n const shouldUseBody = ['POST', 'PUT', 'PATCH'].indexOf(req.method.toUpperCase()) !== -1;\n const shouldStringify = param => ['variables', 'extensions'].indexOf(param.toLowerCase()) !== -1;\n const isBatching = req.body.length;\n let shouldUseMultipart = req.options && req.options.useMultipart;\n let multipartInfo;\n if (shouldUseMultipart) {\n if (isBatching) {\n return new Observable(observer => observer.error(new Error('File upload is not available when combined with Batching')));\n }\n if (!shouldUseBody) {\n return new Observable(observer => observer.error(new Error('File upload is not available when GET is used')));\n }\n if (!extractFiles) {\n return new Observable(observer => observer.error(new Error(`To use File upload you need to pass \"extractFiles\" function from \"extract-files\" library to HttpLink's options`)));\n }\n multipartInfo = extractFiles(req.body);\n shouldUseMultipart = !!multipartInfo.files.size;\n }\n // `body` for some, `params` for others\n let bodyOrParams = {};\n if (isBatching) {\n if (!shouldUseBody) {\n return new Observable(observer => observer.error(new Error('Batching is not available for GET requests')));\n }\n bodyOrParams = {\n body: req.body\n };\n } else {\n const body = shouldUseMultipart ? multipartInfo.clone : req.body;\n if (shouldUseBody) {\n bodyOrParams = {\n body\n };\n } else {\n const params = Object.keys(req.body).reduce((obj, param) => {\n const value = req.body[param];\n obj[param] = shouldStringify(param) ? JSON.stringify(value) : value;\n return obj;\n }, {});\n bodyOrParams = {\n params: params\n };\n }\n }\n if (shouldUseMultipart && shouldUseBody) {\n const form = new FormData();\n form.append('operations', JSON.stringify(bodyOrParams.body));\n const map = {};\n const files = multipartInfo.files;\n let i = 0;\n files.forEach(paths => {\n map[++i] = paths;\n });\n form.append('map', JSON.stringify(map));\n i = 0;\n files.forEach((_, file) => {\n form.append(++i + '', file, file.name);\n });\n bodyOrParams.body = form;\n }\n // create a request\n return httpClient.request(req.method, req.url, {\n observe: 'response',\n responseType: 'json',\n reportProgress: false,\n ...bodyOrParams,\n ...req.options\n });\n};\nconst mergeHeaders = (source, destination) => {\n if (source && destination) {\n const merged = destination.keys().reduce((headers, name) => headers.set(name, destination.getAll(name)), source);\n return merged;\n }\n return destination || source;\n};\nfunction prioritize(...values) {\n const picked = values.find(val => typeof val !== 'undefined');\n if (typeof picked === 'undefined') {\n return values[values.length - 1];\n }\n return picked;\n}\nfunction createHeadersWithClientAwareness(context) {\n // `apollographql-client-*` headers are automatically set if a\n // `clientAwareness` object is found in the context. These headers are\n // set first, followed by the rest of the headers pulled from\n // `context.headers`.\n let headers = context.headers && context.headers instanceof HttpHeaders ? context.headers : new HttpHeaders(context.headers);\n if (context.clientAwareness) {\n const {\n name,\n version\n } = context.clientAwareness;\n // If desired, `apollographql-client-*` headers set by\n // the `clientAwareness` object can be overridden by\n // `apollographql-client-*` headers set in `context.headers`.\n if (name && !headers.has('apollographql-client-name')) {\n headers = headers.set('apollographql-client-name', name);\n }\n if (version && !headers.has('apollographql-client-version')) {\n headers = headers.set('apollographql-client-version', version);\n }\n }\n return headers;\n}\n\n// XXX find a better name for it\nclass HttpLinkHandler extends ApolloLink {\n httpClient;\n options;\n requester;\n print = print;\n constructor(httpClient, options) {\n super();\n this.httpClient = httpClient;\n this.options = options;\n if (this.options.operationPrinter) {\n this.print = this.options.operationPrinter;\n }\n this.requester = operation => new Observable$1(observer => {\n const context = operation.getContext();\n // decides which value to pick, Context, Options or to just use the default\n const pick = (key, init) => {\n return prioritize(context[key], this.options[key], init);\n };\n let method = pick('method', 'POST');\n const includeQuery = pick('includeQuery', true);\n const includeExtensions = pick('includeExtensions', false);\n const url = pick('uri', 'graphql');\n const withCredentials = pick('withCredentials');\n const useMultipart = pick('useMultipart');\n const useGETForQueries = this.options.useGETForQueries === true;\n const isQuery = operation.query.definitions.some(def => def.kind === 'OperationDefinition' && def.operation === 'query');\n if (useGETForQueries && isQuery) {\n method = 'GET';\n }\n const req = {\n method,\n url: typeof url === 'function' ? url(operation) : url,\n body: {\n operationName: operation.operationName,\n variables: operation.variables\n },\n options: {\n withCredentials,\n useMultipart,\n headers: this.options.headers\n }\n };\n if (includeExtensions) {\n req.body.extensions = operation.extensions;\n }\n if (includeQuery) {\n req.body.query = this.print(operation.query);\n }\n const headers = createHeadersWithClientAwareness(context);\n req.options.headers = mergeHeaders(req.options.headers, headers);\n const sub = fetch(req, this.httpClient, this.options.extractFiles).subscribe({\n next: response => {\n operation.setContext({\n response\n });\n observer.next(response.body);\n },\n error: err => observer.error(err),\n complete: () => observer.complete()\n });\n return () => {\n if (!sub.closed) {\n sub.unsubscribe();\n }\n };\n });\n }\n request(op) {\n return this.requester(op);\n }\n}\nlet HttpLink = /*#__PURE__*/(() => {\n class HttpLink {\n httpClient;\n constructor(httpClient) {\n this.httpClient = httpClient;\n }\n create(options) {\n return new HttpLinkHandler(this.httpClient, options);\n }\n static ɵfac = function HttpLink_Factory(t) {\n return new (t || HttpLink)(i0.ɵɵinject(i1.HttpClient));\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: HttpLink,\n factory: HttpLink.ɵfac,\n providedIn: 'root'\n });\n }\n return HttpLink;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\nconst defaults = {\n batchInterval: 10,\n batchMax: 10,\n uri: 'graphql',\n method: 'POST'\n};\nclass HttpBatchLinkHandler extends ApolloLink {\n httpClient;\n options;\n batcher;\n batchInterval;\n batchMax;\n print = print;\n constructor(httpClient, options) {\n super();\n this.httpClient = httpClient;\n this.options = options;\n this.batchInterval = options.batchInterval || defaults.batchInterval;\n this.batchMax = options.batchMax || defaults.batchMax;\n if (this.options.operationPrinter) {\n this.print = this.options.operationPrinter;\n }\n const batchHandler = operations => {\n return new Observable$1(observer => {\n const body = this.createBody(operations);\n const headers = this.createHeaders(operations);\n const {\n method,\n uri,\n withCredentials\n } = this.createOptions(operations);\n if (typeof uri === 'function') {\n throw new Error(`Option 'uri' is a function, should be a string`);\n }\n const req = {\n method,\n url: uri,\n body: body,\n options: {\n withCredentials,\n headers\n }\n };\n const sub = fetch(req, this.httpClient, () => {\n throw new Error('File upload is not available when combined with Batching');\n }).subscribe({\n next: result => observer.next(result.body),\n error: err => observer.error(err),\n complete: () => observer.complete()\n });\n return () => {\n if (!sub.closed) {\n sub.unsubscribe();\n }\n };\n });\n };\n const batchKey = options.batchKey || (operation => {\n return this.createBatchKey(operation);\n });\n this.batcher = new BatchLink({\n batchInterval: this.batchInterval,\n batchMax: this.batchMax,\n batchKey,\n batchHandler\n });\n }\n createOptions(operations) {\n const context = operations[0].getContext();\n return {\n method: prioritize(context.method, this.options.method, defaults.method),\n uri: prioritize(context.uri, this.options.uri, defaults.uri),\n withCredentials: prioritize(context.withCredentials, this.options.withCredentials)\n };\n }\n createBody(operations) {\n return operations.map(operation => {\n const includeExtensions = prioritize(operation.getContext().includeExtensions, this.options.includeExtensions, false);\n const includeQuery = prioritize(operation.getContext().includeQuery, this.options.includeQuery, true);\n const body = {\n operationName: operation.operationName,\n variables: operation.variables\n };\n if (includeExtensions) {\n body.extensions = operation.extensions;\n }\n if (includeQuery) {\n body.query = this.print(operation.query);\n }\n return body;\n });\n }\n createHeaders(operations) {\n return operations.reduce((headers, operation) => {\n return mergeHeaders(headers, operation.getContext().headers);\n }, createHeadersWithClientAwareness({\n headers: this.options.headers,\n clientAwareness: operations[0]?.getContext()?.clientAwareness\n }));\n }\n createBatchKey(operation) {\n const context = operation.getContext();\n if (context.skipBatching) {\n return Math.random().toString(36).substr(2, 9);\n }\n const headers = context.headers && context.headers.keys().map(k => context.headers.get(k));\n const opts = JSON.stringify({\n includeQuery: context.includeQuery,\n includeExtensions: context.includeExtensions,\n headers\n });\n return prioritize(context.uri, this.options.uri) + opts;\n }\n request(op) {\n return this.batcher.request(op);\n }\n}\nlet HttpBatchLink = /*#__PURE__*/(() => {\n class HttpBatchLink {\n httpClient;\n constructor(httpClient) {\n this.httpClient = httpClient;\n }\n create(options) {\n return new HttpBatchLinkHandler(this.httpClient, options);\n }\n static ɵfac = function HttpBatchLink_Factory(t) {\n return new (t || HttpBatchLink)(i0.ɵɵinject(i1.HttpClient));\n };\n static ɵprov = /* @__PURE__ */i0.ɵɵdefineInjectable({\n token: HttpBatchLink,\n factory: HttpBatchLink.ɵfac,\n providedIn: 'root'\n });\n }\n return HttpBatchLink;\n})();\n(() => {\n (typeof ngDevMode === \"undefined\" || ngDevMode) && void 0;\n})();\n\n// http\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { HttpBatchLink, HttpBatchLinkHandler, HttpLink, HttpLinkHandler };\n","// @ts-check\n\n// @deno-types=\"is-plain-obj/index.d.ts\"\nimport isPlainObject from \"is-plain-obj\";\n\n/** @typedef {import(\"./isExtractableFile.mjs\").default} isExtractableFile */\n\n/**\n * Recursively extracts files and their {@link ObjectPath object paths} within a\n * value, replacing them with `null` in a deep clone without mutating the\n * original value.\n * [`FileList`](https://developer.mozilla.org/en-US/docs/Web/API/Filelist)\n * instances are treated as\n * [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) instance\n * arrays.\n * @template Extractable Extractable file type.\n * @param {unknown} value Value to extract files from. Typically an object tree.\n * @param {(value: unknown) => value is Extractable} isExtractable Matches\n * extractable files. Typically {@linkcode isExtractableFile}.\n * @param {ObjectPath} [path] Prefix for object paths for extracted files.\n * Defaults to `\"\"`.\n * @returns {Extraction} Extraction result.\n * @example\n * Extracting files from an object.\n *\n * For the following:\n *\n * ```js\n * import extractFiles from \"extract-files/extractFiles.mjs\";\n * import isExtractableFile from \"extract-files/isExtractableFile.mjs\";\n *\n * const file1 = new File([\"1\"], \"1.txt\", { type: \"text/plain\" });\n * const file2 = new File([\"2\"], \"2.txt\", { type: \"text/plain\" });\n * const value = {\n * a: file1,\n * b: [file1, file2],\n * };\n *\n * const { clone, files } = extractFiles(value, isExtractableFile, \"prefix\");\n * ```\n *\n * `value` remains the same.\n *\n * `clone` is:\n *\n * ```json\n * {\n * \"a\": null,\n * \"b\": [null, null]\n * }\n * ```\n *\n * `files` is a\n * [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)\n * instance containing:\n *\n * | Key | Value |\n * | :------ | :--------------------------- |\n * | `file1` | `[\"prefix.a\", \"prefix.b.0\"]` |\n * | `file2` | `[\"prefix.b.1\"]` |\n */\nexport default function extractFiles(value, isExtractable, path = \"\") {\n if (!arguments.length) throw new TypeError(\"Argument 1 `value` is required.\");\n if (typeof isExtractable !== \"function\") throw new TypeError(\"Argument 2 `isExtractable` must be a function.\");\n if (typeof path !== \"string\") throw new TypeError(\"Argument 3 `path` must be a string.\");\n\n /**\n * Deeply clonable value.\n * @typedef {Array | FileList | {\n * [key: PropertyKey]: unknown\n * }} Cloneable\n */\n\n /**\n * Clone of a {@link Cloneable deeply cloneable value}.\n * @typedef {Exclude} Clone\n */\n\n /**\n * Map of values recursed within the input value and their clones, for reusing\n * clones of values that are referenced multiple times within the input value.\n * @type {Map}\n */\n const clones = new Map();\n\n /**\n * Extracted files and their object paths within the input value.\n * @type {Extraction[\"files\"]}\n */\n const files = new Map();\n\n /**\n * Recursively clones the value, extracting files.\n * @param {unknown} value Value to extract files from.\n * @param {ObjectPath} path Prefix for object paths for extracted files.\n * @param {Set} recursed Recursed values for avoiding infinite\n * recursion of circular references within the input value.\n * @returns {unknown} Clone of the value with files replaced with `null`.\n */\n function recurse(value, path, recursed) {\n if (isExtractable(value)) {\n const filePaths = files.get(value);\n filePaths ? filePaths.push(path) : files.set(value, [path]);\n return null;\n }\n const valueIsList = Array.isArray(value) || typeof FileList !== \"undefined\" && value instanceof FileList;\n const valueIsPlainObject = isPlainObject(value);\n if (valueIsList || valueIsPlainObject) {\n let clone = clones.get(value);\n const uncloned = !clone;\n if (uncloned) {\n clone = valueIsList ? [] :\n // Replicate if the plain object is an `Object` instance.\n value instanceof ( /** @type {any} */Object) ? {} : Object.create(null);\n clones.set(value, /** @type {Clone} */clone);\n }\n if (!recursed.has(value)) {\n const pathPrefix = path ? `${path}.` : \"\";\n const recursedDeeper = new Set(recursed).add(value);\n if (valueIsList) {\n let index = 0;\n for (const item of value) {\n const itemClone = recurse(item, pathPrefix + index++, recursedDeeper);\n if (uncloned) /** @type {Array} */clone.push(itemClone);\n }\n } else for (const key in value) {\n const propertyClone = recurse(value[key], pathPrefix + key, recursedDeeper);\n if (uncloned) /** @type {{ [key: PropertyKey]: unknown }} */clone[key] = propertyClone;\n }\n }\n return clone;\n }\n return value;\n }\n return {\n clone: recurse(value, path, new Set()),\n files\n };\n}\n\n/**\n * An extraction result.\n * @template [Extractable=unknown] Extractable file type.\n * @typedef {object} Extraction\n * @prop {unknown} clone Clone of the original value with extracted files\n * recursively replaced with `null`.\n * @prop {Map>} files Extracted files and their\n * object paths within the original value.\n */\n\n/**\n * String notation for the path to a node in an object tree.\n * @typedef {string} ObjectPath\n * @see [`object-path` on npm](https://npm.im/object-path).\n * @example\n * An object path for object property `a`, array index `0`, object property `b`:\n *\n * ```\n * a.0.b\n * ```\n */","export default function isPlainObject(value) {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);\n}","// @ts-check\n\n/**\n * Checks if a value is an {@link ExtractableFile extractable file}.\n * @param {unknown} value Value to check.\n * @returns {value is ExtractableFile} Is the value an\n * {@link ExtractableFile extractable file}.\n */\nexport default function isExtractableFile(value) {\n return typeof File !== \"undefined\" && value instanceof File || typeof Blob !== \"undefined\" && value instanceof Blob;\n}\n\n/**\n * An extractable file.\n * @typedef {File | Blob} ExtractableFile\n */","import { TranslateLoader } from '@ngx-translate/core';\nimport { from } from 'rxjs';\n\nexport class DynamicImportLoader implements TranslateLoader {\n // eslint-disable-next-line class-methods-use-this\n getTranslation(lang: string) {\n const fetchIt = async () => {\n const arr = await Promise.all([import('./en.json'), import('./it.json')]);\n return arr.reduce((accumulator, currentValue) => ({ ...accumulator, ...currentValue.default }), {});\n };\n\n const fetchEn = async () => (await import('./en.json')).default;\n\n const json$ = lang === 'it' ? fetchIt() : fetchEn();\n\n return from(json$.then((x) => x));\n }\n}\n","// @ts-nocheck\n/* eslint-disable */\nexport const accountCircleIcon = {\n data: ``,\n name: 'account-circle' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const accountPinIcon = {\n data: ``,\n name: 'account-pin' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const addLineIcon = {\n data: ``,\n name: 'add-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const applicationIcon = {\n data: ``,\n name: 'application' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const archiveIcon = {\n data: ``,\n name: 'archive' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const arrowIcon = {\n data: ``,\n name: 'arrow' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const arrowBackIcon = {\n data: ``,\n name: 'arrow-back' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const arrowLeftIcon = {\n data: ``,\n name: 'arrow-left' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const arrowUpIcon = {\n data: ``,\n name: 'arrow-up' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const arrowUpDownFillIcon = {\n data: ``,\n name: 'arrow-up-down-fill' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const cakeLineIcon = {\n data: ``,\n name: 'cake-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const calendarEventIcon = {\n data: ``,\n name: 'calendar-event' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const callIcon = {\n data: ``,\n name: 'call' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const chatSmileIcon = {\n data: ``,\n name: 'chat-smile' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const checkIcon = {\n data: ``,\n name: 'check' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const checkOutlineIcon = {\n data: ``,\n name: 'check-outline' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const chevronDownIcon = {\n data: ``,\n name: 'chevron-down' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const circleIcon = {\n data: ``,\n name: 'circle' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const closeIcon = {\n data: ``,\n name: 'close' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const closeCircleIcon = {\n data: ``,\n name: 'close-circle' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const communicationIcon = {\n data: ``,\n name: 'communication' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const copyIcon = {\n data: ``,\n name: 'copy' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const dashboardLineIcon = {\n data: ``,\n name: 'dashboard-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const datasetIcon = {\n data: ``,\n name: 'dataset' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const deleteBackIcon = {\n data: ``,\n name: 'delete-back' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const deleteBinLineIcon = {\n data: ``,\n name: 'delete-bin-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const downloadIcon = {\n data: ``,\n name: 'download' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const dragHandleIcon = {\n data: ``,\n name: 'drag-handle' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const editIcon = {\n data: ``,\n name: 'edit' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const emailIcon = {\n data: ``,\n name: 'email' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const expandIcon = {\n data: ``,\n name: 'expand' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const eyeLineIcon = {\n data: ``,\n name: 'eye-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const eyeOffLineIcon = {\n data: ``,\n name: 'eye-off-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const feedbackLineIcon = {\n data: ``,\n name: 'feedback-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const fileIcon = {\n data: ``,\n name: 'file' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const filterIcon = {\n data: ``,\n name: 'filter' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const flagIcon = {\n data: ``,\n name: 'flag' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const freshManIcon = {\n data: ``,\n name: 'fresh-man' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const globalIcon = {\n data: ``,\n name: 'global' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const groupLineIcon = {\n data: ``,\n name: 'group-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const homeLineIcon = {\n data: ``,\n name: 'home-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const homeNotIcon = {\n data: ``,\n name: 'home-not' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const inboxUnarchiveIcon = {\n data: ``,\n name: 'inbox-unarchive' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const infoIcon = {\n data: ``,\n name: 'info' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const interculturaIcon = {\n data: ``,\n name: 'intercultura' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const kanbanViewIcon = {\n data: ``,\n name: 'kanban-view' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const leadIcon = {\n data: ``,\n name: 'lead' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const linksFillIcon = {\n data: ``,\n name: 'links-fill' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const loadingIcon = {\n data: ``,\n name: 'loading' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const logOutIcon = {\n data: ``,\n name: 'log-out' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const mailLineIcon = {\n data: ``,\n name: 'mail-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const mailOpenIcon = {\n data: ``,\n name: 'mail-open' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const mailUnreadIcon = {\n data: ``,\n name: 'mail-unread' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const mapPinLineIcon = {\n data: ``,\n name: 'map-pin-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const mapPinRangeLineIcon = {\n data: ``,\n name: 'map-pin-range-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const moreFillIcon = {\n data: ``,\n name: 'more-fill' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const moreFillOrizzontalIcon = {\n data: ``,\n name: 'more-fill-orizzontal' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const noteLineIcon = {\n data: ``,\n name: 'note-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const notificationIcon = {\n data: ``,\n name: 'notification' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const parentIcon = {\n data: ``,\n name: 'parent' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const passportLineIcon = {\n data: ``,\n name: 'passport-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const personIcon = {\n data: ``,\n name: 'person' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const phoneLineIcon = {\n data: ``,\n name: 'phone-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const pinDropIcon = {\n data: ``,\n name: 'pin-drop' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const playCircleIcon = {\n data: ``,\n name: 'play-circle' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const playMiniIcon = {\n data: ``,\n name: 'play-mini' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const priceTagIcon = {\n data: ``,\n name: 'price-tag' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const privateIcon = {\n data: ``,\n name: 'private' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const programIcon = {\n data: ``,\n name: 'program' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const progressIcon = {\n data: ``,\n name: 'progress' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const removeLabelsIcon = {\n data: ``,\n name: 'remove-labels' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const schoolLineIcon = {\n data: ``,\n name: 'school-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const searchIcon = {\n data: ``,\n name: 'search' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const searchEyeIcon = {\n data: ``,\n name: 'search-eye' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const searchShortcutIcon = {\n data: ``,\n name: 'search-shortcut' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const settingIcon = {\n data: ``,\n name: 'setting' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const sortAlphabetIcon = {\n data: ``,\n name: 'sort-alphabet' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const stackLineIcon = {\n data: ``,\n name: 'stack-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const starIcon = {\n data: ``,\n name: 'star' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const starSmileIcon = {\n data: ``,\n name: 'star-smile' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const stickyNoteIcon = {\n data: ``,\n name: 'sticky-note' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const stopCircleIcon = {\n data: ``,\n name: 'stop-circle' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const studentIcon = {\n data: ``,\n name: 'student' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const subtractLineIcon = {\n data: ``,\n name: 'subtract-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const sunIcon = {\n data: ``,\n name: 'sun' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const taskIcon = {\n data: ``,\n name: 'task' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const textIcon = {\n data: ``,\n name: 'text' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const textFieldIcon = {\n data: ``,\n name: 'text-field' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const unknownIcon = {\n data: ``,\n name: 'unknown' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const uploadIcon = {\n data: ``,\n name: 'upload' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const userAddLineIcon = {\n data: ``,\n name: 'user-add-line' as const\n};","// @ts-nocheck\n/* eslint-disable */\nexport const whatsappIcon = {\n data: ``,\n name: 'whatsapp' as const\n};"],"mappings":"u/BAAAA,ICAAC,ICAAC,IASA,SAASC,GAAOC,E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AM,siBACNC,KAAM,cCJVC,IAEO,IAAMC,GAAc,CACvBC,KAAM,0SACNC,KAAM,WCJVC,IAEO,IAAMC,GAAa,CACtBC,KAAM,sRACNC,KAAM,UCJVC,IAEO,IAAMC,GAAkB,CAC3BC,KAAM,61BACNC,KAAM,iBCJVC,IAEO,IAAMC,GAAe,CACxBC,KAAM,wiFACNC,KAAM,YnHwGH,IAAMC,GAAW,CACtBC,GACAC,GACAA,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAA,GACAC,GACAC,GACAA,GACAC,GACAC,GACAA,GACAC,GACAA,GACAC,GACAA,GACAC,GACAA,GACAC,GACAC,GACAC,GACAA,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAA,GACAC,GACAA,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAA,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,EAAY,EAadC,GAAmBC,EAAQ,EAEpB,IAAMC,GAA+B,CAC1CC,UAAW,CACT,CAAEC,QAASC,GAAWC,SAAU,OAAO,EACvCC,GAAcC,GAAQC,GAAyB,CAAE,EACjDC,GAAsB,CACpBC,MAAOxG,GACPyG,oBAAqBhB,GACtB,EACDiB,GACEC,GACAC,GACAC,GAAgBC,QAAQ,CACtBC,OAAQ,CACNC,KAAM,OACNC,OAAQ,SACRC,WAAY,aACZC,UAAW,YACXC,OAAQ,SACRC,WAAY,aACZC,YAAa,cACbC,aAAc,eACdC,WAAY,aACZC,aAAc,eACdC,YAAa,cACbC,cAAe,UACfC,iBAAkB,oBAErB,EACDC,GAAgBf,QAAQ,CACtBgB,gBAAiBC,GAAYC,YAC7BC,OAAQ,CACNhC,QAASiC,GACTC,SAAUC,IAEb,EACDC,GAAmBvB,QAAQ,CAAEwB,QAAS,SAAS,CAAE,CAAC,EAEpDC,GAAiB,EACjBC,EAAe,GDnQnBC,GAAqBC,GAAeC,EAAS,EAAEC,MAAOC,GAAQC,QAAQC,MAAMF,CAAG,CAAC","names":["init_define_NGX_ENV","init_define_NGX_ENV","init_define_NGX_ENV","plural","val","n","i","v","e","it_default","init_define_NGX_ENV","init_define_NGX_ENV","invalidTimingValue","exp","RuntimeError","negativeStepValue","negativeDelayValue","invalidStyleParams","varName","invalidParamValue","invalidNodeType","nodeType","invalidCssUnitValue","userProvidedProperty","value","invalidTrigger","invalidDefinition","invalidState","metadataName","missingSubs","invalidStyleValue","invalidParallelAnimation","prop","firstStart","firstEnd","secondStart","secondEnd","RuntimeError","invalidKeyframes","invalidOffset","keyframeOffsetsOutOfOrder","keyframesMissingOffsets","invalidStagger","invalidQuery","selector","invalidExpression","expr","invalidTransitionAlias","alias","triggerBuildFailed","name","errors","RuntimeError","animationFailed","registerFailed","missingOrDestroyedAnimation","createAnimationFailed","missingPlayer","id","missingTrigger","phase","missingEvent","unsupportedTriggerEvent","unregisteredTrigger","triggerTransitionsFailed","transitionFailed","name","errors","RuntimeError","optimizeGroupPlayer","players","NoopAnimationPlayer","AnimationGroupPlayer","normalizeKeyframes$1","normalizer","keyframes","preStyles","postStyles","errors","normalizedKeyframes","previousOffset","previousKeyframe","kf","offset","isSameOffset","normalizedKeyframe","val","prop","normalizedProp","normalizedValue","ɵPRE_STYLE","AUTO_STYLE","animationFailed","listenOnPlayer","player","eventName","event","callback","copyAnimationEvent","e","phaseName","totalTime","disabled","makeAnimationEvent","data","element","triggerName","fromState","toState","getOrSetDefaultValue","map","key","defaultValue","value","parseTimelineCommand","command","separatorPos","id","action","documentElement","getParentElement","parent","containsVendorPrefix","_CACHED_BODY","_IS_WEBKIT","validateStyleProperty","getBodyNode","result","getBodyNode","containsElement","elm1","elm2","getParentElement","invokeQuery","element","selector","multi","elem","NoopAnimationDriver","_NoopAnimationDriver","prop","validateStyleProperty","_element","_selector","elm1","elm2","containsElement","element","getParentElement","selector","multi","invokeQuery","defaultValue","keyframes","duration","delay","easing","previousPlayers","scrubberAccessRequested","NoopAnimationPlayer","t","ɵɵdefineInjectable","_AnimationDriver","AnimationDriver","AnimationStyleNormalizer","ONE_SECOND","SUBSTITUTION_EXPR_START","SUBSTITUTION_EXPR_END","ENTER_CLASSNAME","LEAVE_CLASSNAME","NG_TRIGGER_CLASSNAME","NG_TRIGGER_SELECTOR","NG_ANIMATING_CLASSNAME","NG_ANIMATING_SELECTOR","resolveTimingValue","value","matches","_convertTimeValueToMS","unit","resolveTiming","timings","errors","allowNegativeValues","parseTimeExpression","exp","regex","duration","delay","easing","invalidTimingValue","delayMatch","easingVal","containsErrors","startIndex","negativeStepValue","negativeDelayValue","normalizeKeyframes","keyframes","kf","setStyles","element","styles","formerStyles","val","prop","camelProp","dashCaseToCamelCase","eraseStyles","_","normalizeAnimationEntry","steps","sequence","validateStyleParams","value","options","errors","params","matches","extractStyleParams","varName","invalidStyleParams","PARAM_REGEX","SUBSTITUTION_EXPR_START","SUBSTITUTION_EXPR_END","match","interpolateParams","original","str","localVal","invalidParamValue","DASH_CASE_REGEXP","input","m","allowPreviousPlayerStylesMerge","duration","delay","balancePreviousStylesIntoKeyframes","element","keyframes","previousStyles","startingKeyframe","missingStyleProps","val","prop","i","kf","computeStyle","visitDslNode","visitor","node","context","AnimationMetadataType","invalidNodeType","DIMENSIONAL_PROP_SET","WebAnimationsStyleNormalizer","AnimationStyleNormalizer","propertyName","errors","dashCaseToCamelCase","userProvidedProperty","normalizedProperty","value","unit","strVal","valAndSuffixMatch","invalidCssUnitValue","ANY_STATE","parseTransitionExpr","transitionValue","errors","expressions","str","parseInnerTransitionStr","eventStr","result","parseAnimationAlias","match","invalidExpression","fromState","separator","toState","makeLambdaFromStates","isFullAnyStateExpr","alias","invalidTransitionAlias","TRUE_BOOLEAN_VALUES","FALSE_BOOLEAN_VALUES","lhs","rhs","LHS_MATCH_BOOLEAN","RHS_MATCH_BOOLEAN","lhsMatch","rhsMatch","SELF_TOKEN","SELF_TOKEN_REGEX","buildAnimationAst","driver","metadata","warnings","AnimationAstBuilderVisitor","ROOT_SELECTOR","_driver","context","AnimationAstBuilderContext","visitDslNode","normalizeAnimationEntry","queryCount","depCount","states","transitions","invalidTrigger","def","AnimationMetadataType","stateDef","name","n","transition","invalidDefinition","styleAst","astParams","missingSubs","params","style","value","extractStyleParams","sub","invalidState","animation","matchers","normalizeAnimationOptions","s","currentTime","furthestTime","steps","step","innerAst","timingAst","constructTimingAst","styleMetadata","isEmpty","newStyleData","_styleAst","ast","styles","metadataStyles","styleTuple","AUTO_STYLE","invalidStyleValue","containsDynamicStyles","collectedEasing","styleData","SUBSTITUTION_EXPR_START","timings","endTime","startTime","tuple","prop","collectedStyles","collectedEntry","updateCollectedStyle","invalidParallelAnimation","validateStyleParams","invalidKeyframes","MAX_KEYFRAME_OFFSET","totalKeyframesWithOffsets","offsets","offsetsOutOfOrder","keyframesOutOfRange","previousOffset","keyframes","offsetVal","consumeOffset","offset","invalidOffset","keyframeOffsetsOutOfOrder","length","generatedOffset","keyframesMissingOffsets","limit","currentAnimateTimings","animateDuration","kf","i","durationUpToThisFrame","parentSelector","options","selector","includeSelf","normalizeSelector","getOrSetDefaultValue","invalidStagger","resolveTiming","hasAmpersand","token","NG_TRIGGER_SELECTOR","NG_ANIMATING_SELECTOR","normalizeParams","obj","__spreadValues","duration","makeTimingAst","strValue","v","delay","easing","createTimelineInstruction","element","preStyleProps","postStyleProps","subTimeline","ElementInstructionMap","instructions","existingInstructions","ONE_FRAME_IN_MILLISECONDS","ENTER_TOKEN","ENTER_TOKEN_REGEX","LEAVE_TOKEN","LEAVE_TOKEN_REGEX","buildAnimationTimelines","rootElement","enterClassName","leaveClassName","startingStyles","finalStyles","subInstructions","AnimationTimelineBuilderVisitor","AnimationTimelineContext","resolveTimingValue","timelines","timeline","lastRootTimeline","elementInstructions","innerContext","animationsRefsOptions","animationRefOptions","animationDelay","animationDelayValue","interpolateParams","instruction","instructionTimings","subContextCount","ctx","DEFAULT_NOOP_PREVIOUS_NODE","innerTimelines","timingValue","innerTimeline","elms","sameElementTimeline","parentContext","tl","maxTime","startingTime","_AnimationTimelineContext","_enterClassName","_leaveClassName","initialTimeline","TimelineBuilder","skipIfExists","newOptions","optionsToUpdate","newParams","paramsToUpdate","oldParams","newTime","target","updatedTimings","builder","SubTimelineBuilder","time","originalSelector","optional","results","multi","elements","invalidQuery","_TimelineBuilder","_elementTimelineStylesLookup","hasPreStyleStep","input","flattenStyles","val","properties","details1","details0","finalKeyframes","keyframe","finalKeyframe","ɵPRE_STYLE","preProps","postProps","kf0","kf1","_stretchStartingKeyframe","newKeyframes","totalTime","startingGap","newFirstKeyframe","oldFirstKeyframe","roundOffset","oldOffset","timeAtKeyframe","decimalPoints","mult","allStyles","allProperties","createTransitionInstruction","triggerName","isRemovalTransition","fromStyles","toStyles","queriedElements","EMPTY_OBJECT","AnimationTransitionFactory","_triggerName","_stateStyles","currentState","nextState","oneOrMoreTransitionsMatch","stateName","styler","currentOptions","nextOptions","skipAstBuild","transitionAnimationParams","currentAnimationParams","currentStateStyles","nextAnimationParams","nextStateStyles","preStyleMap","postStyleMap","isRemoval","animationOptions","applyParamDefaults","elm","oneOrMoreTransitionsMatch","matchFns","currentState","nextState","element","params","fn","applyParamDefaults","userParams","defaults","result","__spreadValues","key","value","AnimationStateStyles","styles","defaultParams","normalizer","errors","finalStyles","combinedParams","val","prop","interpolateParams","normalizedProp","buildTrigger","name","ast","AnimationTrigger","_normalizer","balanceProperties","AnimationTransitionFactory","createFallbackTransition","f","triggerName","states","matchers","fromState","toState","animation","AnimationMetadataType","transition","stateMap","key1","key2","EMPTY_INSTRUCTION_MAP","ElementInstructionMap","TimelineAnimationEngine","bodyNode","_driver","id","metadata","warnings","buildAnimationAst","registerFailed","i","preStyles","postStyles","keyframes","normalizeKeyframes$1","options","instructions","autoStylesMap","buildAnimationTimelines","ENTER_CLASSNAME","LEAVE_CLASSNAME","inst","getOrSetDefaultValue","missingOrDestroyedAnimation","createAnimationFailed","_","AUTO_STYLE","players","player","optimizeGroupPlayer","index","missingPlayer","eventName","callback","baseEvent","makeAnimationEvent","listenOnPlayer","command","args","QUEUED_CLASSNAME","QUEUED_SELECTOR","DISABLED_CLASSNAME","DISABLED_SELECTOR","STAR_CLASSNAME","STAR_SELECTOR","EMPTY_PLAYER_ARRAY","NULL_REMOVAL_STATE","NULL_REMOVED_QUERIED_STATE","REMOVAL_FLAG","StateValue","input","namespaceId","isObj","normalizeTriggerValue","_a","__objRest","newParams","oldParams","VOID_VALUE","DEFAULT_STATE_VALUE","AnimationTransitionNamespace","hostElement","_engine","addClass","phase","missingTrigger","missingEvent","isTriggerEventValid","unsupportedTriggerEvent","listeners","data","triggersWithStates","NG_TRIGGER_CLASSNAME","trigger","unregisteredTrigger","defaultToFallback","TransitionAnimationPlayer","objEquals","fromStyles","toStyles","eraseStyles","setStyles","playersOnElement","isFallbackTransition","removeClass","entry","elementPlayers","rootElement","context","elements","NG_TRIGGER_SELECTOR","elm","namespaces","ns","destroyAfterComplete","triggerStates","previousTriggersValues","state","elementStates","visitedTriggers","listener","engine","containsPotentialParentTransition","currentPlayers","parent","removalFlag","microtaskId","a","b","d0","d1","p","TransitionAnimationEngine","driver","scheduler","namespaceList","namespacesByHostElement","found","ancestor","ancestorNs","stateValue","isElementNode","insertBefore","details","hostNS","hasAnimation","subTimelines","enterClassName","leaveClassName","skipBuildAst","containerElement","NG_ANIMATING_SELECTOR","resolve","node","cleanupFns","quietFns","triggerTransitionsFailed","skippedPlayers","skippedPlayersMap","queuedInstructions","queriedElements","allPreStyleElements","allPostStyleElements","disabledElementsSet","nodesThatAreDisabled","allTriggerElements","enterNodeMap","buildRootMap","enterNodeMapIds","nodes","root","className","allLeaveNodes","mergedLeaveNodes","leaveNodesWithoutAnimations","leaveNodeMapIds","leaveNodeMap","allPlayers","erroneousTransitions","previousValue","nodeIsOrphaned","instruction","timelines","tl","tuple","stringMap","setVal","transitionFailed","allPreviousPlayersMap","animationElementMap","prevPlayer","replaceNodes","replacePostStylesAsPre","postStylesMap","cloakAndComputeStyles","preStylesMap","ɵPRE_STYLE","post","pre","rootPlayers","subPlayers","NO_PARENT_ANIMATION_ELEMENT_DETECTED","parentWithAnimation","parentsToAdd","detectedParent","innerPlayer","parentPlayers","playersForElement","queriedPlayerResults","queriedInnerElements","j","queriedPlayers","activePlayers","removeNodesAfterAnimationDone","isQueriedElement","toStateValue","queriedElementPlayers","isRemovalAnimation","targetNameSpaceId","targetTriggerName","timelineInstruction","realPlayer","allQueriedPlayers","allConsumedElements","allSubElements","allNewPlayers","NoopAnimationPlayer","previousPlayers","flattenGroupPlayers","pp","wrappedPlayer","deleteOrUnsetInMap","NG_ANIMATING_CLASSNAME","callbacks","totalTime","phaseName","map","currentValues","cloakElement","oldValue","valuesMap","elementPropsMap","defaultStyle","cloakVals","failedElements","props","roots","rootMap","NULL_NODE","nodeSet","localRootMap","getRoot","finalPlayers","_flattenGroupPlayersRecur","AnimationGroupPlayer","k1","k2","postEntry","preEntry","AnimationEngine","doc","componentId","cacheKey","triggerBuildFailed","disable","property","action","parseTimelineCommand","eventPhase","cb","packageNonAnimatableStyles","startStyles","endStyles","filterNonAnimatableStyles","SpecialCasedStyles","_SpecialCasedStyles","_element","_startStyles","_endStyles","initialStyles","isNonAnimatableStyle","WebAnimationsPlayer","_specialStyles","onFinish","kfs","frame","computeStyle","methods","WebAnimationsDriver","_selector","elm1","elm2","containsElement","getParentElement","selector","multi","invokeQuery","defaultValue","duration","delay","easing","fill","playerOptions","previousStyles","previousWebAnimationPlayers","allowPreviousPlayerStylesMerge","_keyframes","normalizeKeyframes","balancePreviousStylesIntoKeyframes","specialStyles","ANIMATION_PREFIX","DISABLE_ANIMATIONS_FLAG","BaseAnimationRenderer","namespaceId","delegate","engine","_onDestroy","node","name","namespace","value","parent","newChild","refChild","isMove","oldChild","isHostElement","selectorOrNode","preserveContent","el","style","flags","target","eventName","callback","element","AnimationRenderer","factory","onDestroy","resolveElementFromTarget","phase","parseTriggerCallbackName","event","countId","triggerName","dotIndex","trigger","AnimationRendererFactory","_zone","parentNode","hostElement","type","EMPTY_NAMESPACE_ID","cache","renderer","onRendererDestroy","componentId","registerTrigger","count","fn","data","animationCallbacksBuffer","tuple","InjectableAnimationEngine","_InjectableAnimationEngine","AnimationEngine","doc","driver","normalizer","inject","ChangeDetectionScheduler","t","ɵɵinject","DOCUMENT","AnimationDriver","AnimationStyleNormalizer","ɵɵdefineInjectable","instantiateDefaultStyleNormalizer","WebAnimationsStyleNormalizer","instantiateRendererFactory","renderer","engine","zone","AnimationRendererFactory","SHARED_ANIMATION_PROVIDERS","RendererFactory2","DomRendererFactory2","NgZone","BROWSER_ANIMATIONS_PROVIDERS","WebAnimationsDriver","ANIMATION_MODULE_TYPE","BROWSER_NOOP_ANIMATIONS_PROVIDERS","NoopAnimationDriver","BrowserAnimationsModule","_BrowserAnimationsModule","config","ɵɵdefineNgModule","ɵɵdefineInjector","BrowserModule","init_define_NGX_ENV","init_define_NGX_ENV","clamp","value","min","max","init_define_NGX_ENV","init_define_NGX_ENV","findDiffStart","a","b","pos","i","childA","childB","j","inner","findDiffEnd","posA","posB","iA","iB","size","same","minSize","Fragment","_Fragment","content","from","to","f","nodeStart","parent","child","end","start","blockSeparator","leafText","text","first","node","nodeText","other","last","result","index","current","copy","found","p","otherPos","round","retIndex","curPos","cur","n","schema","value","array","joined","nodes","offset","compareDeep","Mark","type","attrs","set","placed","obj","_","json","mark","marks","ReplaceError","Slice","_Slice","openStart","openEnd","fragment","insertInto","removeRange","openIsolating","indexTo","offsetTo","dist","insert","replace","$from","$to","slice","replaceOuter","depth","close","prepareSliceForReplace","replaceThreeWay","replaceTwoWay","checkJoin","main","sub","joinable","$before","$after","addNode","target","addRange","$start","$end","startIndex","endIndex","$along","extra","ResolvedPos","_ResolvedPos","path","parentOffset","val","dOff","tmp","after","next","pred","d","NodeRange","str","doc","rem","cache","resolveCache","elt","ResolveCache","resolveCacheSize","emptyAttrs","Node","_Node","startPos","includeParents","name","wrapMarks","match","replacement","one","two","m","wrapMarks","marks","str","i","ContentMatch","_ContentMatch","validEnd","string","nodeTypes","stream","TokenStream","expr","parseExpr","match","dfa","nfa","checkForDeadEnds","type","frag","start","end","cur","other","j","after","toEnd","startIndex","seen","search","types","finished","Fragment","tp","next","found","target","computed","active","current","result","obj","n","scan","m","out","tok","exprs","parseExprSeq","parseExprSubscript","parseExprAtom","parseExprRange","parseNum","min","max","resolveName","name","typeName","connect","compile","node","edge","from","to","term","edges","loop","cmp","a","b","nullFrom","labeled","explore","states","set","state","work","dead","nodes","init_define_NGX_ENV","lower16","factor16","makeRecover","index","offset","recoverIndex","value","recoverOffset","DEL_BEFORE","DEL_AFTER","DEL_ACROSS","DEL_SIDE","MapResult","pos","delInfo","recover","StepMap","_StepMap","ranges","inverted","diff","assoc","simple","oldIndex","newIndex","i","start","oldSize","newSize","end","side","result","del","f","oldStart","newStart","n","Mapping","_Mapping","maps","mirror","from","to","map","mirrors","mapping","startSize","mirr","m","totalSize","inverse","corr","stepsByID","Step","other","schema","json","type","id","stepClass","StepResult","_StepResult","doc","failed","message","slice","e","ReplaceError","mapFragment","fragment","parent","mapped","child","Fragment","AddMarkStep","_AddMarkStep","mark","oldSlice","$from","Slice","node","RemoveMarkStep","_RemoveMarkStep","AddNodeMarkStep","_AddNodeMarkStep","updated","newSet","RemoveNodeMarkStep","_RemoveNodeMarkStep","ReplaceStep","_ReplaceStep","structure","contentBetween","ReplaceAroundStep","_ReplaceAroundStep","gapFrom","gapTo","insert","gap","inserted","dist","depth","next","canCut","node","start","end","liftTarget","range","content","depth","index","endIndex","findWrapping","range","nodeType","attrs","innerRange","around","findWrappingOutside","inner","findWrappingInside","withAttrs","type","parent","startIndex","endIndex","outer","inside","innerMatch","i","canSplit","doc","pos","depth","typesAfter","$pos","base","innerType","d","i","node","index","rest","overrideChild","after","baseType","canJoin","doc","pos","$pos","index","joinable","a","b","replaceStep","doc","from","to","slice","Slice","$from","$to","fitsTrivially","ReplaceStep","Fitter","unplaced","Fragment","node","fit","moveInline","placedSize","content","openStart","openEnd","ReplaceAroundStep","startDepth","cur","d","pass","sliceDepth","fragment","parent","contentAt","first","frontierDepth","type","match","wrap","inject","inner","openAtEnd","dropFromFragment","i","taken","add","openEndCount","next","matches","closeNodeStart","toEnd","addToFragment","top","level","contentAfterFits","depth","after","scan","dropInner","close","attrs","count","frag","open","index","invalidMarks","start","AttrStep","_AttrStep","Step","pos","attr","value","doc","node","StepResult","attrs","name","updated","Slice","Fragment","StepMap","mapping","schema","json","DocAttrStep","_DocAttrStep","TransformError","message","err","classesById","Selection","$anchor","$head","ranges","SelectionRange","i","tr","content","Slice","lastNode","lastParent","mapFrom","$from","$to","mapping","selectionToInsertionEnd","node","from","to","$pos","dir","textOnly","inner","TextSelection","findSelectionIn","depth","found","bias","AllSelection","doc","json","cls","id","selectionClass","warnedAboutTextSelection","checkTextSelection","_TextSelection","marks","other","TextBookmark","anchor","head","dPos","_TextBookmark","NodeSelection","_NodeSelection","$end","deleted","pos","Fragment","NodeBookmark","_NodeBookmark","_AllSelection","sel","AllBookmark","index","text","child","startLen","last","step","ReplaceStep","ReplaceAroundStep","map","end","_from","_to","_newFrom","newTo","bind","f","self","FieldDesc","name","desc","baseFields","config","tr","instance","Selection","_marks","_old","state","prev","keys","createKey","name","PluginKey","state","init_define_NGX_ENV","wrapInList","listType","attrs","state","dispatch","$from","$to","range","doJoin","outerRange","$insert","NodeRange","wrap","findWrapping","doWrapInList","tr","wrappers","joinBefore","content","Fragment","i","ReplaceAroundStep","Slice","found","splitDepth","splitPos","parent","e","first","canSplit","liftListItem","itemType","state","dispatch","$from","$to","range","node","liftToOuterList","liftOutOfList","tr","end","endOfList","ReplaceAroundStep","Slice","Fragment","NodeRange","target","liftTarget","after","canJoin","list","pos","i","e","$start","item","atStart","atEnd","parent","indexBefore","start","init_define_NGX_ENV","deleteSelection","state","dispatch","atBlockStart","view","$cursor","joinBackward","$cut","findCutBefore","range","target","liftTarget","before","deleteBarrier","textblockAt","NodeSelection","delStep","replaceStep","Slice","tr","Selection","textblockAt","node","side","only","scan","selectNodeBackward","state","dispatch","view","$head","empty","$cut","findCutBefore","NodeSelection","$pos","i","atBlockEnd","$cursor","joinForward","findCutAfter","after","deleteBarrier","delStep","replaceStep","Slice","tr","Selection","selectNodeForward","parent","lift","state","dispatch","$from","$to","range","target","liftTarget","newlineInCode","$head","$anchor","defaultBlockAt","match","i","type","exitCode","above","after","pos","tr","Selection","createParagraphNear","sel","AllSelection","side","TextSelection","liftEmptyBlock","$cursor","before","canSplit","splitBlockAs","splitNode","NodeSelection","atEnd","deflt","splitType","types","can","first","$first","splitBlock","selectAll","state","dispatch","AllSelection","joinMaybeClear","$pos","before","after","index","canJoin","deleteBarrier","$cut","conn","match","canDelAfter","end","wrap","Fragment","i","tr","ReplaceAroundStep","Slice","joinAt","selAfter","Selection","range","target","liftTarget","textblockAt","at","afterText","afterDepth","selectTextblockSide","side","sel","depth","TextSelection","selectTextblockStart","selectTextblockEnd","wrapIn","nodeType","attrs","$from","$to","wrapping","findWrapping","setBlockType","applicable","from","to","node","pos","markApplies","doc","ranges","type","can","toggleMark","markType","empty","$cursor","has","start","spaceStart","spaceEnd","chainCommands","commands","state","dispatch","view","backspace","deleteSelection","joinBackward","selectNodeBackward","del","joinForward","selectNodeForward","pcBaseKeymap","newlineInCode","createParagraphNear","liftEmptyBlock","splitBlock","exitCode","selectAll","macBaseKeymap","selectTextblockStart","selectTextblockEnd","key","mac","init_define_NGX_ENV","init_define_NGX_ENV","isMarkActive","state","type","from","$from","to","empty","findNodeType","i","isNodeActive","attrs","selection","node","getSelectionMarks","marks","storedMarks","getSelectionNodes","nodes","markApplies","doc","ranges","range","$to","canApply","canInsert","state","nodeType","$from","d","index","removeLink","state","dispatch","doc","selection","tr","schema","pos","from","to","linkMark","$pos","linkStart","linkEnd","applyMark","type","attrs","empty","ranges","$from","$to","TextSelection","$cursor","markApplies","removeMark","storedMarks","range","init_define_NGX_ENV","init_define_NGX_ENV","GOOD_LEAF_SIZE","RopeSequence","other","Append","from","to","i","f","result","elt","values","Leaf","prototypeAccessors","start","left","right","leftLen","inner","dist_default","max_empty_items","Branch","_Branch","items","eventCount","state","preserveItems","end","remap","mapFrom","transform","selection","remaining","addAfter","addBefore","item","i","Item","step","map","histOptions","newItems","oldItems","lastItem","merged","overflow","DEPTH_OVERFLOW","cutOffEvents","from","to","maps","Mapping","mirrorPos","array","rebasedTransform","rebasedCount","rebasedItems","start","mapping","newUntil","iRebased","pos","newMaps","branch","count","upto","events","newItem","last","dist_default","n","cutPoint","_Item","mirrorOffset","other","HistoryState","done","undone","prevRanges","prevTime","prevComposition","histTransaction","history","state","redo","preserveItems","mustPreserveItems","histOptions","historyKey","pop","selection","added","newHist","HistoryState","cachedPreserveItems","cachedPreserveItemsPlugins","plugins","i","historyKey","PluginKey","closeHistoryKey","buildCommand","redo","scroll","state","dispatch","hist","historyKey","tr","histTransaction","undo","undoNoScroll","redoNoScroll","getTrustedTypes","isTrustedHtml","value","Mark","name","state","dispatch","schema","type","applyMark","toggleMark","isMarkActive","Blockqote","lift","wrapIn","isNodeActive","HorizontalRule","tr","canInsert","ListItem","isBulletList","liftListItem","wrapInList","Heading","level","setBlockType","selection","doc","nodePos","attrs","__spreadProps","__spreadValues","nodesInSelection","getSelectionNodes","supportedNodes","node","TextAlign","align","from","to","applicable","pos","nodeType","defaultOptions","Link$1","text","linkAttrs","options","removeLink","testAttrs","Image$1","src","imageAttrs","NodeSelection","resolvedPos","TextColor$1","attrName","empty","getSelectionMarks","mark","removeMark","SAFE_MARKS","FormatClear","ranges","markType","range","indentNodeTypes","minIndent","maxIndent","udpateIndentLevel","method","nodeIndent","newIndent","clamp","Indent","History","mode","undo","redo","STRONG","EM","CODE","UNDERLINE","STRIKE","BLOCKQUOTE","HORIZONTAL_RULE","FORMAT_CLEAR","UL","OL","H1","H2","H3","H4","H5","H6","ALIGN_LEFT","ALIGN_CENTER","ALIGN_RIGHT","ALIGN_JUSTIFY","LINK","IMAGE","TEXT_COLOR","TEXT_BACKGROUND_COLOR","INDENT","OUTDENT","SUPERSCRIPT","SUBSCRIPT","UNDO","REDO","defaults","Locals","newLocals","key","value","isObservable","of","__spreadValues","bold","italic","code","underline","strike","orderedList","bulletList","quote","link","unlink","image","alignLeft","alignCenter","alignRight","alignJustify","textColor","colorFill","horizontalRule","formatClear","indent","outdent","superscript","subscript","undo","redo","DEFAULT_ICON_HEIGHT","DEFAULT_ICON_WIDTH","DEFAULT_ICON_FILL","icons","Icon","name","fill","fullPath","NgxEditorServiceConfig","_NgxEditorServiceConfig","t","ɵɵdefineInjectable","NgxEditorService","_NgxEditorService","config","icon","ɵɵinject","provideMyServiceOptions","SanitizeHtmlPipe","_SanitizeHtmlPipe","sanitizer","isTrustedHtml","ɵɵdirectiveInject","DomSanitizer","ɵɵdefinePipe","MenuModule","_MenuModule","t","ɵɵdefineNgModule","ɵɵdefineInjector","SanitizeHtmlPipe","CommonModule","ReactiveFormsModule","NGX_EDITOR_CONFIG_TOKEN","InjectionToken","defaultConfig","defaults","icons","NgxEditorModule","_NgxEditorModule","config","NgxEditorServiceConfig","provideMyServiceOptions","NgxEditorService","isMacOs","init_define_NGX_ENV","init_define_NGX_ENV","authGuard","_0","__async","url","authenticationService","inject","AuthenticationService","currentUser","firstValueFrom","getMe","environment","production","window","location","href","loginFlowPath","internalLoginFlowPath","init_define_NGX_ENV","uiKitRoutes","path","redirectTo","ui_kit_routes_default","redirectTo","redirectToUrl","route","from","inject","Router","navigateByUrl","queryParamMap","routes","uiKitRoutes","path","loadComponent","canActivate","authGuard","children","pathMatch","init_define_NGX_ENV","init_define_NGX_ENV","fetch","req","httpClient","extractFiles","shouldUseBody","shouldStringify","param","isBatching","shouldUseMultipart","multipartInfo","Observable","observer","bodyOrParams","body","obj","value","form","map","files","i","paths","_","file","__spreadValues","mergeHeaders","source","destination","headers","name","prioritize","values","picked","val","createHeadersWithClientAwareness","context","HttpHeaders","version","HttpLinkHandler","ApolloLink","print","options","operation","pick","key","init","method","includeQuery","includeExtensions","url","withCredentials","useMultipart","useGETForQueries","isQuery","def","sub","response","err","op","HttpLink","t","ɵɵinject","HttpClient","ɵɵdefineInjectable","init_define_NGX_ENV","init_define_NGX_ENV","isPlainObject","value","prototype","extractFiles","value","isExtractable","path","clones","files","recurse","recursed","filePaths","valueIsList","valueIsPlainObject","isPlainObject","clone","uncloned","pathPrefix","recursedDeeper","index","item","itemClone","key","propertyClone","init_define_NGX_ENV","isExtractableFile","value","INSTANT_DATE_OPERATIONS","DOCUMENT_OPERATIONS","YEAR_MONTH_OPERATIONS","NOT_LOCALE_DATE_OPERATIONS","transformDatesToLocaleDate","obj","Date","toLocaleDate","Array","isArray","map","item","Object","keys","reduce","acc","key","transformDatesToYearMonth","toYearMonthDate","apolloOptionsFactory","httpLink","inject","HttpLink","dateMiddleware","ApolloLink","operation","forward","includes","operationName","variables","link","from","create","uri","environment","apiGraphQlPath","extractFiles","body","isExtractableFile","cache","InMemoryCache","graphqlProvider","Apollo","provide","APOLLO_OPTIONS","useFactory","init_define_NGX_ENV","DynamicImportLoader","getTranslation","lang","json$","__async","Promise","all","reduce","accumulator","currentValue","__spreadValues","default","from","then","x","init_define_NGX_ENV","accountCircleIcon","data","name","init_define_NGX_ENV","accountPinIcon","data","name","init_define_NGX_ENV","addLineIcon","data","name","init_define_NGX_ENV","applicationIcon","data","name","init_define_NGX_ENV","archiveIcon","data","name","init_define_NGX_ENV","arrowIcon","data","name","init_define_NGX_ENV","arrowBackIcon","data","name","init_define_NGX_ENV","arrowLeftIcon","data","name","init_define_NGX_ENV","arrowUpIcon","data","name","init_define_NGX_ENV","arrowUpDownFillIcon","data","name","init_define_NGX_ENV","cakeLineIcon","data","name","init_define_NGX_ENV","calendarEventIcon","data","name","init_define_NGX_ENV","callIcon","data","name","init_define_NGX_ENV","chatSmileIcon","data","name","init_define_NGX_ENV","checkIcon","data","name","init_define_NGX_ENV","checkOutlineIcon","data","name","init_define_NGX_ENV","chevronDownIcon","data","name","init_define_NGX_ENV","circleIcon","data","name","init_define_NGX_ENV","closeIcon","data","name","init_define_NGX_ENV","closeCircleIcon","data","name","init_define_NGX_ENV","communicationIcon","data","name","init_define_NGX_ENV","copyIcon","data","name","init_define_NGX_ENV","dashboardLineIcon","data","name","init_define_NGX_ENV","datasetIcon","data","name","init_define_NGX_ENV","deleteBackIcon","data","name","init_define_NGX_ENV","deleteBinLineIcon","data","name","init_define_NGX_ENV","downloadIcon","data","name","init_define_NGX_ENV","dragHandleIcon","data","name","init_define_NGX_ENV","editIcon","data","name","init_define_NGX_ENV","emailIcon","data","name","init_define_NGX_ENV","expandIcon","data","name","init_define_NGX_ENV","eyeLineIcon","data","name","init_define_NGX_ENV","eyeOffLineIcon","data","name","init_define_NGX_ENV","feedbackLineIcon","data","name","init_define_NGX_ENV","fileIcon","data","name","init_define_NGX_ENV","filterIcon","data","name","init_define_NGX_ENV","flagIcon","data","name","init_define_NGX_ENV","freshManIcon","data","name","init_define_NGX_ENV","globalIcon","data","name","init_define_NGX_ENV","groupLineIcon","data","name","init_define_NGX_ENV","homeLineIcon","data","name","init_define_NGX_ENV","homeNotIcon","data","name","init_define_NGX_ENV","inboxUnarchiveIcon","data","name","init_define_NGX_ENV","infoIcon","data","name","init_define_NGX_ENV","interculturaIcon","data","name","init_define_NGX_ENV","kanbanViewIcon","data","name","init_define_NGX_ENV","leadIcon","data","name","init_define_NGX_ENV","linksFillIcon","data","name","init_define_NGX_ENV","loadingIcon","data","name","init_define_NGX_ENV","logOutIcon","data","name","init_define_NGX_ENV","mailLineIcon","data","name","init_define_NGX_ENV","mailOpenIcon","data","name","init_define_NGX_ENV","mailUnreadIcon","data","name","init_define_NGX_ENV","mapPinLineIcon","data","name","init_define_NGX_ENV","mapPinRangeLineIcon","data","name","init_define_NGX_ENV","moreFillIcon","data","name","init_define_NGX_ENV","moreFillOrizzontalIcon","data","name","init_define_NGX_ENV","noteLineIcon","data","name","init_define_NGX_ENV","notificationIcon","data","name","init_define_NGX_ENV","parentIcon","data","name","init_define_NGX_ENV","passportLineIcon","data","name","init_define_NGX_ENV","personIcon","data","name","init_define_NGX_ENV","phoneLineIcon","data","name","init_define_NGX_ENV","pinDropIcon","data","name","init_define_NGX_ENV","playCircleIcon","data","name","init_define_NGX_ENV","playMiniIcon","data","name","init_define_NGX_ENV","priceTagIcon","data","name","init_define_NGX_ENV","privateIcon","data","name","init_define_NGX_ENV","programIcon","data","name","init_define_NGX_ENV","progressIcon","data","name","init_define_NGX_ENV","removeLabelsIcon","data","name","init_define_NGX_ENV","schoolLineIcon","data","name","init_define_NGX_ENV","searchIcon","data","name","init_define_NGX_ENV","searchEyeIcon","data","name","init_define_NGX_ENV","searchShortcutIcon","data","name","init_define_NGX_ENV","settingIcon","data","name","init_define_NGX_ENV","sortAlphabetIcon","data","name","init_define_NGX_ENV","stackLineIcon","data","name","init_define_NGX_ENV","starIcon","data","name","init_define_NGX_ENV","starSmileIcon","data","name","init_define_NGX_ENV","stickyNoteIcon","data","name","init_define_NGX_ENV","stopCircleIcon","data","name","init_define_NGX_ENV","studentIcon","data","name","init_define_NGX_ENV","subtractLineIcon","data","name","init_define_NGX_ENV","sunIcon","data","name","init_define_NGX_ENV","taskIcon","data","name","init_define_NGX_ENV","textIcon","data","name","init_define_NGX_ENV","textFieldIcon","data","name","init_define_NGX_ENV","unknownIcon","data","name","init_define_NGX_ENV","uploadIcon","data","name","init_define_NGX_ENV","userAddLineIcon","data","name","init_define_NGX_ENV","whatsappIcon","data","name","svgIcons","accountCircleIcon","accountPinIcon","addLineIcon","applicationIcon","archiveIcon","arrowBackIcon","arrowIcon","arrowLeftIcon","arrowUpDownFillIcon","arrowUpIcon","cakeLineIcon","calendarEventIcon","callIcon","chatSmileIcon","checkIcon","checkOutlineIcon","chevronDownIcon","circleIcon","closeCircleIcon","closeIcon","communicationIcon","copyIcon","dashboardLineIcon","datasetIcon","deleteBackIcon","deleteBinLineIcon","downloadIcon","dragHandleIcon","editIcon","emailIcon","expandIcon","eyeLineIcon","eyeOffLineIcon","fileIcon","filterIcon","flagIcon","feedbackLineIcon","freshManIcon","globalIcon","groupLineIcon","homeLineIcon","homeNotIcon","inboxUnarchiveIcon","infoIcon","interculturaIcon","kanbanViewIcon","leadIcon","linksFillIcon","loadingIcon","logOutIcon","mailLineIcon","mailOpenIcon","mailUnreadIcon","mapPinLineIcon","mapPinRangeLineIcon","moreFillIcon","moreFillOrizzontalIcon","noteLineIcon","notificationIcon","parentIcon","passportLineIcon","personIcon","phoneLineIcon","pinDropIcon","playCircleIcon","playMiniIcon","priceTagIcon","privateIcon","programIcon","progressIcon","removeLabelsIcon","schoolLineIcon","searchEyeIcon","searchIcon","searchShortcutIcon","settingIcon","sortAlphabetIcon","stackLineIcon","starIcon","starSmileIcon","stickyNoteIcon","stopCircleIcon","studentIcon","subtractLineIcon","sunIcon","taskIcon","textFieldIcon","textIcon","unknownIcon","uploadIcon","userAddLineIcon","whatsappIcon","registerLocaleData","localeIt","appConfig","providers","provide","LOCALE_ID","useValue","provideRouter","routes","withComponentInputBinding","provideSvgIconsConfig","icons","missingIconFallback","importProvidersFrom","BrowserAnimationsModule","HttpClientModule","NgxEditorModule","forRoot","locals","bold","italic","blockquote","underline","strike","text_color","bullet_list","ordered_list","align_left","align_center","align_right","align_justify","background_color","TranslateModule","defaultLanguage","environment","defaultLang","loader","TranslateLoader","useClass","DynamicImportLoader","GoogleChartsModule","version","provideHttpClient","graphqlProvider","bootstrapApplication","RootComponent","appConfig","catch","err","console","error"],"x_google_ignoreList":[2,3,4,5,6,7,8,9,10,11,12,13,14,15,20,21,22,23]}