1import { o as __toESM } from "./chunk-6z4oVpB-.js"; 2import { t as require_react } from "./react-CCT1erMQ.js"; 3import "./prop-types-BP3O0vhg.js"; 4import { t as require_jsx_runtime } from "./jsx-runtime-6ToSbptA.js"; 5import "./hoist-non-react-statics.cjs-aYVW55CP.js"; 6import "./clsx-BbsgvS4T.js"; 7import "./typeof-CtObx4yR.js"; 8import "./Amplify-D0fRojM9.js"; 9import "./types-Badw_GZ3.js"; 10import "./amplifyUrl-DDtOFVK1.js"; 11import "./tslib.es6-DOCxQXyJ.js"; 12import "./api-CPx3dJPV.js"; 13import "./createCognitoUserPoolEndpointResolver-CeOq9LYq.js"; 14import "./auth-112vuqrd.js"; 15import { c as formatDateTimeVerbose, o as formatDate, u as formatNumber } from "./helpers-CIThgqfh.js"; 16import "./getCurrentUser-BNfTg9dP.js"; 17import "./_baseGetTag-DyzlKCT_.js"; 18import "./errors-Bz8_MS_m.js"; 19import "./_arrayPush-zqmRK2Sh.js"; 20import "./isArray-DQJAKxTk.js"; 21import "./isObjectLike-YfNJf3G6.js"; 22import "./isArguments-jbXyUacA.js"; 23import { t as require_shim } from "./shim-tM7ZK01N.js"; 24import { n as require_with_selector } from "./use-isomorphic-layout-effect.browser.esm-B8DPirtA.js"; 25import "./isSymbol-fHles11u.js"; 26import "./debounce-BI4AKE0v.js"; 27import "./dist-9_GVLiOM.js"; 28import "./dist-CuFlg_4O.js"; 29import { t as require_react_dom } from "./react-dom-ld7mzddK.js"; 30import "./dist-DoGjUkMb.js"; 31import "./dist-CNliTmfT.js"; 32import "./classPrivateFieldGet2-T1C0ibFM.js"; 33import "./dist-D_mba0Ln.js"; 34import "./dist-wmihWyUh.js"; 35import "./Combination-CbWrdVoQ.js"; 36import "./dist-DNn8DQrd.js"; 37import "./dist-4SRU2SWZ.js"; 38import "./dist-auk7r2og.js"; 39import "./dist-KMtZa6Tg.js"; 40import "./dropdown-menu-Bura4Dcy.js"; 41import "./select-CAOM9JtG.js"; 42import "./dist-CvnDO-P6.js"; 43import { n as ie } from "./esm-OeroYQy0.js"; 44import { F as useSearchParams, M as useRevalidator, P as useRouteLoaderData, S as useBlocker, r as Link } from "./chunk-62JRHF6Z-af5QuQJC.js"; 45import "./exports-BpI0uky7.js"; 46import "./notifyManager-DecSEhne.js"; 47import "./useBaseQuery-B2Mj_MCe.js"; 48import "./useInfiniteQuery-C4nk9Xz0.js"; 49import "./useMutation-IAQRP4R7.js"; 50import "./QueryClientProvider-C1UBWQV0.js"; 51import { t as useQuery } from "./useQuery-CSX9sxP2.js"; 52import "./constants-DgZg1qAf.js"; 53import "./session-CHB6zjYw.js"; 54import "./iconPropTypes-C5chbmyn-FDi75KL4.js"; 55import { c as ArrowUp } from "./bucket-0-Dd64UaRz.js"; 56import { t as Calendar } from "./bucket-2-BGlGW4ET.js"; 57import { c as ChevronUp, i as ChevronDown, s as ChevronSort } from "./bucket-3-C2c54QJ8.js"; 58import { r as Edit } from "./bucket-6-Bmdc6sX9.js"; 59import { n as Notebook } from "./bucket-12-B_1FDRxt.js"; 60import "./bucket-13-BcEElD4r.js"; 61import { i as Search } from "./bucket-15-CpUGvMi0.js"; 62import "./dist-Z60waVX1.js"; 63import "./dist-CWLu0srv.js"; 64import { t as createLucideIcon } from "./createLucideIcon-COoV7LiJ.js"; 65import "./check-DOlAikXd.js"; 66import "./chevron-right-D6LclTBO.js"; 67import "./more-horizontal-MX1PRlOR.js"; 68import "./search-8Hqcfgqj.js"; 69import { t as cn } from "./utils-DCaTMnxb.js"; 70import { t as toast } from "./use-toast-DjpclxwO.js"; 71import "./mixpanel.module-BACt6dlR.js"; 72import "./subDays-Bn5Ubekx.js"; 73import "./addMonths-DV_ETa6N.js"; 74import "./endOfMonth-DiAWB7_8.js"; 75import "./roundingMethods-XHnUL5k_.js"; 76import "./differenceInWeeks-sFLJRI4F.js"; 77import "./vanilla-CLGkZFy8.js"; 78import "./react-DHanflfZ.js"; 79import "./client.gen-BrTEPecv.js"; 80import "./defineProperty-D5y_YB9q.js"; 81import { t as Button } from "./button-CgeNlB2Q.js"; 82import "./breadcrumb-DV9NvwEZ.js"; 83import { i as TooltipTrigger, n as TooltipContent, r as TooltipProvider, t as Tooltip } from "./tooltip-B35baM50.js"; 84import { n as LongText_default } from "./LongText-BPuPQL-1.js"; 85import { t as Badge } from "./badge-B_ZVhNO-.js"; 86import "./module-icon-B5p6mCCk.js"; 87import "./modules.api-DGo0G0c0.js"; 88import "./dynamic-breadcrumbs-_-fMQBaM.js"; 89import "./xstate-react.esm-Bnt7Kjod.js"; 90import "./utils-B9FPGvAJ.js"; 91import "./atoms-DP7aIs_n.js"; 92import { i as createBreadcrumbConfig } from "./dynamic-breadcrumbs.utils-CfffO9VU.js"; 93import "./useSessionQuery-CaAx9LCq.js"; 94import "./bootstrap-PD0gOsLT.js"; 95import "./command-BOGRc9Sm.js"; 96import "./dist-FSwW85_l.js"; 97import "./dialog-CHSk6eNP.js"; 98import { n as track_default } from "./track-BTherQuK.js"; 99import "./sidebar-DQigFm0E.js"; 100import "./utils-DMECC7FS.js"; 101import "./comments-CJXe8Uor.js"; 102import "./base-path-DffKLrHl.js"; 103import "./zod-Cm5HR22p.js"; 104import { t as Input } from "./input-Ct-ouO13.js"; 105import "./separator-keJIpHAu.js"; 106import "./sheet-DOB9Or8E.js"; 107import { t as Skeleton } from "./skeleton-BN73VL4N.js"; 108import { t as invariant } from "./tiny-invariant-wiz_5cyW.js"; 109import { t as useDebounceCallback } from "./useDebounceCallback-BTOGb8mZ.js"; 110import { i as getCoreRowModel, n as useReactTable, r as createColumnHelper, t as flexRender } from "./lib-BY10gxfc.js"; 111import { t as ControlledPagination } from "./controlled-pagination-CBMDgEEg.js"; 112import { a as TableHead, c as TableRow, n as TableBody, o as TableHeader, r as TableCell, s as TableHeaderRow, t as Table } from "./table-Dy8slfUO.js"; 113import "./reset-to-first-page-C9Ia8cgw.js"; 114import "./filter-search-params-BsP9grdP.js"; 115import { Bt as getUpstreamEventDetail, Dn as updateUpstreamEventInternalStrategy } from "./sdk.gen-Bm4osd6G.js"; 116import "./client-BXjQlaNr.js"; 117import { n as PageLayoutRoot, r as PageLayoutSidebar, t as PageLayoutMain } from "./page-layout-B2r7ZEeF.js"; 118import { t as HeaderBreadcrumb } from "./breadcrumb-BjTrkXIp.js"; 119import { t as containers_default } from "./containers-tCHeBC2a.js"; 120import { t as IconInput } from "./icon-input-CDNXspek.js"; 121import { d as itemSubstitutesQuery, u as itemQueuePaginatedQuery, y as useDisruptionBootstrapQuery } from "./api-DYsscDZP.js"; 122import "./useMatchesData-BspVY2Cp.js"; 123import { m as substitutionsBootstrapQuery } from "./api-BkfjtxrG.js"; 124import "./queries-BCemRJki.js"; 125import "./_baseFlatten-CQ5kwHSA.js"; 126import "./flatten-C45Vd0Yy.js"; 127import "./assignee-select-value-mUf-X1Sf.js"; 128import { I as DEFAULT_DISRUPTION_PARAMS, S as useClinicalLocationsOptions, g as clinicalLocationSearchKeywords, l as validateForDaysCalculated, n as convertFiltersToSearchParams, x as useClinicalLocationGroupOptions } from "./utils-O1BD-TND.js"; 129import { i as getManipulatedERPId } from "./tmpDataManipulation-LqS79Zqw.js"; 130import { i as rightTableCellMeta } from "./table-meta-props-BSU7z6Gh.js";
131import "./Trigger-BoSVQJWZ.js"; 132import "./dist-CbAgl5nj.js"; 133import { n as PopoverContent, r as PopoverTrigger, t as Popover } from "./popover-thS7yP-j.js"; 134import { t as NonParamFilterButton } from "./ToolbarFilterNonParam-O65HaiCQ.js"; 135import "./pluralize-zopUG0kl.js"; 136import "./ToolbarFilterButton-w9NqPSIP.js"; 137import { t as SingleSelectFilterButton } from "./ToolbarFilterSingleSelect-FMP2FxZg.js"; 138import { c as useClinicalLocationGroupsEnabled, l as useClinicalLocationSensitiveContextEnabled } from "./selectors-CPIkrhC2.js"; 139import "./hooks-2c-bdnfb.js"; 140import { t as PERIOD_OPTIONS } from "./period-select-gEwSGf7J.js"; 141import { t as Card } from "./card-CXCpfhnp.js"; 142import { t as deepEqual } from "./es-CIbv_m35.js"; 143import { a as AlertDialogDescription, c as AlertDialogTitle, i as AlertDialogContent, n as AlertDialogAction, o as AlertDialogFooter, r as AlertDialogCancel, s as AlertDialogHeader, t as AlertDialog } from "./alert-dialog-D5UzG0QJ.js"; 144import { i as SideBarSectionContainer, r as SideBarPaddingWrapper } from "./sidebar-DYeG06u4.js"; 145import { t as SidebarDetailContent } from "./SidebarDetailContent-DFM4cpTc.js"; 146import "./utils-nG8rdJfp.js"; 147import { t as CustomerStatusField } from "./customer-status-field-Bl9IOwQ7.js"; 148var Bold = createLucideIcon("Bold", [["path", { 149 d: "M14 12a4 4 0 0 0 0-8H6v8", 150 key: "v2sylx" 151}], ["path", { 152 d: "M15 20a4 4 0 0 0 0-8H6v8Z", 153 key: "1ef5ya" 154}]]); 155var Italic = createLucideIcon("Italic", [ 156 ["line", { 157 x1: "19", 158 x2: "10", 159 y1: "4", 160 y2: "4", 161 key: "15jd3p" 162 }], 163 ["line", { 164 x1: "14", 165 x2: "5", 166 y1: "20", 167 y2: "20", 168 key: "bu0au3" 169 }], 170 ["line", { 171 x1: "15", 172 x2: "9", 173 y1: "4", 174 y2: "20", 175 key: "uljnxc" 176 }] 177]); 178var Link$1 = createLucideIcon("Link", [["path", { 179 d: "M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71", 180 key: "1cjeqo" 181}], ["path", { 182 d: "M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71", 183 key: "19qd67" 184}]]); 185var ListOrdered = createLucideIcon("ListOrdered", [ 186 ["line", { 187 x1: "10", 188 x2: "21", 189 y1: "6", 190 y2: "6", 191 key: "76qw6h" 192 }], 193 ["line", { 194 x1: "10", 195 x2: "21", 196 y1: "12", 197 y2: "12", 198 key: "16nom4" 199 }], 200 ["line", { 201 x1: "10", 202 x2: "21", 203 y1: "18", 204 y2: "18", 205 key: "u3jurt" 206 }], 207 ["path", { 208 d: "M4 6h1v4", 209 key: "cnovpq" 210 }], 211 ["path", { 212 d: "M4 10h2", 213 key: "16xx2s" 214 }], 215 ["path", { 216 d: "M6 18H4c0-1 2-2 2-3s-1-1.5-2-1", 217 key: "m9a95d" 218 }] 219]); 220var List = createLucideIcon("List", [ 221 ["line", { 222 x1: "8", 223 x2: "21", 224 y1: "6", 225 y2: "6", 226 key: "7ey8pc" 227 }], 228 ["line", { 229 x1: "8", 230 x2: "21", 231 y1: "12", 232 y2: "12", 233 key: "rjfblc" 234 }], 235 ["line", { 236 x1: "8", 237 x2: "21", 238 y1: "18", 239 y2: "18", 240 key: "c3b1m8" 241 }], 242 ["line", { 243 x1: "3", 244 x2: "3.01", 245 y1: "6", 246 y2: "6", 247 key: "1g7gq3" 248 }], 249 ["line", { 250 x1: "3", 251 x2: "3.01", 252 y1: "12", 253 y2: "12", 254 key: "1pjlvk" 255 }], 256 ["line", { 257 x1: "3", 258 x2: "3.01", 259 y1: "18", 260 y2: "18", 261 key: "28t2mc" 262 }] 263]); 264var Underline = createLucideIcon("Underline", [["path", { 265 d: "M6 4v6a6 6 0 0 0 12 0V4", 266 key: "9kb039" 267}], ["line", { 268 x1: "4", 269 x2: "20", 270 y1: "20", 271 y2: "20", 272 key: "nun2al" 273}]]); 274var import_react = /* @__PURE__ */ __toESM(require_react(), 1); 275function useUnsavedChangesWarning(isDirty, onDiscard) { 276 const blocker = useBlocker(isDirty); 277 const pendingProceedRef = import_react.useRef(null); 278 const [isTabPromptOpen, setIsTabPromptOpen] = import_react.useState(false); 279 import_react.useEffect(() => { 280 if (!isDirty) return; 281 function onBeforeUnload(event) { 282 event.preventDefault(); 283 event.returnValue = ""; 284 } 285 window.addEventListener("beforeunload", onBeforeUnload); 286 return () => window.removeEventListener("beforeunload", onBeforeUnload); 287 }, [isDirty]); 288 return { 289 confirmIfDirty: import_react.useCallback((proceed) => { 290 if (!isDirty) { 291 proceed(); 292 return; 293 } 294 pendingProceedRef.current = proceed; 295 setIsTabPromptOpen(true); 296 }, [isDirty]), 297 keepEditing: import_react.useCallback(() => { 298 pendingProceedRef.current = null; 299 setIsTabPromptOpen(false); 300 blocker.reset?.(); 301 }, [blocker]), 302 discard: import_react.useCallback(() => { 303 const proceed = pendingProceedRef.current; 304 pendingProceedRef.current = null; 305 setIsTabPromptOpen(false); 306 onDiscard(); 307 if (blocker.state === "blocked") blocker.proceed(); 308 proceed?.(); 309 }, [blocker, onDiscard]), 310 isPromptOpen: blocker.state === "blocked" || isTabPromptOpen 311 }; 312} 313var import_jsx_runtime = /* @__PURE__ */ __toESM(require_jsx_runtime(), 1); 314function EventDetailTabs({ activeTab, onTabChange, itemsCount }) { 315 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("nav", { 316 className: "ml-2 mt-4 flex flex-row items-center justify-start space-x-6 overflow-x-auto", 317 role: "tablist", 318 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabButton, { 319 isActive: activeTab === "overview", 320 onClick: () => onTabChange("overview"), 321 children: "Overview" 322 }
322), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabButton, { 323 isActive: activeTab === "items", 324 onClick: () => onTabChange("items"), 325 children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 326 className: "flex items-center", 327 children: ["Items", /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, { 328 variant: "natural", 329 size: "small", 330 className: "ml-1", 331 children: itemsCount 332 })] 333 }) 334 })] 335 }); 336} 337function TabButton({ isActive: isActive$1, onClick, children }) { 338 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { 339 type: "button", 340 role: "tab", 341 "aria-selected": isActive$1, 342 onClick, 343 className: cn("relative pb-3 pt-2 text-zinc-500 after:absolute after:inset-x-0 after:bottom-0 after:h-[2px] hover:after:bg-indigo-600/40", isActive$1 && "border-b-2 border-indigo-600 font-medium text-zinc-900 after:bg-indigo-600"), 344 children 345 }); 346} 347function EventDetailsTitle() { 348 const event = useEventDetails()?.event; 349 if (!event) return null; 350 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 351 className: "ml-2 flex flex-col items-start gap-2", 352 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 353 className: "type-body-2xl font-medium text-zinc-900", 354 children: event.title 355 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 356 className: "type-body-sm leading-6 text-zinc-500", 357 children: event.summary 358 })] 359 }); 360} 361var DEFAULT_PAGE_SIZE = 100; 362var DEFAULT_SORT = "description|asc"; 363var SEARCH_MIN_LENGTH = 3; 364function useEventItems(eventId) { 365 const [searchParams] = useSearchParams(); 366 const clinicalLocation = searchParams.get("for_clinical_location") || ""; 367 const clinicalLocationGroup = searchParams.get("for_clinical_location_group") || ""; 368 const forDaysCalculated = validateForDaysCalculated(searchParams.get("for_days_calculated")); 369 const [pageNumber, setPageNumber] = import_react.useState(1); 370 const [pageSize, setPageSize] = import_react.useState(DEFAULT_PAGE_SIZE); 371 const [sort, setSort] = import_react.useState(DEFAULT_SORT); 372 const [searchInput, setSearchInput] = import_react.useState(""); 373 const [committedSearch, setCommittedSearch] = import_react.useState(""); 374 const commitSearch = useDebounceCallback((raw) => { 375 const trimmed = raw.trim(); 376 setCommittedSearch(trimmed.length >= SEARCH_MIN_LENGTH ? trimmed : ""); 377 setPageNumber(1); 378 }, 500); 379 import_react.useEffect(() => { 380 setPageNumber(1); 381 }, [ 382 clinicalLocation, 383 clinicalLocationGroup, 384 forDaysCalculated 385 ]); 386 const query = useQuery({ ...itemQueuePaginatedQuery(import_react.useMemo(() => { 387 return { 388 for_event: [eventId], 389 for_days_calculated: forDaysCalculated, 390 page_number: pageNumber, 391 page_size: pageSize, 392 include_doh_rollup: true, 393 include_on_order_qty_rollup: true, 394 sort, 395 ...committedSearch ? { for_search_string: committedSearch } : {}, 396 ...clinicalLocation ? { for_clinical_location: clinicalLocation } : {}, 397 ...clinicalLocationGroup ? { for_clinical_location_group: clinicalLocationGroup } : {} 398 }; 399 }, [ 400 clinicalLocation, 401 clinicalLocationGroup, 402 committedSearch, 403 eventId, 404 forDaysCalculated, 405 pageNumber, 406 pageSize, 407 sort 408 ])) }); 409 const handleSearchChange = import_react.useCallback((value) => { 410 setSearchInput(value); 411 commitSearch(value); 412 }, [commitSearch]); 413 const handleSortChange = import_react.useCallback((field) => { 414 setSort((current) => { 415 const [currentField, currentDir] = current.split("|"); 416 return `${field}|${currentField === field && currentDir === "asc" ? "desc" : "asc"}`; 417 }); 418 setPageNumber(1); 419 }, []); 420 const handlePageSizeChange = import_react.useCallback((nextPageSize) => { 421 setPageSize(nextPageSize); 422 setPageNumber(1); 423 }, []); 424 return { 425 items: query.data?.items ?? [], 426 resultSetSize: query.data?.result_set_size ?? 0,
427 dohRollup: query.data?.doh_rollup, 428 isLoading: query.isLoading, 429 isFetching: query.isFetching, 430 pageNumber, 431 pageSize, 432 sort, 433 searchInput, 434 hasActiveSearch: Boolean(committedSearch), 435 hasItemListFilter: Boolean(committedSearch || clinicalLocation || clinicalLocationGroup), 436 setSearchInput: handleSearchChange, 437 setPageNumber, 438 setPageSize: handlePageSizeChange, 439 setSort: handleSortChange 440 }; 441} 442var SUBSTITUTES_PAGE_SIZE = "100"; 443var APPROVED_SUBSTITUTE_STATUSES = new Set(["Approved", "Completed"]); 444function useEventItemApprovedSubstitutes(clientItemMasterId) { 445 const [searchParams] = useSearchParams(); 446 const clinicalLocation = searchParams.get("for_clinical_location") || ""; 447 const clinicalLocationGroup = searchParams.get("for_clinical_location_group") || ""; 448 const forDaysCalculated = validateForDaysCalculated(searchParams.get("for_days_calculated")); 449 const bootstrapQuery = useQuery({ ...substitutionsBootstrapQuery() }); 450 const approvedStatusIds = import_react.useMemo(() => bootstrapQuery.data?.request_status_options.filter((option) => APPROVED_SUBSTITUTE_STATUSES.has(option.entity_string)).map((option) => option.entity_id) ?? [], [bootstrapQuery.data?.request_status_options]); 451 const substitutesQuery = useQuery({ 452 ...itemSubstitutesQuery(clientItemMasterId, import_react.useMemo(() => { 453 return { 454 include_inactive_items: "true", 455 include_substitute_inventory: "true", 456 sort: "priority|asc", 457 page_size: SUBSTITUTES_PAGE_SIZE, 458 for_days_calculated: forDaysCalculated, 459 ...clinicalLocation ? { for_clinical_location: clinicalLocation } : {}, 460 ...clinicalLocationGroup ? { for_clinical_location_group: clinicalLocationGroup } : {}, 461 ...approvedStatusIds.length > 0 ? { for_status: approvedStatusIds } : {} 462 }; 463 }, [ 464 approvedStatusIds, 465 clinicalLocation, 466 clinicalLocationGroup, 467 forDaysCalculated 468 ]), false), 469 enabled: approvedStatusIds.length > 0 470 }); 471 return { 472 items: substitutesQuery.data?.items ?? [], 473 isLoading: bootstrapQuery.isLoading || approvedStatusIds.length > 0 && substitutesQuery.isLoading, 474 isError: bootstrapQuery.isError || substitutesQuery.isError 475 }; 476} 477const DOH_HEALTH = { 478 critical: { 479 key: "critical", 480 label: "Critical Items", 481 indicatorLabel: "Critical", 482 badge: "Under 5 DOH", 483 badgeClassName: "bg-red-600 text-white", 484 dotClassName: "bg-red-600" 485 }, 486 at_risk: { 487 key: "at_risk", 488 label: "At Risk Items", 489 indicatorLabel: "At Risk", 490 badge: "5-20 DOH", 491 badgeClassName: "bg-amber-500 text-zinc-950", 492 dotClassName: "bg-amber-500" 493 }, 494 healthy: { 495 key: "healthy", 496 label: "Healthy Items", 497 indicatorLabel: "Healthy", 498 badge: "21+ DOH", 499 badgeClassName: "bg-sky-600 text-white", 500 dotClassName: "bg-sky-600" 501 } 502}; 503const DOH_CARDS = [ 504 DOH_HEALTH.critical, 505 DOH_HEALTH.at_risk, 506 DOH_HEALTH.healthy 507]; 508function getDohHealthBand(doh) { 509 if (doh < 5) return "critical"; 510 if (doh < 21) return "at_risk"; 511 return "healthy"; 512} 513function QohCell({ value }) { 514 if (typeof value !== "number") return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: "â" }); 515 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [ 516 formatNumber(value), 517 " ", 518 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { 519 className: "ml-1 text-muted-foreground", 520 children: "EA" 521 }) 522 ] }); 523} 524function DohCell({ value }) { 525 if (typeof value !== "number") return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: "â" }); 526 const rounded = Math.round(value); 527 const band = getDohHealthBand(rounded); 528 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { 529 className: "inline-flex items-center justify-end gap-1.5", 530 children: [ 531 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { 532 "data-testid": "doh-health-dot", 533 className: cn("size-2 shrink-0 rounded-full", DOH_HEALTH[band].dotClassName) 534 }), 535 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { 536 className: "sr-only", 537 children: DOH_HEALTH[band].indicatorLabel 538 }), 539 formatNumber(rounded), 540 " ",
541 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { 542 className: "ml-1 text-muted-foreground", 543 children: "d" 544 }) 545 ] 546 }); 547} 548var NESTED_TABLE_MIN_WIDTH = "min-w-[720px]"; 549var descriptionTableCellMeta$1 = { tableCellProps: { 550 className: "max-w-[230px] overflow-hidden", 551 style: { maxWidth: 230 } 552} }; 553var columnHelper$1 = createColumnHelper(); 554var columns = [ 555 columnHelper$1.accessor("substitute_client_erp_id", { 556 id: "substitute_client_erp_id", 557 header: "ERP ID", 558 cell: ({ row }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SubstituteErpIdCell, { item: row.original }) 559 }), 560 columnHelper$1.accessor("substitute_client_item_description", { 561 id: "substitute_client_item_description", 562 meta: descriptionTableCellMeta$1, 563 header: "Description", 564 cell: ({ getValue }) => { 565 const text$1 = getValue(); 566 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 567 className: "max-w-[230px] overflow-hidden", 568 children: text$1 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LongText_default, { text: text$1 }) : "â" 569 }); 570 } 571 }), 572 columnHelper$1.accessor("substitute_client_manufacturer_name", { 573 id: "substitute_client_manufacturer_name", 574 header: "MFG Name", 575 cell: ({ getValue }) => { 576 const text$1 = getValue(); 577 return text$1 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LongText_default, { text: text$1 }) : "â"; 578 } 579 }), 580 columnHelper$1.accessor("substitute_quantity_on_hand", { 581 id: "substitute_quantity_on_hand", 582 meta: rightTableCellMeta, 583 header: "QOH", 584 cell: ({ getValue }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(QohCell, { value: getValue() }) 585 }), 586 columnHelper$1.accessor("substitute_days_on_hand", { 587 id: "substitute_days_on_hand", 588 meta: rightTableCellMeta, 589 header: "DOH", 590 cell: ({ getValue }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DohCell, { value: getValue() }) 591 }) 592]; 593function EventItemsApprovedSubstitutes({ clientItemMasterId, erpId }) { 594 const flags = ie(); 595 const { items, isLoading, isError } = useEventItemApprovedSubstitutes(clientItemMasterId); 596 const displayErpId = flags["demoDataManipulation"] ? getManipulatedERPId(erpId || "") : erpId; 597 const table = useReactTable({ 598 data: items, 599 columns, 600 getCoreRowModel: getCoreRowModel(), 601 getRowId: (row) => row.substitution_request_id 602 }); 603 const columnCount = table.getAllColumns().length; 604 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 605 className: "bg-zinc-50 px-4 py-3", 606 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { 607 className: "type-body-sm mb-3 font-medium text-zinc-900", 608 children: ["Approved Substitutes for ", displayErpId || "â"] 609 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 610 className: "relative w-full overflow-visible rounded border border-zinc-200", 611 children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("table", { 612 "data-testid": "approved-substitutes-table", 613 className: cn("w-full caption-bottom bg-white text-sm", NESTED_TABLE_MIN_WIDTH), 614 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHeader, { children: table.getHeaderGroups().map((headerGroup) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHeaderRow, { children: headerGroup.headers.map((header) => { 615 const tableCellProps = header.column.columnDef.meta?.tableCellProps ?? {}; 616 const { className: cellClassName,...restTableCellProps } = tableCellProps; 617 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { 618 className: cn("text-nowrap", tableCellProps.align === "right" && "text-right", cellClassName), 619 ...restTableCellProps, 620 children: header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext()) 621 }, header.id); 622 }) }, headerGroup.id)) }
622), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableBody, { children: isLoading ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { 623 colSpan: columnCount, 624 className: "h-24 text-center", 625 children: "Loading..." 626 }) }) : isError ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { 627 colSpan: columnCount, 628 className: "h-24 text-center", 629 children: "Unable to load approved substitutes" 630 }) }) : items.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { 631 colSpan: columnCount, 632 className: "h-24 text-center", 633 children: "No approved substitutes found" 634 }) }) : table.getRowModel().rows.map((row) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: row.getVisibleCells().map((cell) => { 635 const tableCellProps = cell.column.columnDef.meta?.tableCellProps ?? {}; 636 const { className: cellClassName,...restTableCellProps } = tableCellProps; 637 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { 638 className: cn(tableCellProps.align === "right" && "text-right", cellClassName), 639 ...restTableCellProps, 640 children: flexRender(cell.column.columnDef.cell, cell.getContext()) 641 }, cell.id); 642 }) }, row.id)) })] 643 }) 644 })] 645 }); 646} 647function SubstituteErpIdCell({ item }) { 648 const erpId = ie()["demoDataManipulation"] ? getManipulatedERPId(item.substitute_client_erp_id || "") : item.substitute_client_erp_id; 649 if (!item.substitute_client_erp_id || !item.substitute_client_item_master_id) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: erpId || "â" }); 650 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link, { 651 to: `/disruptions/${item.substitute_client_item_master_id}`, 652 className: "font-medium text-indigo-500 hover:underline", 653 children: erpId 654 }); 655} 656var descriptionTableCellMeta = { tableCellProps: { 657 className: "max-w-[230px] overflow-hidden", 658 style: { maxWidth: 230 } 659} }; 660var columnHelper = createColumnHelper(); 661function getEventItemsColumns({ sort, onSort, expandedIds, onToggleExpanded }) { 662 return [ 663 columnHelper.accessor("client_erp_item_id", { 664 id: "client_erp_item_id", 665 header: () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItemsSortHeader, { 666 label: "ERP Item ID", 667 sortField: "client_erp_item_id", 668 sort, 669 onSort 670 }), 671 cell: ({ row }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErpItemIdCell, { item: row.original }) 672 }), 673 columnHelper.accessor("description", { 674 id: "description", 675 meta: descriptionTableCellMeta, 676 header: () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItemsSortHeader, { 677 label: "Description", 678 sortField: "description", 679 sort, 680 onSort 681 }), 682 cell: ({ row }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItemDescriptionCell, { text: row.original.description }) 683 }), 684 columnHelper.accessor("client_manufacturer_name", { 685 id: "client_manufacturer_name", 686 header: () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItemsSortHeader, { 687 label: "MFG Name", 688 sortField: "client_manufacturer_name", 689 sort, 690 onSort 691 }), 692 cell: ({ row }) => { 693 const text$1 = row.original.client_manufacturer_name; 694 return text$1 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LongText_default, { text: text$1 }) : "â"; 695 } 696 }), 697 columnHelper.accessor("unit_quantity_on_hand", { 698 id: "unit_quantity_on_hand", 699 meta: rightTableCellMeta, 700 header: () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItemsSortHeader, { 701 label: "QOH", 702 sortField: "unit_quantity_on_hand", 703 sort, 704 onSort, 705 isNumeric: true 706 }), 707 cell: ({ row }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(QohCell, { value: row.original.unit_quantity_on_hand }) 708 }), 709 columnHelper.accessor("unit_days_on_hand", { 710 id: "unit_days_on_hand", 711 meta: rightTableCellMeta, 712 header: () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItemsSortHeader, { 713 label: "DOH", 714 sortField: "unit_days_on_hand", 715 sort, 716 onSort, 717 isNumeric: true 718 }), 719 cell: ({ row }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DohCell, { value: row.original.unit_days_on_hand }) 720 }), 721 columnHelper.accessor("unit_average_daily_usage", { 722 id: "unit_average_daily_usage", 723 meta: rightTableCellMeta, 724 header: () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItemsSortHeader, { 725 label: "Avg. Daily Use", 726 sortField: "unit_average_daily_usage", 727 sort, 728 onSort, 729 isNumeric: true 730 }), 731 cell: ({ row }) => { 732 const adu = row.original.unit_average_daily_usage; 733 return typeof adu === "number" ? formatNumber(adu, 2) : "â"; 734 } 735 }), 736 columnHelper.accessor("open_purchase_order_count", { 737 id: "open_purchase_order_count", 738 meta: rightTableCellMeta, 739 header: () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItemsSortHeader, { 740 label: "Open POs", 741 sortField: "open_purchase_order_count", 742 sort, 743 onSort, 744 isNumeric: true 745 }), 746 cell: ({ row }) => { 747 const count = row.original.open_purchase_order_count; 748 return typeof count === "number" ? formatNumber(count) : "â"; 749 } 750 }), 751 columnHelper.accessor("open_purchase_order_unit_quantity", { 752 id: "open_purchase_order_unit_quantity", 753 meta: rightTableCellMeta, 754 header: () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItemsSortHeader, { 755 label: "On Order Qty", 756 sortField: "open_purchase_order_unit_quantity", 757 sort, 758 onSort, 759 isNumeric: true 760 }), 761 cell: ({ row }) => {
762 const qty = row.original.open_purchase_order_unit_quantity; 763 return typeof qty === "number" ? formatNumber(Math.round(qty)) : "â"; 764 } 765 }), 766 columnHelper.accessor("approved_substitution_count", { 767 id: "approved_substitution_count", 768 meta: rightTableCellMeta, 769 header: () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItemsSortHeader, { 770 label: "Approved Substitutes", 771 sortField: "approved_substitution_count", 772 sort, 773 onSort, 774 isNumeric: true 775 }), 776 cell: ({ row }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ApprovedSubsCell, { 777 item: row.original, 778 isExpanded: Boolean(expandedIds[row.original.client_item_master_id]), 779 onToggle: () => onToggleExpanded(row.original.client_item_master_id) 780 }) 781 }) 782 ]; 783} 784function EventItemDescriptionCell({ text: text$1 }) { 785 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 786 className: "max-w-[230px] overflow-hidden", 787 children: text$1 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LongText_default, { text: text$1 }) : "â" 788 }); 789} 790function EventItemsSortHeader({ label, sortField, sort, onSort, isNumeric }) { 791 const [field, dir] = sort.split("|"); 792 const isActive$1 = field === sortField; 793 const isDesc = dir === "desc"; 794 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { 795 type: "button", 796 onClick: () => onSort(sortField), 797 className: cn("group flex h-full items-center gap-2 whitespace-nowrap align-text-bottom", isNumeric && "justify-end"), 798 children: [ 799 isNumeric ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SortIcon, { 800 isActive: isActive$1, 801 isDesc 802 }) : null, 803 label, 804 !isNumeric ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SortIcon, { 805 isActive: isActive$1, 806 isDesc 807 }) : null 808 ] 809 }); 810} 811function SortIcon({ isActive: isActive$1, isDesc }) { 812 if (isActive$1) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 813 className: "flex size-4 items-center justify-center", 814 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ArrowUp, { className: cn("size-3", isDesc && "rotate-180") }) 815 }); 816 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronSort, { className: "size-4 opacity-0 group-hover:opacity-70" }); 817} 818function ErpItemIdCell({ item }) { 819 const erpId = ie()["demoDataManipulation"] ? getManipulatedERPId(item.client_erp_item_id || "") : item.client_erp_item_id; 820 if (!item.client_erp_item_id) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: "â" }); 821 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link, { 822 to: `/disruptions/${item.client_item_master_id}`, 823 className: "font-medium text-indigo-500 hover:underline", 824 children: erpId 825 }); 826} 827function ApprovedSubsCell({ item, isExpanded, onToggle }) { 828 const count = item.approved_substitution_count; 829 if (!count) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: "â" }); 830 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { 831 type: "button", 832 variant: "outline", 833 size: "sm", 834 className: "h-7 gap-1 rounded-full px-2.5", 835 "aria-expanded": isExpanded, 836 "aria-label": isExpanded ? `Collapse approved substitutes for ${item.client_erp_item_id ?? "item"}` : `Expand approved substitutes for ${item.client_erp_item_id ?? "item"}`, 837 onClick: onToggle, 838 children: [count, isExpanded ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronUp, { className: "size-4" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronDown, { className: "size-4" })] 839 }); 840} 841function EventItemsDohCards({ dohRollup }) { 842 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 843 className: "grid grid-cols-3 gap-4", 844 children: DOH_CARDS.map((card) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 845 className: "rounded-lg border border-zinc-200 bg-white p-4", 846 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 847 className: "type-body-xs text-zinc-500", 848 children: card.label 849 }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 850 className: "mt-2 flex items-center gap-2", 851 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { 852 className: "type-body-2xl font-medium text-zinc-900", 853 children: dohRollup?.[card.key] ?? 0 854 }
854), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, { 855 variant: "custom", 856 className: card.badgeClassName, 857 children: card.badge 858 })] 859 })] 860 }, card.key)) 861 }); 862} 863function EventItemsFilters() { 864 const [searchParams, setSearchParams] = useSearchParams(); 865 const hasClinicalLocation = useClinicalLocationSensitiveContextEnabled(); 866 const hasClinicalLocationGroups = useClinicalLocationGroupsEnabled(); 867 const clinicalLocationsOptions = useClinicalLocationsOptions(); 868 const groupOptions = useClinicalLocationGroupOptions(); 869 const selectedLocation = searchParams.get("for_clinical_location") || void 0; 870 const selectedGroup = searchParams.get("for_clinical_location_group") || void 0; 871 const currentPeriod = validateForDaysCalculated(searchParams.get("for_days_calculated")); 872 function selectGroup(selected) { 873 const next = new URLSearchParams(searchParams); 874 if (selected.length === 0) { 875 track_default.drm.changeClinicalLocationGroup("All", "Detail"); 876 next.delete("for_clinical_location_group"); 877 } else { 878 track_default.drm.changeClinicalLocationGroup(selected, "Detail"); 879 next.set("for_clinical_location_group", selected); 880 next.delete("for_clinical_location"); 881 } 882 setSearchParams(next); 883 } 884 function selectLocation(selected) { 885 const next = new URLSearchParams(searchParams); 886 if (selected.length === 0) { 887 track_default.drm.changeClinicalLocation("All", "Detail"); 888 next.delete("for_clinical_location"); 889 } else { 890 next.set("for_clinical_location", selected); 891 track_default.drm.changeClinicalLocation(selected, "Detail"); 892 } 893 setSearchParams(next); 894 } 895 function selectPeriod(value) { 896 const next = new URLSearchParams(searchParams); 897 next.set("for_days_calculated", value); 898 track_default.drm.changePeriod(value, "Detail"); 899 setSearchParams(next); 900 } 901 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 902 className: "flex flex-wrap items-center gap-2", 903 children: [ 904 hasClinicalLocationGroups ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SingleSelectFilterButton, { 905 options: groupOptions, 906 attribute: "for_clinical_location_group", 907 label: "Group", 908 selected: selectedGroup, 909 onSelect: selectGroup, 910 persisted: true, 911 inputPlaceholder: "Search", 912 arrowIcon: true, 913 testId: "filter-button-Group" 914 }) : null, 915 hasClinicalLocation ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SingleSelectFilterButton, { 916 options: clinicalLocationsOptions, 917 attribute: "for_clinical_location", 918 label: "Location", 919 selected: selectedLocation, 920 onSelect: selectLocation, 921 persisted: true, 922 inputPlaceholder: "Search", 923 disabled: !!selectedGroup, 924 arrowIcon: true, 925 testId: "filter-button-Location", 926 getSearchKeywords: clinicalLocationSearchKeywords 927 }) : null, 928 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(NonParamFilterButton, { 929 label: "Period", 930 selected: String(currentPeriod), 931 onSelect: selectPeriod, 932 options: PERIOD_OPTIONS, 933 testId: "filter-button-Period" 934 }) 935 ] 936 }); 937} 938function EventItems() { 939 const data = useEventDetails(); 940 const eventId = data?.event?.event_id; 941 if (!eventId) return null; 942 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItemsTable, { 943 eventId, 944 productsAffected: data.event?.products_affected ?? 0 945 }); 946} 947function EventItemsTable({ eventId, productsAffected }) { 948 const { items, resultSetSize, dohRollup, isLoading, isFetching, pageNumber, pageSize, sort, searchInput, hasActiveSearch, hasItemListFilter, setSearchInput, setPageNumber, setPageSize, setSort } = useEventItems(eventId); 949 const [expandedIds, setExpandedIds] = import_react.useState({}); 950 const handleToggleExpanded = import_react.useCallback((id) => { 951 setExpandedIds((current) => ({ 952 ...current, 953 [id]: !current[id] 954 })); 955 }, []); 956 const table = useReactTable({ 957 data: items, 958 columns: import_react.useMemo(() => getEventItemsColumns({ 959 sort, 960 onSort: setSort, 961 expandedIds, 962 onToggleExpanded: handleToggleExpanded 963 }), [ 964 expandedIds, 965 handleToggleExpanded, 966 setSort, 967 sort 968 ]), 969 getCoreRowModel: getCoreRowModel(), 970 manualSorting: true, 971 getRowId: (row) => row.client_item_master_id 972 }); 973 const columnCount = table.getAllColumns().length; 974 const isEmpty = !isLoading && items.length === 0; 975 const emptyMessage = hasItemListFilter || hasActiveSearch ? "No items match the selected filters" : "No items have been matched to this event yet"; 976 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 977 className: "flex flex-col gap-4", 978 children: [
979 /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 980 className: "flex flex-wrap items-center justify-between gap-2", 981 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(IconInput, { 982 icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Search, {}), 983 value: searchInput, 984 onChange: (event) => setSearchInput(event.target.value), 985 className: "mb-0.5 w-72", 986 type: "search", 987 sz: "sm", 988 placeholder: "Filter by SKU IDs & Description" 989 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItemsFilters, {})] 990 }), 991 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItemsDohCards, { dohRollup }), 992 hasItemListFilter ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { 993 className: "type-body-sm text-zinc-500", 994 children: [ 995 "Showing ", 996 resultSetSize, 997 " of ", 998 productsAffected, 999 " items" 1000 ] 1001 }) : null, 1002 /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Table, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHeader, { 1003 sticky: true, 1004 children: table.getHeaderGroups().map((headerGroup) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHeaderRow, { children: headerGroup.headers.map((header) => { 1005 const tableCellProps = header.column.columnDef.meta?.tableCellProps ?? {}; 1006 const { className: cellClassName,...restTableCellProps } = tableCellProps; 1007 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { 1008 className: cn("text-nowrap", tableCellProps.align === "right" && "text-right", cellClassName), 1009 ...restTableCellProps, 1010 children: header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext()) 1011 }, header.id); 1012 }) }, headerGroup.id)) 1013 }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableBody, { children: [isFetching ? /* @__P
1013URE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { 1014 className: "h-1.5 p-0", 1015 colSpan: columnCount, 1016 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Skeleton, { className: "h-full w-full rounded-none bg-gradient-to-l from-primary to-primary-purple" }) 1017 }) }) : null, isLoading ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { 1018 colSpan: columnCount, 1019 className: "h-24 text-center", 1020 children: "Loading..." 1021 }) }) : isEmpty ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { 1022 colSpan: columnCount, 1023 className: "h-24 text-center", 1024 children: emptyMessage 1025 }) }) : table.getRowModel().rows.map((row) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: row.getVisibleCells().map((cell) => { 1026 const tableCellProps = cell.column.columnDef.meta?.tableCellProps ?? {}; 1027 const { className: cellClassName,...restTableCellProps } = tableCellProps; 1028 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { 1029 className: cn(tableCellProps.align === "right" && "text-right", cellClassName), 1030 ...restTableCellProps, 1031 children: flexRender(cell.column.columnDef.cell, cell.getContext()) 1032 }, cell.id); 1033 }) }), expandedIds[row.id] ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { 1034 className: "hover:bg-white", 1035 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { 1036 colSpan: columnCount, 1037 className: "p-0", 1038 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItemsApprovedSubstitutes, { 1039 clientItemMasterId: row.original.client_item_master_id, 1040 erpId: row.original.client_erp_item_id 1041 }) 1042 }) 1043 }) : null] }, row.id))] })] }), 1044 resultSetSize >
1044= pageSize ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ControlledPagination, { 1045 page: pageNumber, 1046 pageSize, 1047 total: resultSetSize, 1048 onPageChange: setPageNumber, 1049 onPageSizeChange: setPageSize, 1050 pageSizeOptions: [ 1051 25, 1052 50, 1053 100 1054 ] 1055 }) : null 1056 ] 1057 }); 1058} 1059function EventOverviewCard({ icon, title, actions, footer, children, className }) { 1060 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Card, { 1061 className: cn("overflow-hidden border-zinc-200 bg-white", className), 1062 children: [ 1063 /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 1064 className: "flex items-center justify-between gap-3 border-b border-zinc-200 bg-indigo-50 px-4 py-2.5", 1065 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 1066 className: "flex items-center gap-2 text-sm font-medium text-zinc-800", 1067 children: [icon, /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h2", { 1068 className: "text-sm font-medium", 1069 children: title 1070 })] 1071 }), actions] 1072 }), 1073 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 1074 className: "px-4 py-4", 1075 children 1076 }), 1077 footer 1078 ] 1079 }); 1080} 1081function formatUpdatePublishedAt(value) { 1082 if (!value) return "Unknown"; 1083 const date = value instanceof Date ? value : new Date(value); 1084 if (Number.isNaN(date.getTime())) return "Unknown"; 1085 return formatDateTimeVerbose(date); 1086} 1087function EventUpdates() { 1088 const updates = useEventDetails()?.event?.updates ?? []; 1089 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventOverviewCard, { 1090 icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Calendar, { size: 16 }), 1091 title: "Event Updates", 1092 children: !updates.length ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 1093 className: "type-body-sm text-center font-medium", 1094 children: "No updates available" 1095 }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 1096 className: "flex flex-col gap-5", 1097 children: updates.map((update) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 1098 className: "flex flex-col gap-2", 1099 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 1100 className: "type-body-sm font-medium", 1101 children: formatUpdatePublishedAt(update.update_published_at) 1102 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 1103 className: "type-body-xs leading-5", 1104 children: update.update_text 1105 })] 1106 }, update.upstream_event_update_id)) 1107 }) 1108 }); 1109} 1110var __defProp = Object.defineProperty; 1111var __exportAll = (all, no_symbols) => { 1112 let target = {}; 1113 for (var name in all) __defProp(target, name, { 1114 get: all[name], 1115 enumerable: true 1116 }); 1117 if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" }); 1118 return target; 1119}; 1120function OrderedMap(content) { 1121 this.content = content; 1122} 1123OrderedMap.prototype = { 1124 constructor: OrderedMap, 1125 find: function(key) { 1126 for (var i$1 = 0; i$1 < this.content.length; i$1 += 2) if (this.content[i$1] === key) return i$1; 1127 return -1; 1128 }, 1129 get: function(key) { 1130 var found$1 = this.find(key); 1131 return found$1 == -1 ? void 0 : this.content[found$1 + 1]; 1132 }, 1133 update: function(key, value, newKey) { 1134 var self = newKey && newKey != key ? this.remove(newKey) : this; 1135 var found$1 = self.find(key), content = self.content.slice(); 1136 if (found$1 == -1) content.push(newKey || key, value); 1137 else { 1138 content[found$1 + 1] = value; 1139 if (newKey) content[found$1] = newKey; 1140 } 1141 return new OrderedMap(content); 1142 }, 1143 remove: function(key) { 1144 var found$1 = this.find(key); 1145 if (found$1 == -1) return this; 1146 var content = this.content.slice(); 1147 content.splice(found$1, 2); 1148 return new OrderedMap(content); 1149 }, 1150 addToStart: function(key, value) { 1151 return new OrderedMap([key, value].concat(this.remove(key).content)); 1152 }, 1153 addToEnd: function(key, value) { 1154 var content = this.remove(key).content.slice(); 1155 content.push(key, value); 1156 return new OrderedMap(content); 1157 }, 1158 addBefore: function(place, key, value) { 1159 var without = this.remove(key), content = without.content.slice(); 1160 var found$1 = without.find(place); 1161 content.splice(found$1 == -1 ? content.length : found$1, 0, key, value); 1162 return new OrderedMap(content); 1163 }, 1164 forEach: function(f) { 1165 for (var i$1 = 0; i$1 < this.content.length; i$1 += 2) f(this.content[i$1], this.content[i$1 + 1]); 1166 }, 1167 prepend: function(map) { 1168 map = OrderedMap.from(map); 1169 if (!map.size) return this; 1170 return new OrderedMap(map.content.concat(this.subtract(map).content)); 1171 }, 1172 append: function(map) { 1173 map = OrderedMap.from(map); 1174 if (!map.size) return this; 1175 return new OrderedMap(this.subtract(map).content.concat(map.content)); 1176 }, 1177 subtract: function(map) { 1178 var result = this; 1179 map = OrderedMap.from(map); 1180 for (var i$1 = 0; i$1 < map.content.length; i$1 += 2) result = result.remove(map.content[i$1]); 1181 return result; 1182 }, 1183 toObject: function() { 1184 var result = {}; 1185 this.forEach(function(key, value) { 1186 result[key] = value; 1187 }); 1188 return result; 1189 }, 1190 get size() { 1191 return this.content.length >> 1; 1192 } 1193}; 1194OrderedMap.from = function(value) { 1195 if (value instanceof OrderedMap) return value; 1196 var content = []; 1197 if (value) for (var prop in value) content.push(prop, value[prop]); 1198 return new OrderedMap(content); 1199}; 1200var dist_default$1 = OrderedMap; 1201function findDiffStart(a, b, pos) { 1202 for (let i$1 = 0;; i$1++) { 1203 if (i$1 == a.childCount || i$1 == b.childCount) return a.childCount == b.childCount ? null : pos; 1204 let childA = a.child(i$1), childB = b.child(i$1); 1205 if (childA == childB) { 1206 pos += childA.nodeSize; 1207 continue; 1208 } 1209 if (!childA.sameMarkup(childB)) return pos; 1210 if (childA.isText && childA.text != childB.text) { 1211 let tA = childA.text, tB = childB.text, j = 0; 1212 for (; tA[j] == tB[j]; j++) pos++; 1213 if (j && j < tA.length && j < tB.length && surrogateHigh(tA.charCodeAt(j - 1)) && surrogateLow(tA.charCodeAt(j))) pos--; 1214 return pos; 1215 } 1216 if (childA.content.size || childB.content.size) { 1217 let inner = findDiffStart(childA.content, childB.content, pos + 1); 1218 if (inner != null) return inner; 1219 } 1220 pos += childA.nodeSize; 1221 } 1222} 1223function findDiffEnd(a, b, posA, posB) { 1224 for (let iA = a.childCount, iB = b.childCount;;) { 1225 if (iA == 0 || iB == 0) return iA == iB ? null : { 1226 a: posA, 1227 b: posB 1228 }; 1229 let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize; 1230 if (childA == childB) { 1231 posA -= size; 1232 posB -= size; 1233 continue; 1234 } 1235 if (!childA.sameMarkup(childB)) return { 1236 a: posA, 1237 b: posB 1238 }; 1239 if (childA.isText && childA.text != childB.text) { 1240 let tA = childA.text, tB = childB.text, iA$1 = tA.length, iB$1 = tB.length; 1241 while (iA$1 > 0 && iB$1 > 0 && tA[iA$1 - 1] == tB[iB$1 - 1]) { 1242 iA$1--; 1243 iB$1--; 1244 posA--; 1245 posB--; 1246 } 1247 if (iA$1 && iB$1 && iA$1 < tA.length && surrogateHigh(tA.charCodeAt(iA$1 - 1)) && surrogateLow(tA.charCodeAt(iA$1))) { 1248 posA++; 1249 posB++; 1250 } 1251 return { 1252 a: posA, 1253 b: posB 1254 }; 1255 } 1256 if (childA.content.size || childB.content.size) { 1257 let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1); 1258 if (inner) return inner; 1259 } 1260 posA -= size; 1261 posB -= size; 1262 } 1263} 1264function surrogateLow(ch) { 1265 return ch >= 56320 && ch < 57344; 1266} 1267function surrogateHigh(ch) { 1268 return ch >= 55296 && ch < 56320; 1269} 1270var Fragment = class Fragment { 1271 constructor(content, size) { 1272 this.content = content; 1273 this.size = size || 0; 1274 if (size == null) for (let i$1 = 0; i$1 < content.length; i$1++) this.size += content[i$1].nodeSize; 1275 } 1276 nodesBetween(from, to, f, nodeStart = 0, parent) { 1277 for (let i$1 = 0, pos = 0; pos < to; i$1++) { 1278 let child = this.content[i$1], end = pos + child.nodeSize; 1279 if (end > from && f(child, nodeStart + pos, parent || null, i$1) !== false && child.content.size) { 1280 let start = pos + 1; 1281 child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start); 1282 } 1283 pos = end; 1284 } 1285 } 1286 descendants(f) { 1287 this.nodesBetween(0, this.size, f); 1288 } 1289 textBetween(from, to, blockSeparator, leafText) { 1290 let text$1 = "", first$1 = true; 1291 this.nodesBetween(from, to, (node, pos) => { 1292 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) : ""; 1293 if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) if (first$1) first$1 = false;
vendor: 24,390 bytes, lines 1294-1995
1294 else text$1 += blockSeparator; 1295 text$1 += nodeText; 1296 }, 0); 1297 return text$1; 1298 } 1299 append(other) { 1300 if (!other.size) return this; 1301 if (!this.size) return other; 1302 let last = this.lastChild, first$1 = other.firstChild, content = this.content.slice(), i$1 = 0; 1303 if (last.isText && last.sameMarkup(first$1)) { 1304 content[content.length - 1] = last.withText(last.text + first$1.text); 1305 i$1 = 1; 1306 } 1307 for (; i$1 < other.content.length; i$1++) content.push(other.content[i$1]); 1308 return new Fragment(content, this.size + other.size); 1309 } 1310 cut(from, to = this.size) { 1311 if (from == 0 && to == this.size) return this; 1312 let result = [], size = 0; 1313 if (to > from) for (let i$1 = 0, pos = 0; pos < to; i$1++) { 1314 let child = this.content[i$1], end = pos + child.nodeSize; 1315 if (end > from) { 1316 if (pos < from || end > to) if (child.isText) child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos)); 1317 else child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1)); 1318 result.push(child); 1319 size += child.nodeSize; 1320 } 1321 pos = end; 1322 } 1323 return new Fragment(result, size); 1324 } 1325 cutByIndex(from, to) { 1326 if (from == to) return Fragment.empty; 1327 if (from == 0 && to == this.content.length) return this; 1328 return new Fragment(this.content.slice(from, to)); 1329 } 1330 replaceChild(index, node) { 1331 let current = this.content[index]; 1332 if (current == node) return this; 1333 let copy$1 = this.content.slice(); 1334 let size = this.size + node.nodeSize - current.nodeSize; 1335 copy$1[index] = node; 1336 return new Fragment(copy$1, size); 1337 } 1338 addToStart(node) { 1339 return new Fragment([node].concat(this.content), this.size + node.nodeSize); 1340 } 1341 addToEnd(node) { 1342 return new Fragment(this.content.concat(node), this.size + node.nodeSize); 1343 } 1344 eq(other) { 1345 if (this.content.length != other.content.length) return false; 1346 for (let i$1 = 0; i$1 < this.content.length; i$1++) if (!this.content[i$1].eq(other.content[i$1])) return false; 1347 return true; 1348 } 1349 get firstChild() { 1350 return this.content.length ? this.content[0] : null; 1351 } 1352 get lastChild() { 1353 return this.content.length ? this.content[this.content.length - 1] : null; 1354 } 1355 get childCount() { 1356 return this.content.length; 1357 } 1358 child(index) { 1359 let found$1 = this.content[index]; 1360 if (!found$1) throw new RangeError("Index " + index + " out of range for " + this); 1361 return found$1; 1362 } 1363 maybeChild(index) { 1364 return this.content[index] || null; 1365 } 1366 forEach(f) { 1367 for (let i$1 = 0, p = 0; i$1 < this.content.length; i$1++) { 1368 let child = this.content[i$1]; 1369 f(child, p, i$1); 1370 p += child.nodeSize; 1371 } 1372 } 1373 findDiffStart(other, pos = 0) { 1374 return findDiffStart(this, other, pos); 1375 } 1376 findDiffEnd(other, pos = this.size, otherPos = other.size) { 1377 return findDiffEnd(this, other, pos, otherPos); 1378 } 1379 findIndex(pos) { 1380 if (pos == 0) return retIndex(0, pos); 1381 if (pos == this.size) return retIndex(this.content.length, pos); 1382 if (pos > this.size || pos < 0) throw new RangeError(`Position ${pos} outside of fragment (${this})`); 1383 for (let i$1 = 0, curPos = 0;; i$1++) { 1384 let cur = this.child(i$1), end = curPos + cur.nodeSize; 1385 if (end >= pos) { 1386 if (end == pos) return retIndex(i$1 + 1, end); 1387 return retIndex(i$1, curPos); 1388 } 1389 curPos = end; 1390 } 1391 } 1392 toString() { 1393 return "<" + this.toStringInner() + ">"; 1394 } 1395 toStringInner() { 1396 return this.content.join(", "); 1397 } 1398 toJSON() { 1399 return this.content.length ? this.content.map((n) => n.toJSON()) : null; 1400 } 1401 static fromJSON(schema, value) { 1402 if (!value) return Fragment.empty; 1403 if (!Array.isArray(value)) throw new RangeError("Invalid input for Fragment.fromJSON"); 1404 return Fragment.fromArray(value.map(schema.nodeFromJSON)); 1405 } 1406 static fromArray(array) { 1407 if (!array.length) return Fragment.empty; 1408 let joined, size = 0; 1409 for (let i$1 = 0; i$1 < array.length; i$1++) { 1410 let node = array[i$1]; 1411 size += node.nodeSize; 1412 if (i$1 && node.isText && array[i$1 - 1].sameMarkup(node)) { 1413 if (!joined) joined = array.slice(0, i$1); 1414 joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text); 1415 } else if (joined) joined.push(node); 1416 } 1417 return new Fragment(joined || array, size); 1418 } 1419 static from(nodes) { 1420 if (!nodes) return Fragment.empty; 1421 if (nodes instanceof Fragment) return nodes; 1422 if (Array.isArray(nodes)) return this.fromArray(nodes); 1423 if (nodes.attrs) return new Fragment([nodes], nodes.nodeSize); 1424 throw new RangeError("Can not convert " + nodes + " to a Fragment" + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : "")); 1425 } 1426}; 1427Fragment.empty = new Fragment([], 0); 1428var found = { 1429 index: 0, 1430 offset: 0 1431}; 1432function retIndex(index, offset) { 1433 found.index = index; 1434 found.offset = offset; 1435 return found; 1436} 1437function compareDeep(a, b) { 1438 if (a === b) return true; 1439 if (!(a && typeof a == "object") || !(b && typeof b == "object")) return false; 1440 let array = Array.isArray(a); 1441 if (Array.isArray(b) != array) return false; 1442 if (array) { 1443 if (a.length != b.length) return false; 1444 for (let i$1 = 0; i$1 < a.length; i$1++) if (!compareDeep(a[i$1], b[i$1])) return false; 1445 } else { 1446 for (let p in a) if (!(p in b) || !compareDeep(a[p], b[p])) return false; 1447 for (let p in b) if (!(p in a)) return false; 1448 } 1449 return true; 1450} 1451var Mark$1 = class Mark$1 { 1452 constructor(type, attrs) { 1453 this.type = type; 1454 this.attrs = attrs; 1455 } 1456 addToSet(set) { 1457 let copy$1, placed = false; 1458 for (let i$1 = 0; i$1 < set.length; i$1++) { 1459 let other = set[i$1]; 1460 if (this.eq(other)) return set; 1461 if (this.type.excludes(other.type)) { 1462 if (!copy$1) copy$1 = set.slice(0, i$1); 1463 } else if (other.type.excludes(this.type)) return set; 1464 else { 1465 if (!placed && other.type.rank > this.type.rank) { 1466 if (!copy$1) copy$1 = set.slice(0, i$1); 1467 copy$1.push(this); 1468 placed = true; 1469 } 1470 if (copy$1) copy$1.push(other); 1471 } 1472 } 1473 if (!copy$1) copy$1 = set.slice(); 1474 if (!placed) copy$1.push(this); 1475 return copy$1; 1476 } 1477 removeFromSet(set) { 1478 for (let i$1 = 0; i$1 < set.length; i$1++) if (this.eq(set[i$1])) return set.slice(0, i$1).concat(set.slice(i$1 + 1)); 1479 return set; 1480 } 1481 isInSet(set) { 1482 for (let i$1 = 0; i$1 < set.length; i$1++) if (this.eq(set[i$1])) return true; 1483 return false; 1484 } 1485 eq(other) { 1486 return this == other || this.type == other.type && compareDeep(this.attrs, other.attrs); 1487 } 1488 toJSON() { 1489 let obj = { type: this.type.name }; 1490 for (let _ in this.attrs) { 1491 obj.attrs = this.attrs; 1492 break; 1493 } 1494 return obj; 1495 } 1496 static fromJSON(schema, json) { 1497 if (!json) throw new RangeError("Invalid input for Mark.fromJSON"); 1498 let type = schema.marks[json.type]; 1499 if (!type) throw new RangeError(`There is no mark type ${json.type} in this schema`); 1500 let mark = type.create(json.attrs); 1501 type.checkAttrs(mark.attrs); 1502 return mark; 1503 } 1504 static sameSet(a, b) { 1505 if (a == b) return true; 1506 if (a.length != b.length) return false; 1507 for (let i$1 = 0; i$1 < a.length; i$1++) if (!a[i$1].eq(b[i$1])) return false; 1508 return true; 1509 } 1510 static setFrom(marks) { 1511 if (!marks || Array.isArray(marks) && marks.length == 0) return Mark$1.none; 1512 if (marks instanceof Mark$1) return [marks]; 1513 let copy$1 = marks.slice(); 1514 copy$1.sort((a, b) => a.type.rank - b.type.rank); 1515 return copy$1; 1516 } 1517}; 1518Mark$1.none = []; 1519var ReplaceError = class extends Error {}; 1520var Slice = class Slice { 1521 constructor(content, openStart, openEnd) { 1522 this.content = content; 1523 this.openStart = openStart; 1524 this.openEnd = openEnd; 1525 } 1526 get size() { 1527 return this.content.size - this.openStart - this.openEnd; 1528 } 1529 insertAt(pos, fragment) { 1530 let content = insertInto(this.content, pos + this.openStart, fragment, this.openStart + 1, this.openEnd + 1); 1531 return content && new Slice(content, this.openStart, this.openEnd); 1532 } 1533 removeBetween(from, to) { 1534 return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd); 1535 } 1536 eq(other) { 1537 return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd; 1538 } 1539 toString() { 1540 return this.content + "(" + this.openStart + "," + this.openEnd + ")"; 1541 } 1542 toJSON() { 1543 if (!this.content.size) return null; 1544 let json = { content: this.content.toJSON() }; 1545 if (this.openStart > 0) json.openStart = this.openStart; 1546 if (this.openEnd > 0) json.openEnd = this.openEnd; 1547 return json; 1548 } 1549 static fromJSON(schema, json) { 1550 if (!json) return Slice.empty; 1551 let openStart = json.openStart || 0, openEnd = json.openEnd || 0; 1552 if (typeof openStart != "number" || typeof openEnd != "number") throw new RangeError("Invalid input for Slice.fromJSON"); 1553 return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd); 1554 } 1555 static maxOpen(fragment, openIsolating = true) { 1556 let openStart = 0, openEnd = 0; 1557 for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild) openStart++; 1558 for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild) openEnd++; 1559 return new Slice(fragment, openStart, openEnd); 1560 } 1561}; 1562Slice.empty = new Slice(Fragment.empty, 0, 0); 1563function removeRange(content, from, to) { 1564 let { index, offset } = content.findIndex(from), child = content.maybeChild(index); 1565 let { index: indexTo, offset: offsetTo } = content.findIndex(to); 1566 if (offset == from || child.isText) { 1567 if (offsetTo != to && !content.child(indexTo).isText) throw new RangeError("Removing non-flat range"); 1568 return content.cut(0, from).append(content.cut(to)); 1569 } 1570 if (index != indexTo) throw new RangeError("Removing non-flat range"); 1571 return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1))); 1572} 1573function insertInto(content, dist, insert, openStart, openEnd, parent) { 1574 let { index, offset } = content.findIndex(dist), child = content.maybeChild(index); 1575 if (offset == dist || child.isText) { 1576 if (parent && openStart <= 0 && openEnd <= 0 && !parent.canReplace(index, index, insert)) return null; 1577 return content.cut(0, dist).append(insert).append(content.cut(dist)); 1578 } 1579 let inner = insertInto(child.content, dist - offset - 1, insert, index == 0 ? openStart - 1 : 0, index == content.childCount - 1 ? openEnd - 1 : 0, child); 1580 return inner && content.replaceChild(index, child.copy(inner)); 1581} 1582function replace($from, $to, slice) { 1583 if (slice.openStart > $from.depth) throw new ReplaceError("Inserted content deeper than insertion position"); 1584 if ($from.depth - slice.openStart != $to.depth - slice.openEnd) throw new ReplaceError("Inconsistent open depths"); 1585 return replaceOuter($from, $to, slice, 0); 1586} 1587function replaceOuter($from, $to, slice, depth) { 1588 let index = $from.index(depth), node = $from.node(depth); 1589 if (index == $to.index(depth) && depth < $from.depth - slice.openStart) { 1590 let inner = replaceOuter($from, $to, slice, depth + 1); 1591 return node.copy(node.content.replaceChild(index, inner)); 1592 } else if (!slice.content.size) return close(node, replaceTwoWay($from, $to, depth)); 1593 else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { 1594 let parent = $from.parent, content = parent.content; 1595 return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset))); 1596 } else { 1597 let { start, end } = prepareSliceForReplace(slice, $from); 1598 return close(node, replaceThreeWay($from, start, end, $to, depth)); 1599 } 1600} 1601function checkJoin(main, sub) { 1602 if (!sub.type.compatibleContent(main.type)) throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name); 1603} 1604function joinable$1($before, $after, depth) { 1605 let node = $before.node(depth); 1606 checkJoin(node, $after.node(depth)); 1607 return node; 1608} 1609function addNode(child, target) { 1610 let last = target.length - 1; 1611 if (last >= 0 && child.isText && child.sameMarkup(target[last])) target[last] = child.withText(target[last].text + child.text); 1612 else target.push(child); 1613} 1614function addRange($start, $end, depth, target) { 1615 let node = ($end || $start).node(depth); 1616 let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount; 1617 if ($start) { 1618 startIndex = $start.index(depth); 1619 if ($start.depth > depth) startIndex++; 1620 else if ($start.textOffset) { 1621 addNode($start.nodeAfter, target); 1622 startIndex++; 1623 } 1624 } 1625 for (let i$1 = startIndex; i$1 < endIndex; i$1++) addNode(node.child(i$1), target); 1626 if ($end && $end.depth == depth && $end.textOffset) addNode($end.nodeBefore, target); 1627} 1628function close(node, content) { 1629 if (!node.type.validContent(content)) throw new ReplaceError("Invalid content for node " + node.type.name); 1630 return node.copy(content); 1631} 1632function replaceThreeWay($from, $start, $end, $to, depth) { 1633 let openStart = $from.depth > depth && joinable$1($from, $start, depth + 1); 1634 let openEnd = $to.depth > depth && joinable$1($end, $to, depth + 1); 1635 let content = []; 1636 addRange(null, $from, depth, content); 1637 if (openStart && openEnd && $start.index(depth) == $end.index(depth)) { 1638 checkJoin(openStart, openEnd); 1639 addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content); 1640 } else { 1641 if (openStart) addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content); 1642 addRange($start, $end, depth, content); 1643 if (openEnd) addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content); 1644 } 1645 addRange($to, null, depth, content); 1646 return new Fragment(content); 1647} 1648function replaceTwoWay($from, $to, depth) { 1649 let content = []; 1650 addRange(null, $from, depth, content); 1651 if ($from.depth > depth) addNode(close(joinable$1($from, $to, depth + 1), replaceTwoWay($from, $to, depth + 1)), content); 1652 addRange($to, null, depth, content); 1653 return new Fragment(content); 1654} 1655function prepareSliceForReplace(slice, $along) { 1656 let extra = $along.depth - slice.openStart; 1657 let node = $along.node(extra).copy(slice.content); 1658 for (let i$1 = extra - 1; i$1 >= 0; i$1--) node = $along.node(i$1).copy(Fragment.from(node)); 1659 return { 1660 start: node.resolveNoCache(slice.openStart + extra), 1661 end: node.resolveNoCache(node.content.size - slice.openEnd - extra) 1662 }; 1663} 1664var ResolvedPos = class ResolvedPos { 1665 constructor(pos, path, parentOffset) { 1666 this.pos = pos; 1667 this.path = path; 1668 this.parentOffset = parentOffset; 1669 this.depth = path.length / 3 - 1; 1670 } 1671 resolveDepth(val) { 1672 if (val == null) return this.depth; 1673 if (val < 0) return this.depth + val; 1674 return val; 1675 } 1676 get parent() { 1677 return this.node(this.depth); 1678 } 1679 get doc() { 1680 return this.node(0); 1681 } 1682 node(depth) { 1683 return this.path[this.resolveDepth(depth) * 3]; 1684 } 1685 index(depth) { 1686 return this.path[this.resolveDepth(depth) * 3 + 1]; 1687 } 1688 indexAfter(depth) { 1689 depth = this.resolveDepth(depth); 1690 return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1); 1691 } 1692 start(depth) { 1693 depth = this.resolveDepth(depth); 1694 return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1; 1695 } 1696 end(depth) { 1697 depth = this.resolveDepth(depth); 1698 return this.start(depth) + this.node(depth).content.size; 1699 } 1700 before(depth) { 1701 depth = this.resolveDepth(depth); 1702 if (!depth) throw new RangeError("There is no position before the top-level node"); 1703 return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1]; 1704 } 1705 after(depth) { 1706 depth = this.resolveDepth(depth); 1707 if (!depth) throw new RangeError("There is no position after the top-level node"); 1708 return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize; 1709 } 1710 get textOffset() { 1711 return this.pos - this.path[this.path.length - 1]; 1712 } 1713 get nodeAfter() { 1714 let parent = this.parent, index = this.index(this.depth); 1715 if (index == parent.childCount) return null; 1716 let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index); 1717 return dOff ? parent.child(index).cut(dOff) : child; 1718 } 1719 get nodeBefore() { 1720 let index = this.index(this.depth); 1721 let dOff = this.pos - this.path[this.path.length - 1]; 1722 if (dOff) return this.parent.child(index).cut(0, dOff); 1723 return index == 0 ? null : this.parent.child(index - 1); 1724 } 1725 posAtIndex(index, depth) { 1726 depth = this.resolveDepth(depth); 1727 let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1; 1728 for (let i$1 = 0; i$1 < index; i$1++) pos += node.child(i$1).nodeSize; 1729 return pos; 1730 } 1731 marks() { 1732 let parent = this.parent, index = this.index(); 1733 if (parent.content.size == 0) return Mark$1.none; 1734 if (this.textOffset) return parent.child(index).marks; 1735 let main = parent.maybeChild(index - 1), other = parent.maybeChild(index); 1736 if (!main) { 1737 let tmp = main; 1738 main = other; 1739 other = tmp; 1740 } 1741 let marks = main.marks; 1742 for (var i$1 = 0; i$1 < marks.length; i$1++) if (marks[i$1].type.spec.inclusive === false && (!other || !marks[i$1].isInSet(other.marks))) marks = marks[i$1--].removeFromSet(marks); 1743 return marks; 1744 } 1745 marksAcross($end) { 1746 let after = this.parent.maybeChild(this.index()); 1747 if (!after || !after.isInline) return null; 1748 let marks = after.marks, next = $end.parent.maybeChild($end.index()); 1749 for (var i$1 = 0; i$1 < marks.length; i$1++) if (marks[i$1].type.spec.inclusive === false && (!next || !marks[i$1].isInSet(next.marks))) marks = marks[i$1--].removeFromSet(marks); 1750 return marks; 1751 } 1752 sharedDepth(pos) { 1753 for (let depth = this.depth; depth > 0; depth--) if (this.start(depth) <= pos && this.end(depth) >= pos) return depth; 1754 return 0; 1755 } 1756 blockRange(other = this, pred) { 1757 if (other.pos < this.pos) return other.blockRange(this); 1758 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); 1759 return null; 1760 } 1761 sameParent(other) { 1762 return this.pos - this.parentOffset == other.pos - other.parentOffset; 1763 } 1764 max(other) { 1765 return other.pos > this.pos ? other : this; 1766 } 1767 min(other) { 1768 return other.pos < this.pos ? other : this; 1769 } 1770 toString() { 1771 let str = ""; 1772 for (let i$1 = 1; i$1 <= this.depth; i$1++) str += (str ? "/" : "") + this.node(i$1).type.name + "_" + this.index(i$1 - 1); 1773 return str + ":" + this.parentOffset; 1774 } 1775 static resolve(doc$2, pos) { 1776 if (!(pos >= 0 && pos <= doc$2.content.size)) throw new RangeError("Position " + pos + " out of range"); 1777 let path = []; 1778 let start = 0, parentOffset = pos; 1779 for (let node = doc$2;;) { 1780 let { index, offset } = node.content.findIndex(parentOffset); 1781 let rem = parentOffset - offset; 1782 path.push(node, index, start + offset); 1783 if (!rem) break; 1784 node = node.child(index); 1785 if (node.isText) break; 1786 parentOffset = rem - 1; 1787 start += offset + 1; 1788 } 1789 return new ResolvedPos(pos, path, parentOffset); 1790 } 1791 static resolveCached(doc$2, pos) { 1792 let cache = resolveCache.get(doc$2); 1793 if (cache) for (let i$1 = 0; i$1 < cache.elts.length; i$1++) { 1794 let elt = cache.elts[i$1]; 1795 if (elt.pos == pos) return elt; 1796 } 1797 else resolveCache.set(doc$2, cache = new ResolveCache()); 1798 let result = cache.elts[cache.i] = ResolvedPos.resolve(doc$2, pos); 1799 cache.i = (cache.i + 1) % resolveCacheSize; 1800 return result; 1801 } 1802}; 1803var ResolveCache = class { 1804 constructor() { 1805 this.elts = []; 1806 this.i = 0; 1807 } 1808}; 1809var resolveCacheSize = 12, resolveCache = /* @__PURE__ */ new WeakMap(); 1810var NodeRange = class { 1811 constructor($from, $to, depth) { 1812 this.$from = $from; 1813 this.$to = $to; 1814 this.depth = depth; 1815 } 1816 get start() { 1817 return this.$from.before(this.depth + 1); 1818 } 1819 get end() { 1820 return this.$to.after(this.depth + 1); 1821 } 1822 get parent() { 1823 return this.$from.node(this.depth); 1824 } 1825 get startIndex() { 1826 return this.$from.index(this.depth); 1827 } 1828 get endIndex() { 1829 return this.$to.indexAfter(this.depth); 1830 } 1831}; 1832var emptyAttrs = Object.create(null); 1833var Node$1 = class Node$1 { 1834 constructor(type, attrs, content, marks = Mark$1.none) { 1835 this.type = type; 1836 this.attrs = attrs; 1837 this.marks = marks; 1838 this.content = content || Fragment.empty; 1839 } 1840 get children() { 1841 return this.content.content; 1842 } 1843 get nodeSize() { 1844 return this.isLeaf ? 1 : 2 + this.content.size; 1845 } 1846 get childCount() { 1847 return this.content.childCount; 1848 } 1849 child(index) { 1850 return this.content.child(index); 1851 } 1852 maybeChild(index) { 1853 return this.content.maybeChild(index); 1854 } 1855 forEach(f) { 1856 this.content.forEach(f); 1857 } 1858 nodesBetween(from, to, f, startPos = 0) { 1859 this.content.nodesBetween(from, to, f, startPos, this); 1860 } 1861 descendants(f) { 1862 this.nodesBetween(0, this.content.size, f); 1863 } 1864 get textContent() { 1865 return this.isLeaf && this.type.spec.leafText ? this.type.spec.leafText(this) : this.textBetween(0, this.content.size, ""); 1866 } 1867 textBetween(from, to, blockSeparator, leafText) { 1868 return this.content.textBetween(from, to, blockSeparator, leafText); 1869 } 1870 get firstChild() { 1871 return this.content.firstChild; 1872 } 1873 get lastChild() { 1874 return this.content.lastChild; 1875 } 1876 eq(other) { 1877 return this == other || this.sameMarkup(other) && this.content.eq(other.content); 1878 } 1879 sameMarkup(other) { 1880 return this.hasMarkup(other.type, other.attrs, other.marks); 1881 } 1882 hasMarkup(type, attrs, marks) { 1883 return this.type == type && compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && Mark$1.sameSet(this.marks, marks || Mark$1.none); 1884 } 1885 copy(content = null) { 1886 if (content == this.content) return this; 1887 return new Node$1(this.type, this.attrs, content, this.marks); 1888 } 1889 mark(marks) { 1890 return marks == this.marks ? this : new Node$1(this.type, this.attrs, this.content, marks); 1891 } 1892 cut(from, to = this.content.size) { 1893 if (from == 0 && to == this.content.size) return this; 1894 return this.copy(this.content.cut(from, to)); 1895 } 1896 slice(from, to = this.content.size, includeParents = false) { 1897 if (from == to) return Slice.empty; 1898 let $from = this.resolve(from), $to = this.resolve(to); 1899 let depth = includeParents ? 0 : $from.sharedDepth(to); 1900 let start = $from.start(depth); 1901 return new Slice($from.node(depth).content.cut($from.pos - start, $to.pos - start), $from.depth - depth, $to.depth - depth); 1902 } 1903 replace(from, to, slice) { 1904 return replace(this.resolve(from), this.resolve(to), slice); 1905 } 1906 nodeAt(pos) { 1907 for (let node = this;;) { 1908 let { index, offset } = node.content.findIndex(pos); 1909 node = node.maybeChild(index); 1910 if (!node) return null; 1911 if (offset == pos || node.isText) return node; 1912 pos -= offset + 1; 1913 } 1914 } 1915 childAfter(pos) { 1916 let { index, offset } = this.content.findIndex(pos); 1917 return { 1918 node: this.content.maybeChild(index), 1919 index, 1920 offset 1921 }; 1922 } 1923 childBefore(pos) { 1924 if (pos == 0) return { 1925 node: null, 1926 index: 0, 1927 offset: 0 1928 }; 1929 let { index, offset } = this.content.findIndex(pos); 1930 if (offset < pos) return { 1931 node: this.content.child(index), 1932 index, 1933 offset 1934 }; 1935 let node = this.content.child(index - 1); 1936 return { 1937 node, 1938 index: index - 1, 1939 offset: offset - node.nodeSize 1940 }; 1941 } 1942 resolve(pos) { 1943 return ResolvedPos.resolveCached(this, pos); 1944 } 1945 resolveNoCache(pos) { 1946 return ResolvedPos.resolve(this, pos); 1947 } 1948 rangeHasMark(from, to, type) { 1949 let found$1 = false; 1950 if (to > from) this.nodesBetween(from, to, (node) => { 1951 if (type.isInSet(node.marks)) found$1 = true; 1952 return !found$1; 1953 }); 1954 return found$1; 1955 } 1956 get isBlock() { 1957 return this.type.isBlock; 1958 } 1959 get isTextblock() { 1960 return this.type.isTextblock; 1961 } 1962 get inlineContent() { 1963 return this.type.inlineContent; 1964 } 1965 get isInline() { 1966 return this.type.isInline; 1967 } 1968 get isText() { 1969 return this.type.isText; 1970 } 1971 get isLeaf() { 1972 return this.type.isLeaf; 1973 } 1974 get isAtom() { 1975 return this.type.isAtom; 1976 } 1977 toString() { 1978 if (this.type.spec.toDebugString) return this.type.spec.toDebugString(this); 1979 let name = this.type.name; 1980 if (this.content.size) name += "(" + this.content.toStringInner() + ")"; 1981 return wrapMarks(this.marks, name); 1982 } 1983 contentMatchAt(index) { 1984 let match = this.type.contentMatch.matchFragment(this.content, 0, index); 1985 if (!match) throw new Error("Called contentMatchAt on a node with invalid content"); 1986 return match; 1987 } 1988 canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) { 1989 let one = this.contentMatchAt(from).matchFragment(replacement, start, end); 1990 let two = one && one.matchFragment(this.content, to); 1991 if (!two || !two.validEnd) return false; 1992 for (let i$1 = start; i$1 < end; i$1++) if (!this.type.allowsMarks(replacement.child(i$1).marks)) return false; 1993 return true; 1994 } 1995 canReplaceWith(from, to, type, marks) {
vendor: 4,331 bytes, lines 1996-2124
1996 if (marks && !this.type.allowsMarks(marks)) return false; 1997 let start = this.contentMatchAt(from).matchType(type); 1998 let end = start && start.matchFragment(this.content, to); 1999 return end ? end.validEnd : false; 2000 } 2001 canAppend(other) { 2002 if (other.content.size) return this.canReplace(this.childCount, this.childCount, other.content); 2003 else return this.type.compatibleContent(other.type); 2004 } 2005 check() { 2006 this.type.checkContent(this.content); 2007 this.type.checkAttrs(this.attrs); 2008 let copy$1 = Mark$1.none; 2009 for (let i$1 = 0; i$1 < this.marks.length; i$1++) { 2010 let mark = this.marks[i$1]; 2011 mark.type.checkAttrs(mark.attrs); 2012 copy$1 = mark.addToSet(copy$1); 2013 } 2014 if (!Mark$1.sameSet(copy$1, this.marks)) throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((m) => m.type.name)}`); 2015 this.content.forEach((node) => node.check()); 2016 } 2017 toJSON() { 2018 let obj = { type: this.type.name }; 2019 for (let _ in this.attrs) { 2020 obj.attrs = this.attrs; 2021 break; 2022 } 2023 if (this.content.size) obj.content = this.content.toJSON(); 2024 if (this.marks.length) obj.marks = this.marks.map((n) => n.toJSON()); 2025 return obj; 2026 } 2027 static fromJSON(schema, json) { 2028 if (!json) throw new RangeError("Invalid input for Node.fromJSON"); 2029 let marks = void 0; 2030 if (json.marks) { 2031 if (!Array.isArray(json.marks)) throw new RangeError("Invalid mark data for Node.fromJSON"); 2032 marks = json.marks.map(schema.markFromJSON); 2033 } 2034 if (json.type == "text") { 2035 if (typeof json.text != "string") throw new RangeError("Invalid text node in JSON"); 2036 return schema.text(json.text, marks); 2037 } 2038 let content = Fragment.fromJSON(schema, json.content); 2039 let node = schema.nodeType(json.type).create(json.attrs, content, marks); 2040 node.type.checkAttrs(node.attrs); 2041 return node; 2042 } 2043}; 2044Node$1.prototype.text = void 0; 2045var TextNode = class TextNode extends Node$1 { 2046 constructor(type, attrs, content, marks) { 2047 super(type, attrs, null, marks); 2048 if (!content) throw new RangeError("Empty text nodes are not allowed"); 2049 this.text = content; 2050 } 2051 toString() { 2052 if (this.type.spec.toDebugString) return this.type.spec.toDebugString(this); 2053 return wrapMarks(this.marks, JSON.stringify(this.text)); 2054 } 2055 get textContent() { 2056 return this.text; 2057 } 2058 textBetween(from, to) { 2059 return this.text.slice(from, to); 2060 } 2061 get nodeSize() { 2062 return this.text.length; 2063 } 2064 mark(marks) { 2065 return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks); 2066 } 2067 withText(text$1) { 2068 if (text$1 == this.text) return this; 2069 return new TextNode(this.type, this.attrs, text$1, this.marks); 2070 } 2071 cut(from = 0, to = this.text.length) { 2072 if (from == 0 && to == this.text.length) return this; 2073 return this.withText(this.text.slice(from, to)); 2074 } 2075 eq(other) { 2076 return this.sameMarkup(other) && this.text == other.text; 2077 } 2078 toJSON() { 2079 let base$1 = super.toJSON(); 2080 base$1.text = this.text; 2081 return base$1; 2082 } 2083}; 2084function wrapMarks(marks, str) { 2085 for (let i$1 = marks.length - 1; i$1 >= 0; i$1--) str = marks[i$1].type.name + "(" + str + ")"; 2086 return str; 2087} 2088var ContentMatch = class ContentMatch { 2089 constructor(validEnd) { 2090 this.validEnd = validEnd; 2091 this.next = []; 2092 this.wrapCache = []; 2093 } 2094 static parse(string, nodeTypes) { 2095 let stream = new TokenStream(string, nodeTypes); 2096 if (stream.next == null) return ContentMatch.empty; 2097 let expr = parseExpr(stream); 2098 if (stream.next) stream.err("Unexpected trailing text"); 2099 let match = dfa(nfa(expr)); 2100 checkForDeadEnds(match, stream); 2101 return match; 2102 } 2103 matchType(type) { 2104 for (let i$1 = 0; i$1 < this.next.length; i$1++) if (this.next[i$1].type == type) return this.next[i$1].next; 2105 return null; 2106 } 2107 matchFragment(frag, start = 0, end = frag.childCount) { 2108 let cur = this; 2109 for (let i$1 = start; cur && i$1 < end; i$1++) cur = cur.matchType(frag.child(i$1).type); 2110 return cur; 2111 } 2112 get inlineContent() { 2113 return this.next.length != 0 && this.next[0].type.isInline; 2114 } 2115 get defaultType() { 2116 for (let i$1 = 0; i$1 < this.next.length; i$1++) { 2117 let { type } = this.next[i$1]; 2118 if (!(type.isText || type.hasRequiredAttrs())) return type; 2119 } 2120 return null; 2121 } 2122 compatible(other) { 2123 for (let i$1 = 0; i$1 < this.next.length; i$1++) for (let j = 0; j < other.next.length; j++) if (this.next[i$1].type == other.next[j].type) return true; 2124 return false;
vendor: 5,355 bytes, lines 2125-2321
2125 } 2126 fillBefore(after, toEnd = false, startIndex = 0) { 2127 let seen = [this]; 2128 function search(match, types) { 2129 let finished = match.matchFragment(after, startIndex); 2130 if (finished && (!toEnd || finished.validEnd)) return Fragment.from(types.map((tp) => tp.createAndFill())); 2131 for (let i$1 = 0; i$1 < match.next.length; i$1++) { 2132 let { type, next } = match.next[i$1]; 2133 if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) { 2134 seen.push(next); 2135 let found$1 = search(next, types.concat(type)); 2136 if (found$1) return found$1; 2137 } 2138 } 2139 return null; 2140 } 2141 return search(this, []); 2142 } 2143 findWrapping(target) { 2144 for (let i$1 = 0; i$1 < this.wrapCache.length; i$1 += 2) if (this.wrapCache[i$1] == target) return this.wrapCache[i$1 + 1]; 2145 let computed = this.computeWrapping(target); 2146 this.wrapCache.push(target, computed); 2147 return computed; 2148 } 2149 computeWrapping(target) { 2150 let seen = Object.create(null), active = [{ 2151 match: this, 2152 type: null, 2153 via: null 2154 }]; 2155 while (active.length) { 2156 let current = active.shift(), match = current.match; 2157 if (match.matchType(target)) { 2158 let result = []; 2159 for (let obj = current; obj.type; obj = obj.via) result.push(obj.type); 2160 return result.reverse(); 2161 } 2162 for (let i$1 = 0; i$1 < match.next.length; i$1++) { 2163 let { type, next } = match.next[i$1]; 2164 if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) { 2165 active.push({ 2166 match: type.contentMatch, 2167 type, 2168 via: current 2169 }); 2170 seen[type.name] = true; 2171 } 2172 } 2173 } 2174 return null; 2175 } 2176 get edgeCount() { 2177 return this.next.length; 2178 } 2179 edge(n) { 2180 if (n >= this.next.length) throw new RangeError(`There's no ${n}th edge in this content match`); 2181 return this.next[n]; 2182 } 2183 toString() { 2184 let seen = []; 2185 function scan(m) { 2186 seen.push(m); 2187 for (let i$1 = 0; i$1 < m.next.length; i$1++) if (seen.indexOf(m.next[i$1].next) == -1) scan(m.next[i$1].next); 2188 } 2189 scan(this); 2190 return seen.map((m, i$1) => { 2191 let out = i$1 + (m.validEnd ? "*" : " ") + " "; 2192 for (let i$2 = 0; i$2 < m.next.length; i$2++) out += (i$2 ? ", " : "") + m.next[i$2].type.name + "->" + seen.indexOf(m.next[i$2].next); 2193 return out; 2194 }).join("\n"); 2195 } 2196}; 2197ContentMatch.empty = new ContentMatch(true); 2198var TokenStream = class { 2199 constructor(string, nodeTypes) { 2200 this.string = string; 2201 this.nodeTypes = nodeTypes; 2202 this.inline = null; 2203 this.pos = 0; 2204 this.tokens = string.split(/\s*(?=\b|\W|$)/); 2205 if (this.tokens[this.tokens.length - 1] == "") this.tokens.pop(); 2206 if (this.tokens[0] == "") this.tokens.shift(); 2207 } 2208 get next() { 2209 return this.tokens[this.pos]; 2210 } 2211 eat(tok) { 2212 return this.next == tok && (this.pos++ || true); 2213 } 2214 err(str) { 2215 throw new SyntaxError(str + " (in content expression '" + this.string + "')"); 2216 } 2217}; 2218function parseExpr(stream) { 2219 let exprs = []; 2220 do 2221 exprs.push(parseExprSeq(stream)); 2222 while (stream.eat("|")); 2223 return exprs.length == 1 ? exprs[0] : { 2224 type: "choice", 2225 exprs 2226 }; 2227} 2228function parseExprSeq(stream) { 2229 let exprs = []; 2230 do 2231 exprs.push(parseExprSubscript(stream)); 2232 while (stream.next && stream.next != ")" && stream.next != "|"); 2233 return exprs.length == 1 ? exprs[0] : { 2234 type: "seq", 2235 exprs 2236 }; 2237} 2238function parseExprSubscript(stream) { 2239 let expr = parseExprAtom(stream); 2240 for (;;) if (stream.eat("+")) expr = { 2241 type: "plus", 2242 expr 2243 }; 2244 else if (stream.eat("*")) expr = { 2245 type: "star", 2246 expr 2247 }; 2248 else if (stream.eat("?")) expr = { 2249 type: "opt", 2250 expr 2251 }; 2252 else if (stream.eat("{")) expr = parseExprRange(stream, expr); 2253 else break; 2254 return expr; 2255} 2256function parseNum(stream) { 2257 if (/\D/.test(stream.next)) stream.err("Expected number, got '" + stream.next + "'"); 2258 let result = Number(stream.next); 2259 stream.pos++; 2260 return result; 2261} 2262function parseExprRange(stream, expr) { 2263 let min = parseNum(stream), max = min; 2264 if (stream.eat(",")) if (stream.next != "}") max = parseNum(stream); 2265 else max = -1; 2266 if (!stream.eat("}")) stream.err("Unclosed braced range"); 2267 return { 2268 type: "range", 2269 min, 2270 max, 2271 expr 2272 }; 2273} 2274function resolveName(stream, name) { 2275 let types = stream.nodeTypes, type = types[name]; 2276 if (type) return [type]; 2277 let result = []; 2278 for (let typeName in types) { 2279 let type$1 = types[typeName]; 2280 if (type$1.isInGroup(name)) result.push(type$1); 2281 } 2282 if (result.length == 0) stream.err("No node type or group '" + name + "' found"); 2283 return result; 2284} 2285function parseExprAtom(stream) { 2286 if (stream.eat("(")) { 2287 let expr = parseExpr(stream); 2288 if (!stream.eat(")")) stream.err("Missing closing paren"); 2289 return expr; 2290 } else if (!/\W/.test(stream.next)) { 2291 let exprs = resolveName(stream, stream.next).map((type) => { 2292 if (stream.inline == null) stream.inline = type.isInline; 2293 else if (stream.inline != type.isInline) stream.err("Mixing inline and block content"); 2294 return { 2295 type: "name", 2296 value: type 2297 }; 2298 }); 2299 stream.pos++; 2300 return exprs.length == 1 ? exprs[0] : { 2301 type: "choice", 2302 exprs 2303 }; 2304 } else stream.err("Unexpected token '" + stream.next + "'"); 2305} 2306function nfa(expr) { 2307 let nfa$1 = [[]]; 2308 connect(compile(expr, 0), node()); 2309 return nfa$1; 2310 function node() { 2311 return nfa$1.push([]) - 1; 2312 } 2313 function edge(from, to, term) { 2314 let edge$1 = { 2315 term, 2316 to 2317 }; 2318 nfa$1[from].push(edge$1); 2319 return edge$1; 2320 } 2321 function connect(edges, to) {
2322 edges.forEach((edge$1) => edge$1.to = to); 2323 } 2324 function compile(expr$1, from) { 2325 if (expr$1.type == "choice") return expr$1.exprs.reduce((out, expr$2) => out.concat(compile(expr$2, from)), []); 2326 else if (expr$1.type == "seq") for (let i$1 = 0;; i$1++) { 2327 let next = compile(expr$1.exprs[i$1], from); 2328 if (i$1 == expr$1.exprs.length - 1) return next; 2329 connect(next, from = node()); 2330 } 2331 else if (expr$1.type == "star") { 2332 let loop = node(); 2333 edge(from, loop); 2334 connect(compile(expr$1.expr, loop), loop); 2335 return [edge(loop)]; 2336 } else if (expr$1.type == "plus") { 2337 let loop = node(); 2338 connect(compile(expr$1.expr, from), loop); 2339 connect(compile(expr$1.expr, loop), loop); 2340 return [edge(loop)]; 2341 } else if (expr$1.type == "opt") return [edge(from)].concat(compile(expr$1.expr, from)); 2342 else if (expr$1.type == "range") { 2343 let cur = from; 2344 for (let i$1 = 0; i$1 < expr$1.min; i$1++) { 2345 let next = node(); 2346 connect(compile(expr$1.expr, cur), next); 2347 cur = next; 2348 } 2349 if (expr$1.max == -1) connect(compile(expr$1.expr, cur), cur); 2350 else for (let i$1 = expr$1.min; i$1 < expr$1.max; i$1++) { 2351 let next = node(); 2352 edge(cur, next); 2353 connect(compile(expr$1.expr, cur), next); 2354 cur = next; 2355 } 2356 return [edge(cur)]; 2357 } else if (expr$1.type == "name") return [edge(from, void 0, expr$1.value)]; 2358 else throw new Error("Unknown expr type"); 2359 } 2360} 2361function cmp(a, b) { 2362 return b - a; 2363} 2364function nullFrom(nfa$1, node) { 2365 let result = []; 2366 scan(node); 2367 return result.sort(cmp); 2368 function scan(node$1) { 2369 let edges = nfa$1[node$1]; 2370 if (edges.length == 1 && !edges[0].term) return scan(edges[0].to); 2371 result.push(node$1); 2372 for (let i$1 = 0; i$1 < edges.length; i$1++) { 2373 let { term, to } = edges[i$1]; 2374 if (!term && result.indexOf(to) == -1) scan(to); 2375 } 2376 } 2377} 2378function dfa(nfa$1) { 2379 let labeled = Object.create(null); 2380 return explore(nullFrom(nfa$1, 0)); 2381 function explore(states) { 2382 let out = []; 2383 states.forEach((node) => { 2384 nfa$1[node].forEach(({ term, to }) => { 2385 if (!term) return; 2386 let set; 2387 for (let i$1 = 0; i$1 < out.length; i$1++) if (out[i$1][0] == term) set = out[i$1][1];
vendor: 9,267 bytes, lines 2388-2631
2388 nullFrom(nfa$1, to).forEach((node$1) => { 2389 if (!set) out.push([term, set = []]); 2390 if (set.indexOf(node$1) == -1) set.push(node$1); 2391 }); 2392 }); 2393 }); 2394 let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa$1.length - 1) > -1); 2395 for (let i$1 = 0; i$1 < out.length; i$1++) { 2396 let states$1 = out[i$1][1].sort(cmp); 2397 state.next.push({ 2398 type: out[i$1][0], 2399 next: labeled[states$1.join(",")] || explore(states$1) 2400 }); 2401 } 2402 return state; 2403 } 2404} 2405function checkForDeadEnds(match, stream) { 2406 for (let i$1 = 0, work = [match]; i$1 < work.length; i$1++) { 2407 let state = work[i$1], dead = !state.validEnd, nodes = []; 2408 for (let j = 0; j < state.next.length; j++) { 2409 let { type, next } = state.next[j]; 2410 nodes.push(type.name); 2411 if (dead && !(type.isText || type.hasRequiredAttrs())) dead = false; 2412 if (work.indexOf(next) == -1) work.push(next); 2413 } 2414 if (dead) stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)"); 2415 } 2416} 2417function defaultAttrs(attrs) { 2418 let defaults$1 = Object.create(null); 2419 for (let attrName in attrs) { 2420 let attr = attrs[attrName]; 2421 if (!attr.hasDefault) return null; 2422 defaults$1[attrName] = attr.default; 2423 } 2424 return defaults$1; 2425} 2426function computeAttrs(attrs, value) { 2427 let built = Object.create(null); 2428 for (let name in attrs) { 2429 let given = value && value[name]; 2430 if (given === void 0) { 2431 let attr = attrs[name]; 2432 if (attr.hasDefault) given = attr.default; 2433 else throw new RangeError("No value supplied for attribute " + name); 2434 } 2435 built[name] = given; 2436 } 2437 return built; 2438} 2439function checkAttrs(attrs, values, type, name) { 2440 for (let attr in values) if (!(attr in attrs)) throw new RangeError(`Unsupported attribute ${attr} for ${type} of type ${name}`); 2441 for (let attr in attrs) if (attrs[attr].validate) attrs[attr].validate(values[attr]); 2442} 2443function initAttrs(typeName, attrs) { 2444 let result = Object.create(null); 2445 if (attrs) for (let name in attrs) result[name] = new Attribute(typeName, name, attrs[name]); 2446 return result; 2447} 2448var NodeType$1 = class NodeType$1 { 2449 constructor(name, schema, spec) { 2450 this.name = name; 2451 this.schema = schema; 2452 this.spec = spec; 2453 this.markSet = null; 2454 this.groups = spec.group ? spec.group.split(" ") : []; 2455 this.attrs = initAttrs(name, spec.attrs); 2456 this.defaultAttrs = defaultAttrs(this.attrs); 2457 this.contentMatch = null; 2458 this.inlineContent = null; 2459 this.isBlock = !(spec.inline || name == "text"); 2460 this.isText = name == "text"; 2461 } 2462 get isInline() { 2463 return !this.isBlock; 2464 } 2465 get isTextblock() { 2466 return this.isBlock && this.inlineContent; 2467 } 2468 get isLeaf() { 2469 return this.contentMatch == ContentMatch.empty; 2470 } 2471 get isAtom() { 2472 return this.isLeaf || !!this.spec.atom; 2473 } 2474 isInGroup(group) { 2475 return this.groups.indexOf(group) > -1; 2476 } 2477 get whitespace() { 2478 return this.spec.whitespace || (this.spec.code ? "pre" : "normal"); 2479 } 2480 hasRequiredAttrs() { 2481 for (let n in this.attrs) if (this.attrs[n].isRequired) return true; 2482 return false; 2483 } 2484 compatibleContent(other) { 2485 return this == other || this.contentMatch.compatible(other.contentMatch); 2486 } 2487 computeAttrs(attrs) { 2488 if (!attrs && this.defaultAttrs) return this.defaultAttrs; 2489 else return computeAttrs(this.attrs, attrs); 2490 } 2491 create(attrs = null, content, marks) { 2492 if (this.isText) throw new Error("NodeType.create can't construct text nodes"); 2493 return new Node$1(this, this.computeAttrs(attrs), Fragment.from(content), Mark$1.setFrom(marks)); 2494 } 2495 createChecked(attrs = null, content, marks) { 2496 content = Fragment.from(content); 2497 this.checkContent(content); 2498 return new Node$1(this, this.computeAttrs(attrs), content, Mark$1.setFrom(marks)); 2499 } 2500 createAndFill(attrs = null, content, marks) { 2501 attrs = this.computeAttrs(attrs); 2502 content = Fragment.from(content); 2503 if (content.size) { 2504 let before = this.contentMatch.fillBefore(content); 2505 if (!before) return null; 2506 content = before.append(content); 2507 } 2508 let matched = this.contentMatch.matchFragment(content); 2509 let after = matched && matched.fillBefore(Fragment.empty, true); 2510 if (!after) return null; 2511 return new Node$1(this, attrs, content.append(after), Mark$1.setFrom(marks)); 2512 } 2513 validContent(content) { 2514 let result = this.contentMatch.matchFragment(content); 2515 if (!result || !result.validEnd) return false; 2516 for (let i$1 = 0; i$1 < content.childCount; i$1++) if (!this.allowsMarks(content.child(i$1).marks)) return false; 2517 return true; 2518 } 2519 checkContent(content) { 2520 if (!this.validContent(content)) throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`); 2521 } 2522 checkAttrs(attrs) { 2523 checkAttrs(this.attrs, attrs, "node", this.name); 2524 } 2525 allowsMarkType(markType) { 2526 return this.markSet == null || this.markSet.indexOf(markType) > -1; 2527 } 2528 allowsMarks(marks) { 2529 if (this.markSet == null) return true; 2530 for (let i$1 = 0; i$1 < marks.length; i$1++) if (!this.allowsMarkType(marks[i$1].type)) return false; 2531 return true; 2532 } 2533 allowedMarks(marks) { 2534 if (this.markSet == null) return marks; 2535 let copy$1; 2536 for (let i$1 = 0; i$1 < marks.length; i$1++) if (!this.allowsMarkType(marks[i$1].type)) { 2537 if (!copy$1) copy$1 = marks.slice(0, i$1); 2538 } else if (copy$1) copy$1.push(marks[i$1]); 2539 return !copy$1 ? marks : copy$1.length ? copy$1 : Mark$1.none; 2540 } 2541 static compile(nodes, schema) { 2542 let result = Object.create(null); 2543 nodes.forEach((name, spec) => result[name] = new NodeType$1(name, schema, spec)); 2544 let topType = schema.spec.topNode || "doc"; 2545 if (!result[topType]) throw new RangeError("Schema is missing its top node type ('" + topType + "')"); 2546 if (!result.text) throw new RangeError("Every schema needs a 'text' type"); 2547 for (let _ in result.text.attrs) throw new RangeError("The text node type should not have attributes"); 2548 return result; 2549 } 2550}; 2551function validateType(typeName, attrName, type) { 2552 let types = type.split("|"); 2553 return (value) => { 2554 let name = value === null ? "null" : typeof value; 2555 if (types.indexOf(name) < 0) throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`); 2556 }; 2557} 2558var Attribute = class { 2559 constructor(typeName, attrName, options) { 2560 this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default"); 2561 this.default = options.default; 2562 this.validate = typeof options.validate == "string" ? validateType(typeName, attrName, options.validate) : options.validate; 2563 } 2564 get isRequired() { 2565 return !this.hasDefault; 2566 } 2567}; 2568var MarkType = class MarkType { 2569 constructor(name, rank, schema, spec) { 2570 this.name = name; 2571 this.rank = rank; 2572 this.schema = schema; 2573 this.spec = spec; 2574 this.attrs = initAttrs(name, spec.attrs); 2575 this.excluded = null; 2576 let defaults$1 = defaultAttrs(this.attrs); 2577 this.instance = defaults$1 ? new Mark$1(this, defaults$1) : null; 2578 } 2579 create(attrs = null) { 2580 if (!attrs && this.instance) return this.instance; 2581 return new Mark$1(this, computeAttrs(this.attrs, attrs)); 2582 } 2583 static compile(marks, schema) { 2584 let result = Object.create(null), rank = 0; 2585 marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec)); 2586 return result; 2587 } 2588 removeFromSet(set) { 2589 for (var i$1 = 0; i$1 < set.length; i$1++) if (set[i$1].type == this) { 2590 set = set.slice(0, i$1).concat(set.slice(i$1 + 1)); 2591 i$1--; 2592 } 2593 return set; 2594 } 2595 isInSet(set) { 2596 for (let i$1 = 0; i$1 < set.length; i$1++) if (set[i$1].type == this) return set[i$1]; 2597 } 2598 checkAttrs(attrs) { 2599 checkAttrs(this.attrs, attrs, "mark", this.name); 2600 } 2601 excludes(other) { 2602 return this.excluded.indexOf(other) > -1; 2603 } 2604}; 2605var Schema = class { 2606 constructor(spec) { 2607 this.linebreakReplacement = null; 2608 this.cached = Object.create(null); 2609 let instanceSpec = this.spec = {}; 2610 for (let prop in spec) instanceSpec[prop] = spec[prop]; 2611 instanceSpec.nodes = dist_default$1.from(spec.nodes), instanceSpec.marks = dist_default$1.from(spec.marks || {}), this.nodes = NodeType$1.compile(this.spec.nodes, this); 2612 this.marks = MarkType.compile(this.spec.marks, this); 2613 let contentExprCache = Object.create(null); 2614 for (let prop in this.nodes) { 2615 if (prop in this.marks) throw new RangeError(prop + " can not be both a node and a mark"); 2616 let type = this.nodes[prop], contentExpr = type.spec.content || "", markExpr = type.spec.marks; 2617 type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes)); 2618 type.inlineContent = type.contentMatch.inlineContent; 2619 if (type.spec.linebreakReplacement) { 2620 if (this.linebreakReplacement) throw new RangeError("Multiple linebreak nodes defined"); 2621 if (!type.isInline || !type.isLeaf) throw new RangeError("Linebreak replacement nodes must be inline leaf nodes"); 2622 this.linebreakReplacement = type; 2623 } 2624 type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null; 2625 } 2626 for (let prop in this.marks) { 2627 let type = this.marks[prop], excl = type.spec.excludes; 2628 type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" ")); 2629 } 2630 this.nodeFromJSON = (json) => Node$1.fromJSON(this, json); 2631 this.markFromJSON = (json) =>
2631 Mark$1.fromJSON(this, json); 2632 this.topNodeType = this.nodes[this.spec.topNode || "doc"]; 2633 this.cached.wrappings = Object.create(null); 2634 } 2635 node(type, attrs = null, content, marks) { 2636 if (typeof type == "string") type = this.nodeType(type); 2637 else if (!(type instanceof NodeType$1)) throw new RangeError("Invalid node type: " + type); 2638 else if (type.schema != this) throw new RangeError("Node type from different schema used (" + type.name + ")"); 2639 return type.createChecked(attrs, content, marks); 2640 } 2641 text(text$1, marks) { 2642 let type = this.nodes.text; 2643 return new TextNode(type, type.defaultAttrs, text$1, Mark$1.setFrom(marks)); 2644 } 2645 mark(type, attrs) { 2646 if (typeof type == "string") type = this.marks[type]; 2647 return type.create(attrs); 2648 } 2649 nodeType(name) { 2650 let found$1 = this.nodes[name]; 2651 if (!found$1) throw new RangeError("Unknown node type: " + name); 2652 return found$1; 2653 } 2654}; 2655function gatherMarks(schema, marks) { 2656 let found$1 = []; 2657 for (let i$1 = 0; i$1 < marks.length; i$1++) { 2658 let name = marks[i$1], mark = schema.marks[name], ok = mark; 2659 if (mark) found$1.push(mark); 2660 else for (let prop in schema.marks) { 2661 let mark$1 = schema.marks[prop]; 2662 if (name == "_" || mark$1.spec.group && mark$1.spec.group.split(" ").indexOf(name) > -1) found$1.push(ok = mark$1); 2663 } 2664 if (!ok) throw new SyntaxError("Unknown mark type: '" + marks[i$1] + "'"); 2665 } 2666 return found$1; 2667} 2668function isTagRule(rule) { 2669 return rule.tag != null; 2670} 2671function isStyleRule(rule) { 2672 return rule.style != null; 2673} 2674var DOMParser = class DOMParser { 2675 constructor(schema, rules) { 2676 this.schema = schema; 2677 this.rules = rules; 2678 this.tags = []; 2679 this.styles = []; 2680 let matchedStyles = this.matchedStyles = [];
2681 rules.forEach((rule) => { 2682 if (isTagRule(rule)) this.tags.push(rule); 2683 else if (isStyleRule(rule)) { 2684 let prop = /[^=]*/.exec(rule.style)[0]; 2685 if (matchedStyles.indexOf(prop) < 0) matchedStyles.push(prop); 2686 this.styles.push(rule); 2687 } 2688 }); 2689 this.normalizeLists = !this.tags.some((r) => { 2690 if (!/^(ul|ol)\b/.test(r.tag) || !r.node) return false; 2691 let node = schema.nodes[r.node]; 2692 return node.contentMatch.matchType(node); 2693 }); 2694 } 2695 parse(dom, options = {}) { 2696 let context = new ParseContext(this, options, false); 2697 context.addAll(dom, Mark$1.none, options.from, options.to); 2698 return context.finish(); 2699 } 2700 parseSlice(dom, options = {}) { 2701 let context = new ParseContext(this, options, true); 2702 context.addAll(dom, Mark$1.none, options.from, options.to); 2703 return Slice.maxOpen(context.finish()); 2704 } 2705 matchTag(dom, context, after) { 2706 for (let i$1 = after ? this.tags.indexOf(after) + 1 : 0; i$1 < this.tags.length; i$1++) { 2707 let rule = this.tags[i$1]; 2708 if (matches(dom, rule.tag) && (rule.namespace === void 0 || dom.namespaceURI == rule.namespace) && (!rule.context || context.matchesContext(rule.context))) { 2709 if (rule.getAttrs) { 2710 let result = rule.getAttrs(dom); 2711 if (result === false) continue; 2712 rule.attrs = result || void 0; 2713 } 2714 return rule; 2715 } 2716 } 2717 } 2718 matchStyle(prop, value, context, after) { 2719 for (let i$1 = after ? this.styles.indexOf(after) + 1 : 0; i$1 < this.styles.length; i$1++) { 2720 let rule = this.styles[i$1], style$1 = rule.style; 2721 if (style$1.indexOf(prop) != 0 || rule.context && !context.matchesContext(rule.context) || style$1.length > prop.length && (style$1.charCodeAt(prop.length) != 61 || style$1.slice(prop.length + 1) != value)) continue; 2722 if (rule.getAttrs) { 2723 let result = rule.getAttrs(value); 2724 if (result === false) continue; 2725 rule.attrs = result || void 0; 2726 } 2727 return rule; 2728 } 2729 } 2730 static schemaRules(schema) { 2731 let result = []; 2732 function insert(rule) { 2733 let priority = rule.priority == null ? 50 : rule.priority, i$1 = 0; 2734 for (; i$1 < result.length; i$1++) { 2735 let next = result[i$1]; 2736 if ((next.priority == null ? 50 : next.priority) < priority) break; 2737 } 2738 result.splice(i$1, 0, rule); 2739 } 2740 for (let name in schema.marks) { 2741 let rules = schema.marks[name].spec.parseDOM;
vendor: 18,880 bytes, lines 2742-3247
2742 if (rules) rules.forEach((rule) => { 2743 insert(rule = copy(rule)); 2744 if (!(rule.mark || rule.ignore || rule.clearMark)) rule.mark = name; 2745 }); 2746 } 2747 for (let name in schema.nodes) { 2748 let rules = schema.nodes[name].spec.parseDOM; 2749 if (rules) rules.forEach((rule) => { 2750 insert(rule = copy(rule)); 2751 if (!(rule.node || rule.ignore || rule.mark)) rule.node = name; 2752 }); 2753 } 2754 return result; 2755 } 2756 static fromSchema(schema) { 2757 return schema.cached.domParser || (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema))); 2758 } 2759}; 2760var blockTags = { 2761 address: true, 2762 article: true, 2763 aside: true, 2764 blockquote: true, 2765 body: true, 2766 canvas: true, 2767 dd: true, 2768 div: true, 2769 dl: true, 2770 fieldset: true, 2771 figcaption: true, 2772 figure: true, 2773 footer: true, 2774 form: true, 2775 h1: true, 2776 h2: true, 2777 h3: true, 2778 h4: true, 2779 h5: true, 2780 h6: true, 2781 header: true, 2782 hgroup: true, 2783 hr: true, 2784 li: true, 2785 noscript: true, 2786 ol: true, 2787 output: true, 2788 p: true, 2789 pre: true, 2790 section: true, 2791 table: true, 2792 tfoot: true, 2793 ul: true 2794}; 2795var ignoreTags = { 2796 head: true, 2797 noscript: true, 2798 object: true, 2799 script: true, 2800 style: true, 2801 title: true 2802}; 2803var listTags = { 2804 ol: true, 2805 ul: true 2806}; 2807var OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4; 2808function wsOptionsFor(type, preserveWhitespace, base$1) { 2809 if (preserveWhitespace != null) return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0); 2810 return type && type.whitespace == "pre" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base$1 & ~OPT_OPEN_LEFT; 2811} 2812var NodeContext = class { 2813 constructor(type, attrs, marks, solid, match, options) { 2814 this.type = type; 2815 this.attrs = attrs; 2816 this.marks = marks; 2817 this.solid = solid; 2818 this.options = options; 2819 this.content = []; 2820 this.activeMarks = Mark$1.none; 2821 this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch); 2822 } 2823 findWrapping(node) { 2824 if (!this.match) { 2825 if (!this.type) return []; 2826 let fill = this.type.contentMatch.fillBefore(Fragment.from(node)); 2827 if (fill) this.match = this.type.contentMatch.matchFragment(fill); 2828 else { 2829 let start = this.type.contentMatch, wrap$1; 2830 if (wrap$1 = start.findWrapping(node.type)) { 2831 this.match = start; 2832 return wrap$1; 2833 } else return null; 2834 } 2835 } 2836 return this.match.findWrapping(node.type); 2837 } 2838 finish(openEnd) { 2839 if (!(this.options & OPT_PRESERVE_WS)) { 2840 let last = this.content[this.content.length - 1], m; 2841 if (last && last.isText && (m = /[ \t\r\n\u000c]+$/.exec(last.text))) { 2842 let text$1 = last; 2843 if (last.text.length == m[0].length) this.content.pop(); 2844 else this.content[this.content.length - 1] = text$1.withText(text$1.text.slice(0, text$1.text.length - m[0].length)); 2845 } 2846 } 2847 let content = Fragment.from(this.content); 2848 if (!openEnd && this.match) content = content.append(this.match.fillBefore(Fragment.empty, true)); 2849 return this.type ? this.type.create(this.attrs, content, this.marks) : content; 2850 } 2851 inlineContext(node) { 2852 if (this.type) return this.type.inlineContent; 2853 if (this.content.length) return this.content[0].isInline; 2854 return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase()); 2855 } 2856}; 2857var ParseContext = class { 2858 constructor(parser, options, isOpen) { 2859 this.parser = parser; 2860 this.options = options; 2861 this.isOpen = isOpen; 2862 this.open = 0; 2863 this.localPreserveWS = false; 2864 let topNode = options.topNode, topContext; 2865 let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0); 2866 if (topNode) topContext = new NodeContext(topNode.type, topNode.attrs, Mark$1.none, true, options.topMatch || topNode.type.contentMatch, topOptions); 2867 else if (isOpen) topContext = new NodeContext(null, null, Mark$1.none, true, null, topOptions); 2868 else topContext = new NodeContext(parser.schema.topNodeType, null, Mark$1.none, true, null, topOptions); 2869 this.nodes = [topContext]; 2870 this.find = options.findPositions; 2871 this.needsBlock = false; 2872 } 2873 get top() { 2874 return this.nodes[this.open]; 2875 } 2876 addDOM(dom, marks) { 2877 if (dom.nodeType == 3) this.addTextNode(dom, marks); 2878 else if (dom.nodeType == 1) this.addElement(dom, marks); 2879 } 2880 addTextNode(dom, marks) { 2881 let value = dom.nodeValue; 2882 let top = this.top, preserveWS = top.options & OPT_PRESERVE_WS_FULL ? "full" : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0; 2883 let { schema } = this.parser; 2884 if (preserveWS === "full" || top.inlineContext(dom) || /[^ \t\r\n\u000c]/.test(value)) { 2885 if (!preserveWS) { 2886 value = value.replace(/[ \t\r\n\u000c]+/g, " "); 2887 if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) { 2888 let nodeBefore = top.content[top.content.length - 1]; 2889 let domNodeBefore = dom.previousSibling; 2890 if (!nodeBefore || domNodeBefore && domNodeBefore.nodeName == "BR" || nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text)) value = value.slice(1); 2891 } 2892 } else if (preserveWS === "full") value = value.replace(/\r\n?/g, "\n"); 2893 else if (schema.linebreakReplacement && /[\r\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) { 2894 let lines = value.split(/\r?\n|\r/); 2895 for (let i$1 = 0; i$1 < lines.length; i$1++) { 2896 if (i$1) this.insertNode(schema.linebreakReplacement.create(), marks, true); 2897 if (lines[i$1]) this.insertNode(schema.text(lines[i$1]), marks, !/\S/.test(lines[i$1])); 2898 } 2899 value = ""; 2900 } else value = value.replace(/\r?\n|\r/g, " "); 2901 if (value) this.insertNode(schema.text(value), marks, !/\S/.test(value)); 2902 this.findInText(dom); 2903 } else this.findInside(dom); 2904 } 2905 addElement(dom, marks, matchAfter) { 2906 let outerWS = this.localPreserveWS, top = this.top; 2907 if (dom.tagName == "PRE" || /pre/.test(dom.style && dom.style.whiteSpace)) this.localPreserveWS = true; 2908 let name = dom.nodeName.toLowerCase(), ruleID; 2909 if (listTags.hasOwnProperty(name) && this.parser.normalizeLists) normalizeList(dom); 2910 let rule = this.options.ruleFromNode && this.options.ruleFromNode(dom) || (ruleID = this.parser.matchTag(dom, this, matchAfter)); 2911 out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) { 2912 this.findInside(dom); 2913 this.ignoreFallback(dom, marks); 2914 } else if (!rule || rule.skip || rule.closeParent) { 2915 if (rule && rule.closeParent) this.open = Math.max(0, this.open - 1); 2916 else if (rule && rule.skip.nodeType) dom = rule.skip; 2917 let sync, oldNeedsBlock = this.needsBlock; 2918 if (blockTags.hasOwnProperty(name)) { 2919 if (top.content.length && top.content[0].isInline && this.open) { 2920 this.open--; 2921 top = this.top; 2922 } 2923 sync = true; 2924 if (!top.type) this.needsBlock = true; 2925 } else if (!dom.firstChild) { 2926 this.leafFallback(dom, marks); 2927 break out; 2928 } 2929 let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks); 2930 if (innerMarks) this.addAll(dom, innerMarks); 2931 if (sync) this.sync(top); 2932 this.needsBlock = oldNeedsBlock; 2933 } else { 2934 let innerMarks = this.readStyles(dom, marks); 2935 if (innerMarks) this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : void 0); 2936 } 2937 this.localPreserveWS = outerWS; 2938 } 2939 leafFallback(dom, marks) { 2940 if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent) this.addTextNode(dom.ownerDocument.createTextNode("\n"), marks); 2941 } 2942 ignoreFallback(dom, marks) { 2943 if (dom.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent)) this.findPlace(this.parser.schema.text("-"), marks, true); 2944 } 2945 readStyles(dom, marks) { 2946 let styles = dom.style; 2947 if (styles && styles.length) for (let i$1 = 0; i$1 < this.parser.matchedStyles.length; i$1++) { 2948 let name = this.parser.matchedStyles[i$1], value = styles.getPropertyValue(name); 2949 if (value) for (let after = void 0;;) { 2950 let rule = this.parser.matchStyle(name, value, this, after); 2951 if (!rule) break; 2952 if (rule.ignore) return null; 2953 if (rule.clearMark) marks = marks.filter((m) => !rule.clearMark(m)); 2954 else marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs)); 2955 if (rule.consuming === false) after = rule; 2956 else break; 2957 } 2958 } 2959 return marks; 2960 } 2961 addElementByRule(dom, rule, marks, continueAfter) { 2962 let sync, nodeType; 2963 if (rule.node) { 2964 nodeType = this.parser.schema.nodes[rule.node]; 2965 if (!nodeType.isLeaf) { 2966 let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace); 2967 if (inner) { 2968 sync = true; 2969 marks = inner; 2970 } 2971 } else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == "BR")) this.leafFallback(dom, marks); 2972 } else { 2973 let markType = this.parser.schema.marks[rule.mark]; 2974 marks = marks.concat(markType.create(rule.attrs)); 2975 } 2976 let startIn = this.top; 2977 if (nodeType && nodeType.isLeaf) this.findInside(dom); 2978 else if (continueAfter) this.addElement(dom, marks, continueAfter); 2979 else if (rule.getContent) { 2980 this.findInside(dom); 2981 rule.getContent(dom, this.parser.schema).forEach((node) => this.insertNode(node, marks, false)); 2982 } else { 2983 let contentDOM = dom; 2984 if (typeof rule.contentElement == "string") contentDOM = dom.querySelector(rule.contentElement); 2985 else if (typeof rule.contentElement == "function") contentDOM = rule.contentElement(dom); 2986 else if (rule.contentElement) contentDOM = rule.contentElement; 2987 this.findAround(dom, contentDOM, true); 2988 this.addAll(contentDOM, marks); 2989 this.findAround(dom, contentDOM, false); 2990 } 2991 if (sync && this.sync(startIn)) this.open--; 2992 } 2993 addAll(parent, marks, startIndex, endIndex) { 2994 let index = startIndex || 0; 2995 for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) { 2996 this.findAtPoint(parent, index); 2997 this.addDOM(dom, marks); 2998 } 2999 this.findAtPoint(parent, index); 3000 } 3001 findPlace(node, marks, cautious) { 3002 let route, sync; 3003 for (let depth = this.open, penalty = 0; depth >= 0; depth--) { 3004 let cx = this.nodes[depth]; 3005 let found$1 = cx.findWrapping(node); 3006 if (found$1 && (!route || route.length > found$1.length + penalty)) { 3007 route = found$1; 3008 sync = cx; 3009 if (!found$1.length) break; 3010 } 3011 if (cx.solid) { 3012 if (cautious) break; 3013 penalty += 2; 3014 } 3015 } 3016 if (!route) return null; 3017 this.sync(sync); 3018 for (let i$1 = 0; i$1 < route.length; i$1++) marks = this.enterInner(route[i$1], null, marks, false); 3019 return marks; 3020 } 3021 insertNode(node, marks, cautious) { 3022 if (node.isInline && this.needsBlock && !this.top.type) { 3023 let block = this.textblockFromContext(); 3024 if (block) marks = this.enterInner(block, null, marks); 3025 } 3026 let innerMarks = this.findPlace(node, marks, cautious); 3027 if (innerMarks) { 3028 this.closeExtra(); 3029 let top = this.top; 3030 if (top.match) top.match = top.match.matchType(node.type); 3031 let nodeMarks = Mark$1.none; 3032 for (let m of innerMarks.concat(node.marks)) if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type)) nodeMarks = m.addToSet(nodeMarks); 3033 top.content.push(node.mark(nodeMarks)); 3034 return true; 3035 } 3036 return false; 3037 } 3038 enter(type, attrs, marks, preserveWS) { 3039 let innerMarks = this.findPlace(type.create(attrs), marks, false); 3040 if (innerMarks) innerMarks = this.enterInner(type, attrs, marks, true, preserveWS); 3041 return innerMarks; 3042 } 3043 enterInner(type, attrs, marks, solid = false, preserveWS) { 3044 this.closeExtra(); 3045 let top = this.top; 3046 top.match = top.match && top.match.matchType(type); 3047 let options = wsOptionsFor(type, preserveWS, top.options); 3048 if (top.options & OPT_OPEN_LEFT && top.content.length == 0) options |= OPT_OPEN_LEFT; 3049 let applyMarks = Mark$1.none; 3050 marks = marks.filter((m) => { 3051 if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) { 3052 applyMarks = m.addToSet(applyMarks); 3053 return false; 3054 } 3055 return true; 3056 }); 3057 this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options)); 3058 this.open++; 3059 return marks; 3060 } 3061 closeExtra(openEnd = false) { 3062 let i$1 = this.nodes.length - 1; 3063 if (i$1 > this.open) { 3064 for (; i$1 > this.open; i$1--) this.nodes[i$1 - 1].content.push(this.nodes[i$1].finish(openEnd)); 3065 this.nodes.length = this.open + 1; 3066 } 3067 } 3068 finish() { 3069 this.open = 0; 3070 this.closeExtra(this.isOpen); 3071 return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen)); 3072 } 3073 sync(to) { 3074 for (let i$1 = this.open; i$1 >= 0; i$1--) if (this.nodes[i$1] == to) { 3075 this.open = i$1; 3076 return true; 3077 } else if (this.localPreserveWS) this.nodes[i$1].options |= OPT_PRESERVE_WS; 3078 return false; 3079 } 3080 get currentPos() { 3081 this.closeExtra(); 3082 let pos = 0; 3083 for (let i$1 = this.open; i$1 >= 0; i$1--) { 3084 let content = this.nodes[i$1].content; 3085 for (let j = content.length - 1; j >= 0; j--) pos += content[j].nodeSize; 3086 if (i$1) pos++; 3087 } 3088 return pos; 3089 } 3090 findAtPoint(parent, offset) { 3091 if (this.find) { 3092 for (let i$1 = 0; i$1 < this.find.length; i$1++) if (this.find[i$1].node == parent && this.find[i$1].offset == offset) this.find[i$1].pos = this.currentPos; 3093 } 3094 } 3095 findInside(parent) { 3096 if (this.find) { 3097 for (let i$1 = 0; i$1 < this.find.length; i$1++) if (this.find[i$1].pos == null && parent.nodeType == 1 && parent.contains(this.find[i$1].node)) this.find[i$1].pos = this.currentPos; 3098 } 3099 } 3100 findAround(parent, content, before) { 3101 if (parent != content && this.find) { 3102 for (let i$1 = 0; i$1 < this.find.length; i$1++) if (this.find[i$1].pos == null && parent.nodeType == 1 && parent.contains(this.find[i$1].node)) { 3103 if (content.compareDocumentPosition(this.find[i$1].node) & (before ? 2 : 4)) this.find[i$1].pos = this.currentPos; 3104 } 3105 } 3106 } 3107 findInText(textNode) { 3108 if (this.find) { 3109 for (let i$1 = 0; i$1 < this.find.length; i$1++) if (this.find[i$1].node == textNode) this.find[i$1].pos = this.currentPos - (textNode.nodeValue.length - this.find[i$1].offset); 3110 } 3111 } 3112 matchesContext(context) { 3113 if (context.indexOf("|") > -1) return context.split(/\s*\|\s*/).some(this.matchesContext, this); 3114 let parts = context.split("/"); 3115 let option = this.options.context; 3116 let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type); 3117 let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1); 3118 let match = (i$1, depth) => { 3119 for (; i$1 >= 0; i$1--) { 3120 let part = parts[i$1]; 3121 if (part == "") { 3122 if (i$1 == parts.length - 1 || i$1 == 0) continue; 3123 for (; depth >= minDepth; depth--) if (match(i$1 - 1, depth)) return true; 3124 return false; 3125 } else { 3126 let next = depth > 0 || depth == 0 && useRoot ? this.nodes[depth].type : option && depth >= minDepth ? option.node(depth - minDepth).type : null; 3127 if (!next || next.name != part && !next.isInGroup(part)) return false; 3128 depth--; 3129 } 3130 } 3131 return true; 3132 }; 3133 return match(parts.length - 1, this.open); 3134 } 3135 textblockFromContext() { 3136 let $context = this.options.context; 3137 if ($context) for (let d = $context.depth; d >= 0; d--) { 3138 let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType; 3139 if (deflt && deflt.isTextblock && deflt.defaultAttrs) return deflt; 3140 } 3141 for (let name in this.parser.schema.nodes) { 3142 let type = this.parser.schema.nodes[name]; 3143 if (type.isTextblock && type.defaultAttrs) return type; 3144 } 3145 } 3146}; 3147function normalizeList(dom) { 3148 for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) { 3149 let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null; 3150 if (name && listTags.hasOwnProperty(name) && prevItem) { 3151 prevItem.appendChild(child); 3152 child = prevItem; 3153 } else if (name == "li") prevItem = child; 3154 else if (name) prevItem = null; 3155 } 3156} 3157function matches(dom, selector) { 3158 return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector); 3159} 3160function copy(obj) { 3161 let copy$1 = {}; 3162 for (let prop in obj) copy$1[prop] = obj[prop]; 3163 return copy$1; 3164} 3165function markMayApply(markType, nodeType) { 3166 let nodes = nodeType.schema.nodes; 3167 for (let name in nodes) { 3168 let parent = nodes[name]; 3169 if (!parent.allowsMarkType(markType)) continue; 3170 let seen = [], scan = (match) => { 3171 seen.push(match); 3172 for (let i$1 = 0; i$1 < match.edgeCount; i$1++) { 3173 let { type, next } = match.edge(i$1); 3174 if (type == nodeType) return true; 3175 if (seen.indexOf(next) < 0 && scan(next)) return true; 3176 } 3177 }; 3178 if (scan(parent.contentMatch)) return true; 3179 } 3180} 3181var DOMSerializer = class DOMSerializer { 3182 constructor(nodes, marks) { 3183 this.nodes = nodes; 3184 this.marks = marks; 3185 } 3186 serializeFragment(fragment, options = {}, target) { 3187 if (!target) target = doc$1(options).createDocumentFragment(); 3188 let top = target, active = []; 3189 fragment.forEach((node) => { 3190 if (active.length || node.marks.length) { 3191 let keep = 0, rendered = 0; 3192 while (keep < active.length && rendered < node.marks.length) { 3193 let next = node.marks[rendered]; 3194 if (!this.marks[next.type.name]) { 3195 rendered++; 3196 continue; 3197 } 3198 if (!next.eq(active[keep][0]) || next.type.spec.spanning === false) break; 3199 keep++; 3200 rendered++; 3201 } 3202 while (keep < active.length) top = active.pop()[1]; 3203 while (rendered < node.marks.length) { 3204 let add = node.marks[rendered++]; 3205 let markDOM = this.serializeMark(add, node.isInline, options); 3206 if (markDOM) { 3207 active.push([add, top]); 3208 top.appendChild(markDOM.dom); 3209 top = markDOM.contentDOM || markDOM.dom; 3210 } 3211 } 3212 } 3213 top.appendChild(this.serializeNodeInner(node, options)); 3214 }); 3215 return target; 3216 } 3217 serializeNodeInner(node, options) { 3218 if (node.isText) return doc$1(options).createTextNode(node.text); 3219 let { dom, contentDOM } = renderSpec(doc$1(options), this.nodes[node.type.name](node), null, node.attrs); 3220 if (contentDOM) { 3221 if (node.isLeaf) throw new RangeError("Content hole not allowed in a leaf node spec"); 3222 this.serializeFragment(node.content, options, contentDOM); 3223 } 3224 return dom; 3225 } 3226 serializeNode(node, options = {}) { 3227 let dom = this.serializeNodeInner(node, options); 3228 for (let i$1 = node.marks.length - 1; i$1 >= 0; i$1--) { 3229 let wrap$1 = this.serializeMark(node.marks[i$1], node.isInline, options); 3230 if (wrap$1) { 3231 (wrap$1.contentDOM || wrap$1.dom).appendChild(dom); 3232 dom = wrap$1.dom; 3233 } 3234 } 3235 return dom; 3236 } 3237 serializeMark(mark, inline, options = {}) { 3238 let toDOM = this.marks[mark.type.name]; 3239 return toDOM && renderSpec(doc$1(options), toDOM(mark, inline), null, mark.attrs); 3240 } 3241 static renderSpec(doc$2, structure, xmlNS = null, blockArraysIn) { 3242 if (typeof structure == "string") return { dom: doc$2.createTextNode(structure) }; 3243 return renderSpec(doc$2, structure, xmlNS, blockArraysIn); 3244 } 3245 static fromSchema(schema) { 3246 return schema.cached.domSerializer || (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema))); 3247 }
3248 static nodesFromSchema(schema) { 3249 let result = gatherToDOM(schema.nodes); 3250 if (!result.text) result.text = (node) => node.text; 3251 return result; 3252 } 3253 static marksFromSchema(schema) { 3254 return gatherToDOM(schema.marks); 3255 } 3256}; 3257function gatherToDOM(obj) { 3258 let result = {}; 3259 for (let name in obj) { 3260 let toDOM = obj[name].spec.toDOM; 3261 if (toDOM) result[name] = toDOM; 3262 } 3263 return result; 3264} 3265function doc$1(options) { 3266 return options.document || window.document; 3267} 3268var suspiciousAttributeCache = /* @__PURE__ */ new WeakMap(); 3269function suspiciousAttributes(attrs) { 3270 let value = suspiciousAttributeCache.get(attrs); 3271 if (value === void 0) suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs)); 3272 return value; 3273} 3274function suspiciousAttributesInner(attrs) { 3275 let result = null; 3276 function scan(value) { 3277 if (value && typeof value == "object") if (Array.isArray(value)) if (typeof value[0] == "string") { 3278 if (!result) result = []; 3279 result.push(value); 3280 } else for (let i$1 = 0; i$1 < value.length; i$1++) scan(value[i$1]); 3281 else for (let prop in value) scan(value[prop]); 3282 } 3283 scan(attrs); 3284 return result; 3285}
vendor: 21,873 bytes, lines 3286-3890
3286function renderSpec(doc$2, structure, xmlNS, blockArraysIn) { 3287 if (structure.nodeType == 1) return { dom: structure }; 3288 if (structure.dom && structure.dom.nodeType == 1) return structure; 3289 let tagName = structure[0], suspicious; 3290 if (typeof tagName != "string") throw new RangeError("Invalid array passed to renderSpec"); 3291 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."); 3292 let space = tagName.indexOf(" "); 3293 if (space > 0) { 3294 xmlNS = tagName.slice(0, space); 3295 tagName = tagName.slice(space + 1); 3296 } 3297 let contentDOM; 3298 let dom = xmlNS ? doc$2.createElementNS(xmlNS, tagName) : doc$2.createElement(tagName); 3299 let attrs = structure[1], start = 1; 3300 if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) { 3301 start = 2; 3302 for (let name in attrs) if (attrs[name] != null) { 3303 let space$1 = name.indexOf(" "); 3304 if (space$1 > 0) dom.setAttributeNS(name.slice(0, space$1), name.slice(space$1 + 1), attrs[name]); 3305 else if (name == "style" && dom.style) dom.style.cssText = attrs[name]; 3306 else dom.setAttribute(name, attrs[name]); 3307 } 3308 } 3309 for (let i$1 = start; i$1 < structure.length; i$1++) { 3310 let child = structure[i$1]; 3311 if (child === 0) { 3312 if (i$1 < structure.length - 1 || i$1 > start) throw new RangeError("Content hole must be the only child of its parent node"); 3313 return { 3314 dom, 3315 contentDOM: dom 3316 }; 3317 } else if (typeof child == "string") dom.appendChild(doc$2.createTextNode(child)); 3318 else { 3319 let { dom: inner, contentDOM: innerContent } = renderSpec(doc$2, child, xmlNS, blockArraysIn); 3320 dom.appendChild(inner); 3321 if (innerContent) { 3322 if (contentDOM) throw new RangeError("Multiple content holes"); 3323 contentDOM = innerContent; 3324 } 3325 } 3326 } 3327 return { 3328 dom, 3329 contentDOM 3330 }; 3331} 3332var lower16 = 65535; 3333var factor16 = Math.pow(2, 16); 3334function makeRecover(index, offset) { 3335 return index + offset * factor16; 3336} 3337function recoverIndex(value) { 3338 return value & lower16; 3339} 3340function recoverOffset(value) { 3341 return (value - (value & lower16)) / factor16; 3342} 3343var DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8; 3344var MapResult = class { 3345 constructor(pos, delInfo, recover) { 3346 this.pos = pos; 3347 this.delInfo = delInfo; 3348 this.recover = recover; 3349 } 3350 get deleted() { 3351 return (this.delInfo & DEL_SIDE) > 0; 3352 } 3353 get deletedBefore() { 3354 return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; 3355 } 3356 get deletedAfter() { 3357 return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; 3358 } 3359 get deletedAcross() { 3360 return (this.delInfo & DEL_ACROSS) > 0; 3361 } 3362}; 3363var StepMap = class StepMap { 3364 constructor(ranges, inverted = false) { 3365 this.ranges = ranges; 3366 this.inverted = inverted; 3367 if (!ranges.length && StepMap.empty) return StepMap.empty; 3368 } 3369 recover(value) { 3370 let diff = 0, index = recoverIndex(value); 3371 if (!this.inverted) for (let i$1 = 0; i$1 < index; i$1++) diff += this.ranges[i$1 * 3 + 2] - this.ranges[i$1 * 3 + 1]; 3372 return this.ranges[index * 3] + diff + recoverOffset(value); 3373 } 3374 mapResult(pos, assoc = 1) { 3375 return this._map(pos, assoc, false); 3376 } 3377 map(pos, assoc = 1) { 3378 return this._map(pos, assoc, true); 3379 } 3380 _map(pos, assoc, simple) { 3381 let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; 3382 for (let i$1 = 0; i$1 < this.ranges.length; i$1 += 3) { 3383 let start = this.ranges[i$1] - (this.inverted ? diff : 0); 3384 if (start > pos) break; 3385 let oldSize = this.ranges[i$1 + oldIndex], newSize = this.ranges[i$1 + newIndex], end = start + oldSize; 3386 if (pos <= end) { 3387 let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc; 3388 let result = start + diff + (side < 0 ? 0 : newSize); 3389 if (simple) return result; 3390 let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i$1 / 3, pos - start); 3391 let del$1 = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS; 3392 if (assoc < 0 ? pos != start : pos != end) del$1 |= DEL_SIDE; 3393 return new MapResult(result, del$1, recover); 3394 } 3395 diff += newSize - oldSize; 3396 } 3397 return simple ? pos + diff : new MapResult(pos + diff, 0, null); 3398 } 3399 touches(pos, recover) { 3400 let diff = 0, index = recoverIndex(recover); 3401 let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; 3402 for (let i$1 = 0; i$1 < this.ranges.length; i$1 += 3) { 3403 let start = this.ranges[i$1] - (this.inverted ? diff : 0); 3404 if (start > pos) break; 3405 let oldSize = this.ranges[i$1 + oldIndex]; 3406 if (pos <= start + oldSize && i$1 == index * 3) return true; 3407 diff += this.ranges[i$1 + newIndex] - oldSize; 3408 } 3409 return false; 3410 } 3411 forEach(f) { 3412 let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; 3413 for (let i$1 = 0, diff = 0; i$1 < this.ranges.length; i$1 += 3) { 3414 let start = this.ranges[i$1], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff); 3415 let oldSize = this.ranges[i$1 + oldIndex], newSize = this.ranges[i$1 + newIndex]; 3416 f(oldStart, oldStart + oldSize, newStart, newStart + newSize); 3417 diff += newSize - oldSize; 3418 } 3419 } 3420 invert() { 3421 return new StepMap(this.ranges, !this.inverted); 3422 } 3423 toString() { 3424 return (this.inverted ? "-" : "") + JSON.stringify(this.ranges); 3425 } 3426 static offset(n) { 3427 return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [ 3428 0, 3429 -n, 3430 0 3431 ] : [ 3432 0, 3433 0, 3434 n 3435 ]); 3436 } 3437}; 3438StepMap.empty = new StepMap([]); 3439var Mapping = class Mapping { 3440 constructor(maps, mirror, from = 0, to = maps ? maps.length : 0) { 3441 this.mirror = mirror; 3442 this.from = from; 3443 this.to = to; 3444 this._maps = maps || []; 3445 this.ownData = !(maps || mirror); 3446 } 3447 get maps() { 3448 return this._maps; 3449 } 3450 slice(from = 0, to = this.maps.length) { 3451 return new Mapping(this._maps, this.mirror, from, to); 3452 } 3453 appendMap(map, mirrors) { 3454 if (!this.ownData) { 3455 this._maps = this._maps.slice(); 3456 this.mirror = this.mirror && this.mirror.slice(); 3457 this.ownData = true; 3458 } 3459 this.to = this._maps.push(map); 3460 if (mirrors != null) this.setMirror(this._maps.length - 1, mirrors); 3461 } 3462 appendMapping(mapping) { 3463 for (let i$1 = 0, startSize = this._maps.length; i$1 < mapping._maps.length; i$1++) { 3464 let mirr = mapping.getMirror(i$1); 3465 this.appendMap(mapping._maps[i$1], mirr != null && mirr < i$1 ? startSize + mirr : void 0); 3466 } 3467 } 3468 getMirror(n) { 3469 if (this.mirror) { 3470 for (let i$1 = 0; i$1 < this.mirror.length; i$1++) if (this.mirror[i$1] == n) return this.mirror[i$1 + (i$1 % 2 ? -1 : 1)]; 3471 } 3472 } 3473 setMirror(n, m) { 3474 if (!this.mirror) this.mirror = []; 3475 this.mirror.push(n, m); 3476 } 3477 appendMappingInverted(mapping) { 3478 for (let i$1 = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i$1 >= 0; i$1--) { 3479 let mirr = mapping.getMirror(i$1); 3480 this.appendMap(mapping._maps[i$1].invert(), mirr != null && mirr > i$1 ? totalSize - mirr - 1 : void 0); 3481 } 3482 } 3483 invert() { 3484 let inverse = new Mapping(); 3485 inverse.appendMappingInverted(this); 3486 return inverse; 3487 } 3488 map(pos, assoc = 1) { 3489 if (this.mirror) return this._map(pos, assoc, true); 3490 for (let i$1 = this.from; i$1 < this.to; i$1++) pos = this._maps[i$1].map(pos, assoc); 3491 return pos; 3492 } 3493 mapResult(pos, assoc = 1) { 3494 return this._map(pos, assoc, false); 3495 } 3496 _map(pos, assoc, simple) { 3497 let delInfo = 0; 3498 for (let i$1 = this.from; i$1 < this.to; i$1++) { 3499 let result = this._maps[i$1].mapResult(pos, assoc); 3500 if (result.recover != null) { 3501 let corr = this.getMirror(i$1); 3502 if (corr != null && corr > i$1 && corr < this.to) { 3503 i$1 = corr; 3504 pos = this._maps[corr].recover(result.recover); 3505 continue; 3506 } 3507 } 3508 delInfo |= result.delInfo; 3509 pos = result.pos; 3510 } 3511 return simple ? pos : new MapResult(pos, delInfo, null); 3512 } 3513}; 3514var stepsByID = Object.create(null); 3515var Step = class { 3516 getMap() { 3517 return StepMap.empty; 3518 } 3519 merge(other) { 3520 return null; 3521 } 3522 static fromJSON(schema, json) { 3523 if (!json || !json.stepType) throw new RangeError("Invalid input for Step.fromJSON"); 3524 let type = stepsByID[json.stepType]; 3525 if (!type) throw new RangeError(`No step type ${json.stepType} defined`); 3526 return type.fromJSON(schema, json); 3527 } 3528 static jsonID(id, stepClass) { 3529 if (id in stepsByID) throw new RangeError("Duplicate use of step JSON ID " + id); 3530 stepsByID[id] = stepClass; 3531 stepClass.prototype.jsonID = id; 3532 return stepClass; 3533 } 3534}; 3535var StepResult = class StepResult { 3536 constructor(doc$2, failed) { 3537 this.doc = doc$2; 3538 this.failed = failed; 3539 } 3540 static ok(doc$2) { 3541 return new StepResult(doc$2, null); 3542 } 3543 static fail(message) { 3544 return new StepResult(null, message); 3545 } 3546 static fromReplace(doc$2, from, to, slice) { 3547 try { 3548 return StepResult.ok(doc$2.replace(from, to, slice)); 3549 } catch (e) { 3550 if (e instanceof ReplaceError) return StepResult.fail(e.message); 3551 throw e; 3552 } 3553 } 3554}; 3555function mapFragment(fragment, f, parent) { 3556 let mapped = []; 3557 for (let i$1 = 0; i$1 < fragment.childCount; i$1++) { 3558 let child = fragment.child(i$1); 3559 if (child.content.size) child = child.copy(mapFragment(child.content, f, child)); 3560 if (child.isInline) child = f(child, parent, i$1); 3561 mapped.push(child); 3562 } 3563 return Fragment.fromArray(mapped); 3564} 3565var AddMarkStep = class AddMarkStep extends Step { 3566 constructor(from, to, mark) { 3567 super(); 3568 this.from = from; 3569 this.to = to; 3570 this.mark = mark; 3571 } 3572 apply(doc$2) { 3573 let oldSlice = doc$2.slice(this.from, this.to), $from = doc$2.resolve(this.from); 3574 let parent = $from.node($from.sharedDepth(this.to)); 3575 let slice = new Slice(mapFragment(oldSlice.content, (node, parent$1) => { 3576 if (!node.isAtom || !parent$1.type.allowsMarkType(this.mark.type)) return node; 3577 return node.mark(this.mark.addToSet(node.marks)); 3578 }, parent), oldSlice.openStart, oldSlice.openEnd); 3579 return StepResult.fromReplace(doc$2, this.from, this.to, slice); 3580 } 3581 invert() { 3582 return new RemoveMarkStep(this.from, this.to, this.mark); 3583 } 3584 map(mapping) { 3585 let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); 3586 if (from.deleted && to.deleted || from.pos >= to.pos) return null; 3587 return new AddMarkStep(from.pos, to.pos, this.mark); 3588 } 3589 merge(other) { 3590 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); 3591 return null; 3592 } 3593 toJSON() { 3594 return { 3595 stepType: "addMark", 3596 mark: this.mark.toJSON(), 3597 from: this.from, 3598 to: this.to 3599 }; 3600 } 3601 static fromJSON(schema, json) { 3602 if (typeof json.from != "number" || typeof json.to != "number") throw new RangeError("Invalid input for AddMarkStep.fromJSON"); 3603 return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark)); 3604 } 3605}; 3606Step.jsonID("addMark", AddMarkStep); 3607var RemoveMarkStep = class RemoveMarkStep extends Step { 3608 constructor(from, to, mark) { 3609 super(); 3610 this.from = from; 3611 this.to = to; 3612 this.mark = mark; 3613 } 3614 apply(doc$2) { 3615 let oldSlice = doc$2.slice(this.from, this.to); 3616 let slice = new Slice(mapFragment(oldSlice.content, (node) => { 3617 return node.mark(this.mark.removeFromSet(node.marks)); 3618 }, doc$2), oldSlice.openStart, oldSlice.openEnd); 3619 return StepResult.fromReplace(doc$2, this.from, this.to, slice); 3620 } 3621 invert() { 3622 return new AddMarkStep(this.from, this.to, this.mark); 3623 } 3624 map(mapping) { 3625 let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); 3626 if (from.deleted && to.deleted || from.pos >= to.pos) return null; 3627 return new RemoveMarkStep(from.pos, to.pos, this.mark); 3628 } 3629 merge(other) { 3630 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); 3631 return null; 3632 } 3633 toJSON() { 3634 return { 3635 stepType: "removeMark", 3636 mark: this.mark.toJSON(), 3637 from: this.from, 3638 to: this.to 3639 }; 3640 } 3641 static fromJSON(schema, json) { 3642 if (typeof json.from != "number" || typeof json.to != "number") throw new RangeError("Invalid input for RemoveMarkStep.fromJSON"); 3643 return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark)); 3644 } 3645}; 3646Step.jsonID("removeMark", RemoveMarkStep); 3647var AddNodeMarkStep = class AddNodeMarkStep extends Step { 3648 constructor(pos, mark) { 3649 super(); 3650 this.pos = pos; 3651 this.mark = mark; 3652 } 3653 apply(doc$2) { 3654 let node = doc$2.nodeAt(this.pos); 3655 if (!node) return StepResult.fail("No node at mark step's position"); 3656 let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks)); 3657 return StepResult.fromReplace(doc$2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); 3658 } 3659 invert(doc$2) { 3660 let node = doc$2.nodeAt(this.pos); 3661 if (node) { 3662 let newSet = this.mark.addToSet(node.marks); 3663 if (newSet.length == node.marks.length) { 3664 for (let i$1 = 0; i$1 < node.marks.length; i$1++) if (!node.marks[i$1].isInSet(newSet)) return new AddNodeMarkStep(this.pos, node.marks[i$1]); 3665 return new AddNodeMarkStep(this.pos, this.mark); 3666 } 3667 } 3668 return new RemoveNodeMarkStep(this.pos, this.mark); 3669 } 3670 map(mapping) { 3671 let pos = mapping.mapResult(this.pos, 1); 3672 return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark); 3673 } 3674 toJSON() { 3675 return { 3676 stepType: "addNodeMark", 3677 pos: this.pos, 3678 mark: this.mark.toJSON() 3679 }; 3680 } 3681 static fromJSON(schema, json) { 3682 if (typeof json.pos != "number") throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON"); 3683 return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark)); 3684 } 3685}; 3686Step.jsonID("addNodeMark", AddNodeMarkStep); 3687var RemoveNodeMarkStep = class RemoveNodeMarkStep extends Step { 3688 constructor(pos, mark) { 3689 super(); 3690 this.pos = pos; 3691 this.mark = mark; 3692 } 3693 apply(doc$2) { 3694 let node = doc$2.nodeAt(this.pos); 3695 if (!node) return StepResult.fail("No node at mark step's position"); 3696 let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks)); 3697 return StepResult.fromReplace(doc$2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); 3698 } 3699 invert(doc$2) { 3700 let node = doc$2.nodeAt(this.pos); 3701 if (!node || !this.mark.isInSet(node.marks)) return this; 3702 return new AddNodeMarkStep(this.pos, this.mark); 3703 } 3704 map(mapping) { 3705 let pos = mapping.mapResult(this.pos, 1); 3706 return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark); 3707 } 3708 toJSON() { 3709 return { 3710 stepType: "removeNodeMark", 3711 pos: this.pos, 3712 mark: this.mark.toJSON() 3713 }; 3714 } 3715 static fromJSON(schema, json) { 3716 if (typeof json.pos != "number") throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON"); 3717 return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark)); 3718 } 3719}; 3720Step.jsonID("removeNodeMark", RemoveNodeMarkStep); 3721var ReplaceStep = class ReplaceStep extends Step { 3722 constructor(from, to, slice, structure = false) { 3723 super(); 3724 this.from = from; 3725 this.to = to; 3726 this.slice = slice; 3727 this.structure = structure; 3728 } 3729 apply(doc$2) { 3730 if (this.structure && contentBetween(doc$2, this.from, this.to)) return StepResult.fail("Structure replace would overwrite content"); 3731 return StepResult.fromReplace(doc$2, this.from, this.to, this.slice); 3732 } 3733 getMap() { 3734 return new StepMap([ 3735 this.from, 3736 this.to - this.from, 3737 this.slice.size 3738 ]); 3739 } 3740 invert(doc$2) { 3741 return new ReplaceStep(this.from, this.from + this.slice.size, doc$2.slice(this.from, this.to)); 3742 } 3743 map(mapping) { 3744 let to = mapping.mapResult(this.to, -1); 3745 let from = this.from == this.to && ReplaceStep.MAP_BIAS < 0 ? to : mapping.mapResult(this.from, 1); 3746 if (from.deletedAcross && to.deletedAcross) return null; 3747 return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice, this.structure); 3748 } 3749 merge(other) { 3750 if (!(other instanceof ReplaceStep) || other.structure || this.structure) return null; 3751 if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) { 3752 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); 3753 return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure); 3754 } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) { 3755 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); 3756 return new ReplaceStep(other.from, this.to, slice, this.structure); 3757 } else return null; 3758 } 3759 toJSON() { 3760 let json = { 3761 stepType: "replace", 3762 from: this.from, 3763 to: this.to 3764 }; 3765 if (this.slice.size) json.slice = this.slice.toJSON(); 3766 if (this.structure) json.structure = true; 3767 return json; 3768 } 3769 static fromJSON(schema, json) { 3770 if (typeof json.from != "number" || typeof json.to != "number") throw new RangeError("Invalid input for ReplaceStep.fromJSON"); 3771 return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure); 3772 } 3773}; 3774ReplaceStep.MAP_BIAS = 1; 3775Step.jsonID("replace", ReplaceStep); 3776var ReplaceAroundStep = class ReplaceAroundStep extends Step { 3777 constructor(from, to, gapFrom, gapTo, slice, insert, structure = false) { 3778 super(); 3779 this.from = from; 3780 this.to = to; 3781 this.gapFrom = gapFrom; 3782 this.gapTo = gapTo; 3783 this.slice = slice; 3784 this.insert = insert; 3785 this.structure = structure; 3786 } 3787 apply(doc$2) { 3788 if (this.structure && (contentBetween(doc$2, this.from, this.gapFrom) || contentBetween(doc$2, this.gapTo, this.to))) return StepResult.fail("Structure gap-replace would overwrite content"); 3789 let gap = doc$2.slice(this.gapFrom, this.gapTo); 3790 if (gap.openStart || gap.openEnd) return StepResult.fail("Gap is not a flat range"); 3791 let inserted = this.slice.insertAt(this.insert, gap.content); 3792 if (!inserted) return StepResult.fail("Content does not fit in gap"); 3793 return StepResult.fromReplace(doc$2, this.from, this.to, inserted); 3794 } 3795 getMap() { 3796 return new StepMap([ 3797 this.from, 3798 this.gapFrom - this.from, 3799 this.insert, 3800 this.gapTo, 3801 this.to - this.gapTo, 3802 this.slice.size - this.insert 3803 ]); 3804 } 3805 invert(doc$2) { 3806 let gap = this.gapTo - this.gapFrom; 3807 return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc$2.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure); 3808 } 3809 map(mapping) { 3810 let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); 3811 let gapFrom = this.from == this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1); 3812 let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1); 3813 if (from.deletedAcross && to.deletedAcross || gapFrom < from.pos || gapTo > to.pos) return null; 3814 return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure); 3815 } 3816 toJSON() { 3817 let json = { 3818 stepType: "replaceAround", 3819 from: this.from, 3820 to: this.to, 3821 gapFrom: this.gapFrom, 3822 gapTo: this.gapTo, 3823 insert: this.insert 3824 }; 3825 if (this.slice.size) json.slice = this.slice.toJSON(); 3826 if (this.structure) json.structure = true; 3827 return json; 3828 } 3829 static fromJSON(schema, json) { 3830 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"); 3831 return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure); 3832 } 3833}; 3834Step.jsonID("replaceAround", ReplaceAroundStep); 3835function contentBetween(doc$2, from, to) { 3836 let $from = doc$2.resolve(from), dist = to - from, depth = $from.depth; 3837 while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) { 3838 depth--; 3839 dist--; 3840 } 3841 if (dist > 0) { 3842 let next = $from.node(depth).maybeChild($from.indexAfter(depth)); 3843 while (dist > 0) { 3844 if (!next || next.isLeaf) return true; 3845 next = next.firstChild; 3846 dist--; 3847 } 3848 } 3849 return false; 3850} 3851function addMark(tr$1, from, to, mark) { 3852 let removed$1 = [], added = []; 3853 let removing, adding; 3854 tr$1.doc.nodesBetween(from, to, (node, pos, parent) => { 3855 if (!node.isInline) return; 3856 let marks = node.marks; 3857 if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) { 3858 let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to); 3859 let newSet = mark.addToSet(marks); 3860 for (let i$1 = 0; i$1 < marks.length; i$1++) if (!marks[i$1].isInSet(newSet)) if (removing && removing.to == start && removing.mark.eq(marks[i$1])) removing.to = end; 3861 else removed$1.push(removing = new RemoveMarkStep(start, end, marks[i$1])); 3862 if (adding && adding.to == start) adding.to = end; 3863 else added.push(adding = new AddMarkStep(start, end, mark)); 3864 } 3865 }); 3866 removed$1.forEach((s) => tr$1.step(s)); 3867 added.forEach((s) => tr$1.step(s)); 3868} 3869function removeMark(tr$1, from, to, mark) { 3870 let matched = [], step = 0; 3871 tr$1.doc.nodesBetween(from, to, (node, pos) => { 3872 if (!node.isInline) return; 3873 step++; 3874 let toRemove = null; 3875 if (mark instanceof MarkType) { 3876 let set = node.marks, found$1; 3877 while (found$1 = mark.isInSet(set)) { 3878 (toRemove || (toRemove = [])).push(found$1); 3879 set = found$1.removeFromSet(set); 3880 } 3881 } else if (mark) { 3882 if (mark.isInSet(node.marks)) toRemove = [mark]; 3883 } else toRemove = node.marks; 3884 if (toRemove && toRemove.length) { 3885 let end = Math.min(pos + node.nodeSize, to); 3886 for (let i$1 = 0; i$1 < toRemove.length; i$1++) { 3887 let style$1 = toRemove[i$1], found$1; 3888 for (let j = 0; j < matched.length; j++) { 3889 let m = matched[j]; 3890 if (m.step == step - 1 && style$1.eq(matched[j].style)) found$
vendor: 27,176 bytes, lines 3890-4490
38901 = m; 3891 } 3892 if (found$1) { 3893 found$1.to = end; 3894 found$1.step = step; 3895 } else matched.push({ 3896 style: style$1, 3897 from: Math.max(pos, from), 3898 to: end, 3899 step 3900 }); 3901 } 3902 } 3903 }); 3904 matched.forEach((m) => tr$1.step(new RemoveMarkStep(m.from, m.to, m.style))); 3905} 3906function clearIncompatible(tr$1, pos, parentType, match = parentType.contentMatch, clearNewlines = true) { 3907 let node = tr$1.doc.nodeAt(pos); 3908 let replSteps = [], cur = pos + 1; 3909 for (let i$1 = 0; i$1 < node.childCount; i$1++) { 3910 let child = node.child(i$1), end = cur + child.nodeSize; 3911 let allowed = match.matchType(child.type); 3912 if (!allowed) replSteps.push(new ReplaceStep(cur, end, Slice.empty)); 3913 else { 3914 match = allowed; 3915 for (let j = 0; j < child.marks.length; j++) if (!parentType.allowsMarkType(child.marks[j].type)) tr$1.step(new RemoveMarkStep(cur, end, child.marks[j])); 3916 if (clearNewlines && child.isText && parentType.whitespace != "pre") { 3917 let m, newline = /\r?\n|\r/g, slice; 3918 while (m = newline.exec(child.text)) { 3919 if (!slice) slice = new Slice(Fragment.from(parentType.schema.text(" ", parentType.allowedMarks(child.marks))), 0, 0); 3920 replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice)); 3921 } 3922 } 3923 } 3924 cur = end; 3925 } 3926 if (!match.validEnd) { 3927 let fill = match.fillBefore(Fragment.empty, true); 3928 tr$1.replace(cur, cur, new Slice(fill, 0, 0)); 3929 } 3930 for (let i$1 = replSteps.length - 1; i$1 >= 0; i$1--) tr$1.step(replSteps[i$1]); 3931} 3932function canCut(node, start, end) { 3933 return (start == 0 || node.canReplace(start, node.childCount)) && (end == node.childCount || node.canReplace(0, end)); 3934} 3935function liftTarget(range) { 3936 let content = range.parent.content.cutByIndex(range.startIndex, range.endIndex); 3937 for (let depth = range.depth, contentBefore = 0, contentAfter = 0;; --depth) { 3938 let node = range.$from.node(depth); 3939 let index = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter; 3940 if (depth < range.depth && node.canReplace(index, endIndex, content)) return depth; 3941 if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex)) break; 3942 if (index) contentBefore = 1; 3943 if (endIndex < node.childCount) contentAfter = 1; 3944 } 3945 return null; 3946} 3947function lift$2(tr$1, range, target) { 3948 let { $from, $to, depth } = range; 3949 let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1); 3950 let start = gapStart, end = gapEnd; 3951 let before = Fragment.empty, openStart = 0; 3952 for (let d = depth, splitting = false; d > target; d--) if (splitting || $from.index(d) > 0) { 3953 splitting = true; 3954 before = Fragment.from($from.node(d).copy(before)); 3955 openStart++; 3956 } else start--; 3957 let after = Fragment.empty, openEnd = 0; 3958 for (let d = depth, splitting = false; d > target; d--) if (splitting || $to.after(d + 1) < $to.end(d)) { 3959 splitting = true; 3960 after = Fragment.from($to.node(d).copy(after)); 3961 openEnd++; 3962 } else end++; 3963 tr$1.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true)); 3964} 3965function findWrapping(range, nodeType, attrs = null, innerRange = range) { 3966 let around = findWrappingOutside(range, nodeType); 3967 let inner = around && findWrappingInside(innerRange, nodeType); 3968 if (!inner) return null; 3969 return around.map(withAttrs).concat({ 3970 type: nodeType, 3971 attrs 3972 }).concat(inner.map(withAttrs)); 3973} 3974function withAttrs(type) { 3975 return { 3976 type, 3977 attrs: null 3978 }; 3979} 3980function findWrappingOutside(range, type) { 3981 let { parent, startIndex, endIndex } = range; 3982 let around = parent.contentMatchAt(startIndex).findWrapping(type); 3983 if (!around) return null; 3984 let outer = around.length ? around[0] : type; 3985 return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null; 3986} 3987function findWrappingInside(range, type) { 3988 let { parent, startIndex, endIndex } = range; 3989 let inner = parent.child(startIndex); 3990 let inside = type.contentMatch.findWrapping(inner.type); 3991 if (!inside) return null; 3992 let innerMatch = (inside.length ? inside[inside.length - 1] : type).contentMatch; 3993 for (let i$1 = startIndex; innerMatch && i$1 < endIndex; i$1++) innerMatch = innerMatch.matchType(parent.child(i$1).type); 3994 if (!innerMatch || !innerMatch.validEnd) return null; 3995 return inside; 3996} 3997function wrap(tr$1, range, wrappers) { 3998 let content = Fragment.empty; 3999 for (let i$1 = wrappers.length - 1; i$1 >= 0; i$1--) { 4000 if (content.size) { 4001 let match = wrappers[i$1].type.contentMatch.matchFragment(content); 4002 if (!match || !match.validEnd) throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper"); 4003 } 4004 content = Fragment.from(wrappers[i$1].type.create(wrappers[i$1].attrs, content)); 4005 } 4006 let start = range.start, end = range.end; 4007 tr$1.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true)); 4008} 4009function setBlockType$1(tr$1, from, to, type, attrs) { 4010 if (!type.isTextblock) throw new RangeError("Type given to setBlockType should be a textblock"); 4011 let mapFrom = tr$1.steps.length; 4012 tr$1.doc.nodesBetween(from, to, (node, pos) => { 4013 let attrsHere = typeof attrs == "function" ? attrs(node) : attrs; 4014 if (node.isTextblock && !node.hasMarkup(type, attrsHere) && canChangeType(tr$1.doc, tr$1.mapping.slice(mapFrom).map(pos), type)) { 4015 let convertNewlines = null; 4016 if (type.schema.linebreakReplacement) { 4017 let pre = type.whitespace == "pre", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement); 4018 if (pre && !supportLinebreak) convertNewlines = false; 4019 else if (!pre && supportLinebreak) convertNewlines = true; 4020 } 4021 if (convertNewlines === false) replaceLinebreaks(tr$1, node, pos, mapFrom); 4022 clearIncompatible(tr$1, tr$1.mapping.slice(mapFrom).map(pos, 1), type, void 0, convertNewlines === null); 4023 let mapping = tr$1.mapping.slice(mapFrom); 4024 let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1); 4025 tr$1.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true)); 4026 if (convertNewlines === true) replaceNewlines(tr$1, node, pos, mapFrom); 4027 return false; 4028 } 4029 }); 4030} 4031function replaceNewlines(tr$1, node, pos, mapFrom) { 4032 node.forEach((child, offset) => { 4033 if (child.isText) { 4034 let m, newline = /\r?\n|\r/g; 4035 while (m = newline.exec(child.text)) { 4036 let start = tr$1.mapping.slice(mapFrom).map(pos + 1 + offset + m.index); 4037 tr$1.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create()); 4038 } 4039 } 4040 }); 4041} 4042function replaceLinebreaks(tr$1, node, pos, mapFrom) { 4043 node.forEach((child, offset) => { 4044 if (child.type == child.type.schema.linebreakReplacement) { 4045 let start = tr$1.mapping.slice(mapFrom).map(pos + 1 + offset); 4046 tr$1.replaceWith(start, start + 1, node.type.schema.text("\n")); 4047 } 4048 }); 4049} 4050function canChangeType(doc$2, pos, type) { 4051 let $pos = doc$2.resolve(pos), index = $pos.index(); 4052 return $pos.parent.canReplaceWith(index, index + 1, type); 4053} 4054function setNodeMarkup(tr$1, pos, type, attrs, marks) { 4055 let node = tr$1.doc.nodeAt(pos); 4056 if (!node) throw new RangeError("No node at given position"); 4057 if (!type) type = node.type; 4058 let newNode = type.create(attrs, null, marks || node.marks); 4059 if (node.isLeaf) return tr$1.replaceWith(pos, pos + node.nodeSize, newNode); 4060 if (!type.validContent(node.content)) throw new RangeError("Invalid content for node type " + type.name); 4061 tr$1.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true)); 4062} 4063function canSplit(doc$2, pos, depth = 1, typesAfter) { 4064 let $pos = doc$2.resolve(pos), base$1 = $pos.depth - depth; 4065 let innerType = typesAfter && typesAfter[typesAfter.length - 1] || $pos.parent; 4066 if (base$1 < 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; 4067 for (let d = $pos.depth - 1, i$1 = depth - 2; d > base$1; d--, i$1--) { 4068 let node = $pos.node(d), index$1 = $pos.index(d); 4069 if (node.type.spec.isolating) return false; 4070 let rest = node.content.cutByIndex(index$1, node.childCount); 4071 let overrideChild = typesAfter && typesAfter[i$1 + 1]; 4072 if (overrideChild) rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs)); 4073 let after = typesAfter && typesAfter[i$1] || node; 4074 if (!node.canReplace(index$1 + 1, node.childCount) || !after.type.validContent(rest)) return false; 4075 } 4076 let index = $pos.indexAfter(base$1); 4077 let baseType = typesAfter && typesAfter[0]; 4078 return $pos.node(base$1).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base$1 + 1).type); 4079} 4080function split(tr$1, pos, depth = 1, typesAfter) { 4081 let $pos = tr$1.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty; 4082 for (let d = $pos.depth, e = $pos.depth - depth, i$1 = depth - 1; d > e; d--, i$1--) { 4083 before = Fragment.from($pos.node(d).copy(before)); 4084 let typeAfter = typesAfter && typesAfter[i$1]; 4085 after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after)); 4086 } 4087 tr$1.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true)); 4088} 4089function canJoin(doc$2, pos) { 4090 let $pos = doc$2.resolve(pos), index = $pos.index(); 4091 return joinable($pos.nodeBefore, $pos.nodeAfter) && $pos.parent.canReplace(index, index + 1); 4092} 4093function canAppendWithSubstitutedLinebreaks(a, b) { 4094 if (!b.content.size) a.type.compatibleContent(b.type); 4095 let match = a.contentMatchAt(a.childCount); 4096 let { linebreakReplacement } = a.type.schema; 4097 for (let i$1 = 0; i$1 < b.childCount; i$1++) { 4098 let child = b.child(i$1); 4099 let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type; 4100 match = match.matchType(type); 4101 if (!match) return false; 4102 if (!a.type.allowsMarks(child.marks)) return false; 4103 } 4104 return match.validEnd; 4105} 4106function joinable(a, b) { 4107 return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b)); 4108} 4109function joinPoint(doc$2, pos, dir = -1) { 4110 let $pos = doc$2.resolve(pos); 4111 for (let d = $pos.depth;; d--) { 4112 let before, after, index = $pos.index(d); 4113 if (d == $pos.depth) { 4114 before = $pos.nodeBefore; 4115 after = $pos.nodeAfter; 4116 } else if (dir > 0) { 4117 before = $pos.node(d + 1); 4118 index++; 4119 after = $pos.node(d).maybeChild(index); 4120 } else { 4121 before = $pos.node(d).maybeChild(index - 1); 4122 after = $pos.node(d + 1); 4123 } 4124 if (before && !before.isTextblock && joinable(before, after) && $pos.node(d).canReplace(index, index + 1)) return pos; 4125 if (d == 0) break; 4126 pos = dir < 0 ? $pos.before(d) : $pos.after(d); 4127 } 4128} 4129function join(tr$1, pos, depth) { 4130 let convertNewlines = null; 4131 let { linebreakReplacement } = tr$1.doc.type.schema; 4132 let $before = tr$1.doc.resolve(pos - depth), beforeType = $before.node().type; 4133 if (linebreakReplacement && beforeType.inlineContent) { 4134 let pre = beforeType.whitespace == "pre"; 4135 let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement); 4136 if (pre && !supportLinebreak) convertNewlines = false; 4137 else if (!pre && supportLinebreak) convertNewlines = true; 4138 } 4139 let mapFrom = tr$1.steps.length; 4140 if (convertNewlines === false) { 4141 let $after = tr$1.doc.resolve(pos + depth); 4142 replaceLinebreaks(tr$1, $after.node(), $after.before(), mapFrom); 4143 } 4144 if (beforeType.inlineContent) clearIncompatible(tr$1, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null); 4145 let mapping = tr$1.mapping.slice(mapFrom), start = mapping.map(pos - depth); 4146 tr$1.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true)); 4147 if (convertNewlines === true) { 4148 let $full = tr$1.doc.resolve(start); 4149 replaceNewlines(tr$1, $full.node(), $full.before(), tr$1.steps.length); 4150 } 4151 return tr$1; 4152} 4153function insertPoint(doc$2, pos, nodeType) { 4154 let $pos = doc$2.resolve(pos); 4155 if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType)) return pos; 4156 if ($pos.parentOffset == 0) for (let d = $pos.depth - 1; d >= 0; d--) { 4157 let index = $pos.index(d); 4158 if ($pos.node(d).canReplaceWith(index, index, nodeType)) return $pos.before(d + 1); 4159 if (index > 0) return null; 4160 } 4161 if ($pos.parentOffset == $pos.parent.content.size) for (let d = $pos.depth - 1; d >= 0; d--) { 4162 let index = $pos.indexAfter(d); 4163 if ($pos.node(d).canReplaceWith(index, index, nodeType)) return $pos.after(d + 1); 4164 if (index < $pos.node(d).childCount) return null; 4165 } 4166 return null; 4167} 4168function dropPoint(doc$2, pos, slice) { 4169 let $pos = doc$2.resolve(pos); 4170 if (!slice.content.size) return pos; 4171 let content = slice.content; 4172 for (let i$1 = 0; i$1 < slice.openStart; i$1++) content = content.firstChild.content; 4173 for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) for (let d = $pos.depth; d >= 0; d--) { 4174 let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1; 4175 let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0); 4176 let parent = $pos.node(d), fits = false; 4177 if (pass == 1) fits = parent.canReplace(insertPos, insertPos, content); 4178 else { 4179 let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type); 4180 fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]); 4181 } 4182 if (fits) return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1); 4183 } 4184 return null; 4185} 4186function replaceStep(doc$2, from, to = from, slice = Slice.empty) { 4187 if (from == to && !slice.size) return null; 4188 let $from = doc$2.resolve(from), $to = doc$2.resolve(to); 4189 if (fitsTrivially($from, $to, slice)) return new ReplaceStep(from, to, slice); 4190 return new Fitter($from, $to, slice).fit(); 4191} 4192function fitsTrivially($from, $to, slice) { 4193 return !slice.openStart && !slice.openEnd && $from.start() == $to.start() && $from.parent.canReplace($from.index(), $to.index(), slice.content); 4194} 4195var Fitter = class { 4196 constructor($from, $to, unplaced) { 4197 this.$from = $from; 4198 this.$to = $to; 4199 this.unplaced = unplaced; 4200 this.frontier = []; 4201 this.placed = Fragment.empty; 4202 for (let i$1 = 0; i$1 <= $from.depth; i$1++) { 4203 let node = $from.node(i$1); 4204 this.frontier.push({ 4205 type: node.type, 4206 match: node.contentMatchAt($from.indexAfter(i$1)) 4207 }); 4208 } 4209 for (let i$1 = $from.depth; i$1 > 0; i$1--) this.placed = Fragment.from($from.node(i$1).copy(this.placed)); 4210 } 4211 get depth() { 4212 return this.frontier.length - 1; 4213 } 4214 fit() { 4215 while (this.unplaced.size) { 4216 let fit = this.findFittable(); 4217 if (fit) this.placeNodes(fit); 4218 else this.openMore() || this.dropNode(); 4219 } 4220 let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth; 4221 let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline)); 4222 if (!$to) return null; 4223 let content = this.placed, openStart = $from.depth, openEnd = $to.depth; 4224 while (openStart && openEnd && content.childCount == 1) { 4225 content = content.firstChild.content; 4226 openStart--; 4227 openEnd--; 4228 } 4229 let slice = new Slice(content, openStart, openEnd); 4230 if (moveInline > -1) return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize); 4231 if (slice.size || $from.pos != this.$to.pos) return new ReplaceStep($from.pos, $to.pos, slice); 4232 return null; 4233 } 4234 findFittable() { 4235 let startDepth = this.unplaced.openStart; 4236 for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) { 4237 let node = cur.firstChild; 4238 if (cur.childCount > 1) openEnd = 0; 4239 if (node.type.spec.isolating && openEnd <= d) { 4240 startDepth = d; 4241 break; 4242 } 4243 cur = node.content; 4244 } 4245 for (let pass = 1; pass <= 2; pass++) for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) { 4246 let fragment, parent = null; 4247 if (sliceDepth) { 4248 parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild; 4249 fragment = parent.content; 4250 } else fragment = this.unplaced.content; 4251 let first$1 = fragment.firstChild; 4252 for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) { 4253 let { type, match } = this.frontier[frontierDepth], wrap$1, inject = null; 4254 if (pass == 1 && (first$1 ? match.matchType(first$1.type) || (inject = match.fillBefore(Fragment.from(first$1), false)) : parent && type.compatibleContent(parent.type))) return { 4255 sliceDepth, 4256 frontierDepth, 4257 parent, 4258 inject 4259 }; 4260 else if (pass == 2 && first$1 && (wrap$1 = match.findWrapping(first$1.type))) return { 4261 sliceDepth, 4262 frontierDepth, 4263 parent, 4264 wrap: wrap$1 4265 }; 4266 if (parent && match.matchType(parent.type)) break; 4267 } 4268 } 4269 } 4270 openMore() { 4271 let { content, openStart, openEnd } = this.unplaced; 4272 if (maxOpen(content, -1) <= openStart) return false; 4273 if (this.unplaced.size > 1 && maxOpen(content, 1) > openEnd) openEnd++; 4274 this.unplaced = new Slice(content, openStart + 1, openEnd); 4275 return true; 4276 } 4277 dropNode() { 4278 let { content, openStart, openEnd } = this.unplaced; 4279 let inner = contentAt(content, openStart); 4280 if (inner.childCount <= 1 && openStart > 0) { 4281 let openAtEnd = content.size - openStart <= openStart + inner.size; 4282 this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd); 4283 } else this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd); 4284 } 4285 placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap: wrap$1 }) { 4286 while (this.depth > frontierDepth) this.closeFrontierNode(); 4287 if (wrap$1) for (let i$1 = 0; i$1 < wrap$1.length; i$1++) this.openFrontierNode(wrap$1[i$1]); 4288 let slice = this.unplaced, fragment = parent ? parent.content : slice.content; 4289 let openStart = slice.openStart - sliceDepth; 4290 let taken = 0, add = []; 4291 let { match, type } = this.frontier[frontierDepth]; 4292 if (inject) { 4293 for (let i$1 = 0; i$1 < inject.childCount; i$1++) add.push(inject.child(i$1)); 4294 match = match.matchFragment(inject); 4295 } 4296 let openEndCount = fragment.size + sliceDepth - (slice.content.size - slice.openEnd); 4297 while (taken < fragment.childCount) { 4298 let next = fragment.child(taken), matches$1 = match.matchType(next.type); 4299 if (!matches$1) break; 4300 taken++; 4301 if (taken > 1 || openStart == 0 || next.content.size) { 4302 match = matches$1; 4303 add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1)); 4304 } 4305 } 4306 let toEnd = taken == fragment.childCount; 4307 if (!toEnd) openEndCount = -1; 4308 this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add)); 4309 this.frontier[frontierDepth].match = match; 4310 if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1) this.closeFrontierNode(); 4311 for (let i$1 = 0, cur = fragment; i$1 < openEndCount; i$1++) { 4312 let node = cur.lastChild; 4313 this.frontier.push({ 4314 type: node.type, 4315 match: node.contentMatchAt(node.childCount) 4316 }); 4317 cur = node.content; 4318 } 4319 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); 4320 } 4321 mustMoveInline() { 4322 if (!this.$to.parent.isTextblock) return -1; 4323 let top = this.frontier[this.depth], level; 4324 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; 4325 let { depth } = this.$to, after = this.$to.after(depth); 4326 while (depth > 1 && after == this.$to.end(--depth)) ++after; 4327 return after; 4328 } 4329 findCloseLevel($to) { 4330 scan: for (let i$1 = Math.min(this.depth, $to.depth); i$1 >= 0; i$1--) { 4331 let { match, type } = this.frontier[i$1]; 4332 let dropInner = i$1 < $to.depth && $to.end(i$1 + 1) == $to.pos + ($to.depth - (i$1 + 1)); 4333 let fit = contentAfterFits($to, i$1, type, match, dropInner); 4334 if (!fit) continue; 4335 for (let d = i$1 - 1; d >= 0; d--) { 4336 let { match: match$1, type: type$1 } = this.frontier[d]; 4337 let matches$1 = contentAfterFits($to, d, type$1, match$1, true); 4338 if (!matches$1 || matches$1.childCount) continue scan; 4339 } 4340 return { 4341 depth: i$1, 4342 fit, 4343 move: dropInner ? $to.doc.resolve($to.after(i$1 + 1)) : $to 4344 }; 4345 } 4346 } 4347 close($to) { 4348 let close$1 = this.findCloseLevel($to); 4349 if (!close$1) return null; 4350 while (this.depth > close$1.depth) this.closeFrontierNode(); 4351 if (close$1.fit.childCount) this.placed = addToFragment(this.placed, close$1.depth, close$1.fit); 4352 $to = close$1.move; 4353 for (let d = close$1.depth + 1; d <= $to.depth; d++) { 4354 let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d)); 4355 this.openFrontierNode(node.type, node.attrs, add); 4356 } 4357 return $to; 4358 } 4359 openFrontierNode(type, attrs = null, content) { 4360 let top = this.frontier[this.depth]; 4361 top.match = top.match.matchType(type); 4362 this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content))); 4363 this.frontier.push({ 4364 type, 4365 match: type.contentMatch 4366 }); 4367 } 4368 closeFrontierNode() { 4369 let add = this.frontier.pop().match.fillBefore(Fragment.empty, true); 4370 if (add.childCount) this.placed = addToFragment(this.placed, this.frontier.length, add); 4371 } 4372}; 4373function dropFromFragment(fragment, depth, count) { 4374 if (depth == 0) return fragment.cutByIndex(count, fragment.childCount); 4375 return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count))); 4376} 4377function addToFragment(fragment, depth, content) { 4378 if (depth == 0) return fragment.append(content); 4379 return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content))); 4380} 4381function contentAt(fragment, depth) { 4382 for (let i$1 = 0; i$1 < depth; i$1++) fragment = fragment.firstChild.content; 4383 return fragment; 4384} 4385function closeNodeStart(node, openStart, openEnd) { 4386 if (openStart <= 0) return node; 4387 let frag = node.content; 4388 if (openStart > 1) frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0)); 4389 if (openStart > 0) { 4390 frag = node.type.contentMatch.fillBefore(frag).append(frag); 4391 if (openEnd <= 0) frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true)); 4392 } 4393 return node.copy(frag); 4394} 4395function contentAfterFits($to, depth, type, match, open) { 4396 let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth); 4397 if (index == node.childCount && !type.compatibleContent(node.type)) return null; 4398 let fit = match.fillBefore(node.content, true, index); 4399 return fit && !invalidMarks(type, node.content, index) ? fit : null; 4400} 4401function invalidMarks(type, fragment, start) { 4402 for (let i$1 = start; i$1 < fragment.childCount; i$1++) if (!type.allowsMarks(fragment.child(i$1).marks)) return true; 4403 return false; 4404} 4405function definesContent(type) { 4406 return type.spec.defining || type.spec.definingForContent; 4407} 4408function maxOpen(frag, side) { 4409 for (let count = 0;; count++) { 4410 let ch = side < 0 ? frag.firstChild : frag.lastChild; 4411 if (!ch || ch.isAtom) return count; 4412 frag = ch.content; 4413 } 4414} 4415function replaceRange(tr$1, from, to, slice) { 4416 if (!slice.size) return tr$1.deleteRange(from, to); 4417 let $from = tr$1.doc.resolve(from), $to = tr$1.doc.resolve(to); 4418 if (fitsTrivially($from, $to, slice)) return tr$1.step(new ReplaceStep(from, to, slice)); 4419 let targetDepths = coveredDepths($from, $to); 4420 if (targetDepths[targetDepths.length - 1] == 0) targetDepths.pop(); 4421 let preferredTarget = -($from.depth + 1); 4422 targetDepths.unshift(preferredTarget); 4423 for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) { 4424 let spec = $from.node(d).type.spec; 4425 if (spec.defining || spec.definingAsContext || spec.isolating) break; 4426 if (targetDepths.indexOf(d) > -1) preferredTarget = d; 4427 else if ($from.before(d) == pos) targetDepths.splice(1, 0, -d); 4428 } 4429 let preferredTargetIndex = targetDepths.indexOf(preferredTarget); 4430 let leftNodes = [], preferredDepth = slice.openStart; 4431 for (let content = slice.content, i$1 = 0;; i$1++) { 4432 let node = content.firstChild; 4433 leftNodes.push(node); 4434 if (i$1 == slice.openStart) break; 4435 content = node.content; 4436 } 4437 for (let d = preferredDepth - 1; d >= 0; d--) { 4438 let leftNode = leftNodes[d], def = definesContent(leftNode.type); 4439 if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1))) preferredDepth = d; 4440 else if (def || !leftNode.type.isTextblock) break; 4441 } 4442 for (let j = slice.openStart; j >= 0; j--) { 4443 let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1); 4444 let insert = leftNodes[openDepth]; 4445 if (!insert) continue; 4446 for (let i$1 = 0; i$1 < targetDepths.length; i$1++) { 4447 let targetDepth = targetDepths[(i$1 + preferredTargetIndex) % targetDepths.length], expand = true; 4448 if (targetDepth < 0) { 4449 expand = false; 4450 targetDepth = -targetDepth; 4451 } 4452 let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1); 4453 if (parent.canReplaceWith(index, index, insert.type, insert.marks)) return tr$1.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd)); 4454 } 4455 } 4456 let startSteps = tr$1.steps.length; 4457 for (let i$1 = targetDepths.length - 1; i$1 >= 0; i$1--) { 4458 tr$1.replace(from, to, slice); 4459 if (tr$1.steps.length > startSteps) break; 4460 let depth = targetDepths[i$1]; 4461 if (depth < 0) continue; 4462 from = $from.before(depth); 4463 to = $to.after(depth); 4464 } 4465} 4466function closeFragment(fragment, depth, oldOpen, newOpen, parent) { 4467 if (depth < oldOpen) { 4468 let first$1 = fragment.firstChild; 4469 fragment = fragment.replaceChild(0, first$1.copy(closeFragment(first$1.content, depth + 1, oldOpen, newOpen, first$1))); 4470 } 4471 if (depth > newOpen) { 4472 let match = parent.contentMatchAt(0); 4473 let start = match.fillBefore(fragment).append(fragment); 4474 fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true)); 4475 } 4476 return fragment; 4477} 4478function replaceRangeWith(tr$1, from, to, node) { 4479 if (!node.isInline && from == to && tr$1.doc.resolve(from).parent.content.size) { 4480 let point = insertPoint(tr$1.doc, from, node.type); 4481 if (point != null) from = to = point; 4482 } 4483 tr$1.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0)); 4484} 4485function deleteRange$1(tr$1, from, to) { 4486 let $from = tr$1.doc.resolve(from), $to = tr$1.doc.resolve(to); 4487 if ($from.parent.isTextblock && $to.parent.isTextblock && $from.start() != $to.start() && $from.parentOffset == 0 && $to.parentOffset == 0) { 4488 let shared = $from.sharedDepth(to), isolated = false; 4489 for (let d = $from.depth; d > shared; d--) if ($from.node(d).type.spec.isolating) isolated = true; 4490 for (let d = $to.depth; d > shared;
vendor: 4,203 bytes, lines 4490-4602
4490 d--) if ($to.node(d).type.spec.isolating) isolated = true; 4491 if (!isolated) { 4492 for (let d = $from.depth; d > 0 && from == $from.start(d); d--) from = $from.before(d); 4493 for (let d = $to.depth; d > 0 && to == $to.start(d); d--) to = $to.before(d); 4494 $from = tr$1.doc.resolve(from); 4495 $to = tr$1.doc.resolve(to); 4496 } 4497 } 4498 let covered = coveredDepths($from, $to); 4499 for (let i$1 = 0; i$1 < covered.length; i$1++) { 4500 let depth = covered[i$1], last = i$1 == covered.length - 1; 4501 if (last && depth == 0 || $from.node(depth).type.contentMatch.validEnd) return tr$1.delete($from.start(depth), $to.end(depth)); 4502 if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1)))) return tr$1.delete($from.before(depth), $to.after(depth)); 4503 } 4504 for (let d = 1; d <= $from.depth && d <= $to.depth; d++) if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d && $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1))) return tr$1.delete($from.before(d), to); 4505 tr$1.delete(from, to); 4506} 4507function coveredDepths($from, $to) { 4508 let result = [], minDepth = Math.min($from.depth, $to.depth); 4509 for (let d = minDepth; d >= 0; d--) { 4510 let start = $from.start(d); 4511 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; 4512 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); 4513 } 4514 return result; 4515} 4516var AttrStep = class AttrStep extends Step { 4517 constructor(pos, attr, value) { 4518 super(); 4519 this.pos = pos; 4520 this.attr = attr; 4521 this.value = value; 4522 } 4523 apply(doc$2) { 4524 let node = doc$2.nodeAt(this.pos); 4525 if (!node) return StepResult.fail("No node at attribute step's position"); 4526 let attrs = Object.create(null); 4527 for (let name in node.attrs) attrs[name] = node.attrs[name]; 4528 attrs[this.attr] = this.value; 4529 let updated = node.type.create(attrs, null, node.marks); 4530 return StepResult.fromReplace(doc$2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); 4531 } 4532 getMap() { 4533 return StepMap.empty; 4534 } 4535 invert(doc$2) { 4536 return new AttrStep(this.pos, this.attr, doc$2.nodeAt(this.pos).attrs[this.attr]); 4537 } 4538 map(mapping) { 4539 let pos = mapping.mapResult(this.pos, 1); 4540 return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value); 4541 } 4542 toJSON() { 4543 return { 4544 stepType: "attr", 4545 pos: this.pos, 4546 attr: this.attr, 4547 value: this.value 4548 }; 4549 } 4550 static fromJSON(schema, json) { 4551 if (typeof json.pos != "number" || typeof json.attr != "string") throw new RangeError("Invalid input for AttrStep.fromJSON"); 4552 return new AttrStep(json.pos, json.attr, json.value); 4553 } 4554}; 4555Step.jsonID("attr", AttrStep); 4556var DocAttrStep = class DocAttrStep extends Step { 4557 constructor(attr, value) { 4558 super(); 4559 this.attr = attr; 4560 this.value = value; 4561 } 4562 apply(doc$2) { 4563 let attrs = Object.create(null); 4564 for (let name in doc$2.attrs) attrs[name] = doc$2.attrs[name]; 4565 attrs[this.attr] = this.value; 4566 let updated = doc$2.type.create(attrs, doc$2.content, doc$2.marks); 4567 return StepResult.ok(updated); 4568 } 4569 getMap() { 4570 return StepMap.empty; 4571 } 4572 invert(doc$2) { 4573 return new DocAttrStep(this.attr, doc$2.attrs[this.attr]); 4574 } 4575 map(mapping) { 4576 return this; 4577 } 4578 toJSON() { 4579 return { 4580 stepType: "docAttr", 4581 attr: this.attr, 4582 value: this.value 4583 }; 4584 } 4585 static fromJSON(schema, json) { 4586 if (typeof json.attr != "string") throw new RangeError("Invalid input for DocAttrStep.fromJSON"); 4587 return new DocAttrStep(json.attr, json.value); 4588 } 4589}; 4590Step.jsonID("docAttr", DocAttrStep); 4591var TransformError = class extends Error {}; 4592TransformError = function TransformError$1(message) { 4593 let err = Error.call(this, message); 4594 err.__proto__ = TransformError$1.prototype; 4595 return err; 4596}; 4597TransformError.prototype = Object.create(Error.prototype); 4598TransformError.prototype.constructor = TransformError; 4599TransformError.prototype.name = "TransformError"; 4600var Transform = class { 4601 constructor(doc$2) { 4602 this.doc = doc$2;
vendor: 5,664 bytes, lines 4603-4799
4603 this.steps = []; 4604 this.docs = []; 4605 this.mapping = new Mapping(); 4606 } 4607 get before() { 4608 return this.docs.length ? this.docs[0] : this.doc; 4609 } 4610 step(step) { 4611 let result = this.maybeStep(step); 4612 if (result.failed) throw new TransformError(result.failed); 4613 return this; 4614 } 4615 maybeStep(step) { 4616 let result = step.apply(this.doc); 4617 if (!result.failed) this.addStep(step, result.doc); 4618 return result; 4619 } 4620 get docChanged() { 4621 return this.steps.length > 0; 4622 } 4623 changedRange() { 4624 let from = 1e9, to = -1e9; 4625 for (let i$1 = 0; i$1 < this.mapping.maps.length; i$1++) { 4626 let map = this.mapping.maps[i$1]; 4627 if (i$1) { 4628 from = map.map(from, 1); 4629 to = map.map(to, -1); 4630 } 4631 map.forEach((_f, _t, fromB, toB) => { 4632 from = Math.min(from, fromB); 4633 to = Math.max(to, toB); 4634 }); 4635 } 4636 return from == 1e9 ? null : { 4637 from, 4638 to 4639 }; 4640 } 4641 addStep(step, doc$2) { 4642 this.docs.push(this.doc); 4643 this.steps.push(step); 4644 this.mapping.appendMap(step.getMap()); 4645 this.doc = doc$2; 4646 } 4647 replace(from, to = from, slice = Slice.empty) { 4648 let step = replaceStep(this.doc, from, to, slice); 4649 if (step) this.step(step); 4650 return this; 4651 } 4652 replaceWith(from, to, content) { 4653 return this.replace(from, to, new Slice(Fragment.from(content), 0, 0)); 4654 } 4655 delete(from, to) { 4656 return this.replace(from, to, Slice.empty); 4657 } 4658 insert(pos, content) { 4659 return this.replaceWith(pos, pos, content); 4660 } 4661 replaceRange(from, to, slice) { 4662 replaceRange(this, from, to, slice); 4663 return this; 4664 } 4665 replaceRangeWith(from, to, node) { 4666 replaceRangeWith(this, from, to, node); 4667 return this; 4668 } 4669 deleteRange(from, to) { 4670 deleteRange$1(this, from, to); 4671 return this; 4672 } 4673 lift(range, target) { 4674 lift$2(this, range, target); 4675 return this; 4676 } 4677 join(pos, depth = 1) { 4678 join(this, pos, depth); 4679 return this; 4680 } 4681 wrap(range, wrappers) { 4682 wrap(this, range, wrappers); 4683 return this; 4684 } 4685 setBlockType(from, to = from, type, attrs = null) { 4686 setBlockType$1(this, from, to, type, attrs); 4687 return this; 4688 } 4689 setNodeMarkup(pos, type, attrs = null, marks) { 4690 setNodeMarkup(this, pos, type, attrs, marks); 4691 return this; 4692 } 4693 setNodeAttribute(pos, attr, value) { 4694 this.step(new AttrStep(pos, attr, value)); 4695 return this; 4696 } 4697 setDocAttribute(attr, value) { 4698 this.step(new DocAttrStep(attr, value)); 4699 return this; 4700 } 4701 addNodeMark(pos, mark) { 4702 this.step(new AddNodeMarkStep(pos, mark)); 4703 return this; 4704 } 4705 removeNodeMark(pos, mark) { 4706 let node = this.doc.nodeAt(pos); 4707 if (!node) throw new RangeError("No node at position " + pos); 4708 if (mark instanceof Mark$1) { 4709 if (mark.isInSet(node.marks)) this.step(new RemoveNodeMarkStep(pos, mark)); 4710 } else { 4711 let set = node.marks, found$1, steps = []; 4712 while (found$1 = mark.isInSet(set)) { 4713 steps.push(new RemoveNodeMarkStep(pos, found$1)); 4714 set = found$1.removeFromSet(set); 4715 } 4716 for (let i$1 = steps.length - 1; i$1 >= 0; i$1--) this.step(steps[i$1]); 4717 } 4718 return this; 4719 } 4720 split(pos, depth = 1, typesAfter) { 4721 split(this, pos, depth, typesAfter); 4722 return this; 4723 } 4724 addMark(from, to, mark) { 4725 addMark(this, from, to, mark); 4726 return this; 4727 } 4728 removeMark(from, to, mark) { 4729 removeMark(this, from, to, mark); 4730 return this; 4731 } 4732 clearIncompatible(pos, parentType, match) { 4733 clearIncompatible(this, pos, parentType, match); 4734 return this; 4735 } 4736}; 4737var classesById = Object.create(null); 4738var Selection$1 = class { 4739 constructor($anchor, $head, ranges) { 4740 this.$anchor = $anchor; 4741 this.$head = $head; 4742 this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))]; 4743 } 4744 get anchor() { 4745 return this.$anchor.pos; 4746 } 4747 get head() { 4748 return this.$head.pos; 4749 } 4750 get from() { 4751 return this.$from.pos; 4752 } 4753 get to() { 4754 return this.$to.pos; 4755 } 4756 get $from() { 4757 return this.ranges[0].$from; 4758 } 4759 get $to() { 4760 return this.ranges[0].$to; 4761 } 4762 get empty() { 4763 let ranges = this.ranges; 4764 for (let i$1 = 0; i$1 < ranges.length; i$1++) if (ranges[i$1].$from.pos != ranges[i$1].$to.pos) return false; 4765 return true; 4766 } 4767 content() { 4768 return this.$from.doc.slice(this.from, this.to, true); 4769 } 4770 replace(tr$1, content = Slice.empty) { 4771 let lastNode = content.content.lastChild, lastParent = null; 4772 for (let i$1 = 0; i$1 < content.openEnd; i$1++) { 4773 lastParent = lastNode; 4774 lastNode = lastNode.lastChild; 4775 } 4776 let mapFrom = tr$1.steps.length, ranges = this.ranges; 4777 for (let i$1 = 0; i$1 < ranges.length; i$1++) { 4778 let { $from, $to } = ranges[i$1], mapping = tr$1.mapping.slice(mapFrom); 4779 tr$1.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i$1 ? Slice.empty : content); 4780 if (i$1 == 0) selectionToInsertionEnd$1(tr$1, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1); 4781 } 4782 } 4783 replaceWith(tr$1, node) { 4784 let mapFrom = tr$1.steps.length, ranges = this.ranges; 4785 for (let i$1 = 0; i$1 < ranges.length; i$1++) { 4786 let { $from, $to } = ranges[i$1], mapping = tr$1.mapping.slice(mapFrom); 4787 let from = mapping.map($from.pos), to = mapping.map($to.pos); 4788 if (i$1) tr$1.deleteRange(from, to); 4789 else { 4790 tr$1.replaceRangeWith(from, to, node); 4791 selectionToInsertionEnd$1(tr$1, mapFrom, node.isInline ? -1 : 1); 4792 } 4793 } 4794 } 4795 static findFrom($pos, dir, textOnly = false) { 4796 let inner = $pos.parent.inlineContent ? new TextSelection($pos) : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly); 4797 if (inner) return inner; 4798 for (let depth = $pos.depth - 1; depth >= 0; depth--) { 4799 let found$1 = 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);
4800 if (found$1) return found$1; 4801 } 4802 return null; 4803 } 4804 static near($pos, bias = 1) { 4805 return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0)); 4806 } 4807 static atStart(doc$2) { 4808 return findSelectionIn(doc$2, doc$2, 0, 0, 1) || new AllSelection(doc$2); 4809 } 4810 static atEnd(doc$2) { 4811 return findSelectionIn(doc$2, doc$2, doc$2.content.size, doc$2.childCount, -1) || new AllSelection(doc$2); 4812 } 4813 static fromJSON(doc$2, json) { 4814 if (!json || !json.type) throw new RangeError("Invalid input for Selection.fromJSON"); 4815 let cls = classesById[json.type]; 4816 if (!cls) throw new RangeError(`No selection type ${json.type} defined`); 4817 return cls.fromJSON(doc$2, json); 4818 } 4819 static jsonID(id, selectionClass) { 4820 if (id in classesById) throw new RangeError("Duplicate use of selection JSON ID " + id); 4821 classesById[id] = selectionClass; 4822 selectionClass.prototype.jsonID = id; 4823 return selectionClass; 4824 } 4825 getBookmark() { 4826 return TextSelection.between(this.$anchor, this.$head).getBookmark(); 4827 } 4828}; 4829Selection$1.prototype.visible = true; 4830var SelectionRange = class { 4831 constructor($from, $to) { 4832 this.$from = $from; 4833 this.$to = $to; 4834 } 4835}; 4836var warnedAboutTextSelection = false; 4837function checkTextSelection($pos) { 4838 if (!warnedAboutTextSelection && !$pos.parent.inlineContent) { 4839 warnedAboutTextSelection = true; 4840 console["warn"]("TextSelection endpoint not pointing into a node with inline content (" + $pos.parent.type.name + ")"); 4841 } 4842} 4843var TextSelection = class TextSelection extends Selection$1 { 4844 constructor($anchor, $head = $anchor) { 4845 checkTextSelection($anchor); 4846 checkTextSelection($head);
vendor: 1,558 bytes, lines 4847-4890
4847 super($anchor, $head); 4848 } 4849 get $cursor() { 4850 return this.$anchor.pos == this.$head.pos ? this.$head : null; 4851 } 4852 map(doc$2, mapping) { 4853 let $head = doc$2.resolve(mapping.map(this.head)); 4854 if (!$head.parent.inlineContent) return Selection$1.near($head); 4855 let $anchor = doc$2.resolve(mapping.map(this.anchor)); 4856 return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head); 4857 } 4858 replace(tr$1, content = Slice.empty) { 4859 super.replace(tr$1, content); 4860 if (content == Slice.empty) { 4861 let marks = this.$from.marksAcross(this.$to); 4862 if (marks) tr$1.ensureMarks(marks); 4863 } 4864 } 4865 eq(other) { 4866 return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head; 4867 } 4868 getBookmark() { 4869 return new TextBookmark(this.anchor, this.head); 4870 } 4871 toJSON() { 4872 return { 4873 type: "text", 4874 anchor: this.anchor, 4875 head: this.head 4876 }; 4877 } 4878 static fromJSON(doc$2, json) { 4879 if (typeof json.anchor != "number" || typeof json.head != "number") throw new RangeError("Invalid input for TextSelection.fromJSON"); 4880 return new TextSelection(doc$2.resolve(json.anchor), doc$2.resolve(json.head)); 4881 } 4882 static create(doc$2, anchor, head = anchor) { 4883 let $anchor = doc$2.resolve(anchor); 4884 return new this($anchor, head == anchor ? $anchor : doc$2.resolve(head)); 4885 } 4886 static between($anchor, $head, bias) { 4887 let dPos = $anchor.pos - $head.pos; 4888 if (!bias || dPos) bias = dPos >= 0 ? 1 : -1; 4889 if (!$head.parent.inlineContent) { 4890 let found$1 = Selection$1.findFrom($head, bias, true) || Selection$1.findFrom($head, -bias, true);
vendor: 7,340 bytes, lines 4891-5125
4891 if (found$1) $head = found$1.$head; 4892 else return Selection$1.near($head, bias); 4893 } 4894 if (!$anchor.parent.inlineContent) if (dPos == 0) $anchor = $head; 4895 else { 4896 $anchor = (Selection$1.findFrom($anchor, -bias, true) || Selection$1.findFrom($anchor, bias, true)).$anchor; 4897 if ($anchor.pos < $head.pos != dPos < 0) $anchor = $head; 4898 } 4899 return new TextSelection($anchor, $head); 4900 } 4901}; 4902Selection$1.jsonID("text", TextSelection); 4903var TextBookmark = class TextBookmark { 4904 constructor(anchor, head) { 4905 this.anchor = anchor; 4906 this.head = head; 4907 } 4908 map(mapping) { 4909 return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head)); 4910 } 4911 resolve(doc$2) { 4912 return TextSelection.between(doc$2.resolve(this.anchor), doc$2.resolve(this.head)); 4913 } 4914}; 4915var NodeSelection = class NodeSelection extends Selection$1 { 4916 constructor($pos) { 4917 let node = $pos.nodeAfter; 4918 let $end = $pos.node(0).resolve($pos.pos + node.nodeSize); 4919 super($pos, $end); 4920 this.node = node; 4921 } 4922 map(doc$2, mapping) { 4923 let { deleted, pos } = mapping.mapResult(this.anchor); 4924 let $pos = doc$2.resolve(pos); 4925 if (deleted) return Selection$1.near($pos); 4926 return new NodeSelection($pos); 4927 } 4928 content() { 4929 return new Slice(Fragment.from(this.node), 0, 0); 4930 } 4931 eq(other) { 4932 return other instanceof NodeSelection && other.anchor == this.anchor; 4933 } 4934 toJSON() { 4935 return { 4936 type: "node", 4937 anchor: this.anchor 4938 }; 4939 } 4940 getBookmark() { 4941 return new NodeBookmark(this.anchor); 4942 } 4943 static fromJSON(doc$2, json) { 4944 if (typeof json.anchor != "number") throw new RangeError("Invalid input for NodeSelection.fromJSON"); 4945 return new NodeSelection(doc$2.resolve(json.anchor)); 4946 } 4947 static create(doc$2, from) { 4948 return new NodeSelection(doc$2.resolve(from)); 4949 } 4950 static isSelectable(node) { 4951 return !node.isText && node.type.spec.selectable !== false; 4952 } 4953}; 4954NodeSelection.prototype.visible = false; 4955Selection$1.jsonID("node", NodeSelection); 4956var NodeBookmark = class NodeBookmark { 4957 constructor(anchor) { 4958 this.anchor = anchor; 4959 } 4960 map(mapping) { 4961 let { deleted, pos } = mapping.mapResult(this.anchor); 4962 return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos); 4963 } 4964 resolve(doc$2) { 4965 let $pos = doc$2.resolve(this.anchor), node = $pos.nodeAfter; 4966 if (node && NodeSelection.isSelectable(node)) return new NodeSelection($pos); 4967 return Selection$1.near($pos); 4968 } 4969}; 4970var AllSelection = class AllSelection extends Selection$1 { 4971 constructor(doc$2) { 4972 super(doc$2.resolve(0), doc$2.resolve(doc$2.content.size)); 4973 } 4974 replace(tr$1, content = Slice.empty) { 4975 if (content == Slice.empty) { 4976 tr$1.delete(0, tr$1.doc.content.size); 4977 let sel = Selection$1.atStart(tr$1.doc); 4978 if (!sel.eq(tr$1.selection)) tr$1.setSelection(sel); 4979 } else super.replace(tr$1, content); 4980 } 4981 toJSON() { 4982 return { type: "all" }; 4983 } 4984 static fromJSON(doc$2) { 4985 return new AllSelection(doc$2); 4986 } 4987 map(doc$2) { 4988 return new AllSelection(doc$2); 4989 } 4990 eq(other) { 4991 return other instanceof AllSelection; 4992 } 4993 getBookmark() { 4994 return AllBookmark; 4995 } 4996}; 4997Selection$1.jsonID("all", AllSelection); 4998var AllBookmark = { 4999 map() { 5000 return this; 5001 }, 5002 resolve(doc$2) { 5003 return new AllSelection(doc$2); 5004 } 5005}; 5006function findSelectionIn(doc$2, node, pos, index, dir, text$1 = false) { 5007 if (node.inlineContent) return TextSelection.create(doc$2, pos); 5008 for (let i$1 = index - (dir > 0 ? 0 : 1); dir > 0 ? i$1 < node.childCount : i$1 >= 0; i$1 += dir) { 5009 let child = node.child(i$1); 5010 if (!child.isAtom) { 5011 let inner = findSelectionIn(doc$2, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text$1); 5012 if (inner) return inner; 5013 } else if (!text$1 && NodeSelection.isSelectable(child)) return NodeSelection.create(doc$2, pos - (dir < 0 ? child.nodeSize : 0)); 5014 pos += child.nodeSize * dir; 5015 } 5016 return null; 5017} 5018function selectionToInsertionEnd$1(tr$1, startLen, bias) { 5019 let last = tr$1.steps.length - 1; 5020 if (last < startLen) return; 5021 let step = tr$1.steps[last]; 5022 if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) return; 5023 let map = tr$1.mapping.maps[last], end; 5024 map.forEach((_from, _to, _newFrom, newTo) => { 5025 if (end == null) end = newTo; 5026 }); 5027 tr$1.setSelection(Selection$1.near(tr$1.doc.resolve(end), bias)); 5028} 5029var UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4; 5030var Transaction = class extends Transform { 5031 constructor(state) { 5032 super(state.doc); 5033 this.curSelectionFor = 0; 5034 this.updated = 0; 5035 this.meta = Object.create(null); 5036 this.time = Date.now(); 5037 this.curSelection = state.selection; 5038 this.storedMarks = state.storedMarks; 5039 } 5040 get selection() { 5041 if (this.curSelectionFor < this.steps.length) { 5042 this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor)); 5043 this.curSelectionFor = this.steps.length; 5044 } 5045 return this.curSelection; 5046 } 5047 setSelection(selection) { 5048 if (selection.$from.doc != this.doc) throw new RangeError("Selection passed to setSelection must point at the current document"); 5049 this.curSelection = selection; 5050 this.curSelectionFor = this.steps.length; 5051 this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS; 5052 this.storedMarks = null; 5053 return this; 5054 } 5055 get selectionSet() { 5056 return (this.updated & UPDATED_SEL) > 0; 5057 } 5058 setStoredMarks(marks) { 5059 this.storedMarks = marks; 5060 this.updated |= UPDATED_MARKS; 5061 return this; 5062 } 5063 ensureMarks(marks) { 5064 if (!Mark$1.sameSet(this.storedMarks || this.selection.$from.marks(), marks)) this.setStoredMarks(marks); 5065 return this; 5066 } 5067 addStoredMark(mark) { 5068 return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks())); 5069 } 5070 removeStoredMark(mark) { 5071 return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks())); 5072 } 5073 get storedMarksSet() { 5074 return (this.updated & UPDATED_MARKS) > 0; 5075 } 5076 addStep(step, doc$2) { 5077 super.addStep(step, doc$2); 5078 this.updated = this.updated & ~UPDATED_MARKS; 5079 this.storedMarks = null; 5080 } 5081 setTime(time) { 5082 this.time = time; 5083 return this; 5084 } 5085 replaceSelection(slice) { 5086 this.selection.replace(this, slice); 5087 return this; 5088 } 5089 replaceSelectionWith(node, inheritMarks = true) { 5090 let selection = this.selection; 5091 if (inheritMarks) node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : selection.$from.marksAcross(selection.$to) || Mark$1.none)); 5092 selection.replaceWith(this, node); 5093 return this; 5094 } 5095 deleteSelection() { 5096 this.selection.replace(this); 5097 return this; 5098 } 5099 insertText(text$1, from, to) { 5100 let schema = this.doc.type.schema; 5101 if (from == null) { 5102 if (!text$1) return this.deleteSelection(); 5103 return this.replaceSelectionWith(schema.text(text$1), true); 5104 } else { 5105 if (to == null) to = from; 5106 if (!text$1) return this.deleteRange(from, to); 5107 let marks = this.storedMarks; 5108 if (!marks) { 5109 let $from = this.doc.resolve(from); 5110 marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to)); 5111 } 5112 this.replaceRangeWith(from, to, schema.text(text$1, marks)); 5113 if (!this.selection.empty && this.selection.to == from + text$1.length) this.setSelection(Selection$1.near(this.selection.$to)); 5114 return this; 5115 } 5116 } 5117 setMeta(key, value) { 5118 this.meta[typeof key == "string" ? key : key.key] = value; 5119 return this; 5120 } 5121 getMeta(key) { 5122 return this.meta[typeof key == "string" ? key : key.key]; 5123 } 5124 get isGeneric() { 5125 for (let _ in this.meta) return false;
vendor: 5,429 bytes, lines 5126-5300
5126 return true; 5127 } 5128 scrollIntoView() { 5129 this.updated |= UPDATED_SCROLL; 5130 return this; 5131 } 5132 get scrolledIntoView() { 5133 return (this.updated & UPDATED_SCROLL) > 0; 5134 } 5135}; 5136function bind(f, self) { 5137 return !self || !f ? f : f.bind(self); 5138} 5139var FieldDesc = class { 5140 constructor(name, desc, self) { 5141 this.name = name; 5142 this.init = bind(desc.init, self); 5143 this.apply = bind(desc.apply, self); 5144 } 5145}; 5146var baseFields = [ 5147 new FieldDesc("doc", { 5148 init(config) { 5149 return config.doc || config.schema.topNodeType.createAndFill(); 5150 }, 5151 apply(tr$1) { 5152 return tr$1.doc; 5153 } 5154 }), 5155 new FieldDesc("selection", { 5156 init(config, instance) { 5157 return config.selection || Selection$1.atStart(instance.doc); 5158 }, 5159 apply(tr$1) { 5160 return tr$1.selection; 5161 } 5162 }), 5163 new FieldDesc("storedMarks", { 5164 init(config) { 5165 return config.storedMarks || null; 5166 }, 5167 apply(tr$1, _marks, _old, state) { 5168 return state.selection.$cursor ? tr$1.storedMarks : null; 5169 } 5170 }), 5171 new FieldDesc("scrollToSelection", { 5172 init() { 5173 return 0; 5174 }, 5175 apply(tr$1, prev) { 5176 return tr$1.scrolledIntoView ? prev + 1 : prev; 5177 } 5178 }) 5179]; 5180var Configuration = class { 5181 constructor(schema, plugins) { 5182 this.schema = schema; 5183 this.plugins = []; 5184 this.pluginsByKey = Object.create(null); 5185 this.fields = baseFields.slice(); 5186 if (plugins) plugins.forEach((plugin) => { 5187 if (this.pluginsByKey[plugin.key]) throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")"); 5188 this.plugins.push(plugin); 5189 this.pluginsByKey[plugin.key] = plugin; 5190 if (plugin.spec.state) this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin)); 5191 }); 5192 } 5193}; 5194var EditorState = class EditorState { 5195 constructor(config) { 5196 this.config = config; 5197 } 5198 get schema() { 5199 return this.config.schema; 5200 } 5201 get plugins() { 5202 return this.config.plugins; 5203 } 5204 apply(tr$1) { 5205 return this.applyTransaction(tr$1).state; 5206 } 5207 filterTransaction(tr$1, ignore = -1) { 5208 for (let i$1 = 0; i$1 < this.config.plugins.length; i$1++) if (i$1 != ignore) { 5209 let plugin = this.config.plugins[i$1]; 5210 if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr$1, this)) return false; 5211 } 5212 return true; 5213 } 5214 applyTransaction(rootTr) { 5215 if (!this.filterTransaction(rootTr)) return { 5216 state: this, 5217 transactions: [] 5218 }; 5219 let trs = [rootTr], newState = this.applyInner(rootTr), seen = null; 5220 for (;;) { 5221 let haveNew = false; 5222 for (let i$1 = 0; i$1 < this.config.plugins.length; i$1++) { 5223 let plugin = this.config.plugins[i$1]; 5224 if (plugin.spec.appendTransaction) { 5225 let n = seen ? seen[i$1].n : 0, oldState = seen ? seen[i$1].state : this; 5226 let tr$1 = n < trs.length && plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState); 5227 if (tr$1 && newState.filterTransaction(tr$1, i$1)) { 5228 tr$1.setMeta("appendedTransaction", rootTr); 5229 if (!seen) { 5230 seen = []; 5231 for (let j = 0; j < this.config.plugins.length; j++) seen.push(j < i$1 ? { 5232 state: newState, 5233 n: trs.length 5234 } : { 5235 state: this, 5236 n: 0 5237 }); 5238 } 5239 trs.push(tr$1); 5240 newState = newState.applyInner(tr$1); 5241 haveNew = true; 5242 } 5243 if (seen) seen[i$1] = { 5244 state: newState, 5245 n: trs.length 5246 }; 5247 } 5248 } 5249 if (!haveNew) return { 5250 state: newState, 5251 transactions: trs 5252 }; 5253 } 5254 } 5255 applyInner(tr$1) { 5256 if (!tr$1.before.eq(this.doc)) throw new RangeError("Applying a mismatched transaction"); 5257 let newInstance = new EditorState(this.config), fields = this.config.fields; 5258 for (let i$1 = 0; i$1 < fields.length; i$1++) { 5259 let field = fields[i$1]; 5260 newInstance[field.name] = field.apply(tr$1, this[field.name], this, newInstance); 5261 } 5262 return newInstance; 5263 } 5264 get tr() { 5265 return new Transaction(this); 5266 } 5267 static create(config) { 5268 let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins); 5269 let instance = new EditorState($config); 5270 for (let i$1 = 0; i$1 < $config.fields.length; i$1++) instance[$config.fields[i$1].name] = $config.fields[i$1].init(config, instance); 5271 return instance; 5272 } 5273 reconfigure(config) { 5274 let $config = new Configuration(this.schema, config.plugins); 5275 let fields = $config.fields, instance = new EditorState($config); 5276 for (let i$1 = 0; i$1 < fields.length; i$1++) { 5277 let name = fields[i$1].name; 5278 instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i$1].init(config, instance); 5279 } 5280 return instance; 5281 } 5282 toJSON(pluginFields) { 5283 let result = { 5284 doc: this.doc.toJSON(), 5285 selection: this.selection.toJSON() 5286 }; 5287 if (this.storedMarks) result.storedMarks = this.storedMarks.map((m) => m.toJSON()); 5288 if (pluginFields && typeof pluginFields == "object") for (let prop in pluginFields) { 5289 if (prop == "doc" || prop == "selection") throw new RangeError("The JSON fields `doc` and `selection` are reserved"); 5290 let plugin = pluginFields[prop], state = plugin.spec.state; 5291 if (state && state.toJSON) result[prop] = state.toJSON.call(plugin, this[plugin.key]); 5292 } 5293 return result; 5294 } 5295 static fromJSON(config, json, pluginFields) { 5296 if (!json) throw new RangeError("Invalid input for EditorState.fromJSON"); 5297 if (!config.schema) throw new RangeError("Required config field 'schema' missing"); 5298 let $config = new Configuration(config.schema, config.plugins); 5299 let instance = new EditorState($config); 5300 $config.fields.forEach((field) => {
vendor: 4,123 bytes, lines 5301-5413
5301 if (field.name == "doc") instance.doc = Node$1.fromJSON(config.schema, json.doc); 5302 else if (field.name == "selection") instance.selection = Selection$1.fromJSON(instance.doc, json.selection); 5303 else if (field.name == "storedMarks") { 5304 if (json.storedMarks) instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON); 5305 } else { 5306 if (pluginFields) for (let prop in pluginFields) { 5307 let plugin = pluginFields[prop], state = plugin.spec.state; 5308 if (plugin.key == field.name && state && state.fromJSON && Object.prototype.hasOwnProperty.call(json, prop)) { 5309 instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance); 5310 return; 5311 } 5312 } 5313 instance[field.name] = field.init(config, instance); 5314 } 5315 }); 5316 return instance; 5317 } 5318}; 5319function bindProps(obj, self, target) { 5320 for (let prop in obj) { 5321 let val = obj[prop]; 5322 if (val instanceof Function) val = val.bind(self); 5323 else if (prop == "handleDOMEvents") val = bindProps(val, self, {}); 5324 target[prop] = val; 5325 } 5326 return target; 5327} 5328var Plugin = class { 5329 constructor(spec) { 5330 this.spec = spec; 5331 this.props = {}; 5332 if (spec.props) bindProps(spec.props, this, this.props); 5333 this.key = spec.key ? spec.key.key : createKey("plugin"); 5334 } 5335 getState(state) { 5336 return state[this.key]; 5337 } 5338}; 5339var keys = Object.create(null); 5340function createKey(name) { 5341 if (name in keys) return name + "$" + ++keys[name]; 5342 keys[name] = 0; 5343 return name + "$"; 5344} 5345var PluginKey = class { 5346 constructor(name = "key") { 5347 this.key = createKey(name); 5348 } 5349 get(state) { 5350 return state.config.pluginsByKey[this.key]; 5351 } 5352 getState(state) { 5353 return state[this.key]; 5354 } 5355}; 5356var deleteSelection$1 = (state, dispatch) => { 5357 if (state.selection.empty) return false; 5358 if (dispatch) dispatch(state.tr.deleteSelection().scrollIntoView()); 5359 return true; 5360}; 5361function atBlockStart(state, view) { 5362 let { $cursor } = state.selection; 5363 if (!$cursor || (view ? !view.endOfTextblock("backward", state) : $cursor.parentOffset > 0)) return null; 5364 return $cursor; 5365} 5366var joinBackward = (state, dispatch, view) => { 5367 let $cursor = atBlockStart(state, view); 5368 if (!$cursor) return false; 5369 let $cut = findCutBefore($cursor); 5370 if (!$cut) { 5371 let range = $cursor.blockRange(), target = range && liftTarget(range); 5372 if (target == null) return false; 5373 if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView()); 5374 return true; 5375 } 5376 let before = $cut.nodeBefore; 5377 if (deleteBarrier(state, $cut, dispatch, -1)) return true; 5378 if ($cursor.parent.content.size == 0 && (textblockAt(before, "end") || NodeSelection.isSelectable(before))) for (let depth = $cursor.depth;; depth--) { 5379 let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty); 5380 if (delStep && delStep.slice.size < delStep.to - delStep.from) { 5381 if (dispatch) { 5382 let tr$1 = state.tr.step(delStep); 5383 tr$1.setSelection(textblockAt(before, "end") ? Selection$1.findFrom(tr$1.doc.resolve(tr$1.mapping.map($cut.pos, -1)), -1) : NodeSelection.create(tr$1.doc, $cut.pos - before.nodeSize)); 5384 dispatch(tr$1.scrollIntoView()); 5385 } 5386 return true; 5387 } 5388 if (depth == 1 || $cursor.node(depth - 1).childCount > 1) break; 5389 } 5390 if (before.isAtom && $cut.depth == $cursor.depth - 1) { 5391 if (dispatch) dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView()); 5392 return true; 5393 } 5394 return false; 5395}; 5396var joinTextblockBackward = (state, dispatch, view) => { 5397 let $cursor = atBlockStart(state, view); 5398 if (!$cursor) return false; 5399 let $cut = findCutBefore($cursor); 5400 return $cut ? joinTextblocksAround(state, $cut, dispatch) : false; 5401}; 5402var joinTextblockForward = (state, dispatch, view) => { 5403 let $cursor = atBlockEnd(state, view); 5404 if (!$cursor) return false; 5405 let $cut = findCutAfter($cursor); 5406 return $cut ? joinTextblocksAround(state, $cut, dispatch) : false; 5407}; 5408function joinTextblocksAround(state, $cut, dispatch) { 5409 let beforeText = $cut.nodeBefore, beforePos = $cut.pos - 1; 5410 for (; !beforeText.isTextblock; beforePos--) { 5411 if (beforeText.type.spec.isolating) return false; 5412 let child = beforeText.lastChild; 5413 if (!child) return false;
vendor: 12,068 bytes, lines 5414-5694
5414 beforeText = child; 5415 } 5416 let afterText = $cut.nodeAfter, afterPos = $cut.pos + 1; 5417 for (; !afterText.isTextblock; afterPos++) { 5418 if (afterText.type.spec.isolating) return false; 5419 let child = afterText.firstChild; 5420 if (!child) return false; 5421 afterText = child; 5422 } 5423 let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty); 5424 if (!step || step.from != beforePos || step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos) return false; 5425 if (dispatch) { 5426 let tr$1 = state.tr.step(step); 5427 tr$1.setSelection(TextSelection.create(tr$1.doc, beforePos)); 5428 dispatch(tr$1.scrollIntoView()); 5429 } 5430 return true; 5431} 5432function textblockAt(node, side, only = false) { 5433 for (let scan = node; scan; scan = side == "start" ? scan.firstChild : scan.lastChild) { 5434 if (scan.isTextblock) return true; 5435 if (only && scan.childCount != 1) return false; 5436 } 5437 return false; 5438} 5439var selectNodeBackward = (state, dispatch, view) => { 5440 let { $head, empty: empty$1 } = state.selection, $cut = $head; 5441 if (!empty$1) return false; 5442 if ($head.parent.isTextblock) { 5443 if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0) return false; 5444 $cut = findCutBefore($head); 5445 } 5446 let node = $cut && $cut.nodeBefore; 5447 if (!node || !NodeSelection.isSelectable(node)) return false; 5448 if (dispatch) dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView()); 5449 return true; 5450}; 5451function findCutBefore($pos) { 5452 if (!$pos.parent.type.spec.isolating) for (let i$1 = $pos.depth - 1; i$1 >= 0; i$1--) { 5453 if ($pos.index(i$1) > 0) return $pos.doc.resolve($pos.before(i$1 + 1)); 5454 if ($pos.node(i$1).type.spec.isolating) break; 5455 } 5456 return null; 5457} 5458function atBlockEnd(state, view) { 5459 let { $cursor } = state.selection; 5460 if (!$cursor || (view ? !view.endOfTextblock("forward", state) : $cursor.parentOffset < $cursor.parent.content.size)) return null; 5461 return $cursor; 5462} 5463var joinForward = (state, dispatch, view) => { 5464 let $cursor = atBlockEnd(state, view); 5465 if (!$cursor) return false; 5466 let $cut = findCutAfter($cursor); 5467 if (!$cut) return false; 5468 let after = $cut.nodeAfter; 5469 if (deleteBarrier(state, $cut, dispatch, 1)) return true; 5470 if ($cursor.parent.content.size == 0 && (textblockAt(after, "start") || NodeSelection.isSelectable(after))) { 5471 let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty); 5472 if (delStep && delStep.slice.size < delStep.to - delStep.from) { 5473 if (dispatch) { 5474 let tr$1 = state.tr.step(delStep); 5475 tr$1.setSelection(textblockAt(after, "start") ? Selection$1.findFrom(tr$1.doc.resolve(tr$1.mapping.map($cut.pos)), 1) : NodeSelection.create(tr$1.doc, tr$1.mapping.map($cut.pos))); 5476 dispatch(tr$1.scrollIntoView()); 5477 } 5478 return true; 5479 } 5480 } 5481 if (after.isAtom && $cut.depth == $cursor.depth - 1) { 5482 if (dispatch) dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView()); 5483 return true; 5484 } 5485 return false; 5486}; 5487var selectNodeForward = (state, dispatch, view) => { 5488 let { $head, empty: empty$1 } = state.selection, $cut = $head; 5489 if (!empty$1) return false; 5490 if ($head.parent.isTextblock) { 5491 if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size) return false; 5492 $cut = findCutAfter($head); 5493 } 5494 let node = $cut && $cut.nodeAfter; 5495 if (!node || !NodeSelection.isSelectable(node)) return false; 5496 if (dispatch) dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView()); 5497 return true; 5498}; 5499function findCutAfter($pos) { 5500 if (!$pos.parent.type.spec.isolating) for (let i$1 = $pos.depth - 1; i$1 >= 0; i$1--) { 5501 let parent = $pos.node(i$1); 5502 if ($pos.index(i$1) + 1 < parent.childCount) return $pos.doc.resolve($pos.after(i$1 + 1)); 5503 if (parent.type.spec.isolating) break; 5504 } 5505 return null; 5506} 5507var joinUp = (state, dispatch) => { 5508 let sel = state.selection, nodeSel = sel instanceof NodeSelection, point; 5509 if (nodeSel) { 5510 if (sel.node.isTextblock || !canJoin(state.doc, sel.from)) return false; 5511 point = sel.from; 5512 } else { 5513 point = joinPoint(state.doc, sel.from, -1); 5514 if (point == null) return false; 5515 } 5516 if (dispatch) { 5517 let tr$1 = state.tr.join(point); 5518 if (nodeSel) tr$1.setSelection(NodeSelection.create(tr$1.doc, point - state.doc.resolve(point).nodeBefore.nodeSize)); 5519 dispatch(tr$1.scrollIntoView()); 5520 } 5521 return true; 5522}; 5523var joinDown = (state, dispatch) => { 5524 let sel = state.selection, point; 5525 if (sel instanceof NodeSelection) { 5526 if (sel.node.isTextblock || !canJoin(state.doc, sel.to)) return false; 5527 point = sel.to; 5528 } else { 5529 point = joinPoint(state.doc, sel.to, 1); 5530 if (point == null) return false; 5531 } 5532 if (dispatch) dispatch(state.tr.join(point).scrollIntoView()); 5533 return true; 5534}; 5535var lift = (state, dispatch) => { 5536 let { $from, $to } = state.selection; 5537 let range = $from.blockRange($to), target = range && liftTarget(range); 5538 if (target == null) return false; 5539 if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView()); 5540 return true; 5541}; 5542var newlineInCode = (state, dispatch) => { 5543 let { $head, $anchor } = state.selection; 5544 if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) return false; 5545 if (dispatch) dispatch(state.tr.insertText("\n").scrollIntoView()); 5546 return true; 5547}; 5548function defaultBlockAt$1(match) { 5549 for (let i$1 = 0; i$1 < match.edgeCount; i$1++) { 5550 let { type } = match.edge(i$1); 5551 if (type.isTextblock && !type.hasRequiredAttrs()) return type; 5552 } 5553 return null; 5554} 5555var exitCode = (state, dispatch) => { 5556 let { $head, $anchor } = state.selection; 5557 if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) return false; 5558 let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt$1(above.contentMatchAt(after)); 5559 if (!type || !above.canReplaceWith(after, after, type)) return false; 5560 if (dispatch) { 5561 let pos = $head.after(), tr$1 = state.tr.replaceWith(pos, pos, type.createAndFill()); 5562 tr$1.setSelection(Selection$1.near(tr$1.doc.resolve(pos), 1)); 5563 dispatch(tr$1.scrollIntoView()); 5564 } 5565 return true; 5566}; 5567var createParagraphNear = (state, dispatch) => { 5568 let sel = state.selection, { $from, $to } = sel; 5569 if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent) return false; 5570 let type = defaultBlockAt$1($to.parent.contentMatchAt($to.indexAfter())); 5571 if (!type || !type.isTextblock) return false; 5572 if (dispatch) { 5573 let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos; 5574 let tr$1 = state.tr.insert(side, type.createAndFill()); 5575 tr$1.setSelection(TextSelection.create(tr$1.doc, side + 1)); 5576 dispatch(tr$1.scrollIntoView()); 5577 } 5578 return true; 5579}; 5580var liftEmptyBlock = (state, dispatch) => { 5581 let { $cursor } = state.selection; 5582 if (!$cursor || $cursor.parent.content.size) return false; 5583 if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) { 5584 let before = $cursor.before(); 5585 if (canSplit(state.doc, before)) { 5586 if (dispatch) dispatch(state.tr.split(before).scrollIntoView()); 5587 return true; 5588 } 5589 } 5590 let range = $cursor.blockRange(), target = range && liftTarget(range); 5591 if (target == null) return false; 5592 if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView()); 5593 return true; 5594}; 5595function splitBlockAs(splitNode) { 5596 return (state, dispatch) => { 5597 if (state.selection instanceof NodeSelection && state.selection.node.isBlock) { 5598 let { $from: $from$1 } = state.selection; 5599 if (!$from$1.parentOffset || !canSplit(state.doc, $from$1.pos)) return false; 5600 if (dispatch) dispatch(state.tr.split($from$1.pos).scrollIntoView()); 5601 return true; 5602 } 5603 if (!state.selection.$from.depth) return false; 5604 let tr$1 = state.tr; 5605 if (!state.selection.empty && (state.selection instanceof TextSelection || state.selection instanceof AllSelection)) tr$1.deleteSelection(); 5606 let { $from } = tr$1.selection, mapFrom = tr$1.steps.length; 5607 let types = []; 5608 let splitDepth, deflt, atEnd = false, atStart = false; 5609 for (let d = $from.depth;; d--) if ($from.node(d).isBlock) { 5610 atEnd = $from.end(d) == $from.pos + ($from.depth - d); 5611 atStart = $from.start(d) == $from.pos - ($from.depth - d); 5612 deflt = defaultBlockAt$1($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1))); 5613 let splitType = splitNode && splitNode($from.parent, atEnd, $from); 5614 types.unshift(splitType || (atEnd && deflt ? { type: deflt } : null)); 5615 splitDepth = d; 5616 break; 5617 } else { 5618 if (d == 1) return false; 5619 types.unshift(null); 5620 } 5621 let splitPos = $from.pos; 5622 let can = canSplit(tr$1.doc, splitPos, types.length, types); 5623 if (!can) { 5624 types[0] = deflt ? { type: deflt } : null; 5625 can = canSplit(tr$1.doc, splitPos, types.length, types); 5626 } 5627 if (!can) return false; 5628 tr$1.split(splitPos, types.length, types); 5629 if (!atEnd && atStart && $from.node(splitDepth).type != deflt) { 5630 let mapping = tr$1.mapping.slice(mapFrom); 5631 let first$1 = mapping.map($from.before(splitDepth)), $first = tr$1.doc.resolve(first$1); 5632 if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt)) tr$1.setNodeMarkup(mapping.map($from.before(splitDepth)), deflt); 5633 } 5634 if (dispatch) dispatch(tr$1.scrollIntoView()); 5635 return true; 5636 }; 5637} 5638var splitBlock$1 = splitBlockAs(); 5639var selectParentNode = (state, dispatch) => { 5640 let { $from, to } = state.selection, pos; 5641 let same = $from.sharedDepth(to); 5642 if (same == 0) return false; 5643 pos = $from.before(same); 5644 if (dispatch) dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos))); 5645 return true; 5646}; 5647var selectAll$1 = (state, dispatch) => { 5648 if (dispatch) dispatch(state.tr.setSelection(new AllSelection(state.doc))); 5649 return true; 5650}; 5651function joinMaybeClear(state, $pos, dispatch) { 5652 let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index(); 5653 if (!before || !after || !before.type.compatibleContent(after.type)) return false; 5654 if (!before.content.size && $pos.parent.canReplace(index - 1, index)) { 5655 if (dispatch) dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView()); 5656 return true; 5657 } 5658 if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos))) return false; 5659 if (dispatch) dispatch(state.tr.join($pos.pos).scrollIntoView()); 5660 return true; 5661} 5662function deleteBarrier(state, $cut, dispatch, dir) { 5663 let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match; 5664 let isolated = before.type.spec.isolating || after.type.spec.isolating; 5665 if (!isolated && joinMaybeClear(state, $cut, dispatch)) return true; 5666 let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1); 5667 if (canDelAfter && (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && match.matchType(conn[0] || after.type).validEnd) { 5668 if (dispatch) { 5669 let end = $cut.pos + after.nodeSize, wrap$1 = Fragment.empty; 5670 for (let i$1 = conn.length - 1; i$1 >= 0; i$1--) wrap$1 = Fragment.from(conn[i$1].create(null, wrap$1)); 5671 wrap$1 = Fragment.from(before.copy(wrap$1)); 5672 let tr$1 = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap$1, 1, 0), conn.length, true)); 5673 let $joinAt = tr$1.doc.resolve(end + 2 * conn.length); 5674 if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type && canJoin(tr$1.doc, $joinAt.pos)) tr$1.join($joinAt.pos); 5675 dispatch(tr$1.scrollIntoView()); 5676 } 5677 return true; 5678 } 5679 let selAfter = after.type.spec.isolating || dir > 0 && isolated ? null : Selection$1.findFrom($cut, 1); 5680 let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range); 5681 if (target != null && target >= $cut.depth) { 5682 if (dispatch) dispatch(state.tr.lift(range, target).scrollIntoView()); 5683 return true; 5684 } 5685 if (canDelAfter && textblockAt(after, "start", true) && textblockAt(before, "end")) { 5686 let at = before, wrap$1 = []; 5687 for (;;) { 5688 wrap$1.push(at); 5689 if (at.isTextblock) break; 5690 at = at.lastChild; 5691 } 5692 let afterText = after, afterDepth = 1; 5693 for (; !afterText.isTextblock; afterText = afterText.firstChild) afterDepth++; 5694 if (at.canReplace(at.childCount, at.childCount, afterText.content)) {
5695 if (dispatch) { 5696 let end = Fragment.empty; 5697 for (let i$1 = wrap$1.length - 1; i$1 >= 0; i$1--) end = Fragment.from(wrap$1[i$1].copy(end)); 5698 dispatch(state.tr.step(new ReplaceAroundStep($cut.pos - wrap$1.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap$1.length, 0), 0, true)).scrollIntoView()); 5699 } 5700 return true; 5701 } 5702 } 5703 return false; 5704} 5705function selectTextblockSide(side) { 5706 return function(state, dispatch) { 5707 let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to; 5708 let depth = $pos.depth; 5709 while ($pos.node(depth).isInline) { 5710 if (!depth) return false; 5711 depth--; 5712 } 5713 if (!$pos.node(depth).isTextblock) return false; 5714 if (dispatch) dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth)))); 5715 return true; 5716 }; 5717} 5718var selectTextblockStart = selectTextblockSide(-1); 5719var selectTextblockEnd = selectTextblockSide(1); 5720function wrapIn(nodeType, attrs = null) { 5721 return function(state, dispatch) { 5722 let { $from, $to } = state.selection; 5723 let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs); 5724 if (!wrapping) return false; 5725 if (dispatch) dispatch(state.tr.wrap(range, wrapping).scrollIntoView()); 5726 return true; 5727 }; 5728} 5729function setBlockType(nodeType, attrs = null) { 5730 return function(state, dispatch) { 5731 let applicable = false; 5732 for (let i$1 = 0; i$1 < state.selection.ranges.length && !applicable; i$1++) { 5733 let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i$1]; 5734 state.doc.nodesBetween(from, to, (node, pos) => { 5735 if (applicable) return false; 5736 if (!node.isTextblock || node.hasMarkup(nodeType, attrs)) return; 5737 if (node.type == nodeType) applicable = true; 5738 else { 5739 let $pos = state.doc.resolve(pos), index = $pos.index(); 5740 applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType); 5741 } 5742 }); 5743 } 5744 if (!applicable) return false; 5745 if (dispatch) { 5746 let tr$1 = state.tr; 5747 for (let i$1 = 0; i$1 < state.selection.ranges.length; i$1++) { 5748 let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i$1]; 5749 tr$1.setBlockType(from, to, nodeType, attrs); 5750 } 5751 dispatch(tr$1.scrollIntoView()); 5752 } 5753 return true; 5754 }; 5755} 5756function chainCommands(...commands) { 5757 return function(state, dispatch, view) { 5758 for (let i$1 = 0; i$1 < commands.length; i$1++) if (commands[i$1](state, dispatch, view)) return true; 5759 return false; 5760 }; 5761} 5762var backspace = chainCommands(deleteSelection$1, joinBackward, selectNodeBackward); 5763var del = chainCommands(deleteSelection$1, joinForward, selectNodeForward); 5764var pcBaseKeymap = { 5765 "Enter": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock$1), 5766 "Mod-Enter": exitCode, 5767 "Backspace": backspace, 5768 "Mod-Backspace": backspace, 5769 "Shift-Backspace": backspace, 5770 "Delete": del, 5771 "Mod-Delete": del, 5772 "Mod-a": selectAll$1 5773}; 5774var macBaseKeymap = { 5775 "Ctrl-h": pcBaseKeymap["Backspace"], 5776 "Alt-Backspace": pcBaseKeymap["Mod-Backspace"], 5777 "Ctrl-d": pcBaseKeymap["Delete"], 5778 "Ctrl-Alt-Backspace": pcBaseKeymap["Mod-Delete"], 5779 "Alt-Delete": pcBaseKeymap["Mod-Delete"], 5780 "Alt-d": pcBaseKeymap["Mod-Delete"], 5781 "Ctrl-a": selectTextblockStart, 5782 "Ctrl-e": selectTextblockEnd 5783}; 5784for (let key in pcBaseKeymap) macBaseKeymap[key] = pcBaseKeymap[key]; 5785typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os != "undefined" && os.platform && os.platform(); 5786function wrapInList(listType, attrs = null) { 5787 return function(state, dispatch) { 5788 let { $from, $to } = state.selection; 5789 let range = $from.blockRange($to); 5790 if (!range) return false; 5791 let tr$1 = dispatch ? state.tr : null; 5792 if (!wrapRangeInList(tr$1, range, listType, attrs)) return false; 5793 if (dispatch) dispatch(tr$1.scrollIntoView()); 5794 return true; 5795 }; 5796} 5797function wrapRangeInList(tr$1, range, listType, attrs = null) { 5798 let doJoin = false, outerRange = range, doc$2 = range.$from.doc; 5799 if (range.depth >= 2 && range.$from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) { 5800 if (range.$from.index(range.depth - 1) == 0) return false;
vendor: 4,147 bytes, lines 5801-5876
5801 let $insert = doc$2.resolve(range.start - 2); 5802 outerRange = new NodeRange($insert, $insert, range.depth); 5803 if (range.endIndex < range.parent.childCount) range = new NodeRange(range.$from, doc$2.resolve(range.$to.end(range.depth)), range.depth); 5804 doJoin = true; 5805 } 5806 let wrap$1 = findWrapping(outerRange, listType, attrs, range); 5807 if (!wrap$1) return false; 5808 if (tr$1) doWrapInList(tr$1, range, wrap$1, doJoin, listType); 5809 return true; 5810} 5811function doWrapInList(tr$1, range, wrappers, joinBefore, listType) { 5812 let content = Fragment.empty; 5813 for (let i$1 = wrappers.length - 1; i$1 >= 0; i$1--) content = Fragment.from(wrappers[i$1].type.create(wrappers[i$1].attrs, content)); 5814 tr$1.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true)); 5815 let found$1 = 0; 5816 for (let i$1 = 0; i$1 < wrappers.length; i$1++) if (wrappers[i$1].type == listType) found$1 = i$1 + 1; 5817 let splitDepth = wrappers.length - found$1; 5818 let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent; 5819 for (let i$1 = range.startIndex, e = range.endIndex, first$1 = true; i$1 < e; i$1++, first$1 = false) { 5820 if (!first$1 && canSplit(tr$1.doc, splitPos, splitDepth)) { 5821 tr$1.split(splitPos, splitDepth); 5822 splitPos += 2 * splitDepth; 5823 } 5824 splitPos += parent.child(i$1).nodeSize; 5825 } 5826 return tr$1; 5827} 5828function liftListItem(itemType) { 5829 return function(state, dispatch) { 5830 let { $from, $to } = state.selection; 5831 let range = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType); 5832 if (!range) return false; 5833 if (!dispatch) return true; 5834 if ($from.node(range.depth - 1).type == itemType) return liftToOuterList(state, dispatch, itemType, range); 5835 else return liftOutOfList(state, dispatch, range); 5836 }; 5837} 5838function liftToOuterList(state, dispatch, itemType, range) { 5839 let tr$1 = state.tr, end = range.end, endOfList = range.$to.end(range.depth); 5840 if (end < endOfList) { 5841 tr$1.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true)); 5842 range = new NodeRange(tr$1.doc.resolve(range.$from.pos), tr$1.doc.resolve(endOfList), range.depth); 5843 } 5844 const target = liftTarget(range); 5845 if (target == null) return false; 5846 tr$1.lift(range, target); 5847 let $after = tr$1.doc.resolve(tr$1.mapping.map(end, -1) - 1); 5848 if (canJoin(tr$1.doc, $after.pos) && $after.nodeBefore.type == $after.nodeAfter.type) tr$1.join($after.pos); 5849 dispatch(tr$1.scrollIntoView()); 5850 return true; 5851} 5852function liftOutOfList(state, dispatch, range) { 5853 let tr$1 = state.tr, list = range.parent; 5854 for (let pos = range.end, i$1 = range.endIndex - 1, e = range.startIndex; i$1 > e; i$1--) { 5855 pos -= list.child(i$1).nodeSize; 5856 tr$1.delete(pos - 1, pos + 1); 5857 } 5858 let $start = tr$1.doc.resolve(range.start), item = $start.nodeAfter; 5859 if (tr$1.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize) return false; 5860 let atStart = range.startIndex == 0, atEnd = range.endIndex == list.childCount; 5861 let parent = $start.node(-1), indexBefore = $start.index(-1); 5862 if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list)))) return false; 5863 let start = $start.pos, end = start + item.nodeSize; 5864 tr$1.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)); 5865 dispatch(tr$1.scrollIntoView()); 5866 return true; 5867} 5868function sinkListItem(itemType) { 5869 return function(state, dispatch) { 5870 let { $from, $to } = state.selection; 5871 let range = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType); 5872 if (!range) return false; 5873 let startIndex = range.startIndex; 5874 if (startIndex == 0) return false; 5875 let parent = range.parent, nodeBefore = parent.child(startIndex - 1); 5876 if (nodeBefore.type != itemType) return false;
5877 if (dispatch) { 5878 let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type; 5879 let inner = Fragment.from(nestedBefore ? itemType.create() : null); 5880 let slice = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0); 5881 let before = range.start, after = range.end; 5882 dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice, 1, true)).scrollIntoView()); 5883 } 5884 return true; 5885 }; 5886} 5887var domIndex = function(node) { 5888 for (var index = 0;; index++) { 5889 node = node.previousSibling; 5890 if (!node) return index; 5891 } 5892}; 5893var parentNode = function(node) { 5894 let parent = node.assignedSlot || node.parentNode; 5895 return parent && parent.nodeType == 11 ? parent.host : parent; 5896}; 5897var reusedRange = null; 5898var textRange = function(node, from, to) { 5899 let range = reusedRange || (reusedRange = document.createRange()); 5900 range.setEnd(node, to == null ? node.nodeValue.length : to); 5901 range.setStart(node, from || 0); 5902 return range; 5903}; 5904var clearReusedRange = function() { 5905 reusedRange = null; 5906}; 5907var isEquivalentPosition = function(node, off, targetNode, targetOff) { 5908 return targetNode && (scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1)); 5909}; 5910var atomElements = /^(img|br|input|textarea|hr)$/i; 5911function scanFor(node, off, targetNode, targetOff, dir) { 5912 var _a; 5913 for (;;) { 5914 if (node == targetNode && off == targetOff) return true; 5915 if (off == (dir < 0 ? 0 : nodeSize(node))) { 5916 let parent = node.parentNode; 5917 if (!parent || parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == "false") return false; 5918 off = domIndex(node) + (dir < 0 ? 0 : 1); 5919 node = parent; 5920 } else if (node.nodeType == 1) { 5921 let child = node.childNodes[off + (dir < 0 ? -1 : 0)]; 5922 if (child.nodeType == 1 && child.contentEditable == "false") if ((_a = child.pmViewDesc) === null || _a === void 0 ? void 0 : _a.ignoreForSelection) off += dir; 5923 else return false; 5924 else { 5925 node = child; 5926 off = dir < 0 ? nodeSize(node) : 0; 5927 } 5928 } else return false; 5929 } 5930} 5931function nodeSize(node) { 5932 return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; 5933} 5934function textNodeBefore$1(node, offset) { 5935 for (;;) { 5936 if (node.nodeType == 3 && offset) return node; 5937 if (node.nodeType == 1 && offset > 0) { 5938 if (node.contentEditable == "false") return null; 5939 node = node.childNodes[offset - 1]; 5940 offset = nodeSize(node); 5941 } else if (node.parentNode && !hasBlockDesc(node)) { 5942 offset = domIndex(node); 5943 node = node.parentNode; 5944 } else return null; 5945 } 5946} 5947function textNodeAfter$1(node, offset) { 5948 for (;;) { 5949 if (node.nodeType == 3 && offset < node.nodeValue.length) return node; 5950 if (node.nodeType == 1 && offset < node.childNodes.length) { 5951 if (node.contentEditable == "false") return null; 5952 node = node.childNodes[offset]; 5953 offset = 0; 5954 } else if (node.parentNode && !hasBlockDesc(node)) { 5955 offset = domIndex(node) + 1; 5956 node = node.parentNode; 5957 } else return null; 5958 } 5959} 5960function isOnEdge(node, offset, parent) { 5961 for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd;) { 5962 if (node == parent) return true; 5963 let index = domIndex(node); 5964 node = node.parentNode; 5965 if (!node) return false; 5966 atStart = atStart && index == 0; 5967 atEnd = atEnd && index == nodeSize(node); 5968 } 5969} 5970function hasBlockDesc(dom) { 5971 let desc; 5972 for (let cur = dom; cur; cur = cur.parentNode) if (desc = cur.pmViewDesc) break; 5973 return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom); 5974} 5975var selectionCollapsed = function(domSel) { 5976 return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset); 5977}; 5978function keyEvent(keyCode, key) { 5979 let event = document.createEvent("Event"); 5980 event.initEvent("keydown", true, true); 5981 event.keyCode = keyCode; 5982 event.key = event.code = key; 5983 return event; 5984} 5985function deepActiveElement(doc$2) { 5986 let elt = doc$2.activeElement; 5987 while (elt && elt.shadowRoot) elt = elt.shadowRoot.activeElement; 5988 return elt; 5989} 5990function caretFromPoint(doc$2, x, y) { 5991 if (doc$2.caretPositionFromPoint) try { 5992 let pos = doc$2.caretPositionFromPoint(x, y); 5993 if (pos) return { 5994 node: pos.offsetNode, 5995 offset: Math.min(nodeSize(pos.offsetNode), pos.offset) 5996 }; 5997 } catch (_) {} 5998 if (doc$2.caretRangeFromPoint) { 5999 let range = doc$2.caretRangeFromPoint(x, y); 6000 if (range) return { 6001 node: range.startContainer, 6002 offset: Math.min(nodeSize(range.startContainer), range.startOffset) 6003 }; 6004 } 6005} 6006var nav = typeof navigator != "undefined" ? navigator : null; 6007var doc = typeof document != "undefined" ? document : null; 6008var agent = nav && nav.userAgent || ""; 6009var ie_edge = /Edge\/(\d+)/.exec(agent); 6010var ie_upto10 = /MSIE \d/.exec(agent); 6011var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(agent); 6012var ie$2 = !!(ie_upto10 || ie_11up || ie_edge); 6013var ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0; 6014var gecko = !ie$2 && /gecko\/(\d+)/i.test(agent); 6015gecko && +(/Firefox\/(\d+)/.exec(agent) || [0, 0])[1]; 6016var _chrome = !ie$2 && /Chrome\/(\d+)/.exec(agent); 6017var chrome = !!_chrome; 6018var chrome_version = _chrome ? +_chrome[1] : 0;
6019var safari = !ie$2 && !!nav && /Apple Computer/.test(nav.vendor); 6020var ios = safari && (/Mobile\/\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2); 6021var mac$2 = ios || (nav ? /Mac/.test(nav.platform) : false); 6022var windows$1 = nav ? /Win/.test(nav.platform) : false; 6023var android = /Android \d/.test(agent); 6024var webkit = !!doc && "webkitFontSmoothing" in doc.documentElement.style; 6025var webkit_version = webkit ? +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0; 6026function windowRect(doc$2) { 6027 let vp = doc$2.defaultView && doc$2.defaultView.visualViewport; 6028 if (vp) return { 6029 left: 0, 6030 right: vp.width, 6031 top: 0, 6032 bottom: vp.height 6033 }; 6034 return { 6035 left: 0, 6036 right: doc$2.documentElement.clientWidth, 6037 top: 0, 6038 bottom: doc$2.documentElement.clientHeight 6039 }; 6040} 6041function getSide(value, side) { 6042 return typeof value == "number" ? value : value[side]; 6043} 6044function clientRect(node) { 6045 let rect = node.getBoundingClientRect(); 6046 let scaleX = rect.width / node.offsetWidth || 1; 6047 let scaleY = rect.height / node.offsetHeight || 1; 6048 return { 6049 left: rect.left, 6050 right: rect.left + node.clientWidth * scaleX, 6051 top: rect.top, 6052 bottom: rect.top + node.clientHeight * scaleY 6053 }; 6054} 6055function scrollRectIntoView(view, rect, startDOM) { 6056 if (!nonZero(rect) && rect.left == 0) return; 6057 let scrollThreshold = view.someProp("scrollThreshold") || 0, scrollMargin = view.someProp("scrollMargin") || 5; 6058 let doc$2 = view.dom.ownerDocument; 6059 for (let parent = startDOM || view.dom;;) { 6060 if (!parent) break; 6061 if (parent.nodeType != 1) { 6062 parent = parentNode(parent); 6063 continue; 6064 } 6065 let elt = parent; 6066 let atTop = elt == doc$2.body; 6067 let bounding = atTop ? windowRect(doc$2) : clientRect(elt); 6068 let moveX = 0, moveY = 0; 6069 if (rect.top < bounding.top + getSide(scrollThreshold, "top")) moveY = -(bounding.top - rect.top + getSide(scrollMargin, "top")); 6070 else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, "bottom")) moveY = rect.bottom - rect.top > bounding.bottom - bounding.top ? rect.top + getSide(scrollMargin, "top") - bounding.top : rect.bottom - bounding.bottom + getSide(scrollMargin, "bottom"); 6071 if (rect.left < bounding.left + getSide(scrollThreshold, "left")) moveX = -(bounding.left - rect.left + getSide(scrollMargin, "left")); 6072 else if (rect.right > bounding.right - getSide(scrollThreshold, "right")) moveX = rect.right - bounding.right + getSide(scrollMargin, "right"); 6073 if (moveX || moveY) if (atTop) doc$2.defaultView.scrollBy(moveX, moveY); 6074 else { 6075 let startX = elt.scrollLeft, startY = elt.scrollTop; 6076 if (moveY) elt.scrollTop += moveY; 6077 if (moveX) elt.scrollLeft += moveX; 6078 let dX = elt.scrollLeft - startX, dY = elt.scrollTop - startY; 6079 rect = { 6080 left: rect.left - dX, 6081 top: rect.top - dY, 6082 right: rect.right - dX, 6083 bottom: rect.bottom - dY 6084 }; 6085 } 6086 let pos = atTop ? "fixed" : getComputedStyle(parent).position; 6087 if (/^(fixed|sticky)$/.test(pos)) break; 6088 parent = pos == "absolute" ? parent.offsetParent : parentNode(parent); 6089 } 6090} 6091function storeScrollPos(view) { 6092 let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top); 6093 let refDOM, refTop; 6094 for (let x = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) { 6095 let dom = view.root.elementFromPoint(x, y); 6096 if (!dom || dom == view.dom || !view.dom.contains(dom)) continue; 6097 let localRect = dom.getBoundingClientRect(); 6098 if (localRect.top >= startY - 20) { 6099 refDOM = dom; 6100 refTop = localRect.top; 6101 break; 6102 } 6103 } 6104 return { 6105 refDOM, 6106 refTop, 6107 stack: scrollStack(view.dom) 6108 }; 6109} 6110function scrollStack(dom) { 6111 let stack = [], doc$2 = dom.ownerDocument; 6112 for (let cur = dom; cur; cur = parentNode(cur)) { 6113 stack.push({ 6114 dom: cur, 6115 top: cur.scrollTop, 6116 left: cur.scrollLeft 6117 }); 6118 if (dom == doc$2) break; 6119 } 6120 return stack; 6121} 6122function resetScrollPos({ refDOM, refTop, stack }) { 6123 let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0; 6124 restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop); 6125} 6126function restoreScrollStack(stack, dTop) { 6127 for (let i$1 = 0; i$1 < stack.length; i$1++) { 6128 let { dom, top, left } = stack[i$1]; 6129 if (dom.scrollTop != top + dTop) dom.scrollTop = top + dTop; 6130 if (dom.scrollLeft != left) dom.scrollLeft = left; 6131 } 6132} 6133var preventScrollSupported = null; 6134function focusPreventScroll(dom) { 6135 if (dom.setActive) return dom.setActive(); 6136 if (preventScrollSupported) return dom.focus(preventScrollSupported); 6137 let stored = scrollStack(dom); 6138 dom.focus(preventScrollSupported == null ? { get preventScroll() { 6139 preventScrollSupported = { preventScroll: true }; 6140 return true; 6141 } } : void 0); 6142 if (!preventScrollSupported) { 6143 preventScrollSupported = false;
vendor: 12,594 bytes, lines 6144-6446
6144 restoreScrollStack(stored, 0); 6145 } 6146} 6147function findOffsetInNode(node, coords) { 6148 let closest, dxClosest = 2e8, coordsClosest, offset = 0; 6149 let rowBot = coords.top, rowTop = coords.top; 6150 let firstBelow, coordsBelow; 6151 for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) { 6152 let rects; 6153 if (child.nodeType == 1) rects = child.getClientRects(); 6154 else if (child.nodeType == 3) rects = textRange(child).getClientRects(); 6155 else continue; 6156 for (let i$1 = 0; i$1 < rects.length; i$1++) { 6157 let rect = rects[i$1]; 6158 if (rect.top <= rowBot && rect.bottom >= rowTop) { 6159 rowBot = Math.max(rect.bottom, rowBot); 6160 rowTop = Math.min(rect.top, rowTop); 6161 let dx = rect.left > coords.left ? rect.left - coords.left : rect.right < coords.left ? coords.left - rect.right : 0; 6162 if (dx < dxClosest) { 6163 closest = child; 6164 dxClosest = dx; 6165 coordsClosest = dx && closest.nodeType == 3 ? { 6166 left: rect.right < coords.left ? rect.right : rect.left, 6167 top: coords.top 6168 } : coords; 6169 if (child.nodeType == 1 && dx) offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0); 6170 continue; 6171 } 6172 } else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) { 6173 firstBelow = child; 6174 coordsBelow = { 6175 left: Math.max(rect.left, Math.min(rect.right, coords.left)), 6176 top: rect.top 6177 }; 6178 } 6179 if (!closest && (coords.left >= rect.right && coords.top >= rect.top || coords.left >= rect.left && coords.top >= rect.bottom)) offset = childIndex + 1; 6180 } 6181 } 6182 if (!closest && firstBelow) { 6183 closest = firstBelow; 6184 coordsClosest = coordsBelow; 6185 dxClosest = 0; 6186 } 6187 if (closest && closest.nodeType == 3) return findOffsetInText(closest, coordsClosest); 6188 if (!closest || dxClosest && closest.nodeType == 1) return { 6189 node, 6190 offset 6191 }; 6192 return findOffsetInNode(closest, coordsClosest); 6193} 6194function findOffsetInText(node, coords) { 6195 let len = node.nodeValue.length; 6196 let range = document.createRange(), result; 6197 for (let i$1 = 0; i$1 < len; i$1++) { 6198 range.setEnd(node, i$1 + 1); 6199 range.setStart(node, i$1); 6200 let rect = singleRect(range, 1); 6201 if (rect.top == rect.bottom) continue; 6202 if (inRect(coords, rect)) { 6203 result = { 6204 node, 6205 offset: i$1 + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) 6206 }; 6207 break; 6208 } 6209 } 6210 range.detach(); 6211 return result || { 6212 node, 6213 offset: 0 6214 }; 6215} 6216function inRect(coords, rect) { 6217 return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 && coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1; 6218} 6219function targetKludge(dom, coords) { 6220 let parent = dom.parentNode; 6221 if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left) return parent; 6222 return dom; 6223} 6224function posFromElement(view, elt, coords) { 6225 let { node, offset } = findOffsetInNode(elt, coords), bias = -1; 6226 if (node.nodeType == 1 && !node.firstChild) { 6227 let rect = node.getBoundingClientRect(); 6228 bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1; 6229 } 6230 return view.docView.posFromDOM(node, offset, bias); 6231} 6232function posFromCaret(view, node, offset, coords) { 6233 let outsideBlock = -1; 6234 for (let cur = node, sawBlock = false;;) { 6235 if (cur == view.dom) break; 6236 let desc = view.docView.nearestDesc(cur, true), rect; 6237 if (!desc) return null; 6238 if (desc.dom.nodeType == 1 && (desc.node.isBlock && desc.parent || !desc.contentDOM) && ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) { 6239 if (desc.node.isBlock && desc.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(desc.dom.nodeName)) { 6240 if (!sawBlock && rect.left > coords.left || rect.top > coords.top) outsideBlock = desc.posBefore; 6241 else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top) outsideBlock = desc.posAfter; 6242 sawBlock = true; 6243 } 6244 if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) return (desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2 : coords.left < (rect.left + rect.right) / 2) ? desc.posBefore : desc.posAfter; 6245 } 6246 cur = desc.dom.parentNode; 6247 } 6248 return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1); 6249} 6250function elementFromPoint(element, coords, box) { 6251 let len = element.childNodes.length; 6252 if (len && box.top < box.bottom) for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i$1 = startI;;) { 6253 let child = element.childNodes[i$1]; 6254 if (child.nodeType == 1) { 6255 let rects = child.getClientRects(); 6256 for (let j = 0; j < rects.length; j++) { 6257 let rect = rects[j]; 6258 if (inRect(coords, rect)) return elementFromPoint(child, coords, rect); 6259 } 6260 } 6261 if ((i$1 = (i$1 + 1) % len) == startI) break; 6262 } 6263 return element; 6264} 6265function posAtCoords(view, coords) { 6266 let doc$2 = view.dom.ownerDocument, node, offset = 0; 6267 let caret = caretFromPoint(doc$2, coords.left, coords.top); 6268 if (caret) ({node, offset} = caret); 6269 let elt = (view.root.elementFromPoint ? view.root : doc$2).elementFromPoint(coords.left, coords.top); 6270 let pos; 6271 if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) { 6272 let box = view.dom.getBoundingClientRect(); 6273 if (!inRect(coords, box)) return null; 6274 elt = elementFromPoint(view.dom, coords, box); 6275 if (!elt) return null; 6276 } 6277 if (safari) { 6278 for (let p = elt; node && p; p = parentNode(p)) if (p.draggable) node = void 0; 6279 } 6280 elt = targetKludge(elt, coords); 6281 if (node) { 6282 if (gecko && node.nodeType == 1) { 6283 offset = Math.min(offset, node.childNodes.length); 6284 if (offset < node.childNodes.length) { 6285 let next = node.childNodes[offset], box; 6286 if (next.nodeName == "IMG" && (box = next.getBoundingClientRect()).right <= coords.left && box.bottom > coords.top) offset++; 6287 } 6288 } 6289 let prev; 6290 if (webkit && offset && node.nodeType == 1 && (prev = node.childNodes[offset - 1]).nodeType == 1 && prev.contentEditable == "false" && prev.getBoundingClientRect().top >= coords.top) offset--; 6291 if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 && coords.top > node.lastChild.getBoundingClientRect().bottom) pos = view.state.doc.content.size; 6292 else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != "BR") pos = posFromCaret(view, node, offset, coords); 6293 } 6294 if (pos == null) pos = posFromElement(view, elt, coords); 6295 let desc = view.docView.nearestDesc(elt, true); 6296 return { 6297 pos, 6298 inside: desc ? desc.posAtStart - desc.border : -1 6299 }; 6300} 6301function nonZero(rect) { 6302 return rect.top < rect.bottom || rect.left < rect.right; 6303} 6304function singleRect(target, bias) { 6305 let rects = target.getClientRects(); 6306 if (rects.length) { 6307 let first$1 = rects[bias < 0 ? 0 : rects.length - 1]; 6308 if (nonZero(first$1)) return first$1; 6309 } 6310 return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect(); 6311} 6312var BIDI = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; 6313function coordsAtPos(view, pos, side) { 6314 let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1); 6315 let supportEmptyRange = webkit || gecko; 6316 if (node.nodeType == 3) if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) { 6317 let rect = singleRect(textRange(node, offset, offset), side); 6318 if (gecko && offset && /\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) { 6319 let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1); 6320 if (rectBefore.top == rect.top) { 6321 let rectAfter = singleRect(textRange(node, offset, offset + 1), -1); 6322 if (rectAfter.top != rect.top) return flattenV(rectAfter, rectAfter.left < rectBefore.left); 6323 } 6324 } 6325 return rect; 6326 } else { 6327 let from = offset, to = offset, takeSide = side < 0 ? 1 : -1; 6328 if (side < 0 && !offset) { 6329 to++; 6330 takeSide = -1; 6331 } else if (side >= 0 && offset == node.nodeValue.length) { 6332 from--; 6333 takeSide = 1; 6334 } else if (side < 0) from--; 6335 else to++; 6336 return flattenV(singleRect(textRange(node, from, to), takeSide), takeSide < 0); 6337 } 6338 if (!view.state.doc.resolve(pos - (atom || 0)).parent.inlineContent) { 6339 if (atom == null && offset && (side < 0 || offset == nodeSize(node))) { 6340 let before = node.childNodes[offset - 1]; 6341 if (before.nodeType == 1) return flattenH(before.getBoundingClientRect(), false); 6342 } 6343 if (atom == null && offset < nodeSize(node)) { 6344 let after = node.childNodes[offset]; 6345 if (after.nodeType == 1) return flattenH(after.getBoundingClientRect(), true); 6346 } 6347 return flattenH(node.getBoundingClientRect(), side >= 0); 6348 } 6349 if (atom == null && offset && (side < 0 || offset == nodeSize(node))) { 6350 let before = node.childNodes[offset - 1]; 6351 let target = before.nodeType == 3 ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1)) : before.nodeType == 1 && (before.nodeName != "BR" || !before.nextSibling) ? before : null; 6352 if (target) return flattenV(singleRect(target, 1), false); 6353 } 6354 if (atom == null && offset < nodeSize(node)) { 6355 let after = node.childNodes[offset]; 6356 while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords) after = after.nextSibling; 6357 let target = !after ? null : after.nodeType == 3 ? textRange(after, 0, supportEmptyRange ? 0 : 1) : after.nodeType == 1 ? after : null; 6358 if (target) return flattenV(singleRect(target, -1), true); 6359 } 6360 return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0); 6361} 6362function flattenV(rect, left) { 6363 if (rect.width == 0) return rect; 6364 let x = left ? rect.left : rect.right; 6365 return { 6366 top: rect.top, 6367 bottom: rect.bottom, 6368 left: x, 6369 right: x 6370 }; 6371} 6372function flattenH(rect, top) { 6373 if (rect.height == 0) return rect; 6374 let y = top ? rect.top : rect.bottom; 6375 return { 6376 top: y, 6377 bottom: y, 6378 left: rect.left, 6379 right: rect.right 6380 }; 6381} 6382function withFlushedState(view, state, f) { 6383 let viewState = view.state, active = view.root.activeElement; 6384 if (viewState != state) view.updateState(state); 6385 if (active != view.dom) view.focus(); 6386 try { 6387 return f(); 6388 } finally { 6389 if (viewState != state) view.updateState(viewState); 6390 if (active != view.dom && active) active.focus(); 6391 } 6392} 6393function endOfTextblockVertical(view, state, dir) { 6394 let sel = state.selection; 6395 let $pos = dir == "up" ? sel.$from : sel.$to; 6396 return withFlushedState(view, state, () => { 6397 let { node: dom } = view.docView.domFromPos($pos.pos, dir == "up" ? -1 : 1); 6398 for (;;) { 6399 let nearest = view.docView.nearestDesc(dom, true); 6400 if (!nearest) break; 6401 if (nearest.node.isBlock) { 6402 dom = nearest.contentDOM || nearest.dom; 6403 break; 6404 } 6405 dom = nearest.dom.parentNode; 6406 } 6407 let coords = coordsAtPos(view, $pos.pos, 1); 6408 for (let child = dom.firstChild; child; child = child.nextSibling) { 6409 let boxes; 6410 if (child.nodeType == 1) boxes = child.getClientRects(); 6411 else if (child.nodeType == 3) boxes = textRange(child, 0, child.nodeValue.length).getClientRects(); 6412 else continue; 6413 for (let i$1 = 0; i$1 < boxes.length; i$1++) { 6414 let box = boxes[i$1]; 6415 if (box.bottom > box.top + 1 && (dir == "up" ? coords.top - box.top > (box.bottom - coords.top) * 2 : box.bottom - coords.bottom > (coords.bottom - box.top) * 2)) return false; 6416 } 6417 } 6418 return true; 6419 }); 6420} 6421var maybeRTL = /[\u0590-\u08ac]/; 6422function endOfTextblockHorizontal(view, state, dir) { 6423 let { $head } = state.selection; 6424 if (!$head.parent.isTextblock) return false; 6425 let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size; 6426 let sel = view.domSelection(); 6427 if (!sel) return $head.pos == $head.start() || $head.pos == $head.end(); 6428 if (!maybeRTL.test($head.parent.textContent) || !sel.modify) return dir == "left" || dir == "backward" ? atStart : atEnd; 6429 return withFlushedState(view, state, () => { 6430 let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange(); 6431 let oldBidiLevel = sel.caretBidiLevel; 6432 sel.modify("move", dir, "character"); 6433 let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom; 6434 let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange(); 6435 let result = newNode && !parentDOM.contains(newNode.nodeType == 1 ? newNode : newNode.parentNode) || oldNode == newNode && oldOff == newOff; 6436 try { 6437 sel.collapse(anchorNode, anchorOffset); 6438 if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend) sel.extend(oldNode, oldOff); 6439 } catch (_) {} 6440 if (oldBidiLevel != null) sel.caretBidiLevel = oldBidiLevel; 6441 return result; 6442 }); 6443} 6444var cachedState = null; 6445var cachedDir = null; 6446var cachedResult = false;
6447function endOfTextblock(view, state, dir) { 6448 if (cachedState == state && cachedDir == dir) return cachedResult; 6449 cachedState = state; 6450 cachedDir = dir; 6451 return cachedResult = dir == "up" || dir == "down" ? endOfTextblockVertical(view, state, dir) : endOfTextblockHorizontal(view, state, dir); 6452} 6453var NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3; 6454var ViewDesc = class { 6455 constructor(parent, children, dom, contentDOM) { 6456 this.parent = parent; 6457 this.children = children; 6458 this.dom = dom; 6459 this.contentDOM = contentDOM; 6460 this.dirty = NOT_DIRTY; 6461 dom.pmViewDesc = this; 6462 } 6463 matchesWidget(widget) { 6464 return false; 6465 } 6466 matchesMark(mark) { 6467 return false; 6468 } 6469 matchesNode(node, outerDeco, innerDeco) { 6470 return false; 6471 } 6472 matchesHack(nodeName) { 6473 return false; 6474 } 6475 parseRule(addedNodes) { 6476 return null; 6477 } 6478 stopEvent(event) { 6479 return false; 6480 } 6481 get size() { 6482 let size = 0; 6483 for (let i$1 = 0; i$1 < this.children.length; i$1++) size += this.children[i$1].size; 6484 return size; 6485 } 6486 get border() { 6487 return 0; 6488 } 6489 destroy() { 6490 this.parent = void 0; 6491 if (this.dom.pmViewDesc == this) this.dom.pmViewDesc = void 0; 6492 for (let i$1 = 0; i$1 < this.children.length; i$1++) this.children[i$1].destroy(); 6493 } 6494 posBeforeChild(child) { 6495 for (let i$1 = 0, pos = this.posAtStart;; i$1++) { 6496 let cur = this.children[i$1]; 6497 if (cur == child) return pos; 6498 pos += cur.size; 6499 } 6500 } 6501 get posBefore() { 6502 return this.parent.posBeforeChild(this); 6503 } 6504 get posAtStart() { 6505 return this.parent ? this.parent.posBeforeChild(this) + this.border : 0; 6506 } 6507 get posAfter() { 6508 return this.posBefore + this.size; 6509 } 6510 get posAtEnd() { 6511 return this.posAtStart + this.size - 2 * this.border; 6512 } 6513 localPosFromDOM(dom, offset, bias) { 6514 if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) if (bias < 0) { 6515 let domBefore, desc; 6516 if (dom == this.contentDOM) domBefore = dom.childNodes[offset - 1]; 6517 else { 6518 while (dom.parentNode != this.contentDOM) dom = dom.parentNode; 6519 domBefore = dom.previousSibling; 6520 } 6521 while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this)) domBefore = domBefore.previousSibling; 6522 return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart; 6523 } else { 6524 let domAfter, desc; 6525 if (dom == this.contentDOM) domAfter = dom.childNodes[offset]; 6526 else { 6527 while (dom.parentNode != this.contentDOM) dom = dom.parentNode; 6528 domAfter = dom.nextSibling; 6529 } 6530 while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this)) domAfter = domAfter.nextSibling; 6531 return domAfter ? this.posBeforeChild(desc) : this.posAtEnd; 6532 } 6533 let atEnd; 6534 if (dom == this.dom && this.contentDOM) atEnd = offset > domIndex(this.contentDOM); 6535 else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) atEnd = dom.compareDocumentPosition(this.contentDOM) & 2; 6536 else if (this.dom.firstChild) { 6537 if (offset == 0) for (let search = dom;; search = search.parentNode) { 6538 if (search == this.dom) { 6539 atEnd = false; 6540 break; 6541 } 6542 if (search.previousSibling) break; 6543 }
vendor: 18,193 bytes, lines 6544-7035
6544 if (atEnd == null && offset == dom.childNodes.length) for (let search = dom;; search = search.parentNode) { 6545 if (search == this.dom) { 6546 atEnd = true; 6547 break; 6548 } 6549 if (search.nextSibling) break; 6550 } 6551 } 6552 return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart; 6553 } 6554 nearestDesc(dom, onlyNodes = false) { 6555 for (let first$1 = true, cur = dom; cur; cur = cur.parentNode) { 6556 let desc = this.getDesc(cur), nodeDOM; 6557 if (desc && (!onlyNodes || desc.node)) if (first$1 && (nodeDOM = desc.nodeDOM) && !(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom)) first$1 = false; 6558 else return desc; 6559 } 6560 } 6561 getDesc(dom) { 6562 let desc = dom.pmViewDesc; 6563 for (let cur = desc; cur; cur = cur.parent) if (cur == this) return desc; 6564 } 6565 posFromDOM(dom, offset, bias) { 6566 for (let scan = dom; scan; scan = scan.parentNode) { 6567 let desc = this.getDesc(scan); 6568 if (desc) return desc.localPosFromDOM(dom, offset, bias); 6569 } 6570 return -1; 6571 } 6572 descAt(pos) { 6573 for (let i$1 = 0, offset = 0; i$1 < this.children.length; i$1++) { 6574 let child = this.children[i$1], end = offset + child.size; 6575 if (offset == pos && end != offset) { 6576 while (!child.border && child.children.length) for (let i$2 = 0; i$2 < child.children.length; i$2++) { 6577 let inner = child.children[i$2]; 6578 if (inner.size) { 6579 child = inner; 6580 break; 6581 } 6582 } 6583 return child; 6584 } 6585 if (pos < end) return child.descAt(pos - offset - child.border); 6586 offset = end; 6587 } 6588 } 6589 domFromPos(pos, side) { 6590 if (!this.contentDOM) return { 6591 node: this.dom, 6592 offset: 0, 6593 atom: pos + 1 6594 }; 6595 let i$1 = 0, offset = 0; 6596 for (let curPos = 0; i$1 < this.children.length; i$1++) { 6597 let child = this.children[i$1], end = curPos + child.size; 6598 if (end > pos || child instanceof TrailingHackViewDesc) { 6599 offset = pos - curPos; 6600 break; 6601 } 6602 curPos = end; 6603 } 6604 if (offset) return this.children[i$1].domFromPos(offset - this.children[i$1].border, side); 6605 for (let prev; i$1 && !(prev = this.children[i$1 - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i$1--); 6606 if (side <= 0) { 6607 let prev, enter$1 = true; 6608 for (;; i$1--, enter$1 = false) { 6609 prev = i$1 ? this.children[i$1 - 1] : null; 6610 if (!prev || prev.dom.parentNode == this.contentDOM) break; 6611 } 6612 if (prev && side && enter$1 && !prev.border && !prev.domAtom) return prev.domFromPos(prev.size, side); 6613 return { 6614 node: this.contentDOM, 6615 offset: prev ? domIndex(prev.dom) + 1 : 0 6616 }; 6617 } else { 6618 let next, enter$1 = true; 6619 for (;; i$1++, enter$1 = false) { 6620 next = i$1 < this.children.length ? this.children[i$1] : null; 6621 if (!next || next.dom.parentNode == this.contentDOM) break; 6622 } 6623 if (next && enter$1 && !next.border && !next.domAtom) return next.domFromPos(0, side); 6624 return { 6625 node: this.contentDOM, 6626 offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length 6627 }; 6628 } 6629 } 6630 parseRange(from, to, base$1 = 0) { 6631 if (this.children.length == 0) return { 6632 node: this.contentDOM, 6633 from, 6634 to, 6635 fromOffset: 0, 6636 toOffset: this.contentDOM.childNodes.length 6637 }; 6638 let fromOffset = -1, toOffset = -1; 6639 for (let offset = base$1, i$1 = 0;; i$1++) { 6640 let child = this.children[i$1], end = offset + child.size; 6641 if (fromOffset == -1 && from <= end) { 6642 let childBase = offset + child.border; 6643 if (from >= childBase && to <= end - child.border && child.node && child.contentDOM && this.contentDOM.contains(child.contentDOM)) return child.parseRange(from, to, childBase); 6644 from = offset; 6645 for (let j = i$1; j > 0; j--) { 6646 let prev = this.children[j - 1]; 6647 if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) { 6648 fromOffset = domIndex(prev.dom) + 1; 6649 break; 6650 } 6651 from -= prev.size; 6652 } 6653 if (fromOffset == -1) fromOffset = 0; 6654 } 6655 if (fromOffset > -1 && (end > to || i$1 == this.children.length - 1)) { 6656 to = end; 6657 for (let j = i$1 + 1; j < this.children.length; j++) { 6658 let next = this.children[j]; 6659 if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) { 6660 toOffset = domIndex(next.dom); 6661 break; 6662 } 6663 to += next.size; 6664 } 6665 if (toOffset == -1) toOffset = this.contentDOM.childNodes.length; 6666 break; 6667 } 6668 offset = end; 6669 } 6670 return { 6671 node: this.contentDOM, 6672 from, 6673 to, 6674 fromOffset, 6675 toOffset 6676 }; 6677 } 6678 emptyChildAt(side) { 6679 if (this.border || !this.contentDOM || !this.children.length) return false; 6680 let child = this.children[side < 0 ? 0 : this.children.length - 1]; 6681 return child.size == 0 || child.emptyChildAt(side); 6682 } 6683 domAfterPos(pos) { 6684 let { node, offset } = this.domFromPos(pos, 0); 6685 if (node.nodeType != 1 || offset == node.childNodes.length) throw new RangeError("No node after pos " + pos); 6686 return node.childNodes[offset]; 6687 } 6688 setSelection(anchor, head, view, force = false) { 6689 let from = Math.min(anchor, head), to = Math.max(anchor, head); 6690 for (let i$1 = 0, offset = 0; i$1 < this.children.length; i$1++) { 6691 let child = this.children[i$1], end = offset + child.size; 6692 if (from > offset && to < end) return child.setSelection(anchor - offset - child.border, head - offset - child.border, view, force); 6693 offset = end; 6694 } 6695 let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1); 6696 let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1); 6697 let domSel = view.root.getSelection(); 6698 let selRange = view.domSelectionRange(); 6699 let brKludge = false; 6700 if ((gecko || safari) && anchor == head) { 6701 let { node, offset } = anchorDOM; 6702 if (node.nodeType == 3) { 6703 brKludge = !!(offset && node.nodeValue[offset - 1] == "\n"); 6704 if (brKludge && offset == node.nodeValue.length) for (let scan = node, after; scan; scan = scan.parentNode) { 6705 if (after = scan.nextSibling) { 6706 if (after.nodeName == "BR") anchorDOM = headDOM = { 6707 node: after.parentNode, 6708 offset: domIndex(after) + 1 6709 }; 6710 break; 6711 } 6712 let desc = scan.pmViewDesc; 6713 if (desc && desc.node && desc.node.isBlock) break; 6714 } 6715 } else { 6716 let prev = node.childNodes[offset - 1]; 6717 brKludge = prev && (prev.nodeName == "BR" || prev.contentEditable == "false"); 6718 } 6719 } 6720 if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && selRange.focusNode.nodeType == 1) { 6721 let after = selRange.focusNode.childNodes[selRange.focusOffset]; 6722 if (after && after.contentEditable == "false") force = true; 6723 } 6724 if (!(force || brKludge && safari) && isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) && isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset)) return; 6725 let domSelExtended = false; 6726 if ((domSel.extend || anchor == head) && !(brKludge && gecko)) { 6727 domSel.collapse(anchorDOM.node, anchorDOM.offset); 6728 try { 6729 if (anchor != head) domSel.extend(headDOM.node, headDOM.offset); 6730 domSelExtended = true; 6731 } catch (_) {} 6732 } 6733 if (!domSelExtended) { 6734 if (anchor > head) { 6735 let tmp = anchorDOM; 6736 anchorDOM = headDOM; 6737 headDOM = tmp; 6738 } 6739 let range = document.createRange(); 6740 range.setEnd(headDOM.node, headDOM.offset); 6741 range.setStart(anchorDOM.node, anchorDOM.offset); 6742 domSel.removeAllRanges(); 6743 domSel.addRange(range); 6744 } 6745 } 6746 ignoreMutation(mutation) { 6747 return !this.contentDOM && mutation.type != "selection"; 6748 } 6749 get contentLost() { 6750 return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM); 6751 } 6752 markDirty(from, to) { 6753 for (let offset = 0, i$1 = 0; i$1 < this.children.length; i$1++) { 6754 let child = this.children[i$1], end = offset + child.size; 6755 if (offset == end ? from <= end && to >= offset : from < end && to > offset) { 6756 let startInside = offset + child.border, endInside = end - child.border; 6757 if (from >= startInside && to <= endInside) { 6758 this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY; 6759 if (from == startInside && to == endInside && (child.contentLost || child.dom.parentNode != this.contentDOM)) child.dirty = NODE_DIRTY; 6760 else child.markDirty(from - startInside, to - startInside); 6761 return; 6762 } else child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length ? CONTENT_DIRTY : NODE_DIRTY; 6763 } 6764 offset = end; 6765 } 6766 this.dirty = CONTENT_DIRTY; 6767 } 6768 markParentsDirty() { 6769 let level = 1; 6770 for (let node = this.parent; node; node = node.parent, level++) { 6771 let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY; 6772 if (node.dirty < dirty) node.dirty = dirty; 6773 } 6774 } 6775 get domAtom() { 6776 return false; 6777 } 6778 get ignoreForCoords() { 6779 return false; 6780 } 6781 get ignoreForSelection() { 6782 return false; 6783 } 6784 isText(text$1) { 6785 return false; 6786 } 6787}; 6788var WidgetViewDesc = class extends ViewDesc { 6789 constructor(parent, widget, view, pos) { 6790 let self, dom = widget.type.toDOM; 6791 if (typeof dom == "function") dom = dom(view, () => { 6792 if (!self) return pos; 6793 if (self.parent) return self.parent.posBeforeChild(self); 6794 }); 6795 if (!widget.type.spec.raw) { 6796 if (dom.nodeType != 1) { 6797 let wrap$1 = document.createElement("span"); 6798 wrap$1.appendChild(dom); 6799 dom = wrap$1; 6800 } 6801 if (!dom.hasAttribute("contenteditable")) dom.contentEditable = "false"; 6802 dom.classList.add("ProseMirror-widget"); 6803 } 6804 super(parent, [], dom, null); 6805 this.widget = widget; 6806 this.widget = widget; 6807 self = this; 6808 } 6809 matchesWidget(widget) { 6810 return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type); 6811 } 6812 parseRule() { 6813 return { ignore: true }; 6814 } 6815 stopEvent(event) { 6816 let stop = this.widget.spec.stopEvent; 6817 return stop ? stop(event) : false; 6818 } 6819 ignoreMutation(mutation) { 6820 return mutation.type != "selection" || this.widget.spec.ignoreSelection; 6821 } 6822 destroy() { 6823 this.widget.type.destroy(this.dom); 6824 super.destroy(); 6825 } 6826 get domAtom() { 6827 return true; 6828 } 6829 get ignoreForSelection() { 6830 return !!this.widget.type.spec.relaxedSide; 6831 } 6832 get side() { 6833 return this.widget.type.side; 6834 } 6835}; 6836var CompositionViewDesc = class extends ViewDesc { 6837 constructor(parent, dom, textDOM, text$1) { 6838 super(parent, [], dom, null); 6839 this.textDOM = textDOM; 6840 this.text = text$1; 6841 } 6842 get size() { 6843 return this.text.length; 6844 } 6845 localPosFromDOM(dom, offset) { 6846 if (dom != this.textDOM) return this.posAtStart + (offset ? this.size : 0); 6847 return this.posAtStart + offset; 6848 } 6849 domFromPos(pos) { 6850 return { 6851 node: this.textDOM, 6852 offset: pos 6853 }; 6854 } 6855 ignoreMutation(mut) { 6856 return mut.type === "characterData" && mut.target.nodeValue == mut.oldValue; 6857 } 6858}; 6859var MarkViewDesc = class MarkViewDesc extends ViewDesc { 6860 constructor(parent, mark, dom, contentDOM, spec) { 6861 super(parent, [], dom, contentDOM); 6862 this.mark = mark; 6863 this.spec = spec; 6864 } 6865 static create(parent, mark, inline, view) { 6866 let custom = view.nodeViews[mark.type.name]; 6867 let spec = custom && custom(mark, view, inline); 6868 if (!spec || !spec.dom) spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline), null, mark.attrs); 6869 return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec); 6870 } 6871 parseRule() { 6872 if (this.dirty & NODE_DIRTY || this.mark.type.spec.reparseInView) return null; 6873 return { 6874 mark: this.mark.type.name, 6875 attrs: this.mark.attrs, 6876 contentElement: this.contentDOM 6877 }; 6878 } 6879 matchesMark(mark) { 6880 return this.dirty != NODE_DIRTY && this.mark.eq(mark); 6881 } 6882 markDirty(from, to) { 6883 super.markDirty(from, to); 6884 if (this.dirty != NOT_DIRTY) { 6885 let parent = this.parent; 6886 while (!parent.node) parent = parent.parent; 6887 if (parent.dirty < this.dirty) parent.dirty = this.dirty; 6888 this.dirty = NOT_DIRTY; 6889 } 6890 } 6891 slice(from, to, view) { 6892 let copy$1 = MarkViewDesc.create(this.parent, this.mark, true, view); 6893 let nodes = this.children, size = this.size; 6894 if (to < size) nodes = replaceNodes(nodes, to, size, view); 6895 if (from > 0) nodes = replaceNodes(nodes, 0, from, view); 6896 for (let i$1 = 0; i$1 < nodes.length; i$1++) nodes[i$1].parent = copy$1; 6897 copy$1.children = nodes; 6898 return copy$1; 6899 } 6900 ignoreMutation(mutation) { 6901 return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation); 6902 } 6903 destroy() { 6904 if (this.spec.destroy) this.spec.destroy(); 6905 super.destroy(); 6906 } 6907}; 6908var NodeViewDesc = class NodeViewDesc extends ViewDesc { 6909 constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM) { 6910 super(parent, [], dom, contentDOM); 6911 this.node = node; 6912 this.outerDeco = outerDeco; 6913 this.innerDeco = innerDeco; 6914 this.nodeDOM = nodeDOM; 6915 } 6916 static create(parent, node, outerDeco, innerDeco, view, pos) { 6917 let custom = view.nodeViews[node.type.name], descObj; 6918 let spec = custom && custom(node, view, () => { 6919 if (!descObj) return pos; 6920 if (descObj.parent) return descObj.parent.posBeforeChild(descObj); 6921 }, outerDeco, innerDeco); 6922 let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM; 6923 if (node.isText) { 6924 if (!dom) dom = document.createTextNode(node.text); 6925 else if (dom.nodeType != 3) throw new RangeError("Text must be rendered as a DOM text node"); 6926 } else if (!dom) { 6927 let spec$1 = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs); 6928 ({dom, contentDOM} = spec$1); 6929 } 6930 if (!contentDOM && !node.isText && dom.nodeName != "BR") { 6931 if (!dom.hasAttribute("contenteditable")) dom.contentEditable = "false"; 6932 if (node.type.spec.draggable) dom.draggable = true; 6933 } 6934 let nodeDOM = dom; 6935 dom = applyOuterDeco(dom, outerDeco, node); 6936 if (spec) return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec); 6937 else if (node.isText) return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM); 6938 else return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM); 6939 } 6940 parseRule(addedNodes) { 6941 if (this.node.type.spec.reparseInView) return null; 6942 let rule = { 6943 node: this.node.type.name, 6944 attrs: this.node.attrs 6945 }; 6946 if (this.node.type.whitespace == "pre") rule.preserveWhitespace = "full"; 6947 if (!this.contentDOM) rule.getContent = () => this.node.content; 6948 else if (!this.contentLost) rule.contentElement = this.contentDOM; 6949 else { 6950 for (let i$1 = this.children.length - 1; i$1 >= 0; i$1--) { 6951 let child = this.children[i$1]; 6952 if (this.dom.contains(child.dom.parentNode)) { 6953 rule.contentElement = child.dom.parentNode; 6954 break; 6955 } 6956 } 6957 if (!rule.contentElement) { 6958 let found$1 = addedNodes && addedNodes.find((n) => n.nodeType == 1 && addedNodes.indexOf(n.parentNode) < 0 && this.dom.contains(n)); 6959 if (found$1) rule.contentElement = found$1; 6960 else rule.getContent = () => Fragment.empty; 6961 } 6962 } 6963 return rule; 6964 } 6965 matchesNode(node, outerDeco, innerDeco) { 6966 return this.dirty == NOT_DIRTY && node.eq(this.node) && sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco); 6967 } 6968 get size() { 6969 return this.node.nodeSize; 6970 } 6971 get border() { 6972 return this.node.isLeaf ? 0 : 1; 6973 } 6974 updateChildren(view, pos) { 6975 let inline = this.node.inlineContent, off = pos; 6976 let composition = view.composing ? this.localCompositionInfo(view, pos) : null; 6977 let localComposition = composition && composition.pos > -1 ? composition : null; 6978 let compositionInChild = composition && composition.pos < 0; 6979 let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view); 6980 iterDeco(this.node, this.innerDeco, (widget, i$1, insideNode) => { 6981 if (widget.spec.marks) updater.syncToMarks(widget.spec.marks, inline, view, i$1); 6982 else if (widget.type.side >= 0 && !insideNode) updater.syncToMarks(i$1 == this.node.childCount ? Mark$1.none : this.node.child(i$1).marks, inline, view, i$1); 6983 updater.placeWidget(widget, view, off); 6984 }, (child, outerDeco, innerDeco, i$1) => { 6985 updater.syncToMarks(child.marks, inline, view, i$1); 6986 let compIndex; 6987 if (updater.findNodeMatch(child, outerDeco, innerDeco, i$1)); 6988 else if (compositionInChild && view.state.selection.from > off && view.state.selection.to < off + child.nodeSize && (compIndex = updater.findIndexWithChild(composition.node)) > -1 && updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)); 6989 else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i$1, off)); 6990 else updater.addNode(child, outerDeco, innerDeco, view, off); 6991 off += child.nodeSize; 6992 }); 6993 updater.syncToMarks([], inline, view, 0); 6994 if (this.node.isTextblock) updater.addTextblockHacks(); 6995 updater.destroyRest(); 6996 if (updater.changed || this.dirty == CONTENT_DIRTY) { 6997 if (localComposition) this.protectLocalComposition(view, localComposition); 6998 renderDescs(this.contentDOM, this.children, view); 6999 if (ios) iosHacks(this.dom); 7000 } 7001 } 7002 localCompositionInfo(view, pos) { 7003 let { from, to } = view.state.selection; 7004 if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size) return null; 7005 let textNode = view.input.compositionNode; 7006 if (!textNode || !this.dom.contains(textNode.parentNode)) return null; 7007 if (this.node.inlineContent) { 7008 let text$1 = textNode.nodeValue; 7009 let textPos = findTextInFragment(this.node.content, text$1, from - pos, to - pos); 7010 return textPos < 0 ? null : { 7011 node: textNode, 7012 pos: textPos, 7013 text: text$1 7014 }; 7015 } else return { 7016 node: textNode, 7017 pos: -1, 7018 text: "" 7019 }; 7020 } 7021 protectLocalComposition(view, { node, pos, text: text$1 }) { 7022 if (this.getDesc(node)) return; 7023 let topNode = node; 7024 for (;; topNode = topNode.parentNode) { 7025 if (topNode.parentNode == this.contentDOM) break; 7026 while (topNode.previousSibling) topNode.parentNode.removeChild(topNode.previousSibling); 7027 while (topNode.nextSibling) topNode.parentNode.removeChild(topNode.nextSibling); 7028 if (topNode.pmViewDesc) topNode.pmViewDesc = void 0; 7029 } 7030 let desc = new CompositionViewDesc(this, topNode, node, text$1); 7031 view.input.compositionNodes.push(desc); 7032 this.children = replaceNodes(this.children, pos, pos + text$1.length, view, desc); 7033 } 7034 update(node, outerDeco, innerDeco, view) { 7035 if (this.dirty == NODE_DIRTY || !node.sameMarkup(this.node)) return false;
7036 this.updateInner(node, outerDeco, innerDeco, view); 7037 return true; 7038 } 7039 updateInner(node, outerDeco, innerDeco, view) { 7040 this.updateOuterDeco(outerDeco); 7041 this.node = node; 7042 this.innerDeco = innerDeco; 7043 if (this.contentDOM) this.updateChildren(view, this.posAtStart); 7044 this.dirty = NOT_DIRTY; 7045 } 7046 updateOuterDeco(outerDeco) { 7047 if (sameOuterDeco(outerDeco, this.outerDeco)) return; 7048 let needsWrap = this.nodeDOM.nodeType != 1; 7049 let oldDOM = this.dom; 7050 this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap)); 7051 if (this.dom != oldDOM) { 7052 oldDOM.pmViewDesc = void 0; 7053 this.dom.pmViewDesc = this; 7054 } 7055 this.outerDeco = outerDeco; 7056 } 7057 selectNode() { 7058 if (this.nodeDOM.nodeType == 1) { 7059 this.nodeDOM.classList.add("ProseMirror-selectednode"); 7060 if (this.contentDOM || !this.node.type.spec.draggable) this.nodeDOM.draggable = true; 7061 } 7062 } 7063 deselectNode() { 7064 if (this.nodeDOM.nodeType == 1) { 7065 this.nodeDOM.classList.remove("ProseMirror-selectednode"); 7066 if (this.contentDOM || !this.node.type.spec.draggable) this.nodeDOM.removeAttribute("draggable"); 7067 } 7068 } 7069 get domAtom() { 7070 return this.node.isAtom; 7071 } 7072}; 7073function docViewDesc(doc$2, outerDeco, innerDeco, dom, view) { 7074 applyOuterDeco(dom, outerDeco, doc$2); 7075 let docView = new NodeViewDesc(void 0, doc$2, outerDeco, innerDeco, dom, dom, dom); 7076 if (docView.contentDOM) docView.updateChildren(view, 0); 7077 return docView; 7078} 7079var TextViewDesc = class TextViewDesc extends NodeViewDesc { 7080 constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM) { 7081 super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM); 7082 } 7083 parseRule() { 7084 let skip = this.nodeDOM.parentNode; 7085 while (skip && skip != this.dom && !skip.pmIsDeco) skip = skip.parentNode; 7086 return { skip: skip || true }; 7087 } 7088 update(node, outerDeco, innerDeco, view) { 7089 if (this.dirty == NODE_DIRTY || this.dirty != NOT_DIRTY && !this.inParent() || !node.sameMarkup(this.node)) return false; 7090 this.updateOuterDeco(outerDeco); 7091 if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) { 7092 this.nodeDOM.nodeValue = node.text; 7093 if (view.trackWrites == this.nodeDOM) view.trackWrites = null; 7094 } 7095 this.node = node; 7096 this.dirty = NOT_DIRTY; 7097 return true; 7098 } 7099 inParent() { 7100 let parentDOM = this.parent.contentDOM; 7101 for (let n = this.nodeDOM; n; n = n.parentNode) if (n == parentDOM) return true; 7102 return false; 7103 } 7104 domFromPos(pos) { 7105 return { 7106 node: this.nodeDOM, 7107 offset: pos 7108 }; 7109 } 7110 localPosFromDOM(dom, offset, bias) { 7111 if (dom == this.nodeDOM) return this.posAtStart + Math.min(offset, this.node.text.length); 7112 return super.localPosFromDOM(dom, offset, bias); 7113 } 7114 ignoreMutation(mutation) { 7115 return mutation.type != "characterData" && mutation.type != "selection"; 7116 } 7117 slice(from, to, _view) { 7118 let node = this.node.cut(from, to), dom = document.createTextNode(node.text); 7119 return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom); 7120 } 7121 markDirty(from, to) { 7122 super.markDirty(from, to); 7123 if (this.dom != this.nodeDOM && (from == 0 || to == this.nodeDOM.nodeValue.length)) this.dirty = NODE_DIRTY; 7124 } 7125 get domAtom() { 7126 return false; 7127 } 7128 isText(text$1) { 7129 return this.node.text == text$1; 7130 } 7131}; 7132var TrailingHackViewDesc = class extends ViewDesc { 7133 parseRule() { 7134 return { ignore: true }; 7135 } 7136 matchesHack(nodeName) { 7137 return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName; 7138 } 7139 get domAtom() { 7140 return true; 7141 } 7142 get ignoreForCoords() { 7143 return this.dom.nodeName == "IMG"; 7144 } 7145}; 7146var CustomNodeViewDesc = class extends NodeViewDesc { 7147 constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec) { 7148 super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM); 7149 this.spec = spec; 7150 } 7151 update(node, outerDeco, innerDeco, view) { 7152 if (this.dirty == NODE_DIRTY) return false; 7153 if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) { 7154 let result = this.spec.update(node, outerDeco, innerDeco); 7155 if (result) this.updateInner(node, outerDeco, innerDeco, view); 7156 return result; 7157 } else if (!this.contentDOM && !node.isLeaf) return false;
vendor: 8,639 bytes, lines 7158-7387
7158 else return super.update(node, outerDeco, innerDeco, view); 7159 } 7160 selectNode() { 7161 this.spec.selectNode ? this.spec.selectNode() : super.selectNode(); 7162 } 7163 deselectNode() { 7164 this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode(); 7165 } 7166 setSelection(anchor, head, view, force) { 7167 this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root) : super.setSelection(anchor, head, view, force); 7168 } 7169 destroy() { 7170 if (this.spec.destroy) this.spec.destroy(); 7171 super.destroy(); 7172 } 7173 stopEvent(event) { 7174 return this.spec.stopEvent ? this.spec.stopEvent(event) : false; 7175 } 7176 ignoreMutation(mutation) { 7177 return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation); 7178 } 7179}; 7180function renderDescs(parentDOM, descs, view) { 7181 let dom = parentDOM.firstChild, written = false; 7182 for (let i$1 = 0; i$1 < descs.length; i$1++) { 7183 let desc = descs[i$1], childDOM = desc.dom; 7184 if (childDOM.parentNode == parentDOM) { 7185 while (childDOM != dom) { 7186 dom = rm(dom); 7187 written = true; 7188 } 7189 dom = dom.nextSibling; 7190 } else { 7191 written = true; 7192 parentDOM.insertBefore(childDOM, dom); 7193 } 7194 if (desc instanceof MarkViewDesc) { 7195 let pos = dom ? dom.previousSibling : parentDOM.lastChild; 7196 renderDescs(desc.contentDOM, desc.children, view); 7197 dom = pos ? pos.nextSibling : parentDOM.firstChild; 7198 } 7199 } 7200 while (dom) { 7201 dom = rm(dom); 7202 written = true; 7203 } 7204 if (written && view.trackWrites == parentDOM) view.trackWrites = null; 7205} 7206var OuterDecoLevel = function(nodeName) { 7207 if (nodeName) this.nodeName = nodeName; 7208}; 7209OuterDecoLevel.prototype = Object.create(null); 7210var noDeco = [new OuterDecoLevel()]; 7211function computeOuterDeco(outerDeco, node, needsWrap) { 7212 if (outerDeco.length == 0) return noDeco; 7213 let top = needsWrap ? noDeco[0] : new OuterDecoLevel(), result = [top]; 7214 for (let i$1 = 0; i$1 < outerDeco.length; i$1++) { 7215 let attrs = outerDeco[i$1].type.attrs; 7216 if (!attrs) continue; 7217 if (attrs.nodeName) result.push(top = new OuterDecoLevel(attrs.nodeName)); 7218 for (let name in attrs) { 7219 let val = attrs[name]; 7220 if (val == null) continue; 7221 if (needsWrap && result.length == 1) result.push(top = new OuterDecoLevel(node.isInline ? "span" : "div")); 7222 if (name == "class") top.class = (top.class ? top.class + " " : "") + val; 7223 else if (name == "style") top.style = (top.style ? top.style + ";" : "") + val; 7224 else if (name != "nodeName") top[name] = val; 7225 } 7226 } 7227 return result; 7228} 7229function patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) { 7230 if (prevComputed == noDeco && curComputed == noDeco) return nodeDOM; 7231 let curDOM = nodeDOM; 7232 for (let i$1 = 0; i$1 < curComputed.length; i$1++) { 7233 let deco = curComputed[i$1], prev = prevComputed[i$1]; 7234 if (i$1) { 7235 let parent; 7236 if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM && (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) curDOM = parent; 7237 else { 7238 parent = document.createElement(deco.nodeName); 7239 parent.pmIsDeco = true; 7240 parent.appendChild(curDOM); 7241 prev = noDeco[0]; 7242 curDOM = parent; 7243 } 7244 } 7245 patchAttributes(curDOM, prev || noDeco[0], deco); 7246 } 7247 return curDOM; 7248} 7249function patchAttributes(dom, prev, cur) { 7250 for (let name in prev) if (name != "class" && name != "style" && name != "nodeName" && !(name in cur)) dom.removeAttribute(name); 7251 for (let name in cur) if (name != "class" && name != "style" && name != "nodeName" && cur[name] != prev[name]) dom.setAttribute(name, cur[name]); 7252 if (prev.class != cur.class) { 7253 let prevList = prev.class ? prev.class.split(" ").filter(Boolean) : []; 7254 let curList = cur.class ? cur.class.split(" ").filter(Boolean) : []; 7255 for (let i$1 = 0; i$1 < prevList.length; i$1++) if (curList.indexOf(prevList[i$1]) == -1) dom.classList.remove(prevList[i$1]); 7256 for (let i$1 = 0; i$1 < curList.length; i$1++) if (prevList.indexOf(curList[i$1]) == -1) dom.classList.add(curList[i$1]); 7257 if (dom.classList.length == 0) dom.removeAttribute("class"); 7258 } 7259 if (prev.style != cur.style) { 7260 if (prev.style) { 7261 let prop = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, m; 7262 while (m = prop.exec(prev.style)) dom.style.removeProperty(m[1]); 7263 } 7264 if (cur.style) dom.style.cssText += cur.style; 7265 } 7266} 7267function applyOuterDeco(dom, deco, node) { 7268 return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1)); 7269} 7270function sameOuterDeco(a, b) { 7271 if (a.length != b.length) return false; 7272 for (let i$1 = 0; i$1 < a.length; i$1++) if (!a[i$1].type.eq(b[i$1].type)) return false; 7273 return true; 7274} 7275function rm(dom) { 7276 let next = dom.nextSibling; 7277 dom.parentNode.removeChild(dom); 7278 return next; 7279} 7280var ViewTreeUpdater = class { 7281 constructor(top, lock, view) { 7282 this.lock = lock; 7283 this.view = view; 7284 this.index = 0; 7285 this.stack = []; 7286 this.changed = false; 7287 this.top = top; 7288 this.preMatch = preMatch(top.node.content, top); 7289 } 7290 destroyBetween(start, end) { 7291 if (start == end) return; 7292 for (let i$1 = start; i$1 < end; i$1++) this.top.children[i$1].destroy(); 7293 this.top.children.splice(start, end - start); 7294 this.changed = true; 7295 } 7296 destroyRest() { 7297 this.destroyBetween(this.index, this.top.children.length); 7298 } 7299 syncToMarks(marks, inline, view, parentIndex) { 7300 let keep = 0, depth = this.stack.length >> 1; 7301 let maxKeep = Math.min(depth, marks.length); 7302 while (keep < maxKeep && (keep == depth - 1 ? this.top : this.stack[keep + 1 << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false) keep++; 7303 while (keep < depth) { 7304 this.destroyRest(); 7305 this.top.dirty = NOT_DIRTY; 7306 this.index = this.stack.pop(); 7307 this.top = this.stack.pop(); 7308 depth--; 7309 } 7310 while (depth < marks.length) { 7311 this.stack.push(this.top, this.index + 1); 7312 let found$1 = -1, scanTo = this.top.children.length; 7313 if (parentIndex < this.preMatch.index) scanTo = Math.min(this.index + 3, scanTo); 7314 for (let i$1 = this.index; i$1 < scanTo; i$1++) { 7315 let next = this.top.children[i$1]; 7316 if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) { 7317 found$1 = i$1; 7318 break; 7319 } 7320 } 7321 if (found$1 < 0 && this.index < this.top.children.length) { 7322 let cur = this.top.children[this.index]; 7323 if (cur instanceof MarkViewDesc && cur.dirty != NODE_DIRTY && cur.mark.type == marks[depth].type && cur.spec.update && !this.isLocked(cur.dom) && cur.spec.update(marks[depth])) { 7324 cur.mark = marks[depth]; 7325 found$1 = this.index; 7326 this.changed = true; 7327 } 7328 } 7329 if (found$1 > -1) { 7330 if (found$1 > this.index) { 7331 this.changed = true; 7332 this.destroyBetween(this.index, found$1); 7333 } 7334 this.top = this.top.children[this.index]; 7335 } else { 7336 let markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view); 7337 this.top.children.splice(this.index, 0, markDesc); 7338 this.top = markDesc; 7339 this.changed = true; 7340 } 7341 this.index = 0; 7342 depth++; 7343 } 7344 } 7345 findNodeMatch(node, outerDeco, innerDeco, index) { 7346 let found$1 = -1, targetDesc; 7347 if (index >= this.preMatch.index && (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top && targetDesc.matchesNode(node, outerDeco, innerDeco)) found$1 = this.top.children.indexOf(targetDesc, this.index); 7348 else for (let i$1 = this.index, e = Math.min(this.top.children.length, i$1 + 5); i$1 < e; i$1++) { 7349 let child = this.top.children[i$1]; 7350 if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) { 7351 found$1 = i$1; 7352 break; 7353 } 7354 } 7355 if (found$1 < 0) return false; 7356 this.destroyBetween(this.index, found$1); 7357 this.index++; 7358 return true; 7359 } 7360 updateNodeAt(node, outerDeco, innerDeco, index, view) { 7361 let child = this.top.children[index]; 7362 if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM) child.dirty = CONTENT_DIRTY; 7363 if (!child.update(node, outerDeco, innerDeco, view)) return false; 7364 this.destroyBetween(this.index, index); 7365 this.index++; 7366 return true; 7367 } 7368 findIndexWithChild(domNode) { 7369 for (;;) { 7370 let parent = domNode.parentNode; 7371 if (!parent) return -1; 7372 if (parent == this.top.contentDOM) { 7373 let desc = domNode.pmViewDesc; 7374 if (desc) { 7375 for (let i$1 = this.index; i$1 < this.top.children.length; i$1++) if (this.top.children[i$1] == desc) return i$1; 7376 } 7377 return -1; 7378 } 7379 domNode = parent; 7380 } 7381 } 7382 updateNextNode(node, outerDeco, innerDeco, view, index, pos) { 7383 for (let i$1 = this.index; i$1 < this.top.children.length; i$1++) { 7384 let next = this.top.children[i$1]; 7385 if (next instanceof NodeViewDesc) { 7386 let preMatch$1 = this.preMatch.matched.get(next); 7387 if (preMatch$1 != null && preMatch$1 != index) return false;
vendor: 7,177 bytes, lines 7388-7577
7388 let nextDOM = next.dom, updated; 7389 let locked = this.isLocked(nextDOM) && !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text && next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco)); 7390 if (!locked && next.update(node, outerDeco, innerDeco, view)) { 7391 this.destroyBetween(this.index, i$1); 7392 if (next.dom != nextDOM) this.changed = true; 7393 this.index++; 7394 return true; 7395 } else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) { 7396 this.destroyBetween(this.index, i$1); 7397 this.top.children[this.index] = updated; 7398 if (updated.contentDOM) { 7399 updated.dirty = CONTENT_DIRTY; 7400 updated.updateChildren(view, pos + 1); 7401 updated.dirty = NOT_DIRTY; 7402 } 7403 this.changed = true; 7404 this.index++; 7405 return true; 7406 } 7407 break; 7408 } 7409 } 7410 return false; 7411 } 7412 recreateWrapper(next, node, outerDeco, innerDeco, view, pos) { 7413 if (next.dirty || node.isAtom || !next.children.length || !next.node.content.eq(node.content) || !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco)) return null; 7414 let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos); 7415 if (wrapper.contentDOM) { 7416 wrapper.children = next.children; 7417 next.children = []; 7418 for (let ch of wrapper.children) ch.parent = wrapper; 7419 } 7420 next.destroy(); 7421 return wrapper; 7422 } 7423 addNode(node, outerDeco, innerDeco, view, pos) { 7424 let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos); 7425 if (desc.contentDOM) desc.updateChildren(view, pos + 1); 7426 this.top.children.splice(this.index++, 0, desc); 7427 this.changed = true; 7428 } 7429 placeWidget(widget, view, pos) { 7430 let next = this.index < this.top.children.length ? this.top.children[this.index] : null; 7431 if (next && next.matchesWidget(widget) && (widget == next.widget || !next.widget.type.toDOM.parentNode)) this.index++; 7432 else { 7433 let desc = new WidgetViewDesc(this.top, widget, view, pos); 7434 this.top.children.splice(this.index++, 0, desc); 7435 this.changed = true; 7436 } 7437 } 7438 addTextblockHacks() { 7439 let lastChild = this.top.children[this.index - 1], parent = this.top; 7440 while (lastChild instanceof MarkViewDesc) { 7441 parent = lastChild; 7442 lastChild = parent.children[parent.children.length - 1]; 7443 } 7444 if (!lastChild || !(lastChild instanceof TextViewDesc) || /\n$/.test(lastChild.node.text) || this.view.requiresGeckoHackNode && /\s$/.test(lastChild.node.text)) { 7445 if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == "false") this.addHackNode("IMG", parent); 7446 this.addHackNode("BR", this.top); 7447 } 7448 } 7449 addHackNode(nodeName, parent) { 7450 if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) this.index++; 7451 else { 7452 let dom = document.createElement(nodeName); 7453 if (nodeName == "IMG") { 7454 dom.className = "ProseMirror-separator"; 7455 dom.alt = ""; 7456 } 7457 if (nodeName == "BR") dom.className = "ProseMirror-trailingBreak"; 7458 let hack = new TrailingHackViewDesc(this.top, [], dom, null); 7459 if (parent != this.top) parent.children.push(hack); 7460 else parent.children.splice(this.index++, 0, hack); 7461 this.changed = true; 7462 } 7463 } 7464 isLocked(node) { 7465 return this.lock && (node == this.lock || node.nodeType == 1 && node.contains(this.lock.parentNode)); 7466 } 7467}; 7468function preMatch(frag, parentDesc) { 7469 let curDesc = parentDesc, descI = curDesc.children.length; 7470 let fI = frag.childCount, matched = /* @__PURE__ */ new Map(), matches$1 = []; 7471 outer: while (fI > 0) { 7472 let desc; 7473 for (;;) if (descI) { 7474 let next = curDesc.children[descI - 1]; 7475 if (next instanceof MarkViewDesc) { 7476 curDesc = next; 7477 descI = next.children.length; 7478 } else { 7479 desc = next; 7480 descI--; 7481 break; 7482 } 7483 } else if (curDesc == parentDesc) break outer; 7484 else { 7485 descI = curDesc.parent.children.indexOf(curDesc); 7486 curDesc = curDesc.parent; 7487 } 7488 let node = desc.node; 7489 if (!node) continue; 7490 if (node != frag.child(fI - 1)) break; 7491 --fI; 7492 matched.set(desc, fI); 7493 matches$1.push(desc); 7494 } 7495 return { 7496 index: fI, 7497 matched, 7498 matches: matches$1.reverse() 7499 }; 7500} 7501function compareSide(a, b) { 7502 return a.type.side - b.type.side; 7503} 7504function iterDeco(parent, deco, onWidget, onNode) { 7505 let locals = deco.locals(parent), offset = 0; 7506 if (locals.length == 0) { 7507 for (let i$1 = 0; i$1 < parent.childCount; i$1++) { 7508 let child = parent.child(i$1); 7509 onNode(child, locals, deco.forChild(offset, child), i$1); 7510 offset += child.nodeSize; 7511 } 7512 return; 7513 } 7514 let decoIndex = 0, active = [], restNode = null; 7515 for (let parentIndex = 0;;) { 7516 let widget, widgets; 7517 while (decoIndex < locals.length && locals[decoIndex].to == offset) { 7518 let next = locals[decoIndex++]; 7519 if (next.widget) if (!widget) widget = next; 7520 else (widgets || (widgets = [widget])).push(next); 7521 } 7522 if (widget) if (widgets) { 7523 widgets.sort(compareSide); 7524 for (let i$1 = 0; i$1 < widgets.length; i$1++) onWidget(widgets[i$1], parentIndex, !!restNode); 7525 } else onWidget(widget, parentIndex, !!restNode); 7526 let child, index; 7527 if (restNode) { 7528 index = -1; 7529 child = restNode; 7530 restNode = null; 7531 } else if (parentIndex < parent.childCount) { 7532 index = parentIndex; 7533 child = parent.child(parentIndex++); 7534 } else break; 7535 for (let i$1 = 0; i$1 < active.length; i$1++) if (active[i$1].to <= offset) active.splice(i$1--, 1); 7536 while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset) active.push(locals[decoIndex++]); 7537 let end = offset + child.nodeSize; 7538 if (child.isText) { 7539 let cutAt = end; 7540 if (decoIndex < locals.length && locals[decoIndex].from < cutAt) cutAt = locals[decoIndex].from; 7541 for (let i$1 = 0; i$1 < active.length; i$1++) if (active[i$1].to < cutAt) cutAt = active[i$1].to; 7542 if (cutAt < end) { 7543 restNode = child.cut(cutAt - offset); 7544 child = child.cut(0, cutAt - offset); 7545 end = cutAt; 7546 index = -1; 7547 } 7548 } else while (decoIndex < locals.length && locals[decoIndex].to < end) decoIndex++; 7549 let outerDeco = child.isInline && !child.isLeaf ? active.filter((d) => !d.inline) : active.slice(); 7550 onNode(child, outerDeco, deco.forChild(offset, child), index); 7551 offset = end; 7552 } 7553} 7554function iosHacks(dom) { 7555 if (dom.nodeName == "UL" || dom.nodeName == "OL") { 7556 let oldCSS = dom.style.cssText; 7557 dom.style.cssText = oldCSS + "; list-style: square !important"; 7558 window.getComputedStyle(dom).listStyle; 7559 dom.style.cssText = oldCSS; 7560 } 7561} 7562function findTextInFragment(frag, text$1, from, to) { 7563 for (let i$1 = 0, pos = 0; i$1 < frag.childCount && pos <= to;) { 7564 let child = frag.child(i$1++), childStart = pos; 7565 pos += child.nodeSize; 7566 if (!child.isText) continue; 7567 let str = child.text; 7568 while (i$1 < frag.childCount) { 7569 let next = frag.child(i$1++); 7570 pos += next.nodeSize; 7571 if (!next.isText) break; 7572 str += next.text; 7573 } 7574 if (pos >= from) { 7575 if (pos >= to && str.slice(to - text$1.length - childStart, to - childStart) == text$1) return to - text$1.length; 7576 let found$1 = childStart < to ? str.lastIndexOf(text$1, to - childStart - 1) : -1; 7577 if (found$1 >= 0 && found$1 + text$1.length + childStart >
vendor: 9,215 bytes, lines 7577-7787
7577= from) return childStart + found$1; 7578 if (from == to && str.length >= to + text$1.length - childStart && str.slice(to - childStart, to - childStart + text$1.length) == text$1) return to; 7579 } 7580 } 7581 return -1; 7582} 7583function replaceNodes(nodes, from, to, view, replacement) { 7584 let result = []; 7585 for (let i$1 = 0, off = 0; i$1 < nodes.length; i$1++) { 7586 let child = nodes[i$1], start = off, end = off += child.size; 7587 if (start >= to || end <= from) result.push(child); 7588 else { 7589 if (start < from) result.push(child.slice(0, from - start, view)); 7590 if (replacement) { 7591 result.push(replacement); 7592 replacement = void 0; 7593 } 7594 if (end > to) result.push(child.slice(to - start, child.size, view)); 7595 } 7596 } 7597 return result; 7598} 7599function selectionFromDOM(view, origin = null) { 7600 let domSel = view.domSelectionRange(), doc$2 = view.state.doc; 7601 if (!domSel.focusNode) return null; 7602 let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0; 7603 let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1); 7604 if (head < 0) return null; 7605 let $head = doc$2.resolve(head), anchor, selection; 7606 if (selectionCollapsed(domSel)) { 7607 anchor = head; 7608 while (nearestDesc && !nearestDesc.node) nearestDesc = nearestDesc.parent; 7609 let nearestDescNode = nearestDesc.node; 7610 if (nearestDesc && nearestDescNode.isAtom && NodeSelection.isSelectable(nearestDescNode) && nearestDesc.parent && !(nearestDescNode.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) { 7611 let pos = nearestDesc.posBefore; 7612 selection = new NodeSelection(head == pos ? $head : doc$2.resolve(pos)); 7613 } 7614 } else { 7615 if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) { 7616 let min = head, max = head; 7617 for (let i$1 = 0; i$1 < domSel.rangeCount; i$1++) { 7618 let range = domSel.getRangeAt(i$1); 7619 min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1)); 7620 max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1)); 7621 } 7622 if (min < 0) return null; 7623 [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max]; 7624 $head = doc$2.resolve(head); 7625 } else anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1); 7626 if (anchor < 0) return null; 7627 } 7628 let $anchor = doc$2.resolve(anchor); 7629 if (!selection) { 7630 let bias = origin == "pointer" || view.state.selection.head < $head.pos && !inWidget ? 1 : -1; 7631 selection = selectionBetween(view, $anchor, $head, bias); 7632 } 7633 return selection; 7634} 7635function editorOwnsSelection(view) { 7636 return view.editable ? view.hasFocus() : hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom); 7637} 7638function selectionToDOM(view, force = false) { 7639 let sel = view.state.selection; 7640 syncNodeSelection(view, sel); 7641 if (!editorOwnsSelection(view)) return; 7642 let mouseDown = view.input.mouseDown; 7643 if (!force && chrome && mouseDown) { 7644 let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection; 7645 if (domSel.anchorNode && curSel.anchorNode && isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset) && mouseDown.delaySelUpdate()) { 7646 view.domObserver.setCurSelection(); 7647 return; 7648 } 7649 } 7650 view.domObserver.disconnectSelection(); 7651 if (view.cursorWrapper) selectCursorWrapper(view); 7652 else { 7653 let { anchor, head } = sel, resetEditableFrom, resetEditableTo; 7654 if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) { 7655 if (!sel.$from.parent.inlineContent) resetEditableFrom = temporarilyEditableNear(view, sel.from); 7656 if (!sel.empty && !sel.$from.parent.inlineContent) resetEditableTo = temporarilyEditableNear(view, sel.to); 7657 } 7658 view.docView.setSelection(anchor, head, view, force); 7659 if (brokenSelectBetweenUneditable) { 7660 if (resetEditableFrom) resetEditable(resetEditableFrom); 7661 if (resetEditableTo) resetEditable(resetEditableTo); 7662 } 7663 if (sel.visible) view.dom.classList.remove("ProseMirror-hideselection"); 7664 else { 7665 view.dom.classList.add("ProseMirror-hideselection"); 7666 if ("onselectionchange" in document) removeClassOnSelectionChange(view); 7667 } 7668 } 7669 view.domObserver.setCurSelection(); 7670 view.domObserver.connectSelection(); 7671} 7672var brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63; 7673function temporarilyEditableNear(view, pos) { 7674 let { node, offset } = view.docView.domFromPos(pos, 0); 7675 let after = offset < node.childNodes.length ? node.childNodes[offset] : null; 7676 let before = offset ? node.childNodes[offset - 1] : null; 7677 if (safari && after && after.contentEditable == "false") return setEditable(after); 7678 if ((!after || after.contentEditable == "false") && (!before || before.contentEditable == "false")) { 7679 if (after) return setEditable(after); 7680 else if (before) return setEditable(before); 7681 } 7682} 7683function setEditable(element) { 7684 element.contentEditable = "true"; 7685 if (safari && element.draggable) { 7686 element.draggable = false; 7687 element.wasDraggable = true; 7688 } 7689 return element; 7690} 7691function resetEditable(element) { 7692 element.contentEditable = "false"; 7693 if (element.wasDraggable) { 7694 element.draggable = true; 7695 element.wasDraggable = null; 7696 } 7697} 7698function removeClassOnSelectionChange(view) { 7699 let doc$2 = view.dom.ownerDocument; 7700 doc$2.removeEventListener("selectionchange", view.input.hideSelectionGuard); 7701 let domSel = view.domSelectionRange(); 7702 let node = domSel.anchorNode, offset = domSel.anchorOffset; 7703 doc$2.addEventListener("selectionchange", view.input.hideSelectionGuard = () => { 7704 if (domSel.anchorNode != node || domSel.anchorOffset != offset) { 7705 doc$2.removeEventListener("selectionchange", view.input.hideSelectionGuard); 7706 setTimeout(() => { 7707 if (!editorOwnsSelection(view) || view.state.selection.visible) view.dom.classList.remove("ProseMirror-hideselection"); 7708 }, 20); 7709 } 7710 }); 7711} 7712function selectCursorWrapper(view) { 7713 let domSel = view.domSelection(); 7714 if (!domSel) return; 7715 let node = view.cursorWrapper.dom, img = node.nodeName == "IMG"; 7716 if (img) domSel.collapse(node.parentNode, domIndex(node) + 1); 7717 else domSel.collapse(node, 0); 7718 if (!img && !view.state.selection.visible && ie$2 && ie_version <= 11) { 7719 node.disabled = true; 7720 node.disabled = false; 7721 } 7722} 7723function syncNodeSelection(view, sel) { 7724 if (sel instanceof NodeSelection) { 7725 let desc = view.docView.descAt(sel.from); 7726 if (desc != view.lastSelectedViewDesc) { 7727 clearNodeSelection(view); 7728 if (desc) desc.selectNode(); 7729 view.lastSelectedViewDesc = desc; 7730 } 7731 } else clearNodeSelection(view); 7732} 7733function clearNodeSelection(view) { 7734 if (view.lastSelectedViewDesc) { 7735 if (view.lastSelectedViewDesc.parent) view.lastSelectedViewDesc.deselectNode(); 7736 view.lastSelectedViewDesc = void 0; 7737 } 7738} 7739function selectionBetween(view, $anchor, $head, bias) { 7740 return view.someProp("createSelectionBetween", (f) => f(view, $anchor, $head)) || TextSelection.between($anchor, $head, bias); 7741} 7742function hasFocusAndSelection(view) { 7743 if (view.editable && !view.hasFocus()) return false; 7744 return hasSelection(view); 7745} 7746function hasSelection(view) { 7747 let sel = view.domSelectionRange(); 7748 if (!sel.anchorNode) return false; 7749 try { 7750 return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) && (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode)); 7751 } catch (_) { 7752 return false; 7753 } 7754} 7755function anchorInRightPlace(view) { 7756 let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0); 7757 let domSel = view.domSelectionRange(); 7758 return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset); 7759} 7760function moveSelectionBlock(state, dir) { 7761 let { $anchor, $head } = state.selection; 7762 let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head); 7763 let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null; 7764 return $start && Selection$1.findFrom($start, dir); 7765} 7766function apply$1(view, sel) { 7767 view.dispatch(view.state.tr.setSelection(sel).scrollIntoView()); 7768 return true; 7769} 7770function selectHorizontally(view, dir, mods) { 7771 let sel = view.state.selection; 7772 if (sel instanceof TextSelection) { 7773 if (mods.indexOf("s") > -1) { 7774 let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter; 7775 if (!node || node.isText || !node.isLeaf) return false; 7776 let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1)); 7777 return apply$1(view, new TextSelection(sel.$anchor, $newHead)); 7778 } else if (!sel.empty) return false; 7779 else if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) { 7780 let next = moveSelectionBlock(view.state, dir); 7781 if (next && next instanceof NodeSelection) return apply$1(view, next); 7782 return false; 7783 } else if (!(mac$2 && mods.indexOf("m") > -1)) { 7784 let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc; 7785 if (!node || node.isText) return false; 7786 let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos; 7787 if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM)) return false;
vendor: 4,885 bytes, lines 7788-7942
7788 if (NodeSelection.isSelectable(node)) return apply$1(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head)); 7789 else if (webkit) return apply$1(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize))); 7790 else return false; 7791 } 7792 } else if (sel instanceof NodeSelection && sel.node.isInline) return apply$1(view, new TextSelection(dir > 0 ? sel.$to : sel.$from)); 7793 else { 7794 let next = moveSelectionBlock(view.state, dir); 7795 if (next) return apply$1(view, next); 7796 return false; 7797 } 7798} 7799function nodeLen(node) { 7800 return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; 7801} 7802function isIgnorable(dom, dir) { 7803 let desc = dom.pmViewDesc; 7804 return desc && desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != "BR"); 7805} 7806function skipIgnoredNodes(view, dir) { 7807 return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view); 7808} 7809function skipIgnoredNodesBefore(view) { 7810 let sel = view.domSelectionRange(); 7811 let node = sel.focusNode, offset = sel.focusOffset; 7812 if (!node) return; 7813 let moveNode, moveOffset, force = false; 7814 if (gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset], -1)) force = true; 7815 for (;;) if (offset > 0) if (node.nodeType != 1) break; 7816 else { 7817 let before = node.childNodes[offset - 1]; 7818 if (isIgnorable(before, -1)) { 7819 moveNode = node; 7820 moveOffset = --offset; 7821 } else if (before.nodeType == 3) { 7822 node = before; 7823 offset = node.nodeValue.length; 7824 } else break; 7825 } 7826 else if (isBlockNode(node)) break; 7827 else { 7828 let prev = node.previousSibling; 7829 while (prev && isIgnorable(prev, -1)) { 7830 moveNode = node.parentNode; 7831 moveOffset = domIndex(prev); 7832 prev = prev.previousSibling; 7833 } 7834 if (!prev) { 7835 node = node.parentNode; 7836 if (node == view.dom) break; 7837 offset = 0; 7838 } else { 7839 node = prev; 7840 offset = nodeLen(node); 7841 } 7842 } 7843 if (force) setSelFocus(view, node, offset); 7844 else if (moveNode) setSelFocus(view, moveNode, moveOffset); 7845} 7846function skipIgnoredNodesAfter(view) { 7847 let sel = view.domSelectionRange(); 7848 let node = sel.focusNode, offset = sel.focusOffset; 7849 if (!node) return; 7850 let len = nodeLen(node); 7851 let moveNode, moveOffset; 7852 for (;;) if (offset < len) { 7853 if (node.nodeType != 1) break; 7854 let after = node.childNodes[offset]; 7855 if (isIgnorable(after, 1)) { 7856 moveNode = node; 7857 moveOffset = ++offset; 7858 } else break; 7859 } else if (isBlockNode(node)) break; 7860 else { 7861 let next = node.nextSibling; 7862 while (next && isIgnorable(next, 1)) { 7863 moveNode = next.parentNode; 7864 moveOffset = domIndex(next) + 1; 7865 next = next.nextSibling; 7866 } 7867 if (!next) { 7868 node = node.parentNode; 7869 if (node == view.dom) break; 7870 offset = len = 0; 7871 } else { 7872 node = next; 7873 offset = 0; 7874 len = nodeLen(node); 7875 } 7876 } 7877 if (moveNode) setSelFocus(view, moveNode, moveOffset); 7878} 7879function isBlockNode(dom) { 7880 let desc = dom.pmViewDesc; 7881 return desc && desc.node && desc.node.isBlock; 7882} 7883function textNodeAfter(node, offset) { 7884 while (node && offset == node.childNodes.length && !hasBlockDesc(node)) { 7885 offset = domIndex(node) + 1; 7886 node = node.parentNode; 7887 } 7888 while (node && offset < node.childNodes.length) { 7889 let next = node.childNodes[offset]; 7890 if (next.nodeType == 3) return next; 7891 if (next.nodeType == 1 && next.contentEditable == "false") break; 7892 node = next; 7893 offset = 0; 7894 } 7895} 7896function textNodeBefore(node, offset) { 7897 while (node && !offset && !hasBlockDesc(node)) { 7898 offset = domIndex(node); 7899 node = node.parentNode; 7900 } 7901 while (node && offset) { 7902 let next = node.childNodes[offset - 1]; 7903 if (next.nodeType == 3) return next; 7904 if (next.nodeType == 1 && next.contentEditable == "false") break; 7905 node = next; 7906 offset = node.childNodes.length; 7907 } 7908} 7909function setSelFocus(view, node, offset) { 7910 if (node.nodeType != 3) { 7911 let before, after; 7912 if (after = textNodeAfter(node, offset)) { 7913 node = after; 7914 offset = 0; 7915 } else if (before = textNodeBefore(node, offset)) { 7916 node = before; 7917 offset = before.nodeValue.length; 7918 } 7919 } 7920 let sel = view.domSelection(); 7921 if (!sel) return; 7922 if (selectionCollapsed(sel)) { 7923 let range = document.createRange(); 7924 range.setEnd(node, offset); 7925 range.setStart(node, offset); 7926 sel.removeAllRanges(); 7927 sel.addRange(range); 7928 } else if (sel.extend) sel.extend(node, offset); 7929 view.domObserver.setCurSelection(); 7930 let { state } = view; 7931 setTimeout(() => { 7932 if (view.state == state) selectionToDOM(view); 7933 }, 50); 7934} 7935function findDirection(view, pos) { 7936 let $pos = view.state.doc.resolve(pos); 7937 if (!(chrome || windows$1) && $pos.parent.inlineContent) { 7938 let coords = view.coordsAtPos(pos); 7939 if (pos > $pos.start()) { 7940 let before = view.coordsAtPos(pos - 1); 7941 let mid = (before.top + before.bottom) / 2; 7942 if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1) return before.left < coords.left ? "ltr" : "rtl";
7943 } 7944 if (pos < $pos.end()) { 7945 let after = view.coordsAtPos(pos + 1); 7946 let mid = (after.top + after.bottom) / 2; 7947 if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1) return after.left > coords.left ? "ltr" : "rtl"; 7948 } 7949 } 7950 return getComputedStyle(view.dom).direction == "rtl" ? "rtl" : "ltr"; 7951} 7952function selectVertically(view, dir, mods) { 7953 let sel = view.state.selection; 7954 if (sel instanceof TextSelection && !sel.empty || mods.indexOf("s") > -1) return false; 7955 if (mac$2 && mods.indexOf("m") > -1) return false; 7956 let { $from, $to } = sel; 7957 if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) { 7958 let next = moveSelectionBlock(view.state, dir); 7959 if (next && next instanceof NodeSelection) return apply$1(view, next); 7960 } 7961 if (!$from.parent.inlineContent) { 7962 let side = dir < 0 ? $from : $to; 7963 let beyond = sel instanceof AllSelection ? Selection$1.near(side, dir) : Selection$1.findFrom(side, dir); 7964 return beyond ? apply$1(view, beyond) : false; 7965 } 7966 return false; 7967} 7968function stopNativeHorizontalDelete(view, dir) { 7969 if (!(view.state.selection instanceof TextSelection)) return true; 7970 let { $head, $anchor, empty: empty$1 } = view.state.selection; 7971 if (!$head.sameParent($anchor)) return true; 7972 if (!empty$1) return false; 7973 if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) return true; 7974 let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter); 7975 if (nextNode && !nextNode.isText) { 7976 let tr$1 = view.state.tr; 7977 if (dir < 0) tr$1.delete($head.pos - nextNode.nodeSize, $head.pos); 7978 else tr$1.delete($head.pos, $head.pos + nextNode.nodeSize); 7979 view.dispatch(tr$1); 7980 return true; 7981 } 7982 return false; 7983} 7984function switchEditable(view, node, state) { 7985 view.domObserver.stop(); 7986 node.contentEditable = state; 7987 view.domObserver.start(); 7988} 7989function safariDownArrowBug(view) { 7990 if (!safari || view.state.selection.$head.parentOffset > 0) return false; 7991 let { focusNode, focusOffset } = view.domSelectionRange(); 7992 if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 && focusNode.firstChild && focusNode.firstChild.contentEditable == "false") { 7993 let child = focusNode.firstChild; 7994 switchEditable(view, child, "true"); 7995 setTimeout(() => switchEditable(view, child, "false"), 20); 7996 } 7997 return false; 7998} 7999function getMods(event) { 8000 let result = ""; 8001 if (event.ctrlKey) result += "c"; 8002 if (event.metaKey) result += "m"; 8003 if (event.altKey) result += "a"; 8004 if (event.shiftKey) result += "s"; 8005 return result; 8006} 8007function captureKeyDown(view, event) { 8008 let code$1 = event.keyCode, mods = getMods(event); 8009 if (code$1 == 8 || mac$2 && code$1 == 72 && mods == "c") return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1); 8010 else if (code$1 == 46 && !event.shiftKey || mac$2 && code$1 == 68 && mods == "c") return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1); 8011 else if (code$1 == 13 || code$1 == 27) return true; 8012 else if (code$1 == 37 || mac$2 && code$1 == 66 && mods == "c") { 8013 let dir = code$1 == 37 ? findDirection(view, view.state.selection.from) == "ltr" ? -1 : 1 : -1; 8014 return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir); 8015 } else if (code$1 == 39 || mac$2 && code$1 == 70 && mods == "c") { 8016 let dir = code$1 == 39 ? findDirection(view, view.state.selection.from) == "ltr" ? 1 : -1 : 1; 8017 return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir); 8018 } else if (code$1 == 38 || mac$2 && code$1 == 80 && mods == "c") return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1); 8019 else if (code$1 == 40 || mac$2 && code$1 == 78 && mods == "c") return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1); 8020 else if (mods == (mac$2 ? "m" : "c") && (code$1 == 66 || code$1 == 73 || code$1 == 89 || code$1 == 90)) return true; 8021 return false; 8022} 8023function serializeForClipboard(view, slice) { 8024 view.someProp("transformCopied", (f) => { 8025 slice = f(slice, view); 8026 }); 8027 let context = [], { content, openStart, openEnd } = slice; 8028 while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) { 8029 openStart--; 8030 openEnd--; 8031 let node = content.firstChild;
8032 context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null); 8033 content = node.content; 8034 } 8035 let serializer = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema); 8036 let doc$2 = detachedDoc(), wrap$1 = doc$2.createElement("div"); 8037 wrap$1.appendChild(serializer.serializeFragment(content, { document: doc$2 })); 8038 let firstChild = wrap$1.firstChild, needsWrap, wrappers = 0; 8039 while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) { 8040 for (let i$1 = needsWrap.length - 1; i$1 >= 0; i$1--) { 8041 let wrapper = doc$2.createElement(needsWrap[i$1]); 8042 while (wrap$1.firstChild) wrapper.appendChild(wrap$1.firstChild); 8043 wrap$1.appendChild(wrapper); 8044 wrappers++; 8045 } 8046 firstChild = wrap$1.firstChild; 8047 } 8048 if (firstChild && firstChild.nodeType == 1) firstChild.setAttribute("data-pm-slice", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : ""} ${JSON.stringify(context)}`); 8049 return { 8050 dom: wrap$1, 8051 text: view.someProp("clipboardTextSerializer", (f) => f(slice, view)) || slice.content.textBetween(0, slice.content.size, "\n\n"), 8052 slice 8053 }; 8054} 8055function parseFromClipboard(view, text$1, html$2, plainText, $context) { 8056 let inCode = $context.parent.type.spec.code; 8057 let dom, slice; 8058 if (!html$2 && !text$1) return null; 8059 let asText = !!text$1 && (plainText || inCode || !html$2); 8060 if (asText) { 8061 view.someProp("transformPastedText", (f) => { 8062 text$1 = f(text$1, inCode || plainText, view); 8063 }); 8064 if (inCode) { 8065 slice = new Slice(Fragment.from(view.state.schema.text(text$1.replace(/\r\n?/g, "\n"))), 0, 0); 8066 view.someProp("transformPasted", (f) => { 8067 slice = f(slice, view, true); 8068 }); 8069 return slice; 8070 } 8071 let parsed = view.someProp("clipboardTextParser", (f) => f(text$1, $context, plainText, view)); 8072 if (parsed) slice = parsed; 8073 else { 8074 let marks = $context.marks(); 8075 let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema); 8076 dom = document.createElement("div"); 8077 text$1.split(/(?:\r\n?|\n)+/).forEach((block) => { 8078 let p = dom.appendChild(document.createElement("p")); 8079 if (block) p.appendChild(serializer.serializeNode(schema.text(block, marks))); 8080 }); 8081 } 8082 } else { 8083 view.someProp("transformPastedHTML", (f) => { 8084 html$2 = f(html$2, view); 8085 }); 8086 dom = readHTML(html$2); 8087 if (webkit) restoreReplacedSpaces(dom); 8088 } 8089 let contextNode = dom && dom.querySelector("[data-pm-slice]"); 8090 let sliceData = contextNode && /^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(contextNode.getAttribute("data-pm-slice") || ""); 8091 if (sliceData && sliceData[3]) for (let i$1 = +sliceData[3]; i$1 > 0; i$1--) { 8092 let child = dom.firstChild; 8093 while (child && child.nodeType != 1) child = child.nextSibling; 8094 if (!child) break; 8095 dom = child; 8096 } 8097 if (!slice) slice = (view.someProp("clipboardParser") || view.someProp("domParser") || DOMParser.fromSchema(view.state.schema)).parseSlice(dom, { 8098 preserveWhitespace: !!(asText || sliceData), 8099 context: $context, 8100 ruleFromNode(dom$1) { 8101 if (dom$1.nodeName == "BR" && !dom$1.nextSibling && dom$1.parentNode && !inlineParents.test(dom$1.parentNode.nodeName)) return { ignore: true }; 8102 return null; 8103 } 8104 }); 8105 if (sliceData) slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[4]); 8106 else { 8107 slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), true); 8108 if (slice.openStart || slice.openEnd) { 8109 let openStart = 0, openEnd = 0; 8110 for (let node = slice.content.firstChild; openStart < slice.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild); 8111 for (let node = slice.content.lastChild; openEnd < slice.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild); 8112 slice = closeSlice(slice, openStart, openEnd); 8113 } 8114 } 8115 view.someProp("transformPasted", (f) => { 8116 slice = f(slice, view, asText); 8117 }); 8118 return slice; 8119} 8120var inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i; 8121function normalizeSiblings(fragment, $context) { 8122 if (fragment.childCount < 2) return fragment; 8123 for (let d = $context.depth; d >= 0; d--) {
vendor: 4,475 bytes, lines 8124-8227
8124 let match = $context.node(d).contentMatchAt($context.index(d)); 8125 let lastWrap, result = []; 8126 fragment.forEach((node) => { 8127 if (!result) return; 8128 let wrap$1 = match.findWrapping(node.type), inLast; 8129 if (!wrap$1) return result = null; 8130 if (inLast = result.length && lastWrap.length && addToSibling(wrap$1, lastWrap, node, result[result.length - 1], 0)) result[result.length - 1] = inLast; 8131 else { 8132 if (result.length) result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length); 8133 let wrapped = withWrappers(node, wrap$1); 8134 result.push(wrapped); 8135 match = match.matchType(wrapped.type); 8136 lastWrap = wrap$1; 8137 } 8138 }); 8139 if (result) return Fragment.from(result); 8140 } 8141 return fragment; 8142} 8143function withWrappers(node, wrap$1, from = 0) { 8144 for (let i$1 = wrap$1.length - 1; i$1 >= from; i$1--) node = wrap$1[i$1].create(null, Fragment.from(node)); 8145 return node; 8146} 8147function addToSibling(wrap$1, lastWrap, node, sibling, depth) { 8148 if (depth < wrap$1.length && depth < lastWrap.length && wrap$1[depth] == lastWrap[depth]) { 8149 let inner = addToSibling(wrap$1, lastWrap, node, sibling.lastChild, depth + 1); 8150 if (inner) return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner)); 8151 if (sibling.contentMatchAt(sibling.childCount).matchType(depth == wrap$1.length - 1 ? node.type : wrap$1[depth + 1])) return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap$1, depth + 1)))); 8152 } 8153} 8154function closeRight(node, depth) { 8155 if (depth == 0) return node; 8156 let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1)); 8157 let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true); 8158 return node.copy(fragment.append(fill)); 8159} 8160function closeRange(fragment, side, from, to, depth, openEnd) { 8161 let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content; 8162 if (fragment.childCount > 1) openEnd = 0; 8163 if (depth < to - 1) inner = closeRange(inner, side, from, to, depth + 1, openEnd); 8164 if (depth >= from) inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner) : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true)); 8165 return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner)); 8166} 8167function closeSlice(slice, openStart, openEnd) { 8168 if (openStart < slice.openStart) slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd); 8169 if (openEnd < slice.openEnd) slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd); 8170 return slice; 8171} 8172var wrapMap = { 8173 thead: ["table"], 8174 tbody: ["table"], 8175 tfoot: ["table"], 8176 caption: ["table"], 8177 colgroup: ["table"], 8178 col: ["table", "colgroup"], 8179 tr: ["table", "tbody"], 8180 td: [ 8181 "table", 8182 "tbody", 8183 "tr" 8184 ], 8185 th: [ 8186 "table", 8187 "tbody", 8188 "tr" 8189 ] 8190}; 8191function detachedDoc() { 8192 return document.implementation.createHTMLDocument("title"); 8193} 8194var _policy = null; 8195function maybeWrapTrusted(html$2) { 8196 let trustedTypes = window.trustedTypes; 8197 if (!trustedTypes) return html$2; 8198 if (!_policy) { 8199 if (_policy = trustedTypes.defaultPolicy) try { 8200 return _policy.createHTML(html$2); 8201 } catch (_a) {} 8202 _policy = trustedTypes.createPolicy("ProseMirrorClipboard", { createHTML: (s) => s }); 8203 } 8204 return _policy.createHTML(html$2); 8205} 8206function readHTML(html$2) { 8207 let metas = /^(\s*<meta [^>]*>)*/.exec(html$2); 8208 if (metas) html$2 = html$2.slice(metas[0].length); 8209 let doc$2 = detachedDoc(), elt = doc$2.body; 8210 let firstTag = /<([a-z][^>\s]+)/i.exec(html$2), wrap$1; 8211 if (wrap$1 = firstTag && wrapMap[firstTag[1].toLowerCase()]) html$2 = wrap$1.map((n) => "<" + n + ">").join("") + html$2 + wrap$1.map((n) => "</" + n + ">").reverse().join(""); 8212 elt.innerHTML = maybeWrapTrusted(html$2); 8213 if (wrap$1) for (let i$1 = 0; i$1 < wrap$1.length; i$1++) elt = elt.querySelector(wrap$1[i$1]) || elt; 8214 for (let i$1 = 0; i$1 < doc$2.styleSheets.length; i$1++) { 8215 let style$1 = doc$2.styleSheets[i$1]; 8216 for (let j = 0; j < style$1.rules.length; j++) { 8217 let rule = style$1.rules[j]; 8218 if (rule instanceof CSSStyleRule) { 8219 let matches$1 = elt.querySelectorAll(rule.selectorText); 8220 for (let k = 0; k < matches$1.length; k++) matches$1[k].style.cssText += rule.style.cssText; 8221 } 8222 } 8223 } 8224 return elt; 8225} 8226function restoreReplacedSpaces(dom) { 8227 let nodes = dom.querySelectorAll(chrome ? "span:not([class]):not
8227([style])" : "span.Apple-converted-space"); 8228 for (let i$1 = 0; i$1 < nodes.length; i$1++) { 8229 let node = nodes[i$1]; 8230 if (node.childNodes.length == 1 && node.textContent == "\xA0" && node.parentNode) node.parentNode.replaceChild(dom.ownerDocument.createTextNode(" "), node); 8231 } 8232} 8233function addContext(slice, context) { 8234 if (!slice.size) return slice; 8235 let schema = slice.content.firstChild.type.schema, array; 8236 try { 8237 array = JSON.parse(context); 8238 } catch (e) { 8239 return slice; 8240 } 8241 let { content, openStart, openEnd } = slice; 8242 for (let i$1 = array.length - 2; i$1 >= 0; i$1 -= 2) { 8243 let type = schema.nodes[array[i$1]]; 8244 if (!type || type.hasRequiredAttrs()) break; 8245 try { 8246 type.checkAttrs(array[i$1 + 1]); 8247 } catch (e) { 8248 break; 8249 } 8250 content = Fragment.from(type.create(array[i$1 + 1], content)); 8251 openStart++; 8252 openEnd++; 8253 } 8254 return new Slice(content, openStart, openEnd); 8255} 8256var handlers = {}; 8257var editHandlers = {}; 8258var passiveHandlers = { 8259 touchstart: true, 8260 touchmove: true 8261}; 8262var InputState = class { 8263 constructor() { 8264 this.shiftKey = false; 8265 this.mouseDown = null; 8266 this.lastKeyCode = null; 8267 this.lastKeyCodeTime = 0; 8268 this.lastClick = { 8269 time: 0, 8270 x: 0, 8271 y: 0, 8272 type: "", 8273 button: 0 8274 }; 8275 this.lastSelectionOrigin = null; 8276 this.lastSelectionTime = 0; 8277 this.lastIOSEnter = 0; 8278 this.lastIOSEnterFallbackTimeout = -1; 8279 this.lastFocus = 0; 8280 this.lastTouch = 0; 8281 this.lastChromeDelete = 0; 8282 this.composing = false; 8283 this.compositionNode = null; 8284 this.composingTimeout = -1; 8285 this.compositionNodes = []; 8286 this.compositionEndedAt = -2e8; 8287 this.compositionID = 1; 8288 this.badSafariComposition = false; 8289 this.compositionPendingChanges = 0; 8290 this.domChangeCount = 0; 8291 this.eventHandlers = Object.create(null); 8292 this.hideSelectionGuard = null; 8293 } 8294}; 8295function initInput(view) { 8296 for (let event in handlers) { 8297 let handler = handlers[event]; 8298 view.dom.addEventListener(event, view.input.eventHandlers[event] = (event$1) => { 8299 if (eventBelongsToView(view, event$1) && !runCustomHandler(view, event$1) && (view.editable || !(event$1.type in editHandlers))) handler(view, event$1); 8300 }, passiveHandlers[event] ? { passive: true } : void 0); 8301 } 8302 if (safari) view.dom.addEventListener("input", () => null); 8303 ensureListeners(view); 8304} 8305function setSelectionOrigin(view, origin) { 8306 view.input.lastSelectionOrigin = origin; 8307 view.input.lastSelectionTime = Date.now(); 8308} 8309function destroyInput(view) { 8310 if (view.input.mouseDown) view.input.mouseDown.done(); 8311 view.domObserver.stop(); 8312 for (let type in view.input.eventHandlers) view.dom.removeEventListener(type, view.input.eventHandlers[type]); 8313 clearTimeout(view.input.composingTimeout); 8314 clearTimeout(view.input.lastIOSEnterFallbackTimeout); 8315} 8316function ensureListeners(view) { 8317 view.someProp("handleDOMEvents", (currentHandlers) => { 8318 for (let type in currentHandlers) if (!view.input.eventHandlers[type]) view.dom.addEventListener(type, view.input.eventHandlers[type] = (event) => runCustomHandler(view, event)); 8319 }); 8320} 8321function runCustomHandler(view, event) { 8322 return view.someProp("handleDOMEvents", (handlers$1) => { 8323 let handler = handlers$1[event.type]; 8324 return handler ? handler(view, event) || event.defaultPrevented : false; 8325 }); 8326} 8327function eventBelongsToView(view, event) { 8328 if (!event.bubbles) return true; 8329 if (event.defaultPrevented) return false; 8330 for (let node = event.target; node != view.dom; node = node.parentNode) if (!node || node.nodeType == 11 || node.pmViewDesc && node.pmViewDesc.stopEvent(event)) return false; 8331 return true; 8332} 8333function dispatchEvent(view, event) { 8334 if (!runCustomHandler(view, event) && handlers[event.type] && (view.editable || !(event.type in editHandlers))) handlers[event.type](view, event); 8335} 8336editHandlers.keydown = (view, _event) => { 8337 let event = _event; 8338 view.input.shiftKey = event.keyCode == 16 || event.shiftKey; 8339 if (inOrNearComposition(view)) return; 8340 view.input.lastKeyCode = event.keyCode; 8341 view.input.lastKeyCodeTime = Date.now(); 8342 if (android && chrome && event.keyCode == 13) return; 8343 if (event.keyCode != 229) view.domObserver.forceFlush(); 8344 if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) { 8345 let now = Date.now(); 8346 view.input.lastIOSEnter = now; 8347 view.input.lastIOSEnterFallbackTimeout = setTimeout(() => { 8348 if (view.input.lastIOSEnter == now) { 8349 view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter"))); 8350 view.input.lastIOSEnter = 0; 8351 } 8352 }, 200); 8353 } else if (view.someProp("handleKeyDown", (f) =>
8353 f(view, event)) || captureKeyDown(view, event)) event.preventDefault(); 8354 else setSelectionOrigin(view, "key"); 8355}; 8356editHandlers.keyup = (view, event) => { 8357 if (event.keyCode == 16) view.input.shiftKey = false; 8358}; 8359editHandlers.keypress = (view, _event) => { 8360 let event = _event; 8361 if (inOrNearComposition(view) || !event.charCode || event.ctrlKey && !event.altKey || mac$2 && event.metaKey) return; 8362 if (view.someProp("handleKeyPress", (f) => f(view, event))) { 8363 event.preventDefault(); 8364 return; 8365 } 8366 let sel = view.state.selection; 8367 if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) { 8368 let text$1 = String.fromCharCode(event.charCode); 8369 let deflt = () => view.state.tr.insertText(text$1).scrollIntoView(); 8370 if (!/[\r\n]/.test(text$1) && !view.someProp("handleTextInput", (f) => f(view, sel.$from.pos, sel.$to.pos, text$1, deflt))) view.dispatch(deflt()); 8371 event.preventDefault(); 8372 } 8373}; 8374function eventCoords(event) { 8375 return { 8376 left: event.clientX, 8377 top: event.clientY 8378 }; 8379} 8380function isNear(event, click) { 8381 let dx = click.x - event.clientX, dy = click.y - event.clientY; 8382 return dx * dx + dy * dy < 100; 8383} 8384function runHandlerOnContext(view, propName, pos, inside, event) { 8385 if (inside == -1) return false; 8386 let $pos = view.state.doc.resolve(inside); 8387 for (let i$1 = $pos.depth + 1; i$1 > 0; i$1--) if (view.someProp(propName, (f) => i$1 > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i$1), event, true) : f(view, pos, $pos.node(i$1), $pos.before(i$1), event, false))) return true; 8388 return false; 8389} 8390function updateSelection(view, selection, origin) { 8391 if (!view.focused) view.focus(); 8392 if (view.state.selection.eq(selection)) return; 8393 let tr$1 = view.state.tr.setSelection(selection); 8394 if (origin == "pointer") tr$1.setMeta("pointer", true); 8395 view.dispatch(tr$1); 8396} 8397function selectClickedLeaf(view, inside) { 8398 if (inside == -1) return false; 8399 let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter; 8400 if (node && node.isAtom && NodeSelection.isSelectable(node)) { 8401 updateSelection(view, new NodeSelection($pos), "pointer"); 8402 return true; 8403 } 8404 return false; 8405} 8406function selectClickedNode(view, inside) { 8407 if (inside == -1) return false; 8408 let sel = view.state.selection, selectedNode, selectAt;
8409 if (sel instanceof NodeSelection) selectedNode = sel.node; 8410 let $pos = view.state.doc.resolve(inside); 8411 for (let i$1 = $pos.depth + 1; i$1 > 0; i$1--) { 8412 let node = i$1 > $pos.depth ? $pos.nodeAfter : $pos.node(i$1); 8413 if (NodeSelection.isSelectable(node)) { 8414 if (selectedNode && sel.$from.depth > 0 && i$1 >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos) selectAt = $pos.before(sel.$from.depth); 8415 else selectAt = $pos.before(i$1); 8416 break; 8417 } 8418 } 8419 if (selectAt != null) { 8420 updateSelection(view, NodeSelection.create(view.state.doc, selectAt), "pointer"); 8421 return true; 8422 } else return false; 8423} 8424function handleSingleClick(view, pos, inside, event, selectNode) { 8425 return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || view.someProp("handleClick", (f) => f(view, pos, event)) || (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside)); 8426} 8427function handleDoubleClick(view, pos, inside, event) { 8428 return runHandlerOnContext(view, "handleDoubleClickOn", pos, inside, event) || view.someProp("handleDoubleClick", (f) => f(view, pos, event)); 8429} 8430function handleTripleClick(view, pos, inside, event) { 8431 return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || view.someProp("handleTripleClick", (f) => f(view, pos, event)) || defaultTripleClick(view, inside, event); 8432} 8433function defaultTripleClick(view, inside, event) { 8434 if (event.button != 0) return false; 8435 let selection = selectionForTripleClick(view, inside, true), doc$2 = view.state.doc; 8436 if (!selection) return false; 8437 updateSelection(view, selection, "pointer"); 8438 if (selection instanceof TextSelection && doc$2.eq(view.state.doc)) view.input.mouseDown = new TripleClickDrag(view, selection); 8439 return true; 8440} 8441function selectionForTripleClick(view, inside, selectNodes) { 8442 let doc$2 = view.state.doc; 8443 if (inside == -1) return doc$2.inlineContent ? TextSelection.create(doc$2, 0, doc$2.content.size) : null; 8444 let $pos = doc$2.resolve(inside); 8445 for (let i$1 = $pos.depth + 1; i$1 > 0; i$1--) { 8446 let node = i$1 > $pos.depth ? $pos.nodeAfter : $pos.node(i$1); 8447 let nodePos = $pos.before(i$1); 8448 if (node.inlineContent) return TextSelection.create(doc$2, nodePos + 1, nodePos + 1 + node.content.size); 8449 else if (selectNodes && NodeSelection.isSelectable(node)) return NodeSelection.create(doc$2, nodePos); 8450 } 8451 return null; 8452} 8453function forceDOMFlush(view) { 8454 return endComposition(view); 8455} 8456var selectNodeModifier = mac$2 ? "metaKey" : "ctrlKey"; 8457handlers.mousedown = (view, _event) => { 8458 let event = _event; 8459 view.input.shiftKey = event.shiftKey; 8460 let flushed = forceDOMFlush(view); 8461 let now = Date.now(), type = "singleClick"; 8462 if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier] && view.input.lastClick.button == event.button) { 8463 if (view.input.lastClick.type == "singleClick") type = "doubleClick"; 8464 else if (view.input.lastClick.type == "doubleClick") type = "tripleClick"; 8465 } 8466 view.input.lastClick = { 8467 time: now, 8468 x: event.clientX, 8469 y: event.clientY, 8470 type, 8471 button: event.button 8472 }; 8473 if (view.input.mouseDown) view.input.mouseDown.done(); 8474 let pos = view.posAtCoords(eventCoords(event)); 8475 if (!pos) return; 8476 if (type == "singleClick") view.input.mouseDown = new LeftMouseDown(view, pos, event, !!flushed); 8477 else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) event.preventDefault(); 8478 else setSelectionOrigin(view, "pointer"); 8479}; 8480var MouseDown = class { 8481 constructor(view) { 8482 this.view = view; 8483 this.mightDrag = null; 8484 view.root.addEventListener("mouseup", this.up = this.up.bind(this)); 8485 view.root.addEventListener("mousemove", this.move = this.move.bind(this)); 8486 } 8487 up(event) { 8488 this.done(); 8489 } 8490 move(event) { 8491 if (event.buttons == 0) this.done(); 8492 } 8493 done() { 8494 this.view.root.removeEventListener("mouseup", this.up); 8495 this.view.root.removeEventListener("mousemove", this.move); 8496 if (this.view.input.mouseDown == this) this.view.input.mouseDown = null; 8497 } 8498 delaySelUpdate() { 8499 return false; 8500 } 8501}; 8502var LeftMouseDown = class extends MouseDown { 8503 constructor(view, pos, event, flushed) { 8504 super(view); 8505 this.pos = pos; 8506 this.event = event; 8507 this.flushed = flushed; 8508 this.delayedSelectionSync = false;
vendor: 10,200 bytes, lines 8509-8746
8509 this.startDoc = view.state.doc; 8510 this.selectNode = !!event[selectNodeModifier]; 8511 this.allowDefault = event.shiftKey; 8512 let targetNode, targetPos; 8513 if (pos.inside > -1) { 8514 targetNode = view.state.doc.nodeAt(pos.inside); 8515 targetPos = pos.inside; 8516 } else { 8517 let $pos = view.state.doc.resolve(pos.pos); 8518 targetNode = $pos.parent; 8519 targetPos = $pos.depth ? $pos.before() : 0; 8520 } 8521 const target = flushed ? null : event.target; 8522 const targetDesc = target ? view.docView.nearestDesc(target, true) : null; 8523 this.target = targetDesc && targetDesc.nodeDOM.nodeType == 1 ? targetDesc.nodeDOM : null; 8524 let { selection } = view.state; 8525 if (event.button == 0 && (targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false || selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos)) this.mightDrag = { 8526 node: targetNode, 8527 pos: targetPos, 8528 addAttr: !!(this.target && !this.target.draggable), 8529 setUneditable: !!(this.target && gecko && !this.target.hasAttribute("contentEditable")) 8530 }; 8531 if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) { 8532 this.view.domObserver.stop(); 8533 if (this.mightDrag.addAttr) this.target.draggable = true; 8534 if (this.mightDrag.setUneditable) setTimeout(() => { 8535 if (this.view.input.mouseDown == this) this.target.setAttribute("contentEditable", "false"); 8536 }, 20); 8537 this.view.domObserver.start(); 8538 } 8539 setSelectionOrigin(view, "pointer"); 8540 } 8541 done() { 8542 super.done(); 8543 if (this.mightDrag && this.target) { 8544 this.view.domObserver.stop(); 8545 if (this.mightDrag.addAttr) this.target.removeAttribute("draggable"); 8546 if (this.mightDrag.setUneditable) this.target.removeAttribute("contentEditable"); 8547 this.view.domObserver.start(); 8548 } 8549 if (this.delayedSelectionSync) setTimeout(() => { 8550 if (!this.view.isDestroyed) selectionToDOM(this.view); 8551 }); 8552 } 8553 up(event) { 8554 this.done(); 8555 if (!this.view.dom.contains(event.target)) return; 8556 let pos = this.pos; 8557 if (this.view.state.doc != this.startDoc) pos = this.view.posAtCoords(eventCoords(event)); 8558 this.updateAllowDefault(event); 8559 if (this.allowDefault || !pos) setSelectionOrigin(this.view, "pointer"); 8560 else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) event.preventDefault(); 8561 else if (event.button == 0 && (this.flushed || safari && this.mightDrag && !this.mightDrag.node.isAtom || chrome && !this.view.state.selection.visible && Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2)) { 8562 updateSelection(this.view, Selection$1.near(this.view.state.doc.resolve(pos.pos)), "pointer"); 8563 event.preventDefault(); 8564 } else setSelectionOrigin(this.view, "pointer"); 8565 } 8566 move(event) { 8567 this.updateAllowDefault(event); 8568 setSelectionOrigin(this.view, "pointer"); 8569 super.move(event); 8570 } 8571 updateAllowDefault(event) { 8572 if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || Math.abs(this.event.y - event.clientY) > 4)) this.allowDefault = true; 8573 } 8574 delaySelUpdate() { 8575 if (!this.allowDefault) return false; 8576 this.delayedSelectionSync = true; 8577 return true; 8578 } 8579}; 8580var TripleClickDrag = class extends MouseDown { 8581 constructor(view, startSelection) { 8582 super(view); 8583 this.startSelection = startSelection; 8584 this.startDoc = view.state.doc; 8585 } 8586 move(event) { 8587 if (event.buttons == 0 || this.view.isDestroyed || !this.view.state.doc.eq(this.startDoc)) { 8588 this.done(); 8589 return; 8590 } 8591 event.preventDefault(); 8592 setSelectionOrigin(this.view, "pointer"); 8593 let pos = this.view.posAtCoords(eventCoords(event)); 8594 let target = pos && selectionForTripleClick(this.view, pos.inside, false); 8595 if (!target) return; 8596 let { doc: doc$2 } = this.view.state, start = this.startSelection; 8597 let [anchor, head] = target.from < start.from ? [start.to, target.from] : [start.from, target.to]; 8598 updateSelection(this.view, TextSelection.create(doc$2, anchor, head), "pointer"); 8599 } 8600}; 8601handlers.touchstart = (view) => { 8602 view.input.lastTouch = Date.now(); 8603 forceDOMFlush(view); 8604 setSelectionOrigin(view, "pointer"); 8605}; 8606handlers.touchmove = (view) => { 8607 view.input.lastTouch = Date.now(); 8608 setSelectionOrigin(view, "pointer"); 8609}; 8610handlers.contextmenu = (view) => forceDOMFlush(view); 8611function inOrNearComposition(view, event) { 8612 if (view.composing) return true; 8613 if (safari && Math.abs(Date.now() - view.input.compositionEndedAt) < 500) { 8614 view.input.compositionEndedAt = -2e8; 8615 return true; 8616 } 8617 return false; 8618} 8619var timeoutComposition = android ? 5e3 : -1; 8620editHandlers.compositionstart = editHandlers.compositionupdate = (view) => { 8621 if (!view.composing) { 8622 view.domObserver.flush(); 8623 let { state } = view, $pos = state.selection.$to; 8624 if (state.selection instanceof TextSelection && (state.storedMarks || !$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some((m) => m.type.spec.inclusive === false) || chrome && windows$1 && selectionBeforeUneditable(view))) { 8625 view.markCursor = view.state.storedMarks || $pos.marks(); 8626 endComposition(view, true); 8627 view.markCursor = null; 8628 } else { 8629 endComposition(view, !state.selection.empty); 8630 if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) { 8631 let sel = view.domSelectionRange(); 8632 for (let node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0;) { 8633 let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1]; 8634 if (!before) break; 8635 if (before.nodeType == 3) { 8636 let sel$1 = view.domSelection(); 8637 if (sel$1) sel$1.collapse(before, before.nodeValue.length); 8638 break; 8639 } else { 8640 node = before; 8641 offset = -1; 8642 } 8643 } 8644 } 8645 } 8646 view.input.composing = true; 8647 } 8648 scheduleComposeEnd(view, timeoutComposition); 8649}; 8650function selectionBeforeUneditable(view) { 8651 let { focusNode, focusOffset } = view.domSelectionRange(); 8652 if (!focusNode || focusNode.nodeType != 1 || focusOffset >= focusNode.childNodes.length) return false; 8653 let next = focusNode.childNodes[focusOffset]; 8654 return next.nodeType == 1 && next.contentEditable == "false"; 8655} 8656editHandlers.compositionend = (view, event) => { 8657 if (view.composing) { 8658 view.input.composing = false; 8659 view.input.compositionEndedAt = Date.now(); 8660 view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0; 8661 view.input.compositionNode = null; 8662 if (view.input.badSafariComposition) view.domObserver.forceFlush(); 8663 else if (view.input.compositionPendingChanges) Promise.resolve().then(() => view.domObserver.flush()); 8664 view.input.compositionID++; 8665 scheduleComposeEnd(view, 20); 8666 } 8667}; 8668function scheduleComposeEnd(view, delay) { 8669 clearTimeout(view.input.composingTimeout); 8670 if (delay > -1) view.input.composingTimeout = setTimeout(() => endComposition(view), delay); 8671} 8672function clearComposition(view) { 8673 if (view.composing) { 8674 view.input.composing = false; 8675 view.input.compositionEndedAt = Date.now(); 8676 } 8677 while (view.input.compositionNodes.length > 0) view.input.compositionNodes.pop().markParentsDirty(); 8678} 8679function findCompositionNode(view) { 8680 let sel = view.domSelectionRange(); 8681 if (!sel.focusNode) return null; 8682 let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset); 8683 let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset); 8684 if (textBefore && textAfter && textBefore != textAfter) { 8685 let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode; 8686 if (textBefore == lastChanged || textAfter == lastChanged) return lastChanged; 8687 if (!descAfter || !descAfter.isText(textAfter.nodeValue)) return textAfter; 8688 else if (view.input.compositionNode == textAfter) { 8689 let descBefore = textBefore.pmViewDesc; 8690 if (!(!descBefore || !descBefore.isText(textBefore.nodeValue))) return textAfter; 8691 } 8692 } 8693 return textBefore || textAfter; 8694} 8695function endComposition(view, restarting = false) { 8696 if (android && view.domObserver.flushingSoon >= 0) return; 8697 view.domObserver.forceFlush(); 8698 clearComposition(view); 8699 if (restarting || view.docView && view.docView.dirty) { 8700 let sel = selectionFromDOM(view), cur = view.state.selection; 8701 if (sel && !sel.eq(cur)) view.dispatch(view.state.tr.setSelection(sel)); 8702 else if ((view.markCursor || restarting) && !cur.$from.node(cur.$from.sharedDepth(cur.to)).inlineContent) view.dispatch(view.state.tr.deleteSelection()); 8703 else view.updateState(view.state); 8704 return true; 8705 } 8706 return false; 8707} 8708function captureCopy(view, dom) { 8709 if (!view.dom.parentNode) return; 8710 let wrap$1 = view.dom.parentNode.appendChild(document.createElement("div")); 8711 wrap$1.appendChild(dom); 8712 wrap$1.style.cssText = "position: fixed; left: -10000px; top: 10px"; 8713 let sel = getSelection(), range = document.createRange(); 8714 range.selectNodeContents(dom); 8715 view.dom.blur(); 8716 sel.removeAllRanges(); 8717 sel.addRange(range); 8718 setTimeout(() => { 8719 if (wrap$1.parentNode) wrap$1.parentNode.removeChild(wrap$1); 8720 view.focus(); 8721 }, 50); 8722} 8723var brokenClipboardAPI = ie$2 && ie_version < 15 || ios && webkit_version < 604; 8724handlers.copy = editHandlers.cut = (view, _event) => { 8725 let event = _event; 8726 let sel = view.state.selection, cut$1 = event.type == "cut"; 8727 if (sel.empty) return; 8728 let data = brokenClipboardAPI ? null : event.clipboardData; 8729 let { dom, text: text$1 } = serializeForClipboard(view, sel.content()); 8730 if (data) { 8731 event.preventDefault(); 8732 data.clearData(); 8733 data.setData("text/html", dom.innerHTML); 8734 data.setData("text/plain", text$1); 8735 } else captureCopy(view, dom); 8736 if (cut$1) view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut")); 8737}; 8738function sliceSingleNode(slice) { 8739 return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null; 8740} 8741function capturePaste(view, event) { 8742 if (!view.dom.parentNode) return; 8743 let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code; 8744 let target = view.dom.parentNode.appendChild(document.createElement(plainText ? "textarea" : "div")); 8745 if (!plainText) target.contentEditable = "true"; 8746 target.style.cssText = "position: fixed; left: -10000px; top: 10px";
8747 target.focus(); 8748 let plain = view.input.shiftKey && view.input.lastKeyCode != 45; 8749 setTimeout(() => { 8750 view.focus(); 8751 if (target.parentNode) target.parentNode.removeChild(target); 8752 if (plainText) doPaste(view, target.value, null, plain, event); 8753 else doPaste(view, target.textContent, target.innerHTML, plain, event); 8754 }, 50); 8755} 8756function doPaste(view, text$1, html$2, preferPlain, event) { 8757 let slice = parseFromClipboard(view, text$1, html$2, preferPlain, view.state.selection.$from); 8758 if (view.someProp("handlePaste", (f) => f(view, event, slice || Slice.empty))) return true; 8759 if (!slice) return false; 8760 let singleNode = sliceSingleNode(slice); 8761 let tr$1 = singleNode ? view.state.tr.replaceSelectionWith(singleNode, preferPlain) : view.state.tr.replaceSelection(slice); 8762 view.dispatch(tr$1.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste")); 8763 return true; 8764} 8765function getText$1(clipboardData) { 8766 let text$1 = clipboardData.getData("text/plain") || clipboardData.getData("Text"); 8767 if (text$1) return text$1; 8768 let uris = clipboardData.getData("text/uri-list"); 8769 return uris ? uris.replace(/\r?\n/g, " ") : ""; 8770} 8771editHandlers.paste = (view, _event) => { 8772 let event = _event; 8773 if (view.composing && !android) return; 8774 let data = brokenClipboardAPI ? null : event.clipboardData; 8775 let plain = view.input.shiftKey && view.input.lastKeyCode != 45; 8776 if (data && doPaste(view, getText$1(data), data.getData("text/html"), plain, event)) event.preventDefault(); 8777 else capturePaste(view, event); 8778}; 8779var Dragging = class { 8780 constructor(slice, move, node) { 8781 this.slice = slice; 8782 this.move = move; 8783 this.node = node; 8784 } 8785}; 8786var dragCopyModifier = mac$2 ? "altKey" : "ctrlKey"; 8787function dragMoves(view, event) { 8788 let copy$1; 8789 view.someProp("dragCopies", (test) => { 8790 copy$1 = copy$1 || test(event); 8791 }); 8792 return copy$1 != null ? !copy$1 : !event[dragCopyModifier]; 8793} 8794handlers.dragstart = (view, _event) => { 8795 let event = _event; 8796 let mouseDown = view.input.mouseDown; 8797 if (mouseDown) mouseDown.done(); 8798 if (!event.dataTransfer) return; 8799 let sel = view.state.selection; 8800 let pos = sel.empty ? null : view.posAtCoords(eventCoords(event)); 8801 let node; 8802 if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)); 8803 else if (mouseDown && mouseDown.mightDrag) node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos); 8804 else if (event.target && event.target.nodeType == 1) { 8805 let desc = view.docView.nearestDesc(event.target, true); 8806 if (desc && desc.node.type.spec.draggable && desc != view.docView) node = NodeSelection.create(view.state.doc, desc.posBefore); 8807 } 8808 let { dom, text: text$1, slice } = serializeForClipboard(view, (node || view.state.selection).content()); 8809 if (!event.dataTransfer.files.length || !chrome || chrome_version > 120) event.dataTransfer.clearData(); 8810 event.dataTransfer.setData(brokenClipboardAPI ? "Text" : "text/html", dom.innerHTML); 8811 event.dataTransfer.effectAllowed = "copyMove"; 8812 if (!brokenClipboardAPI) event.dataTransfer.setData("text/plain", text$1); 8813 view.dragging = new Dragging(slice, dragMoves(view, event), node); 8814}; 8815handlers.dragend = (view) => { 8816 let dragging = view.dragging; 8817 window.setTimeout(() => { 8818 if (view.dragging == dragging) view.dragging = null; 8819 }, 50); 8820}; 8821editHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault(); 8822editHandlers.drop = (view, event) => { 8823 try { 8824 handleDrop(view, event, view.dragging); 8825 } finally { 8826 view.dragging = null; 8827 } 8828}; 8829function handleDrop(view, event, dragging) { 8830 if (!event.dataTransfer) return; 8831 let eventPos = view.posAtCoords(eventCoords(event)); 8832 if (!eventPos) return; 8833 let $mouse = view.state.doc.resolve(eventPos.pos); 8834 let slice = dragging && dragging.slice; 8835 if (slice) view.someProp("transformPasted", (f) => { 8836 slice = f(slice, view, false); 8837 }); 8838 else slice = parseFromClipboard(view, getText$1(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData("text/html"), false, $mouse); 8839 let move = !!(dragging && dragMoves(view, event)); 8840 if (view.someProp("handleDrop", (f) => f(view, event, slice || Slice.empty, move))) { 8841 event.preventDefault(); 8842 return; 8843 } 8844 if (!slice) return; 8845 event.preventDefault(); 8846 let insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos; 8847 if (insertPos == null) insertPos = $mouse.pos; 8848 let tr$1 = view.state.tr; 8849 if (move) { 8850 let { node } = dragging; 8851 if (node) node.replace(tr$1); 8852 else tr$1.deleteSelection(); 8853 } 8854 let pos = tr$1.mapping.map(insertPos); 8855 let isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1; 8856 let beforeInsert = tr$1.doc; 8857 if (isNode) tr$1.replaceRangeWith(pos, pos, slice.content.firstChild); 8858 else tr$1.replaceRange(pos, pos, slice); 8859 if (tr$1.doc.eq(beforeInsert)) return; 8860 let $pos = tr$1.doc.resolve(pos); 8861 if (isNode && NodeSelection.isSelectable(slice.content.firstChild) && $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) tr$1.setSelection(new NodeSelection($pos)); 8862 else { 8863 let end = tr$1.mapping.map(insertPos);
vendor: 10,152 bytes, lines 8864-9126
8864 tr$1.mapping.maps[tr$1.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo); 8865 tr$1.setSelection(selectionBetween(view, $pos, tr$1.doc.resolve(end))); 8866 } 8867 view.focus(); 8868 view.dispatch(tr$1.setMeta("uiEvent", "drop")); 8869} 8870handlers.focus = (view) => { 8871 view.input.lastFocus = Date.now(); 8872 if (!view.focused) { 8873 view.domObserver.stop(); 8874 view.dom.classList.add("ProseMirror-focused"); 8875 view.domObserver.start(); 8876 view.focused = true; 8877 setTimeout(() => { 8878 if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange())) selectionToDOM(view); 8879 }, 20); 8880 } 8881}; 8882handlers.blur = (view, _event) => { 8883 let event = _event; 8884 if (view.focused) { 8885 view.domObserver.stop(); 8886 view.dom.classList.remove("ProseMirror-focused"); 8887 view.domObserver.start(); 8888 if (event.relatedTarget && view.dom.contains(event.relatedTarget)) view.domObserver.currentSelection.clear(); 8889 view.focused = false; 8890 } 8891}; 8892handlers.beforeinput = (view, _event) => { 8893 if (android && _event.inputType == "deleteContentBackward") { 8894 view.domObserver.flushSoon(); 8895 let { domChangeCount } = view.input; 8896 setTimeout(() => { 8897 if (view.input.domChangeCount != domChangeCount) return; 8898 view.dom.blur(); 8899 view.focus(); 8900 if (view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace")))) return; 8901 let { $cursor } = view.state.selection; 8902 if ($cursor && $cursor.pos > 0) view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView()); 8903 }, 50); 8904 } 8905}; 8906for (let prop in editHandlers) handlers[prop] = editHandlers[prop]; 8907function compareObjs(a, b) { 8908 if (a == b) return true; 8909 for (let p in a) if (a[p] !== b[p]) return false; 8910 for (let p in b) if (!(p in a)) return false; 8911 return true; 8912} 8913var WidgetType = class WidgetType { 8914 constructor(toDOM, spec) { 8915 this.toDOM = toDOM; 8916 this.spec = spec || noSpec; 8917 this.side = this.spec.side || 0; 8918 } 8919 map(mapping, span, offset, oldOffset) { 8920 let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1); 8921 return deleted ? null : new Decoration(pos - offset, pos - offset, this); 8922 } 8923 valid() { 8924 return true; 8925 } 8926 eq(other) { 8927 return this == other || other instanceof WidgetType && (this.spec.key && this.spec.key == other.spec.key || this.toDOM == other.toDOM && compareObjs(this.spec, other.spec)); 8928 } 8929 destroy(node) { 8930 if (this.spec.destroy) this.spec.destroy(node); 8931 } 8932}; 8933var InlineType = class InlineType { 8934 constructor(attrs, spec) { 8935 this.attrs = attrs; 8936 this.spec = spec || noSpec; 8937 } 8938 map(mapping, span, offset, oldOffset) { 8939 let from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset; 8940 let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset; 8941 return from >= to ? null : new Decoration(from, to, this); 8942 } 8943 valid(_, span) { 8944 return span.from < span.to; 8945 } 8946 eq(other) { 8947 return this == other || other instanceof InlineType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec); 8948 } 8949 static is(span) { 8950 return span.type instanceof InlineType; 8951 } 8952 destroy() {} 8953}; 8954var NodeType = class NodeType { 8955 constructor(attrs, spec) { 8956 this.attrs = attrs; 8957 this.spec = spec || noSpec; 8958 } 8959 map(mapping, span, offset, oldOffset) { 8960 let from = mapping.mapResult(span.from + oldOffset, 1); 8961 if (from.deleted) return null; 8962 let to = mapping.mapResult(span.to + oldOffset, -1); 8963 if (to.deleted || to.pos <= from.pos) return null; 8964 return new Decoration(from.pos - offset, to.pos - offset, this); 8965 } 8966 valid(node, span) { 8967 let { index, offset } = node.content.findIndex(span.from), child; 8968 return offset == span.from && !(child = node.child(index)).isText && offset + child.nodeSize == span.to; 8969 } 8970 eq(other) { 8971 return this == other || other instanceof NodeType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec); 8972 } 8973 destroy() {} 8974}; 8975var Decoration = class Decoration { 8976 constructor(from, to, type) { 8977 this.from = from; 8978 this.to = to; 8979 this.type = type; 8980 } 8981 copy(from, to) { 8982 return new Decoration(from, to, this.type); 8983 } 8984 eq(other, offset = 0) { 8985 return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to; 8986 } 8987 map(mapping, offset, oldOffset) { 8988 return this.type.map(mapping, this, offset, oldOffset); 8989 } 8990 static widget(pos, toDOM, spec) { 8991 return new Decoration(pos, pos, new WidgetType(toDOM, spec)); 8992 } 8993 static inline(from, to, attrs, spec) { 8994 return new Decoration(from, to, new InlineType(attrs, spec)); 8995 } 8996 static node(from, to, attrs, spec) { 8997 return new Decoration(from, to, new NodeType(attrs, spec)); 8998 } 8999 get spec() { 9000 return this.type.spec; 9001 } 9002 get inline() { 9003 return this.type instanceof InlineType; 9004 } 9005 get widget() { 9006 return this.type instanceof WidgetType; 9007 } 9008}; 9009var none = [], noSpec = {}; 9010var DecorationSet = class DecorationSet { 9011 constructor(local, children) { 9012 this.local = local.length ? local : none; 9013 this.children = children.length ? children : none; 9014 } 9015 static create(doc$2, decorations) { 9016 return decorations.length ? buildTree(decorations, doc$2, 0, noSpec) : empty; 9017 } 9018 find(start, end, predicate) { 9019 let result = []; 9020 this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate); 9021 return result; 9022 } 9023 findInner(start, end, result, offset, predicate) { 9024 for (let i$1 = 0; i$1 < this.local.length; i$1++) { 9025 let span = this.local[i$1]; 9026 if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec))) result.push(span.copy(span.from + offset, span.to + offset)); 9027 } 9028 for (let i$1 = 0; i$1 < this.children.length; i$1 += 3) if (this.children[i$1] < end && this.children[i$1 + 1] > start) { 9029 let childOff = this.children[i$1] + 1; 9030 this.children[i$1 + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate); 9031 } 9032 } 9033 map(mapping, doc$2, options) { 9034 if (this == empty || mapping.maps.length == 0) return this; 9035 return this.mapInner(mapping, doc$2, 0, 0, options || noSpec); 9036 } 9037 mapInner(mapping, node, offset, oldOffset, options) { 9038 let newLocal; 9039 for (let i$1 = 0; i$1 < this.local.length; i$1++) { 9040 let mapped = this.local[i$1].map(mapping, offset, oldOffset); 9041 if (mapped && mapped.type.valid(node, mapped)) (newLocal || (newLocal = [])).push(mapped); 9042 else if (options.onRemove) options.onRemove(this.local[i$1].spec); 9043 } 9044 if (this.children.length) return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options); 9045 else return newLocal ? new DecorationSet(newLocal.sort(byPos), none) : empty; 9046 } 9047 add(doc$2, decorations) { 9048 if (!decorations.length) return this; 9049 if (this == empty) return DecorationSet.create(doc$2, decorations); 9050 return this.addInner(doc$2, decorations, 0); 9051 } 9052 addInner(doc$2, decorations, offset) { 9053 let children, childIndex = 0; 9054 doc$2.forEach((childNode, childOffset) => { 9055 let baseOffset = childOffset + offset, found$1; 9056 if (!(found$1 = takeSpansForNode(decorations, childNode, baseOffset))) return; 9057 if (!children) children = this.children.slice(); 9058 while (childIndex < children.length && children[childIndex] < childOffset) childIndex += 3; 9059 if (children[childIndex] == childOffset) children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found$1, baseOffset + 1); 9060 else children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found$1, childNode, baseOffset + 1, noSpec)); 9061 childIndex += 3; 9062 }); 9063 let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset); 9064 for (let i$1 = 0; i$1 < local.length; i$1++) if (!local[i$1].type.valid(doc$2, local[i$1])) local.splice(i$1--, 1); 9065 return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children); 9066 } 9067 remove(decorations) { 9068 if (decorations.length == 0 || this == empty) return this; 9069 return this.removeInner(decorations, 0); 9070 } 9071 removeInner(decorations, offset) { 9072 let children = this.children, local = this.local; 9073 for (let i$1 = 0; i$1 < children.length; i$1 += 3) { 9074 let found$1; 9075 let from = children[i$1] + offset, to = children[i$1 + 1] + offset; 9076 for (let j = 0, span; j < decorations.length; j++) if (span = decorations[j]) { 9077 if (span.from > from && span.to < to) { 9078 decorations[j] = null; 9079 (found$1 || (found$1 = [])).push(span); 9080 } 9081 } 9082 if (!found$1) continue; 9083 if (children == this.children) children = this.children.slice(); 9084 let removed$1 = children[i$1 + 2].removeInner(found$1, from + 1); 9085 if (removed$1 != empty) children[i$1 + 2] = removed$1; 9086 else { 9087 children.splice(i$1, 3); 9088 i$1 -= 3; 9089 } 9090 } 9091 if (local.length) { 9092 for (let i$1 = 0, span; i$1 < decorations.length; i$1++) if (span = decorations[i$1]) { 9093 for (let j = 0; j < local.length; j++) if (local[j].eq(span, offset)) { 9094 if (local == this.local) local = this.local.slice(); 9095 local.splice(j--, 1); 9096 } 9097 } 9098 } 9099 if (children == this.children && local == this.local) return this; 9100 return local.length || children.length ? new DecorationSet(local, children) : empty; 9101 } 9102 forChild(offset, node) { 9103 if (this == empty) return this; 9104 if (node.isLeaf) return DecorationSet.empty; 9105 let child, local; 9106 for (let i$1 = 0; i$1 < this.children.length; i$1 += 3) if (this.children[i$1] >= offset) { 9107 if (this.children[i$1] == offset) child = this.children[i$1 + 2]; 9108 break; 9109 } 9110 let start = offset + 1, end = start + node.content.size; 9111 for (let i$1 = 0; i$1 < this.local.length; i$1++) { 9112 let dec = this.local[i$1]; 9113 if (dec.from < end && dec.to > start && dec.type instanceof InlineType) { 9114 let from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start; 9115 if (from < to) (local || (local = [])).push(dec.copy(from, to)); 9116 } 9117 } 9118 if (local) { 9119 let localSet = new DecorationSet(local.sort(byPos), none); 9120 return child ? new DecorationGroup([localSet, child]) : localSet; 9121 } 9122 return child || empty; 9123 } 9124 eq(other) { 9125 if (this == other) return true; 9126 if (!(other instanceof DecorationSet) || this.local.length != other.local.length || this.children.length != other.children.length) return false;
9127 for (let i$1 = 0; i$1 < this.local.length; i$1++) if (!this.local[i$1].eq(other.local[i$1])) return false; 9128 for (let i$1 = 0; i$1 < this.children.length; i$1 += 3) if (this.children[i$1] != other.children[i$1] || this.children[i$1 + 1] != other.children[i$1 + 1] || !this.children[i$1 + 2].eq(other.children[i$1 + 2])) return false; 9129 return true; 9130 } 9131 locals(node) { 9132 return removeOverlap(this.localsInner(node)); 9133 } 9134 localsInner(node) { 9135 if (this == empty) return none; 9136 if (node.inlineContent || !this.local.some(InlineType.is)) return this.local; 9137 let result = []; 9138 for (let i$1 = 0; i$1 < this.local.length; i$1++) if (!(this.local[i$1].type instanceof InlineType)) result.push(this.local[i$1]); 9139 return result; 9140 } 9141 forEachSet(f) { 9142 f(this); 9143 } 9144}; 9145DecorationSet.empty = new DecorationSet([], []); 9146DecorationSet.removeOverlap = removeOverlap; 9147var empty = DecorationSet.empty; 9148var DecorationGroup = class DecorationGroup { 9149 constructor(members) { 9150 this.members = members; 9151 } 9152 map(mapping, doc$2) { 9153 const mappedDecos = this.members.map((member) => member.map(mapping, doc$2, noSpec)); 9154 return DecorationGroup.from(mappedDecos); 9155 } 9156 forChild(offset, child) { 9157 if (child.isLeaf) return DecorationSet.empty; 9158 let found$1 = []; 9159 for (let i$1 = 0; i$1 < this.members.length; i$1++) { 9160 let result = this.members[i$1].forChild(offset, child); 9161 if (result == empty) continue; 9162 if (result instanceof DecorationGroup) found$1 = found$1.concat(result.members); 9163 else found$1.push(result); 9164 } 9165 return DecorationGroup.from(found$1); 9166 } 9167 eq(other) { 9168 if (!(other instanceof DecorationGroup) || other.members.length != this.members.length) return false; 9169 for (let i$1 = 0; i$1 < this.members.length; i$1++) if (!this.members[i$1].eq(other.members[i$1])) return false; 9170 return true; 9171 } 9172 locals(node) { 9173 let result, sorted = true; 9174 for (let i$1 = 0; i$1 < this.members.length; i$1++) { 9175 let locals = this.members[i$1].localsInner(node); 9176 if (!locals.length) continue; 9177 if (!result) result = locals; 9178 else { 9179 if (sorted) { 9180 result = result.slice(); 9181 sorted = false; 9182 } 9183 for (let j = 0; j < locals.length; j++) result.push(locals[j]); 9184 } 9185 } 9186 return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none; 9187 } 9188 static from(members) { 9189 switch (members.length) { 9190 case 0: return empty; 9191 case 1: return members[0]; 9192 default: return new DecorationGroup(members.every((m) => m instanceof DecorationSet) ? members : members.reduce((r, m) => r.concat(m instanceof DecorationSet ? m : m.members), [])); 9193 } 9194 } 9195 forEachSet(f) { 9196 for (let i$1 = 0; i$1 < this.members.length; i$1++) this.members[i$1].forEachSet(f); 9197 } 9198}; 9199function mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) { 9200 let children = oldChildren.slice(); 9201 for (let i$1 = 0, baseOffset = oldOffset; i$1 < mapping.maps.length; i$1++) { 9202 let moved = 0; 9203 mapping.maps[i$1].forEach((oldStart, oldEnd, newStart, newEnd) => { 9204 let dSize = newEnd - newStart - (oldEnd - oldStart); 9205 for (let i$2 = 0; i$2 < children.length; i$2 += 3) { 9206 let end = children[i$2 + 1]; 9207 if (end < 0 || oldStart > end + baseOffset - moved) continue; 9208 let start = children[i$2] + baseOffset - moved; 9209 if (oldEnd >= start) children[i$2 + 1] = oldStart <= start ? -2 : -1; 9210 else if (oldStart >= baseOffset && dSize) { 9211 children[i$2] += dSize; 9212 children[i$2 + 1] += dSize; 9213 } 9214 } 9215 moved += dSize; 9216 }); 9217 baseOffset = mapping.maps[i$1].map(baseOffset, -1); 9218 } 9219 let mustRebuild = false; 9220 for (let i$1 = 0; i$1 < children.length; i$1 += 3) if (children[i$1 + 1] < 0) { 9221 if (children[i$1 + 1] == -2) { 9222 mustRebuild = true; 9223 children[i$1 + 1] = -1; 9224 continue; 9225 } 9226 let from = mapping.map(oldChildren[i$1] + oldOffset), fromLocal = from - offset; 9227 if (fromLocal < 0 || fromLocal >= node.content.size) { 9228 mustRebuild = true; 9229 continue; 9230 } 9231 let toLocal = mapping.map(oldChildren[i$1 + 1] + oldOffset, -1) - offset; 9232 let { index, offset: childOffset } = node.content.findIndex(fromLocal); 9233 let childNode = node.maybeChild(index); 9234 if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) { 9235 let mapped = children[i$1 + 2].mapInner(mapping, childNode, from + 1, oldChildren[i$1] + oldOffset + 1, options); 9236 if (mapped != empty) { 9237 children[i$1] = fromLocal; 9238 children[i$1 + 1] = toLocal; 9239 children[i$1 + 2] = mapped; 9240 } else {
vendor: 10,644 bytes, lines 9241-9530
9241 children[i$1 + 1] = -2; 9242 mustRebuild = true; 9243 } 9244 } else mustRebuild = true; 9245 } 9246 if (mustRebuild) { 9247 let built = buildTree(mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options), node, 0, options); 9248 newLocal = built.local; 9249 for (let i$1 = 0; i$1 < children.length; i$1 += 3) if (children[i$1 + 1] < 0) { 9250 children.splice(i$1, 3); 9251 i$1 -= 3; 9252 } 9253 for (let i$1 = 0, j = 0; i$1 < built.children.length; i$1 += 3) { 9254 let from = built.children[i$1]; 9255 while (j < children.length && children[j] < from) j += 3; 9256 children.splice(j, 0, built.children[i$1], built.children[i$1 + 1], built.children[i$1 + 2]); 9257 } 9258 } 9259 return new DecorationSet(newLocal.sort(byPos), children); 9260} 9261function moveSpans(spans, offset) { 9262 if (!offset || !spans.length) return spans; 9263 let result = []; 9264 for (let i$1 = 0; i$1 < spans.length; i$1++) { 9265 let span = spans[i$1]; 9266 result.push(new Decoration(span.from + offset, span.to + offset, span.type)); 9267 } 9268 return result; 9269} 9270function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) { 9271 function gather(set, oldOffset$1) { 9272 for (let i$1 = 0; i$1 < set.local.length; i$1++) { 9273 let mapped = set.local[i$1].map(mapping, offset, oldOffset$1); 9274 if (mapped) decorations.push(mapped); 9275 else if (options.onRemove) options.onRemove(set.local[i$1].spec); 9276 } 9277 for (let i$1 = 0; i$1 < set.children.length; i$1 += 3) gather(set.children[i$1 + 2], set.children[i$1] + oldOffset$1 + 1); 9278 } 9279 for (let i$1 = 0; i$1 < children.length; i$1 += 3) if (children[i$1 + 1] == -1) gather(children[i$1 + 2], oldChildren[i$1] + oldOffset + 1); 9280 return decorations; 9281} 9282function takeSpansForNode(spans, node, offset) { 9283 if (node.isLeaf) return null; 9284 let end = offset + node.nodeSize, found$1 = null; 9285 for (let i$1 = 0, span; i$1 < spans.length; i$1++) if ((span = spans[i$1]) && span.from > offset && span.to < end) { 9286 (found$1 || (found$1 = [])).push(span); 9287 spans[i$1] = null; 9288 } 9289 return found$1; 9290} 9291function withoutNulls(array) { 9292 let result = []; 9293 for (let i$1 = 0; i$1 < array.length; i$1++) if (array[i$1] != null) result.push(array[i$1]); 9294 return result; 9295} 9296function buildTree(spans, node, offset, options) { 9297 let children = [], hasNulls = false; 9298 node.forEach((childNode, localStart) => { 9299 let found$1 = takeSpansForNode(spans, childNode, localStart + offset); 9300 if (found$1) { 9301 hasNulls = true; 9302 let subtree = buildTree(found$1, childNode, offset + localStart + 1, options); 9303 if (subtree != empty) children.push(localStart, localStart + childNode.nodeSize, subtree); 9304 } 9305 }); 9306 let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos); 9307 for (let i$1 = 0; i$1 < locals.length; i$1++) if (!locals[i$1].type.valid(node, locals[i$1])) { 9308 if (options.onRemove) options.onRemove(locals[i$1].spec); 9309 locals.splice(i$1--, 1); 9310 } 9311 return locals.length || children.length ? new DecorationSet(locals, children) : empty; 9312} 9313function byPos(a, b) { 9314 return a.from - b.from || a.to - b.to; 9315} 9316function removeOverlap(spans) { 9317 let working = spans; 9318 for (let i$1 = 0; i$1 < working.length - 1; i$1++) { 9319 let span = working[i$1]; 9320 if (span.from != span.to) for (let j = i$1 + 1; j < working.length; j++) { 9321 let next = working[j]; 9322 if (next.from == span.from) { 9323 if (next.to != span.to) { 9324 if (working == spans) working = spans.slice(); 9325 working[j] = next.copy(next.from, span.to); 9326 insertAhead(working, j + 1, next.copy(span.to, next.to)); 9327 } 9328 continue; 9329 } else { 9330 if (next.from < span.to) { 9331 if (working == spans) working = spans.slice(); 9332 working[i$1] = span.copy(span.from, next.from); 9333 insertAhead(working, j, span.copy(next.from, span.to)); 9334 } 9335 break; 9336 } 9337 } 9338 } 9339 return working; 9340} 9341function insertAhead(array, i$1, deco) { 9342 while (i$1 < array.length && byPos(deco, array[i$1]) > 0) i$1++; 9343 array.splice(i$1, 0, deco); 9344} 9345function viewDecorations(view) { 9346 let found$1 = []; 9347 view.someProp("decorations", (f) => { 9348 let result = f(view.state); 9349 if (result && result != empty) found$1.push(result); 9350 }); 9351 if (view.cursorWrapper) found$1.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco])); 9352 return DecorationGroup.from(found$1); 9353} 9354var observeOptions = { 9355 childList: true, 9356 characterData: true, 9357 characterDataOldValue: true, 9358 attributes: true, 9359 attributeOldValue: true, 9360 subtree: true 9361}; 9362var useCharData = ie$2 && ie_version <= 11; 9363var SelectionState = class { 9364 constructor() { 9365 this.anchorNode = null; 9366 this.anchorOffset = 0; 9367 this.focusNode = null; 9368 this.focusOffset = 0; 9369 } 9370 set(sel) { 9371 this.anchorNode = sel.anchorNode; 9372 this.anchorOffset = sel.anchorOffset; 9373 this.focusNode = sel.focusNode; 9374 this.focusOffset = sel.focusOffset; 9375 } 9376 clear() { 9377 this.anchorNode = this.focusNode = null; 9378 } 9379 eq(sel) { 9380 return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset && sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset; 9381 } 9382}; 9383var DOMObserver = class { 9384 constructor(view, handleDOMChange) { 9385 this.view = view; 9386 this.handleDOMChange = handleDOMChange; 9387 this.queue = []; 9388 this.flushingSoon = -1; 9389 this.observer = null; 9390 this.currentSelection = new SelectionState(); 9391 this.onCharData = null; 9392 this.suppressingSelectionUpdates = false; 9393 this.lastChangedTextNode = null; 9394 this.observer = window.MutationObserver && new window.MutationObserver((mutations) => { 9395 for (let i$1 = 0; i$1 < mutations.length; i$1++) this.queue.push(mutations[i$1]); 9396 if (ie$2 && ie_version <= 11 && mutations.some((m) => m.type == "childList" && m.removedNodes.length || m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length)) this.flushSoon(); 9397 else if (safari && view.composing && mutations.some((m) => m.type == "childList" && m.target.nodeName == "TR")) { 9398 view.input.badSafariComposition = true; 9399 this.flushSoon(); 9400 } else this.flush(); 9401 }); 9402 if (useCharData) this.onCharData = (e) => { 9403 this.queue.push({ 9404 target: e.target, 9405 type: "characterData", 9406 oldValue: e.prevValue 9407 }); 9408 this.flushSoon(); 9409 }; 9410 this.onSelectionChange = this.onSelectionChange.bind(this); 9411 } 9412 flushSoon() { 9413 if (this.flushingSoon < 0) this.flushingSoon = window.setTimeout(() => { 9414 this.flushingSoon = -1; 9415 this.flush(); 9416 }, 20); 9417 } 9418 forceFlush() { 9419 if (this.flushingSoon > -1) { 9420 window.clearTimeout(this.flushingSoon); 9421 this.flushingSoon = -1; 9422 this.flush(); 9423 } 9424 } 9425 start() { 9426 if (this.observer) { 9427 this.observer.takeRecords(); 9428 this.observer.observe(this.view.dom, observeOptions); 9429 } 9430 if (this.onCharData) this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData); 9431 this.connectSelection(); 9432 } 9433 stop() { 9434 if (this.observer) { 9435 let take = this.observer.takeRecords(); 9436 if (take.length) { 9437 for (let i$1 = 0; i$1 < take.length; i$1++) this.queue.push(take[i$1]); 9438 window.setTimeout(() => this.flush(), 20); 9439 } 9440 this.observer.disconnect(); 9441 } 9442 if (this.onCharData) this.view.dom.removeEventListener("DOMCharacterDataModified", this.onCharData); 9443 this.disconnectSelection(); 9444 } 9445 connectSelection() { 9446 this.view.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange); 9447 } 9448 disconnectSelection() { 9449 this.view.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange); 9450 } 9451 suppressSelectionUpdates() { 9452 this.suppressingSelectionUpdates = true; 9453 setTimeout(() => this.suppressingSelectionUpdates = false, 50); 9454 } 9455 onSelectionChange() { 9456 if (!hasFocusAndSelection(this.view)) return; 9457 if (this.suppressingSelectionUpdates) return selectionToDOM(this.view); 9458 if (ie$2 && ie_version <= 11 && !this.view.state.selection.empty) { 9459 let sel = this.view.domSelectionRange(); 9460 if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) return this.flushSoon(); 9461 } 9462 this.flush(); 9463 } 9464 setCurSelection() { 9465 this.currentSelection.set(this.view.domSelectionRange()); 9466 } 9467 ignoreSelectionChange(sel) { 9468 if (!sel.focusNode) return true; 9469 let ancestors = /* @__PURE__ */ new Set(), container; 9470 for (let scan = sel.focusNode; scan; scan = parentNode(scan)) ancestors.add(scan); 9471 for (let scan = sel.anchorNode; scan; scan = parentNode(scan)) if (ancestors.has(scan)) { 9472 container = scan; 9473 break; 9474 } 9475 let desc = container && this.view.docView.nearestDesc(container); 9476 if (desc && desc.ignoreMutation({ 9477 type: "selection", 9478 target: container.nodeType == 3 ? container.parentNode : container 9479 })) { 9480 this.setCurSelection(); 9481 return true; 9482 } 9483 } 9484 pendingRecords() { 9485 if (this.observer) for (let mut of this.observer.takeRecords()) this.queue.push(mut); 9486 return this.queue; 9487 } 9488 flush() { 9489 let { view } = this; 9490 if (!view.docView || this.flushingSoon > -1) return; 9491 let mutations = this.pendingRecords(); 9492 if (mutations.length) this.queue = []; 9493 let sel = view.domSelectionRange(); 9494 let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel); 9495 let from = -1, to = -1, typeOver = false, added = []; 9496 if (view.editable) for (let i$1 = 0; i$1 < mutations.length; i$1++) { 9497 let result = this.registerMutation(mutations[i$1], added); 9498 if (result) { 9499 from = from < 0 ? result.from : Math.min(result.from, from); 9500 to = to < 0 ? result.to : Math.max(result.to, to); 9501 if (result.typeOver) typeOver = true; 9502 } 9503 } 9504 if (added.some((n) => n.nodeName == "BR") && (view.input.lastKeyCode == 8 || view.input.lastKeyCode == 46 || chrome && (view.composing || view.input.compositionEndedAt > Date.now() - 50) && mutations.some((m) => m.type == "childList" && m.removedNodes.length))) { 9505 for (let node of added) if (node.nodeName == "BR" && node.parentNode) { 9506 let after = node.nextSibling; 9507 while (after && after.nodeType == 1) { 9508 if (after.contentEditable == "false") { 9509 node.parentNode.removeChild(node); 9510 break; 9511 } 9512 after = after.firstChild; 9513 } 9514 } 9515 } else if (gecko && added.length) { 9516 let brs = added.filter((n) => n.nodeName == "BR"); 9517 if (brs.length == 2) { 9518 let [a, b] = brs; 9519 if (a.parentNode && a.parentNode.parentNode == b.parentNode) b.remove(); 9520 else a.remove(); 9521 } else { 9522 let { focusNode } = this.currentSelection; 9523 for (let br of brs) { 9524 let parent = br.parentNode; 9525 if (parent && parent.nodeName == "LI" && (!focusNode || blockParent(view, focusNode) != parent)) br.remove(); 9526 } 9527 } 9528 } 9529 let readSel = null; 9530 if (from < 0 && newSel && view.input.lastFocus > Date.now() - 200 && Math.max(view.input.lastTouch, view.input.last
9530Click.time) < Date.now() - 300 && selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) && readSel.eq(Selection$1.near(view.state.doc.resolve(0), 1))) { 9531 view.input.lastFocus = 0; 9532 selectionToDOM(view); 9533 this.currentSelection.set(sel); 9534 view.scrollToSelection(); 9535 } else if (from > -1 || newSel) { 9536 if (from > -1) { 9537 view.docView.markDirty(from, to); 9538 checkCSS(view); 9539 } 9540 if (view.input.badSafariComposition) { 9541 view.input.badSafariComposition = false; 9542 fixUpBadSafariComposition(view, added); 9543 } 9544 this.handleDOMChange(from, to, typeOver, added); 9545 if (view.docView && view.docView.dirty) view.updateState(view.state); 9546 else if (!this.currentSelection.eq(sel)) selectionToDOM(view); 9547 this.currentSelection.set(sel); 9548 } 9549 } 9550 registerMutation(mut, added) { 9551 if (added.indexOf(mut.target) > -1) return null; 9552 let desc = this.view.docView.nearestDesc(mut.target); 9553 if (mut.type == "attributes" && (desc == this.view.docView || mut.attributeName == "contenteditable" || mut.attributeName == "style" && !mut.oldValue && !mut.target.getAttribute("style"))) return null; 9554 if (!desc || desc.ignoreMutation(mut)) return null; 9555 if (mut.type == "childList") { 9556 for (let i$1 = 0; i$1 < mut.addedNodes.length; i$1++) { 9557 let node = mut.addedNodes[i$1]; 9558 added.push(node); 9559 if (node.nodeType == 3) this.lastChangedTextNode = node; 9560 } 9561 if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target)) return { 9562 from: desc.posBefore, 9563 to: desc.posAfter 9564 }; 9565 let prev = mut.previousSibling, next = mut.nextSibling; 9566 if (ie$2 && ie_version <= 11 && mut.addedNodes.length) for (let i$1 = 0; i$1 < mut.addedNodes.length; i$1++) { 9567 let { previousSibling, nextSibling } = mut.addedNodes[i$1]; 9568 if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0) prev = previousSibling; 9569 if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0) next = nextSibling; 9570 } 9571 let fromOffset = prev && prev.parentNode == mut.target ? domIndex(prev) + 1 : 0; 9572 let from = desc.localPosFromDOM(mut.target, fromOffset, -1); 9573 let toOffset = next && next.parentNode == mut.target ? domIndex(next) : mut.target.childNodes.length; 9574 return { 9575 from, 9576 to: desc.localPosFromDOM(mut.target, toOffset, 1) 9577 }; 9578 } else if (mut.type == "attributes") return { 9579 from: desc.posAtStart - desc.border, 9580 to: desc.posAtEnd + desc.border 9581 }; 9582 else { 9583 this.lastChangedTextNode = mut.target; 9584 return { 9585 from: desc.posAtStart, 9586 to: desc.posAtEnd, 9587 typeOver: mut.target.nodeValue == mut.oldValue 9588 }; 9589 } 9590 } 9591}; 9592var cssChecked = /* @__PURE__ */ new WeakMap(); 9593var cssCheckWarned = false; 9594function checkCSS(view) { 9595 if (cssChecked.has(view)) return; 9596 cssChecked.set(view, null); 9597 if ([ 9598 "normal", 9599 "nowrap", 9600 "pre-line" 9601 ].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) { 9602 view.requiresGeckoHackNode = gecko; 9603 if (cssCheckWarned) return; 9604 console["warn"]("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package."); 9605 cssCheckWarned = true; 9606 } 9607} 9608function rangeToSelectionRange(view, range) { 9609 let anchorNode = range.startContainer, anchorOffset = range.startOffset; 9610 let focusNode = range.endContainer, focusOffset = range.endOffset; 9611 let currentAnchor = view.domAtPos(view.state.selection.anchor); 9612 if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset)) [anchorNode, anchorOffset, focusNode, focusOffset] = [ 9613 focusNode, 9614 focusOffset, 9615 anchorNode, 9616 anchorOffset 9617 ]; 9618 return { 9619 anchorNode, 9620 anchorOffset, 9621 focusNode, 9622 focusOffset 9623 }; 9624} 9625function safariShadowSelectionRange(view, selection) { 9626 if (selection.getComposedRanges) { 9627 let range = selection.getComposedRanges(view.root)[0]; 9628 if (range) return rangeToSelectionRange(view, range); 9629 } 9630 let found$1; 9631 function read(event) { 9632 event.preventDefault(); 9633 event.stopImmediatePropagation(); 9634 found$1 = event.getTargetRanges()[0]; 9635 } 9636 view.dom.addEventListener("beforeinput", read, true); 9637 document.execCommand("indent"); 9638 view.dom.removeEventListener("beforeinput", read, true);
vendor: 5,562 bytes, lines 9639-9769
9639 return found$1 ? rangeToSelectionRange(view, found$1) : null; 9640} 9641function blockParent(view, node) { 9642 for (let p = node.parentNode; p && p != view.dom; p = p.parentNode) { 9643 let desc = view.docView.nearestDesc(p, true); 9644 if (desc && desc.node.isBlock) return p; 9645 } 9646 return null; 9647} 9648function fixUpBadSafariComposition(view, addedNodes) { 9649 var _a; 9650 let { focusNode, focusOffset } = view.domSelectionRange(); 9651 for (let node of addedNodes) if (((_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.nodeName) == "TR") { 9652 let nextCell = node.nextSibling; 9653 while (nextCell && nextCell.nodeName != "TD" && nextCell.nodeName != "TH") nextCell = nextCell.nextSibling; 9654 if (nextCell) { 9655 let parent = nextCell; 9656 for (;;) { 9657 let first$1 = parent.firstChild; 9658 if (!first$1 || first$1.nodeType != 1 || first$1.contentEditable == "false" || /^(BR|IMG)$/.test(first$1.nodeName)) break; 9659 parent = first$1; 9660 } 9661 parent.insertBefore(node, parent.firstChild); 9662 if (focusNode == node) view.domSelection().collapse(node, focusOffset); 9663 } else node.parentNode.removeChild(node); 9664 } 9665} 9666function parseBetween(view, from_, to_, addedNodes) { 9667 let { node: parent, fromOffset, toOffset, from, to } = view.docView.parseRange(from_, to_); 9668 let domSel = view.domSelectionRange(); 9669 let find$1; 9670 let anchor = domSel.anchorNode; 9671 if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) { 9672 find$1 = [{ 9673 node: anchor, 9674 offset: domSel.anchorOffset 9675 }]; 9676 if (!selectionCollapsed(domSel)) find$1.push({ 9677 node: domSel.focusNode, 9678 offset: domSel.focusOffset 9679 }); 9680 } 9681 if (chrome && view.input.lastKeyCode === 8) for (let off = toOffset; off > fromOffset; off--) { 9682 let node = parent.childNodes[off - 1], desc = node.pmViewDesc; 9683 if (node.nodeName == "BR" && !desc) { 9684 toOffset = off; 9685 break; 9686 } 9687 if (!desc || desc.size) break; 9688 } 9689 let startDoc = view.state.doc; 9690 let parser = view.someProp("domParser") || DOMParser.fromSchema(view.state.schema); 9691 let $from = startDoc.resolve(from); 9692 let sel = null, doc$2 = parser.parse(parent, { 9693 topNode: $from.parent, 9694 topMatch: $from.parent.contentMatchAt($from.index()), 9695 topOpen: true, 9696 from: fromOffset, 9697 to: toOffset, 9698 preserveWhitespace: $from.parent.type.whitespace == "pre" ? "full" : true, 9699 findPositions: find$1, 9700 ruleFromNode: ruleFromNode(addedNodes), 9701 context: $from 9702 }); 9703 if (find$1 && find$1[0].pos != null) { 9704 let anchor$1 = find$1[0].pos, head = find$1[1] && find$1[1].pos; 9705 if (head == null) head = anchor$1; 9706 sel = { 9707 anchor: anchor$1 + from, 9708 head: head + from 9709 }; 9710 } 9711 return { 9712 doc: doc$2, 9713 sel, 9714 from, 9715 to 9716 }; 9717} 9718var ruleFromNode = (added) => (dom) => { 9719 let desc = dom.pmViewDesc; 9720 if (desc) return desc.parseRule(added); 9721 else if (dom.nodeName == "BR" && dom.parentNode) { 9722 if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) { 9723 let skip = document.createElement("div"); 9724 skip.appendChild(document.createElement("li")); 9725 return { skip }; 9726 } else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) return { ignore: true }; 9727 } else if (dom.nodeName == "IMG" && dom.getAttribute("mark-placeholder")) return { ignore: true }; 9728 return null; 9729}; 9730var isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i; 9731function readDOMChange(view, from, to, typeOver, addedNodes) { 9732 let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0); 9733 view.input.compositionPendingChanges = 0; 9734 if (from < 0) { 9735 let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null; 9736 let newSel = selectionFromDOM(view, origin); 9737 if (newSel && !view.state.selection.eq(newSel)) { 9738 if (chrome && android && view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) return; 9739 let tr$1 = view.state.tr.setSelection(newSel); 9740 if (origin == "pointer") tr$1.setMeta("pointer", true); 9741 else if (origin == "key") tr$1.scrollIntoView(); 9742 if (compositionID) tr$1.setMeta("composition", compositionID); 9743 view.dispatch(tr$1); 9744 } 9745 return; 9746 } 9747 let $before = view.state.doc.resolve(from); 9748 let shared = $before.sharedDepth(to); 9749 from = $before.before(shared + 1); 9750 to = view.state.doc.resolve(to).after(shared + 1); 9751 let sel = view.state.selection; 9752 let parse = parseBetween(view, from, to, addedNodes); 9753 let doc$2 = view.state.doc, compare = doc$2.slice(parse.from, parse.to); 9754 let preferredPos, preferredSide; 9755 if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) { 9756 preferredPos = view.state.selection.to; 9757 preferredSide = "end"; 9758 } else { 9759 preferredPos = view.state.selection.from; 9760 preferredSide = "start"; 9761 } 9762 view.input.lastKeyCode = null; 9763 let change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide); 9764 if (change) view.input.domChangeCount++; 9765 if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) && addedNodes.some((n) => n.nodeType == 1 && !isInline.test(n.nodeName)) && (!change || change.endA >= change.endB) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) { 9766 view.input.lastIOSEnter = 0; 9767 return; 9768 } 9769 if (!change) if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) && !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)
vendor: 4,910 bytes, lines 9769-9853
9769) change = { 9770 start: sel.from, 9771 endA: sel.to, 9772 endB: sel.to 9773 }; 9774 else { 9775 if (parse.sel) { 9776 let sel$1 = resolveSelection(view, view.state.doc, parse.sel); 9777 if (sel$1 && !sel$1.eq(view.state.selection)) { 9778 let tr$1 = view.state.tr.setSelection(sel$1); 9779 if (compositionID) tr$1.setMeta("composition", compositionID); 9780 view.dispatch(tr$1); 9781 } 9782 } 9783 return; 9784 } 9785 if (view.state.selection.from < view.state.selection.to && change.start == change.endB && view.state.selection instanceof TextSelection) { 9786 if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 && view.state.selection.from >= parse.from) change.start = view.state.selection.from; 9787 else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 && view.state.selection.to <= parse.to) { 9788 change.endB += view.state.selection.to - change.endA; 9789 change.endA = view.state.selection.to; 9790 } 9791 } 9792 if (ie$2 && ie_version <= 11 && change.endB == change.start + 1 && change.endA == change.start && change.start > parse.from && parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == " \xA0") { 9793 change.start--; 9794 change.endA--; 9795 change.endB--; 9796 } 9797 let $from = parse.doc.resolveNoCache(change.start - parse.from); 9798 let $to = parse.doc.resolveNoCache(change.endB - parse.from); 9799 let $fromA = doc$2.resolve(change.start); 9800 let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA; 9801 if ((ios && view.input.lastIOSEnter > Date.now() - 225 && (!inlineChange || addedNodes.some((n) => n.nodeName == "DIV" || n.nodeName == "P")) || !inlineChange && $from.pos < parse.doc.content.size && (!$from.sameParent($to) || !$from.parent.inlineContent) && $from.pos < $to.pos && !/\S/.test(parse.doc.textBetween($from.pos, $to.pos, "", ""))) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) { 9802 view.input.lastIOSEnter = 0; 9803 return; 9804 } 9805 if (view.state.selection.anchor > change.start && looksLikeBackspace(doc$2, change.start, change.endA, $from, $to) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace")))) { 9806 if (android && chrome) view.domObserver.suppressSelectionUpdates(); 9807 return; 9808 } 9809 if (chrome && change.endB == change.start) view.input.lastChromeDelete = Date.now(); 9810 if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth && parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) { 9811 change.endB -= 2; 9812 $to = parse.doc.resolveNoCache(change.endB - parse.from); 9813 setTimeout(() => { 9814 view.someProp("handleKeyDown", function(f) { 9815 return f(view, keyEvent(13, "Enter")); 9816 }); 9817 }, 20); 9818 } 9819 let chFrom = change.start, chTo = change.endA; 9820 let mkTr = (base$1) => { 9821 let tr$1 = base$1 || view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from)); 9822 if (parse.sel) { 9823 let sel$1 = resolveSelection(view, tr$1.doc, parse.sel); 9824 if (sel$1 && !(chrome && view.composing && sel$1.empty && (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) && (sel$1.head == chFrom || sel$1.head == tr$1.mapping.map(chTo) - 1) || ie$2 && sel$1.empty && sel$1.head == chFrom)) tr$1.setSelection(sel$1); 9825 } 9826 if (compositionID) tr$1.setMeta("composition", compositionID); 9827 return tr$1.scrollIntoView(); 9828 }; 9829 let markChange; 9830 if (inlineChange) if ($from.pos == $to.pos) { 9831 if (ie$2 && ie_version <= 11 && $from.parentOffset == 0) { 9832 view.domObserver.suppressSelectionUpdates(); 9833 setTimeout(() => selectionToDOM(view), 20); 9834 } 9835 let tr$1 = mkTr(view.state.tr.delete(chFrom, chTo)); 9836 let marks = doc$2.resolve(change.start).marksAcross(doc$2.resolve(change.endA)); 9837 if (marks) tr$1.ensureMarks(marks); 9838 view.dispatch(tr$1); 9839 } else if (change.endA == change.endB && (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())))) { 9840 let tr$1 = mkTr(view.state.tr); 9841 if (markChange.type == "add") tr$1.addMark(chFrom, chTo, markChange.mark); 9842 else tr$1.removeMark(chFrom, chTo, markChange.mark); 9843 view.dispatch(tr$1); 9844 } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) { 9845 let text$1 = $from.parent.textBetween($from.parentOffset, $to.parentOffset); 9846 let deflt = () => mkTr(view.state.tr.insertText(text$1, chFrom, chTo)); 9847 if (!view.someProp("handleTextInput", (f) => f(view, chFrom, chTo, text$1, deflt))) view.dispatch(deflt()); 9848 } else view.dispatch(mkTr()); 9849 else view.dispatch(mkTr()); 9850} 9851function resolveSelection(view, doc$2, parsedSel) { 9852 if (Math.max(parsedSel.anchor, parsedSel.head) > doc$2.content.size) return null; 9853 return selectionBetween(view, doc$2.resolve(parsedSel.anchor), doc$2.resolve(parsedSel.head)
vendor: 5,050 bytes, lines 9853-9997
9853); 9854} 9855function isMarkChange(cur, prev) { 9856 let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks; 9857 let added = curMarks, removed$1 = prevMarks, type, mark, update; 9858 for (let i$1 = 0; i$1 < prevMarks.length; i$1++) added = prevMarks[i$1].removeFromSet(added); 9859 for (let i$1 = 0; i$1 < curMarks.length; i$1++) removed$1 = curMarks[i$1].removeFromSet(removed$1); 9860 if (added.length == 1 && removed$1.length == 0) { 9861 mark = added[0]; 9862 type = "add"; 9863 update = (node) => node.mark(mark.addToSet(node.marks)); 9864 } else if (added.length == 0 && removed$1.length == 1) { 9865 mark = removed$1[0]; 9866 type = "remove"; 9867 update = (node) => node.mark(mark.removeFromSet(node.marks)); 9868 } else return null; 9869 let updated = []; 9870 for (let i$1 = 0; i$1 < prev.childCount; i$1++) updated.push(update(prev.child(i$1))); 9871 if (Fragment.from(updated).eq(cur)) return { 9872 mark, 9873 type 9874 }; 9875} 9876function looksLikeBackspace(old, start, end, $newStart, $newEnd) { 9877 if (end - start <= $newEnd.pos - $newStart.pos || skipClosingAndOpening($newStart, true, false) < $newEnd.pos) return false; 9878 let $start = old.resolve(start); 9879 if (!$newStart.parent.isTextblock) { 9880 let after = $start.nodeAfter; 9881 return after != null && end == start + after.nodeSize; 9882 } 9883 if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock) return false; 9884 let $next = old.resolve(skipClosingAndOpening($start, true, true)); 9885 if (!$next.parent.isTextblock || $next.pos > end || skipClosingAndOpening($next, true, false) < end) return false; 9886 return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content); 9887} 9888function skipClosingAndOpening($pos, fromEnd, mayOpen) { 9889 let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos; 9890 while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) { 9891 depth--; 9892 end++; 9893 fromEnd = false; 9894 } 9895 if (mayOpen) { 9896 let next = $pos.node(depth).maybeChild($pos.indexAfter(depth)); 9897 while (next && !next.isLeaf) { 9898 next = next.firstChild; 9899 end++; 9900 } 9901 } 9902 return end; 9903} 9904function findDiff(a, b, pos, preferredPos, preferredSide) { 9905 let start = a.findDiffStart(b, pos), lenA = pos + a.size, lenB = pos + b.size; 9906 if (start == null) return null; 9907 let { a: endA, b: endB } = a.findDiffEnd(b, lenA, lenB); 9908 if (preferredSide == "end") { 9909 let adjust = Math.max(0, start - Math.min(endA, endB)); 9910 preferredPos -= endA + adjust - start; 9911 } 9912 if (endA < start && lenA < lenB) { 9913 let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0; 9914 start -= move; 9915 endB = start + (endB - endA); 9916 endA = start; 9917 } else if (endB < start) { 9918 let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0; 9919 start -= move; 9920 endA = start + (endA - endB); 9921 endB = start; 9922 } 9923 return { 9924 start, 9925 endA, 9926 endB 9927 }; 9928} 9929var EditorView = class { 9930 constructor(place, props) { 9931 this._root = null; 9932 this.focused = false; 9933 this.trackWrites = null; 9934 this.mounted = false; 9935 this.markCursor = null; 9936 this.cursorWrapper = null; 9937 this.lastSelectedViewDesc = void 0; 9938 this.input = new InputState(); 9939 this.prevDirectPlugins = []; 9940 this.pluginViews = []; 9941 this.requiresGeckoHackNode = false; 9942 this.dragging = null; 9943 this._props = props; 9944 this.state = props.state; 9945 this.directPlugins = props.plugins || []; 9946 this.directPlugins.forEach(checkStateComponent); 9947 this.dispatch = this.dispatch.bind(this); 9948 this.dom = place && place.mount || document.createElement("div"); 9949 if (place) { 9950 if (place.appendChild) place.appendChild(this.dom); 9951 else if (typeof place == "function") place(this.dom); 9952 else if (place.mount) this.mounted = true; 9953 } 9954 this.editable = getEditable(this); 9955 updateCursorWrapper(this); 9956 this.nodeViews = buildNodeViews(this); 9957 this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this); 9958 this.domObserver = new DOMObserver(this, (from, to, typeOver, added) => readDOMChange(this, from, to, typeOver, added)); 9959 this.domObserver.start(); 9960 initInput(this); 9961 this.updatePluginViews(); 9962 } 9963 get composing() { 9964 return this.input.composing; 9965 } 9966 get props() { 9967 if (this._props.state != this.state) { 9968 let prev = this._props; 9969 this._props = {}; 9970 for (let name in prev) this._props[name] = prev[name]; 9971 this._props.state = this.state; 9972 } 9973 return this._props; 9974 } 9975 update(props) { 9976 if (props.handleDOMEvents != this._props.handleDOMEvents) ensureListeners(this); 9977 let prevProps = this._props; 9978 this._props = props; 9979 if (props.plugins) { 9980 props.plugins.forEach(checkStateComponent); 9981 this.directPlugins = props.plugins; 9982 } 9983 this.updateStateInner(props.state, prevProps); 9984 } 9985 setProps(props) { 9986 let updated = {}; 9987 for (let name in this._props) updated[name] = this._props[name]; 9988 updated.state = this.state; 9989 for (let name in props) updated[name] = props[name]; 9990 this.update(updated); 9991 } 9992 updateState(state) { 9993 this.updateStateInner(state, this._props); 9994 } 9995 updateStateInner(state, prevProps) { 9996 var _a; 9997 let prev = this.state, redraw = false, updateSel = false;
9998 if (state.storedMarks && this.composing) { 9999 clearComposition(this); 10000 updateSel = true; 10001 } 10002 this.state = state; 10003 let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins; 10004 if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) { 10005 let nodeViews = buildNodeViews(this); 10006 if (changedNodeViews(nodeViews, this.nodeViews)) { 10007 this.nodeViews = nodeViews; 10008 redraw = true; 10009 } 10010 } 10011 if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) ensureListeners(this); 10012 this.editable = getEditable(this); 10013 updateCursorWrapper(this); 10014 let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this); 10015 let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? "reset" : state.scrollToSelection > prev.scrollToSelection ? "to selection" : "preserve"; 10016 let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco); 10017 if (updateDoc || !state.selection.eq(prev.selection)) updateSel = true; 10018 let oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this); 10019 if (updateSel) { 10020 this.domObserver.stop(); 10021 let forceSelUpdate = updateDoc && (ie$2 || chrome) && !this.composing && !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection); 10022 if (updateDoc) { 10023 let chromeKludge = chrome ? this.trackWrites = this.domSelectionRange().focusNode : null; 10024 if (this.composing) this.input.compositionNode = findCompositionNode(this); 10025 if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) { 10026 this.docView.updateOuterDeco(outerDeco); 10027 this.docView.destroy(); 10028 this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this); 10029 } 10030 if (chromeKludge && (!this.trackWrites || !this.dom.contains(this.trackWrites))) forceSelUpdate = true; 10031 } 10032 let mouseDown = this.input.mouseDown; 10033 if (forceSelUpdate || !(mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) && anchorInRightPlace(this) && mouseDown.delaySelUpdate())) selectionToDOM(this, forceSelUpdate); 10034 else { 10035 syncNodeSelection(this, state.selection); 10036 this.domObserver.setCurSelection(); 10037 } 10038 this.domObserver.start(); 10039 } 10040 this.updatePluginViews(prev); 10041 if (((_a = this.dragging) === null || _a === void 0 ? void 0 : _a.node) && !prev.doc.eq(state.doc)) this.updateDraggedNode(this.dragging, prev); 10042 if (scroll == "reset") this.dom.scrollTop = 0; 10043 else if (scroll == "to selection") this.scrollToSelection(); 10044 else if (oldScrollPos) resetScrollPos(oldScrollPos); 10045 } 10046 scrollToSelection() { 10047 let startDOM = this.domSelectionRange().focusNode; 10048 if (!startDOM || !this.dom.contains(startDOM.nodeType == 1 ? startDOM : startDOM.parentNode)); 10049 else if (this.someProp("handleScrollToSelection", (f) => f(this))); 10050 else if (this.state.selection instanceof NodeSelection) { 10051 let target = this.docView.domAfterPos(this.state.selection.from); 10052 if (target.nodeType == 1) scrollRectIntoView(this, target.getBoundingClientRect(), startDOM); 10053 } else scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM); 10054 } 10055 destroyPluginViews() { 10056 let view; 10057 while (view = this.pluginViews.pop()) if (view.destroy) view.destroy(); 10058 } 10059 updatePluginViews(prevState) { 10060 if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) { 10061 this.prevDirectPlugins = this.directPlugins; 10062 this.destroyPluginViews(); 10063 for (let i$1 = 0; i$1 < this.directPlugins.length; i$1++) { 10064 let plugin = this.directPlugins[i$1]; 10065 if (plugin.spec.view) this.pluginViews.push(plugin.spec.view(this)); 10066 } 10067 for (let i$1 = 0; i$1 < this.state.plugins.length; i$1++) { 10068 let plugin = this.state.plugins[i$1]; 10069 if (plugin.spec.view) this.pluginViews.push(plugin.spec.view(this)); 10070 } 10071 } else for (let i$1 = 0; i$1 < this.pluginViews.length; i$1++) { 10072 let pluginView = this.pluginViews[i$1]; 10073 if (pluginView.update) pluginView.update(this, prevState); 10074 } 10075 } 10076 updateDraggedNode(dragging, prev) { 10077 let sel = dragging.node, found$1 = -1;
10078 if (sel.from < this.state.doc.content.size && this.state.doc.nodeAt(sel.from) == sel.node) found$1 = sel.from; 10079 else { 10080 let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size); 10081 if ((movedPos > 0 && movedPos < this.state.doc.content.size && this.state.doc.nodeAt(movedPos)) == sel.node) found$1 = movedPos; 10082 } 10083 this.dragging = new Dragging(dragging.slice, dragging.move, found$1 < 0 ? void 0 : NodeSelection.create(this.state.doc, found$1)); 10084 } 10085 someProp(propName, f) { 10086 let prop = this._props && this._props[propName], value; 10087 if (prop != null && (value = f ? f(prop) : prop)) return value; 10088 for (let i$1 = 0; i$1 < this.directPlugins.length; i$1++) { 10089 let prop$1 = this.directPlugins[i$1].props[propName]; 10090 if (prop$1 != null && (value = f ? f(prop$1) : prop$1)) return value; 10091 } 10092 let plugins = this.state.plugins; 10093 if (plugins) for (let i$1 = 0; i$1 < plugins.length; i$1++) { 10094 let prop$1 = plugins[i$1].props[propName]; 10095 if (prop$1 != null && (value = f ? f(prop$1) : prop$1)) return value; 10096 } 10097 } 10098 hasFocus() { 10099 if (ie$2) { 10100 let node = this.root.activeElement; 10101 if (node == this.dom) return true; 10102 if (!node || !this.dom.contains(node)) return false; 10103 while (node && this.dom != node && this.dom.contains(node)) { 10104 if (node.contentEditable == "false") return false; 10105 node = node.parentElement; 10106 } 10107 return true; 10108 } 10109 return this.root.activeElement == this.dom; 10110 } 10111 focus() { 10112 this.domObserver.stop(); 10113 if (this.editable) focusPreventScroll(this.dom); 10114 selectionToDOM(this); 10115 this.domObserver.start(); 10116 } 10117 get root() { 10118 let cached = this._root; 10119 if (cached == null) { 10120 for (let search = this.dom.parentNode; search; search = search.parentNode) if (search.nodeType == 9 || search.nodeType == 11 && search.host) { 10121 if (!search.getSelection) Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection(); 10122 return this._root = search; 10123 } 10124 } 10125 return cached || document; 10126 } 10127 updateRoot() { 10128 this._root = null; 10129 } 10130 posAtCoords(coords) { 10131 return posAtCoords(this, coords); 10132 } 10133 coordsAtPos(pos, side = 1) { 10134 return coordsAtPos(this, pos, side); 10135 } 10136 domAtPos(pos, side = 0) { 10137 return this.docView.domFromPos(pos, side); 10138 } 10139 nodeDOM(pos) { 10140 let desc = this.docView.descAt(pos); 10141 return desc ? desc.nodeDOM : null; 10142 } 10143 posAtDOM(node, offset, bias = -1) { 10144 let pos = this.docView.posFromDOM(node, offset, bias); 10145 if (pos == null) throw new RangeError("DOM position not inside the editor"); 10146 return pos; 10147 } 10148 endOfTextblock(dir, state) { 10149 return endOfTextblock(this, state || this.state, dir); 10150 } 10151 pasteHTML(html$2, event) { 10152 return doPaste(this, "", html$2, false, event || new ClipboardEvent("paste")); 10153 } 10154 pasteText(text$1, event) { 10155 return doPaste(this, text$1, null, true, event || new ClipboardEvent("paste")); 10156 } 10157 serializeForClipboard(slice) { 10158 return serializeForClipboard(this, slice); 10159 } 10160 destroy() { 10161 if (!this.docView) return; 10162 destroyInput(this); 10163 this.destroyPluginViews(); 10164 if (this.mounted) { 10165 this.docView.update(this.state.doc, [], viewDecorations(this), this); 10166 this.dom.textContent = ""; 10167 } else if (this.dom.parentNode) this.dom.parentNode.removeChild(this.dom); 10168 this.docView.destroy(); 10169 this.docView = null; 10170 clearReusedRange(); 10171 } 10172 get isDestroyed() { 10173 return this.docView == null; 10174 } 10175 dispatchEvent(event) {
vendor: 9,605 bytes, lines 10176-10498
10176 return dispatchEvent(this, event); 10177 } 10178 domSelectionRange() { 10179 let sel = this.domSelection(); 10180 if (!sel) return { 10181 focusNode: null, 10182 focusOffset: 0, 10183 anchorNode: null, 10184 anchorOffset: 0 10185 }; 10186 return safari && this.root.nodeType === 11 && deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel; 10187 } 10188 domSelection() { 10189 return this.root.getSelection(); 10190 } 10191}; 10192EditorView.prototype.dispatch = function(tr$1) { 10193 let dispatchTransaction = this._props.dispatchTransaction; 10194 if (dispatchTransaction) dispatchTransaction.call(this, tr$1); 10195 else this.updateState(this.state.apply(tr$1)); 10196}; 10197function computeDocDeco(view) { 10198 let attrs = Object.create(null); 10199 attrs.class = "ProseMirror"; 10200 attrs.contenteditable = String(view.editable); 10201 view.someProp("attributes", (value) => { 10202 if (typeof value == "function") value = value(view.state); 10203 if (value) { 10204 for (let attr in value) if (attr == "class") attrs.class += " " + value[attr]; 10205 else if (attr == "style") attrs.style = (attrs.style ? attrs.style + ";" : "") + value[attr]; 10206 else if (!attrs[attr] && attr != "contenteditable" && attr != "nodeName") attrs[attr] = String(value[attr]); 10207 } 10208 }); 10209 if (!attrs.translate) attrs.translate = "no"; 10210 return [Decoration.node(0, view.state.doc.content.size, attrs)]; 10211} 10212function updateCursorWrapper(view) { 10213 if (view.markCursor) { 10214 let dom = document.createElement("img"); 10215 dom.className = "ProseMirror-separator"; 10216 dom.setAttribute("mark-placeholder", "true"); 10217 dom.setAttribute("alt", ""); 10218 view.cursorWrapper = { 10219 dom, 10220 deco: Decoration.widget(view.state.selection.from, dom, { 10221 raw: true, 10222 marks: view.markCursor 10223 }) 10224 }; 10225 } else view.cursorWrapper = null; 10226} 10227function getEditable(view) { 10228 return !view.someProp("editable", (value) => value(view.state) === false); 10229} 10230function selectionContextChanged(sel1, sel2) { 10231 let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head)); 10232 return sel1.$anchor.start(depth) != sel2.$anchor.start(depth); 10233} 10234function buildNodeViews(view) { 10235 let result = Object.create(null); 10236 function add(obj) { 10237 for (let prop in obj) if (!Object.prototype.hasOwnProperty.call(result, prop)) result[prop] = obj[prop]; 10238 } 10239 view.someProp("nodeViews", add); 10240 view.someProp("markViews", add); 10241 return result; 10242} 10243function changedNodeViews(a, b) { 10244 let nA = 0, nB = 0; 10245 for (let prop in a) { 10246 if (a[prop] != b[prop]) return true; 10247 nA++; 10248 } 10249 for (let _ in b) nB++; 10250 return nA != nB; 10251} 10252function checkStateComponent(plugin) { 10253 if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction) throw new RangeError("Plugins passed directly to the view must not have a state component"); 10254} 10255var base = { 10256 8: "Backspace", 10257 9: "Tab", 10258 10: "Enter", 10259 12: "NumLock", 10260 13: "Enter", 10261 16: "Shift", 10262 17: "Control", 10263 18: "Alt", 10264 20: "CapsLock", 10265 27: "Escape", 10266 32: " ", 10267 33: "PageUp", 10268 34: "PageDown", 10269 35: "End", 10270 36: "Home", 10271 37: "ArrowLeft", 10272 38: "ArrowUp", 10273 39: "ArrowRight", 10274 40: "ArrowDown", 10275 44: "PrintScreen", 10276 45: "Insert", 10277 46: "Delete", 10278 59: ";", 10279 61: "=", 10280 91: "Meta", 10281 92: "Meta", 10282 106: "*", 10283 107: "+", 10284 108: ",", 10285 109: "-", 10286 110: ".", 10287 111: "/", 10288 144: "NumLock", 10289 145: "ScrollLock", 10290 160: "Shift", 10291 161: "Shift", 10292 162: "Control", 10293 163: "Control", 10294 164: "Alt", 10295 165: "Alt", 10296 173: "-", 10297 186: ";", 10298 187: "=", 10299 188: ",", 10300 189: "-", 10301 190: ".", 10302 191: "/", 10303 192: "`", 10304 219: "[", 10305 220: "\\", 10306 221: "]", 10307 222: "'" 10308}; 10309var shift = { 10310 48: ")", 10311 49: "!", 10312 50: "@", 10313 51: "#", 10314 52: "$", 10315 53: "%", 10316 54: "^", 10317 55: "&", 10318 56: "*", 10319 57: "(", 10320 59: ":", 10321 61: "+", 10322 173: "_", 10323 186: ":", 10324 187: "+", 10325 188: "<", 10326 189: "_", 10327 190: ">", 10328 191: "?", 10329 192: "~", 10330 219: "{", 10331 220: "|", 10332 221: "}", 10333 222: "\"" 10334}; 10335var mac$1 = typeof navigator != "undefined" && /Mac/.test(navigator.platform); 10336var ie$1 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); 10337for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i); 10338for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i; 10339for (var i = 65; i <= 90; i++) { 10340 base[i] = String.fromCharCode(i + 32); 10341 shift[i] = String.fromCharCode(i); 10342} 10343for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]; 10344function keyName(event) { 10345 var name = !(mac$1 && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie$1 && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified") && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified"; 10346 if (name == "Esc") name = "Escape"; 10347 if (name == "Del") name = "Delete"; 10348 if (name == "Left") name = "ArrowLeft"; 10349 if (name == "Up") name = "ArrowUp"; 10350 if (name == "Right") name = "ArrowRight"; 10351 if (name == "Down") name = "ArrowDown"; 10352 return name; 10353} 10354var mac = typeof navigator != "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform); 10355var windows = typeof navigator != "undefined" && /Win/.test(navigator.platform); 10356function normalizeKeyName$1(name) { 10357 let parts = name.split(/-(?!$)/), result = parts[parts.length - 1]; 10358 if (result == "Space") result = " "; 10359 let alt, ctrl, shift$1, meta; 10360 for (let i$1 = 0; i$1 < parts.length - 1; i$1++) { 10361 let mod = parts[i$1]; 10362 if (/^(cmd|meta|m)$/i.test(mod)) meta = true; 10363 else if (/^a(lt)?$/i.test(mod)) alt = true; 10364 else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; 10365 else if (/^s(hift)?$/i.test(mod)) shift$1 = true; 10366 else if (/^mod$/i.test(mod)) if (mac) meta = true; 10367 else ctrl = true; 10368 else throw new Error("Unrecognized modifier name: " + mod); 10369 } 10370 if (alt) result = "Alt-" + result; 10371 if (ctrl) result = "Ctrl-" + result; 10372 if (meta) result = "Meta-" + result; 10373 if (shift$1) result = "Shift-" + result; 10374 return result; 10375} 10376function normalize(map) { 10377 let copy$1 = Object.create(null); 10378 for (let prop in map) copy$1[normalizeKeyName$1(prop)] = map[prop]; 10379 return copy$1; 10380} 10381function modifiers(name, event, shift$1 = true) { 10382 if (event.altKey) name = "Alt-" + name; 10383 if (event.ctrlKey) name = "Ctrl-" + name; 10384 if (event.metaKey) name = "Meta-" + name; 10385 if (shift$1 && event.shiftKey) name = "Shift-" + name; 10386 return name; 10387} 10388function keymap(bindings) { 10389 return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } }); 10390} 10391function keydownHandler(bindings) { 10392 let map = normalize(bindings); 10393 return function(view, event) { 10394 let name = keyName(event), baseName, direct = map[modifiers(name, event)]; 10395 if (direct && direct(view.state, view.dispatch, view)) return true; 10396 if (name.length == 1 && name != " ") { 10397 if (event.shiftKey) { 10398 let noShift = map[modifiers(name, event, false)]; 10399 if (noShift && noShift(view.state, view.dispatch, view)) return true; 10400 } 10401 if ((event.altKey || event.metaKey || event.ctrlKey) && !(windows && event.ctrlKey && event.altKey) && (baseName = base[event.keyCode]) && baseName != name) { 10402 let fromCode = map[modifiers(baseName, event)]; 10403 if (fromCode && fromCode(view.state, view.dispatch, view)) return true; 10404 } 10405 } 10406 return false; 10407 }; 10408} 10409function createChainableState(config) { 10410 const { state, transaction } = config; 10411 let { selection } = transaction; 10412 let { doc: doc$2 } = transaction; 10413 let { storedMarks } = transaction; 10414 return { 10415 ...state, 10416 apply: state.apply.bind(state), 10417 applyTransaction: state.applyTransaction.bind(state), 10418 plugins: state.plugins, 10419 schema: state.schema, 10420 reconfigure: state.reconfigure.bind(state), 10421 toJSON: state.toJSON.bind(state), 10422 get storedMarks() { 10423 return storedMarks; 10424 }, 10425 get selection() { 10426 return selection; 10427 }, 10428 get doc() { 10429 return doc$2; 10430 }, 10431 get tr() { 10432 selection = transaction.selection; 10433 doc$2 = transaction.doc; 10434 storedMarks = transaction.storedMarks; 10435 return transaction; 10436 } 10437 }; 10438} 10439var CommandManager = class CommandManager$1 { 10440 constructor(props) { 10441 this.editor = props.editor; 10442 this.rawCommands = this.editor.extensionManager.commands; 10443 this.customState = props.state; 10444 } 10445 get hasCustomState() { 10446 return !!this.customState; 10447 } 10448 get state() { 10449 return this.customState || this.editor.state; 10450 } 10451 get commands() { 10452 const { rawCommands, editor, state } = this; 10453 const { view } = editor; 10454 const { tr: tr$1 } = state; 10455 const props = this.buildProps(tr$1); 10456 return Object.fromEntries(Object.entries(rawCommands).map(([name, command$1]) => { 10457 const method = (...args) => { 10458 const callback = command$1(...args)(props); 10459 if (!tr$1.getMeta("preventDispatch") && !this.hasCustomState) view.dispatch(tr$1); 10460 return callback; 10461 }; 10462 return [name, method]; 10463 })); 10464 } 10465 get chain() { 10466 return () => this.createChain(); 10467 } 10468 get can() { 10469 return () => this.createCan(); 10470 } 10471 createChain(startTr, shouldDispatch = true) { 10472 const { rawCommands, editor, state } = this; 10473 const { view } = editor; 10474 const callbacks = []; 10475 const hasStartTransaction = !!startTr; 10476 const tr$1 = startTr || state.tr; 10477 const run$3 = () => { 10478 if (!hasStartTransaction && shouldDispatch && !tr$1.getMeta("preventDispatch") && !this.hasCustomState) view.dispatch(tr$1); 10479 return callbacks.every((callback) => callback === true); 10480 }; 10481 const chain = { 10482 ...Object.fromEntries(Object.entries(rawCommands).map(([name, command$1]) => { 10483 const chainedCommand = (...args) => { 10484 const props = this.buildProps(tr$1, shouldDispatch); 10485 const callback = command$1(...args)(props); 10486 callbacks.push(callback); 10487 return chain; 10488 }; 10489 return [name, chainedCommand]; 10490 })), 10491 run: run$3 10492 }; 10493 return chain; 10494 } 10495 static createFakeChain() { 10496 const chain = new Proxy({}, { get: (_target, property) => { 10497 if (property === "then") return; 10498 if (property === "run") return () => false;
10499 return () => chain; 10500 } }); 10501 return chain; 10502 } 10503 createCan(startTr) { 10504 const { rawCommands, state } = this; 10505 const dispatch = false; 10506 const tr$1 = startTr || state.tr; 10507 const props = this.buildProps(tr$1, dispatch); 10508 return { 10509 ...Object.fromEntries(Object.entries(rawCommands).map(([name, command$1]) => { 10510 return [name, (...args) => command$1(...args)({ 10511 ...props, 10512 dispatch: void 0 10513 })]; 10514 })), 10515 chain: () => this.createChain(tr$1, dispatch) 10516 }; 10517 } 10518 static createFallbackCan() { 10519 const chain = CommandManager$1.createFakeChain(); 10520 return new Proxy({ chain: () => chain }, { get: (target, property) => { 10521 if (property === "then") return; 10522 if (property === "chain") return target.chain; 10523 return () => false; 10524 } }); 10525 } 10526 buildProps(tr$1, shouldDispatch = true) { 10527 const { rawCommands, editor, state } = this; 10528 const { view } = editor; 10529 const props = { 10530 tr: tr$1, 10531 editor, 10532 view, 10533 state: createChainableState({ 10534 state, 10535 transaction: tr$1 10536 }), 10537 dispatch: shouldDispatch ? () => void 0 : void 0, 10538 chain: () => this.createChain(tr$1, shouldDispatch), 10539 can: () => this.createCan(tr$1), 10540 get commands() { 10541 return Object.fromEntries(Object.entries(rawCommands).map(([name, command$1]) => { 10542 return [name, (...args) => command$1(...args)(props)]; 10543 })); 10544 } 10545 }; 10546 return props; 10547 } 10548}; 10549var blur = () => ({ editor, view }) => { 10550 requestAnimationFrame(() => { 10551 if (!editor.isDestroyed) { 10552 var _window; 10553 view.dom.blur(); 10554 (_window = window) === null || _window === void 0 || (_window = _window.getSelection()) === null || _window === void 0 || _window.removeAllRanges(); 10555 } 10556 }); 10557 return true; 10558}; 10559var clearContent = (emitUpdate = true) => ({ commands }) => { 10560 return commands.setContent("", { emitUpdate }); 10561}; 10562var clearNodes = () => ({ state, tr: tr$1, dispatch }) => { 10563 const { selection } = tr$1; 10564 const { ranges } = selection; 10565 if (!dispatch) return true; 10566 ranges.forEach(({ $from, $to }) => { 10567 state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => { 10568 if (node.type.isText) return; 10569 const { doc: doc$2, mapping } = tr$1; 10570 const $mappedFrom = doc$2.resolve(mapping.map(pos)); 10571 const $mappedTo = doc$2.resolve(mapping.map(pos + node.nodeSize)); 10572 const nodeRange = $mappedFrom.blockRange($mappedTo); 10573 if (!nodeRange) return; 10574 const targetLiftDepth = liftTarget(nodeRange); 10575 if (node.type.isTextblock) { 10576 const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index()); 10577 tr$1.setNodeMarkup(nodeRange.start, defaultType); 10578 } 10579 if (targetLiftDepth || targetLiftDepth === 0) tr$1.lift(nodeRange, targetLiftDepth); 10580 }); 10581 }); 10582 return true; 10583}; 10584var command = (fn) => (props) => { 10585 return fn(props); 10586}; 10587var createParagraphNear$1 = () => ({ state, dispatch }) => { 10588 return createParagraphNear(state, dispatch); 10589}; 10590var cut = (originRange, targetPos) => ({ editor, tr: tr$1 }) => { 10591 const { state } = editor; 10592 const contentSlice = state.doc.slice(originRange.from, originRange.to); 10593 tr$1.deleteRange(originRange.from, originRange.to); 10594 const newPos = tr$1.mapping.map(targetPos); 10595 tr$1.insert(newPos, contentSlice.content); 10596 tr$1.setSelection(new TextSelection(tr$1.doc.resolve(Math.max(newPos - 1, 0)))); 10597 return true; 10598}; 10599var deleteCurrentNode = () => ({ tr: tr$1, dispatch }) => { 10600 const { selection } = tr$1; 10601 const currentNode = selection.$anchor.node(); 10602 if (currentNode.content.size > 0) return false; 10603 const $pos = tr$1.selection.$anchor; 10604 for (let depth = $pos.depth; depth > 0; depth -= 1) if ($pos.node(depth).type === currentNode.type) { 10605 if (dispatch) { 10606 const from = $pos.before(depth); 10607 const to = $pos.after(depth); 10608 tr$1.delete(from, to).scrollIntoView(); 10609 } 10610 return true; 10611 } 10612 return false; 10613}; 10614function getNodeType(nameOrType, schema) { 10615 if (typeof nameOrType === "string") { 10616 if (!schema.nodes[nameOrType]) throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`); 10617 return schema.nodes[nameOrType]; 10618 } 10619 return nameOrType; 10620} 10621var deleteNode = (typeOrName) => ({ tr: tr$1, state, dispatch }) => { 10622 const type = getNodeType(typeOrName, state.schema); 10623 const $pos = tr$1.selection.$anchor; 10624 for (let depth = $pos.depth; depth > 0; depth -= 1) if ($pos.node(depth).type === type) {
10625 if (dispatch) { 10626 const from = $pos.before(depth); 10627 const to = $pos.after(depth); 10628 tr$1.delete(from, to).scrollIntoView(); 10629 } 10630 return true; 10631 } 10632 return false; 10633}; 10634var deleteRange = (range) => ({ tr: tr$1, dispatch }) => { 10635 const { from, to } = range; 10636 if (dispatch) tr$1.delete(from, to); 10637 return true; 10638}; 10639var hasTextContent = (nodeSpec) => { 10640 if (!nodeSpec.content) return false; 10641 return /^text(\*|\+)/.test(nodeSpec.content); 10642}; 10643var expandSelectionForSide = ($pos, schema, side) => { 10644 if (!$pos.parent.isInline) return $pos.pos; 10645 if (side === "left" && $pos.pos > $pos.start() || side === "right" && $pos.pos < $pos.end()) return $pos.pos; 10646 const parentContent = schema.nodes[$pos.parent.type.name].spec; 10647 if (!hasTextContent(parentContent)) return $pos.pos; 10648 return side === "left" ? $pos.start() - 1 : $pos.end() + 1; 10649}; 10650var expandSelectionForInlineText = ($from, $to, schema) => { 10651 return { 10652 from: expandSelectionForSide($from, schema, "left"), 10653 to: expandSelectionForSide($to, schema, "right") 10654 }; 10655}; 10656var deleteSelection = () => ({ state, dispatch }) => { 10657 if (state.selection.empty) return false; 10658 if (dispatch) { 10659 const tr$1 = state.tr; 10660 const { ranges } = state.selection; 10661 const mapFrom = tr$1.steps.length; 10662 ranges.forEach((range) => { 10663 const mapping = tr$1.mapping.slice(mapFrom); 10664 const { from, to } = expandSelectionForInlineText(tr$1.doc.resolve(mapping.map(range.$from.pos)), tr$1.doc.resolve(mapping.map(range.$to.pos)), state.schema); 10665 tr$1.deleteRange(from, to); 10666 }); 10667 if (!tr$1.selection.empty) tr$1.setSelection(TextSelection.near(tr$1.doc.resolve(tr$1.selection.from))); 10668 tr$1.scrollIntoView(); 10669 dispatch(tr$1); 10670 } 10671 return true; 10672}; 10673var enter = () => ({ commands }) => { 10674 return commands.keyboardShortcut("Enter"); 10675}; 10676var exitCode$1 = () => ({ state, dispatch }) => { 10677 return exitCode(state, dispatch); 10678}; 10679function isRegExp(value) { 10680 return Object.prototype.toString.call(value) === "[object RegExp]"; 10681} 10682function objectIncludes(object1, object2, options = { strict: true }) { 10683 const keys$1 = Object.keys(object2); 10684 if (!keys$1.length) return true; 10685 return keys$1.every((key) => { 10686 if (options.strict) return object2[key] === object1[key]; 10687 if (isRegExp(object2[key])) return object2[key].test(object1[key]); 10688 return object2[key] === object1[key]; 10689 }); 10690} 10691function findMarkInSet(marks, type, attributes = {}) { 10692 return marks.find((item) => { 10693 return item.type === type && objectIncludes(Object.fromEntries(Object.keys(attributes).map((k) => [k, item.attrs[k]])), attributes); 10694 }); 10695} 10696function isMarkInSet(marks, type, attributes = {}) { 10697 return !!findMarkInSet(marks, type, attributes); 10698} 10699function getMarkRange($pos, type, attributes) { 10700 if (!$pos || !type) return; 10701 let start = $pos.parent.childAfter($pos.parentOffset); 10702 if (!start.node || !start.node.marks.some((mark) => mark.type === type)) start = $pos.parent.childBefore($pos.parentOffset); 10703 if (!start.node || !start.node.marks.some((mark) => mark.type === type)) return; 10704 if (!attributes) { 10705 const firstMark = start.node.marks.find((mark) => mark.type === type); 10706 if (firstMark) attributes = firstMark.attrs; 10707 } 10708 if (!findMarkInSet([...start.node.marks], type, attributes)) return; 10709 let startIndex = start.index; 10710 let startPos = $pos.start() + start.offset; 10711 let endIndex = startIndex + 1; 10712 let endPos = startPos + start.node.nodeSize; 10713 while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) { 10714 startIndex -= 1; 10715 startPos -= $pos.parent.child(startIndex).nodeSize; 10716 } 10717 while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) { 10718 endPos += $pos.parent.child(endIndex).nodeSize; 10719 endIndex += 1; 10720 } 10721 return { 10722 from: startPos, 10723 to: endPos 10724 }; 10725} 10726function getMarkType(nameOrType, schema) { 10727 if (typeof nameOrType === "string") { 10728 if (!schema.marks[nameOrType]) throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`); 10729 return schema.marks[nameOrType]; 10730 } 10731 return nameOrType; 10732} 10733var extendMarkRange = (typeOrName, attributes) => ({ tr: tr$1, state, dispatch }) => { 10734 const type = getMarkType(typeOrName, state.schema); 10735 const { doc: doc$2, selection } = tr$1; 10736 const { $from, from, to } = selection;
vendor: 13,909 bytes, lines 10737-11122
10737 if (dispatch) { 10738 const range = getMarkRange($from, type, attributes); 10739 if (range && range.from <= from && range.to >= to) { 10740 const newSelection = TextSelection.create(doc$2, range.from, range.to); 10741 tr$1.setSelection(newSelection); 10742 } 10743 } 10744 return true; 10745}; 10746var first = (commands) => (props) => { 10747 const items = typeof commands === "function" ? commands(props) : commands; 10748 for (let i$1 = 0; i$1 < items.length; i$1 += 1) if (items[i$1](props)) return true; 10749 return false; 10750}; 10751function isTextSelection(value) { 10752 return value instanceof TextSelection; 10753} 10754function minMax(value = 0, min = 0, max = 0) { 10755 return Math.min(Math.max(value, min), max); 10756} 10757function resolveFocusPosition(doc$2, position = null) { 10758 if (!position) return null; 10759 const selectionAtStart = Selection$1.atStart(doc$2); 10760 const selectionAtEnd = Selection$1.atEnd(doc$2); 10761 if (position === "start" || position === true) return selectionAtStart; 10762 if (position === "end") return selectionAtEnd; 10763 const minPos = selectionAtStart.from; 10764 const maxPos = selectionAtEnd.to; 10765 if (position === "all") return TextSelection.create(doc$2, minMax(0, minPos, maxPos), minMax(doc$2.content.size, minPos, maxPos)); 10766 return TextSelection.create(doc$2, minMax(position, minPos, maxPos), minMax(position, minPos, maxPos)); 10767} 10768function isAndroid() { 10769 return ["Android"].includes(navigator.platform) || /android/i.test(navigator.userAgent); 10770} 10771function isiOS() { 10772 return [ 10773 "iPad Simulator", 10774 "iPhone Simulator", 10775 "iPod Simulator", 10776 "iPad", 10777 "iPhone", 10778 "iPod" 10779 ].includes(navigator.platform) || navigator.userAgent.includes("Mac") && "ontouchend" in document; 10780} 10781function isSafari() { 10782 return typeof navigator !== "undefined" ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false; 10783} 10784var focus = (position = null, options = {}) => ({ editor, view, tr: tr$1, dispatch }) => { 10785 options = { 10786 scrollIntoView: true, 10787 ...options 10788 }; 10789 const delayedFocus = () => { 10790 if (isiOS() || isAndroid()) view.dom.focus(); 10791 if (isSafari() && !isiOS() && !isAndroid()) view.dom.focus({ preventScroll: true }); 10792 requestAnimationFrame(() => { 10793 if (!editor.isDestroyed) { 10794 view.focus(); 10795 if (options === null || options === void 0 ? void 0 : options.scrollIntoView) editor.commands.scrollIntoView(); 10796 } 10797 }); 10798 }; 10799 try { 10800 if (view.hasFocus() && position === null || position === false) return true; 10801 } catch { 10802 return false; 10803 } 10804 if (dispatch && position === null && !isTextSelection(editor.state.selection)) { 10805 delayedFocus(); 10806 return true; 10807 } 10808 const selection = resolveFocusPosition(tr$1.doc, position) || editor.state.selection; 10809 const isSameSelection = editor.state.selection.eq(selection); 10810 if (dispatch) { 10811 if (!isSameSelection) tr$1.setSelection(selection); 10812 if (isSameSelection && tr$1.storedMarks) tr$1.setStoredMarks(tr$1.storedMarks); 10813 delayedFocus(); 10814 } 10815 return true; 10816}; 10817var forEach = (items, fn) => (props) => { 10818 return items.every((item, index) => fn(item, { 10819 ...props, 10820 index 10821 })); 10822}; 10823var insertContent = (value, options) => ({ tr: tr$1, commands }) => { 10824 return commands.insertContentAt({ 10825 from: tr$1.selection.from, 10826 to: tr$1.selection.to 10827 }, value, options); 10828}; 10829var removeWhitespaces = (node) => { 10830 const children = node.childNodes; 10831 for (let i$1 = children.length - 1; i$1 >= 0; i$1 -= 1) { 10832 const child = children[i$1]; 10833 if (child.nodeType === 3 && child.nodeValue && /^(\n\s\s|\n)$/.test(child.nodeValue)) node.removeChild(child); 10834 else if (child.nodeType === 1) removeWhitespaces(child); 10835 } 10836 return node; 10837}; 10838function elementFromString(value) { 10839 if (typeof window === "undefined") throw new Error("[tiptap error]: there is no window object available, so this function cannot be used"); 10840 const wrappedValue = `<body>${value}</body>`; 10841 const html$2 = new window.DOMParser().parseFromString(wrappedValue, "text/html").body; 10842 return removeWhitespaces(html$2); 10843} 10844function isProseMirrorContent(value) { 10845 return typeof (value === null || value === void 0 ? void 0 : value.nodesBetween) === "function"; 10846} 10847function createNodeFromContent(content, schema, options) { 10848 if (isProseMirrorContent(content)) return content; 10849 const isJSONContent = typeof content === "object" && content !== null; 10850 options = { 10851 slice: true, 10852 parseOptions: {}, 10853 ...options 10854 }; 10855 const isTextContent = typeof content === "string"; 10856 if (isJSONContent) try { 10857 if (Array.isArray(content) && content.length > 0) return Fragment.fromArray(content.map((item) => schema.nodeFromJSON(item))); 10858 const node = schema.nodeFromJSON(content); 10859 if (options.errorOnInvalidContent) node.check(); 10860 return node; 10861 } catch (error) { 10862 if (options.errorOnInvalidContent) throw new Error("[tiptap error]: Invalid JSON content", { cause: error }); 10863 console.warn("[tiptap warn]: Invalid content.", "Passed value:", content, "Error:", error); 10864 return createNodeFromContent("", schema, options); 10865 } 10866 if (isTextContent) { 10867 if (options.errorOnInvalidContent) { 10868 let hasInvalidContent = false; 10869 let invalidContent = ""; 10870 const contentCheckSchema = new Schema({ 10871 topNode: schema.spec.topNode, 10872 marks: schema.spec.marks, 10873 nodes: schema.spec.nodes.append({ __tiptap__private__unknown__catch__all__node: { 10874 content: "inline*", 10875 group: "block", 10876 parseDOM: [{ 10877 tag: "*", 10878 getAttrs: (e) => { 10879 hasInvalidContent = true; 10880 invalidContent = typeof e === "string" ? e : e.outerHTML; 10881 return null; 10882 } 10883 }] 10884 } }) 10885 }); 10886 if (options.slice) DOMParser.fromSchema(contentCheckSchema).parseSlice(elementFromString(content), options.parseOptions); 10887 else DOMParser.fromSchema(contentCheckSchema).parse(elementFromString(content), options.parseOptions); 10888 if (options.errorOnInvalidContent && hasInvalidContent) throw new Error("[tiptap error]: Invalid HTML content", { cause: /* @__PURE__ */ new Error(`Invalid element found: ${invalidContent}`) }); 10889 } 10890 const parser = DOMParser.fromSchema(schema); 10891 if (options.slice) return parser.parseSlice(elementFromString(content), options.parseOptions).content; 10892 return parser.parse(elementFromString(content), options.parseOptions); 10893 } 10894 return createNodeFromContent("", schema, options); 10895} 10896function isFragment(nodeOrFragment) { 10897 return !("type" in nodeOrFragment); 10898} 10899function selectionToInsertionEnd(tr$1, startLen, bias) { 10900 const last = tr$1.steps.length - 1; 10901 if (last < startLen) return; 10902 const step = tr$1.steps[last]; 10903 if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) return; 10904 const map = tr$1.mapping.maps[last]; 10905 let end = 0; 10906 map.forEach((_from, _to, _newFrom, newTo) => { 10907 if (end === 0) end = newTo; 10908 }); 10909 tr$1.setSelection(Selection$1.near(tr$1.doc.resolve(end), bias)); 10910} 10911var insertContentAt = (position, value, options) => ({ tr: tr$1, dispatch, editor }) => { 10912 if (dispatch) { 10913 options = { 10914 parseOptions: editor.options.parseOptions, 10915 updateSelection: true, 10916 applyInputRules: false, 10917 applyPasteRules: false, 10918 ...options 10919 }; 10920 let content; 10921 const emitContentError = (error) => { 10922 editor.emit("contentError", { 10923 editor, 10924 error, 10925 disableCollaboration: () => { 10926 if ("collaboration" in editor.storage && typeof editor.storage.collaboration === "object" && editor.storage.collaboration) editor.storage.collaboration.isDisabled = true; 10927 } 10928 }); 10929 }; 10930 const parseOptions = { 10931 preserveWhitespace: "full", 10932 ...options.parseOptions 10933 }; 10934 if (!options.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) try { 10935 createNodeFromContent(value, editor.schema, { 10936 parseOptions, 10937 errorOnInvalidContent: true 10938 }); 10939 } catch (e) { 10940 emitContentError(e); 10941 } 10942 try { 10943 var _options$errorOnInval; 10944 content = createNodeFromContent(value, editor.schema, { 10945 parseOptions, 10946 errorOnInvalidContent: (_options$errorOnInval = options.errorOnInvalidContent) !== null && _options$errorOnInval !== void 0 ? _options$errorOnInval : editor.options.enableContentCheck 10947 }); 10948 } catch (e) { 10949 emitContentError(e); 10950 return false; 10951 } 10952 let { from, to } = typeof position === "number" ? { 10953 from: position, 10954 to: position 10955 } : { 10956 from: position.from, 10957 to: position.to 10958 }; 10959 let isOnlyTextContent = true; 10960 let isOnlyBlockContent = true; 10961 const nodes = isFragment(content) ? content.content : [content]; 10962 nodes.forEach((node) => { 10963 node.check(); 10964 isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false; 10965 isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false; 10966 }); 10967 if (from === to && isOnlyBlockContent) { 10968 const { parent } = tr$1.doc.resolve(from); 10969 if (parent.isTextblock && !parent.type.spec.code && !parent.childCount) { 10970 from -= 1; 10971 to += 1; 10972 } 10973 } 10974 let newContent; 10975 if (isOnlyTextContent) { 10976 if (Array.isArray(value)) newContent = value.map((item) => item.text || "").join(""); 10977 else if (isProseMirrorContent(value)) newContent = nodes.map((node) => { 10978 var _node$text; 10979 return (_node$text = node.text) !== null && _node$text !== void 0 ? _node$text : ""; 10980 }).join(""); 10981 else if (typeof value === "object" && !!value && !!value.text) newContent = value.text; 10982 else newContent = value; 10983 tr$1.insertText(newContent, from, to); 10984 } else { 10985 newContent = Fragment.from(nodes); 10986 const $from = tr$1.doc.resolve(from); 10987 const $fromNode = $from.node(); 10988 const fromSelectionAtStart = $from.parentOffset === 0; 10989 const isTextSelection$1 = $fromNode.isText || $fromNode.isTextblock; 10990 const hasContent = $fromNode.content.size > 0; 10991 if (fromSelectionAtStart && isTextSelection$1 && hasContent && isOnlyBlockContent) from = Math.max(0, from - 1); 10992 tr$1.replaceWith(from, to, nodes); 10993 } 10994 if (options.updateSelection) selectionToInsertionEnd(tr$1, tr$1.steps.length - 1, -1); 10995 if (options.applyInputRules) tr$1.setMeta("applyInputRules", { 10996 from, 10997 text: newContent 10998 }); 10999 if (options.applyPasteRules) tr$1.setMeta("applyPasteRules", { 11000 from, 11001 text: newContent 11002 }); 11003 } 11004 return true; 11005}; 11006function defaultBlockAt(match) { 11007 for (let i$1 = 0; i$1 < match.edgeCount; i$1 += 1) { 11008 const { type } = match.edge(i$1); 11009 if (type.isTextblock && !type.hasRequiredAttrs()) return type; 11010 } 11011 return null; 11012} 11013var insertDefaultBlock = (options = {}) => ({ tr: tr$1, dispatch, editor }) => { 11014 const { pos, attrs, content, updateSelection: updateSelection$1 = true } = options; 11015 let $pos; 11016 if (typeof pos === "number") $pos = tr$1.doc.resolve(pos); 11017 else if (pos) $pos = pos; 11018 else $pos = tr$1.selection.$from; 11019 const defaultType = defaultBlockAt($pos.parent.contentMatchAt($pos.index())); 11020 if (!defaultType) return false; 11021 const validAttrKeys = Object.keys(defaultType.spec.attrs || {}); 11022 const filteredAttrs = attrs ? Object.fromEntries(Object.entries(attrs).filter(([key]) => validAttrKeys.includes(key))) : {}; 11023 let node; 11024 if (content) { 11025 const parsed = createNodeFromContent(content, editor.schema); 11026 node = defaultType.createAndFill(filteredAttrs, parsed); 11027 } else node = defaultType.createAndFill(filteredAttrs); 11028 if (!node) return false; 11029 if (dispatch) { 11030 tr$1.insert($pos.pos, node); 11031 if (updateSelection$1) selectionToInsertionEnd(tr$1, tr$1.steps.length - 1, -1); 11032 } 11033 return true; 11034}; 11035var joinUp$1 = () => ({ state, dispatch }) => { 11036 return joinUp(state, dispatch); 11037}; 11038var joinDown$1 = () => ({ state, dispatch }) => { 11039 return joinDown(state, dispatch); 11040}; 11041var joinBackward$1 = () => ({ state, dispatch }) => { 11042 return joinBackward(state, dispatch); 11043}; 11044var joinForward$1 = () => ({ state, dispatch }) => { 11045 return joinForward(state, dispatch); 11046}; 11047var joinItemBackward = () => ({ state, dispatch, tr: tr$1 }) => { 11048 try { 11049 const point = joinPoint(state.doc, state.selection.$from.pos, -1); 11050 if (point === null || point === void 0) return false; 11051 tr$1.join(point, 2); 11052 if (dispatch) dispatch(tr$1); 11053 return true; 11054 } catch { 11055 return false; 11056 } 11057}; 11058var joinItemForward = () => ({ state, dispatch, tr: tr$1 }) => { 11059 try { 11060 const point = joinPoint(state.doc, state.selection.$from.pos, 1); 11061 if (point === null || point === void 0) return false; 11062 tr$1.join(point, 2); 11063 if (dispatch) dispatch(tr$1); 11064 return true; 11065 } catch { 11066 return false; 11067 } 11068}; 11069var joinTextblockBackward$1 = () => ({ state, dispatch }) => { 11070 return joinTextblockBackward(state, dispatch); 11071}; 11072var joinTextblockForward$1 = () => ({ state, dispatch }) => { 11073 return joinTextblockForward(state, dispatch); 11074}; 11075function isMacOS() { 11076 return typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false; 11077} 11078function normalizeKeyName(name) { 11079 const parts = name.split(/-(?!$)/); 11080 let result = parts[parts.length - 1]; 11081 if (result === "Space") result = " "; 11082 let alt; 11083 let ctrl; 11084 let shift$1; 11085 let meta; 11086 for (let i$1 = 0; i$1 < parts.length - 1; i$1 += 1) { 11087 const mod = parts[i$1]; 11088 if (/^(cmd|meta|m)$/i.test(mod)) meta = true; 11089 else if (/^a(lt)?$/i.test(mod)) alt = true; 11090 else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; 11091 else if (/^s(hift)?$/i.test(mod)) shift$1 = true; 11092 else if (/^mod$/i.test(mod)) if (isiOS() || isMacOS()) meta = true; 11093 else ctrl = true; 11094 else throw new Error(`Unrecognized modifier name: ${mod}`); 11095 } 11096 if (alt) result = `Alt-${result}`; 11097 if (ctrl) result = `Ctrl-${result}`; 11098 if (meta) result = `Meta-${result}`; 11099 if (shift$1) result = `Shift-${result}`; 11100 return result; 11101} 11102var keyboardShortcut = (name) => ({ editor, view, tr: tr$1, dispatch }) => { 11103 const keys$1 = normalizeKeyName(name).split(/-(?!$)/); 11104 const key = keys$1.find((item) => ![ 11105 "Alt", 11106 "Ctrl", 11107 "Meta", 11108 "Shift" 11109 ].includes(item)); 11110 const event = new KeyboardEvent("keydown", { 11111 key: key === "Space" ? " " : key, 11112 altKey: keys$1.includes("Alt"), 11113 ctrlKey: keys$1.includes("Ctrl"), 11114 metaKey: keys$1.includes("Meta"), 11115 shiftKey: keys$1.includes("Shift"), 11116 bubbles: true, 11117 cancelable: true 11118 }); 11119 const capturedTransaction = editor.captureTransaction(() => { 11120 view.someProp("handleKeyDown", (f) => f(view, event)); 11121 }); 11122 capturedTransaction === null || capturedTransaction === void 0 || c
11122apturedTransaction.steps.forEach((step) => { 11123 const newStep = step.map(tr$1.mapping); 11124 if (newStep && dispatch) tr$1.maybeStep(newStep); 11125 }); 11126 return true; 11127}; 11128function isNodeActive(state, typeOrName, attributes = {}) { 11129 const { from, to, empty: empty$1 } = state.selection; 11130 const type = typeOrName ? getNodeType(typeOrName, state.schema) : null; 11131 const nodeRanges = []; 11132 state.doc.nodesBetween(from, to, (node, pos) => { 11133 if (node.isText) return; 11134 const relativeFrom = Math.max(from, pos); 11135 const relativeTo = Math.min(to, pos + node.nodeSize); 11136 nodeRanges.push({ 11137 node, 11138 from: relativeFrom, 11139 to: relativeTo 11140 }); 11141 }); 11142 const selectionRange = to - from; 11143 const matchedNodeRanges = nodeRanges.filter((nodeRange) => { 11144 if (!type) return true; 11145 return type.name === nodeRange.node.type.name; 11146 }).filter((nodeRange) => objectIncludes(nodeRange.node.attrs, attributes, { strict: false })); 11147 if (empty$1) return !!matchedNodeRanges.length; 11148 return matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0) >= selectionRange; 11149} 11150var lift$1 = (typeOrName, attributes = {}) => ({ state, dispatch }) => { 11151 if (!isNodeActive(state, getNodeType(typeOrName, state.schema), attributes)) return false; 11152 return lift(state, dispatch); 11153}; 11154var liftEmptyBlock$1 = () => ({ state, dispatch }) => { 11155 return liftEmptyBlock(state, dispatch); 11156}; 11157var liftListItem$1 = (typeOrName) => ({ state, dispatch }) => { 11158 return liftListItem(getNodeType(typeOrName, state.schema))(state, dispatch); 11159}; 11160var newlineInCode$1 = () => ({ state, dispatch }) => { 11161 return newlineInCode(state, dispatch); 11162}; 11163function getSchemaTypeNameByName(name, schema) { 11164 if (schema.nodes[name]) return "node"; 11165 if (schema.marks[name]) return "mark"; 11166 return null; 11167} 11168function deleteProps(obj, propOrProps) { 11169 const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps; 11170 return Object.keys(obj).reduce((newObj, prop) => { 11171 if (!props.includes(prop)) newObj[prop] = obj[prop]; 11172 return newObj; 11173 }, {}); 11174} 11175var resetAttributes = (typeOrName, attributes) => ({ tr: tr$1, state, dispatch }) => { 11176 let nodeType = null; 11177 let markType = null; 11178 const schemaType = getSchemaTypeNameByName(typeof typeOrName === "string" ? typeOrName : typeOrName.name, state.schema); 11179 if (!schemaType) return false; 11180 if (schemaType === "node") nodeType = getNodeType(typeOrName, state.schema); 11181 if (schemaType === "mark") markType = getMarkType(typeOrName, state.schema); 11182 let canReset = false; 11183 tr$1.selection.ranges.forEach((range) => { 11184 state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => { 11185 if (nodeType && nodeType === node.type) { 11186 canReset = true; 11187 if (dispatch) tr$1.setNodeMarkup(pos, void 0, deleteProps(node.attrs, attributes)); 11188 } 11189 if (markType && node.marks.length) node.marks.forEach((mark) => { 11190 if (markType === mark.type) { 11191 canReset = true; 11192 if (dispatch) tr$1.addMark(pos, pos + node.nodeSize, markType.create(deleteProps(mark.attrs, attributes))); 11193 } 11194 }); 11195 }); 11196 }); 11197 return canReset; 11198}; 11199var scrollIntoView = () => ({ tr: tr$1, dispatch }) => { 11200 if (dispatch) tr$1.scrollIntoView(); 11201 return true; 11202}; 11203var selectAll = () => ({ tr: tr$1, dispatch }) => { 11204 if (dispatch) { 11205 const selection = new AllSelection(tr$1.doc); 11206 tr$1.setSelection(selection); 11207 } 11208 return true; 11209}; 11210var selectNodeBackward$1 = () => ({ state, dispatch }) => { 11211 return selectNodeBackward(state, dispatch); 11212}; 11213var selectNodeForward$1 = () => ({ state, dispatch }) => { 11214 return selectNodeForward(state, dispatch); 11215}; 11216var selectParentNode$1 = () => ({ state, dispatch }) => { 11217 return selectParentNode(state, dispatch); 11218}; 11219var selectTextblockEnd$1 = () => ({ state, dispatch }) => { 11220 return selectTextblockEnd(state, dispatch); 11221}; 11222var selectTextblockStart$1 = () => ({ state, dispatch }) => { 11223 return selectTextblockStart(state, dispatch); 11224}; 11225function createDocument(content, schema, parseOptions = {}, options = {}) { 11226 return createNodeFromContent(content, schema, { 11227 slice: false, 11228 parseOptions, 11229 errorOnInvalidContent: options.errorOnInvalidContent 11230 }); 11231} 11232var setContent = (content, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) => ({ editor, tr: tr$1, dispatch, commands }) => { 11233 const { doc: doc$2 } = tr$1; 11234 if (parseOptions.preserveWhitespace !== "full") { 11235 const document$1 = createDocument(content, editor.schema, parseOptions, { errorOnInvalidContent: errorOnInvalidContent !== null && errorOnInvalidContent !== void 0 ? errorOnInvalidContent : editor.options.enableContentCheck });
vendor: 4,556 bytes, lines 11236-11366
11236 if (dispatch) { 11237 const nodes = isFragment(document$1) ? document$1.content : [document$1]; 11238 tr$1.replaceWith(0, doc$2.content.size, nodes).setMeta("preventUpdate", !emitUpdate); 11239 } 11240 return true; 11241 } 11242 if (dispatch) tr$1.setMeta("preventUpdate", !emitUpdate); 11243 return commands.insertContentAt({ 11244 from: 0, 11245 to: doc$2.content.size 11246 }, content, { 11247 parseOptions, 11248 errorOnInvalidContent: errorOnInvalidContent !== null && errorOnInvalidContent !== void 0 ? errorOnInvalidContent : editor.options.enableContentCheck 11249 }); 11250}; 11251function getMarkAttributes(state, typeOrName) { 11252 const type = getMarkType(typeOrName, state.schema); 11253 const { from, to, empty: empty$1 } = state.selection; 11254 const marks = []; 11255 if (empty$1) { 11256 if (state.storedMarks) marks.push(...state.storedMarks); 11257 marks.push(...state.selection.$head.marks()); 11258 } else state.doc.nodesBetween(from, to, (node) => { 11259 marks.push(...node.marks); 11260 }); 11261 const mark = marks.find((markItem) => markItem.type.name === type.name); 11262 if (!mark) return {}; 11263 return { ...mark.attrs }; 11264} 11265function combineTransactionSteps(oldDoc, transactions) { 11266 const transform = new Transform(oldDoc); 11267 transactions.forEach((transaction) => { 11268 transaction.steps.forEach((step) => { 11269 transform.step(step); 11270 }); 11271 }); 11272 return transform; 11273} 11274function findChildrenInRange(node, range, predicate) { 11275 const nodesWithPos = []; 11276 node.nodesBetween(range.from, range.to, (child, pos) => { 11277 if (predicate(child)) nodesWithPos.push({ 11278 node: child, 11279 pos 11280 }); 11281 }); 11282 return nodesWithPos; 11283} 11284function findParentNodeClosestToPos($pos, predicate) { 11285 for (let i$1 = $pos.depth; i$1 > 0; i$1 -= 1) { 11286 const node = $pos.node(i$1); 11287 if (predicate(node)) return { 11288 pos: i$1 > 0 ? $pos.before(i$1) : 0, 11289 start: $pos.start(i$1), 11290 depth: i$1, 11291 node 11292 }; 11293 } 11294} 11295function findParentNode(predicate) { 11296 return (selection) => findParentNodeClosestToPos(selection.$from, predicate); 11297} 11298function getExtensionField(extension, field, context) { 11299 if (extension.config[field] === void 0 && extension.parent) return getExtensionField(extension.parent, field, context); 11300 if (typeof extension.config[field] === "function") return extension.config[field].bind({ 11301 ...context, 11302 parent: extension.parent ? getExtensionField(extension.parent, field, context) : null 11303 }); 11304 return extension.config[field]; 11305} 11306function flattenExtensions(extensions) { 11307 return extensions.map((extension) => { 11308 const addExtensions = getExtensionField(extension, "addExtensions", { 11309 name: extension.name, 11310 options: extension.options, 11311 storage: extension.storage 11312 }); 11313 if (addExtensions) return [extension, ...flattenExtensions(addExtensions())]; 11314 return extension; 11315 }).flat(10); 11316} 11317function getHTMLFromFragment(fragment, schema) { 11318 const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment); 11319 const container = document.implementation.createHTMLDocument().createElement("div"); 11320 container.appendChild(documentFragment); 11321 return container.innerHTML; 11322} 11323function isFunction(value) { 11324 return typeof value === "function"; 11325} 11326function callOrReturn(value, context = void 0, ...props) { 11327 if (isFunction(value)) { 11328 if (context) return value.bind(context)(...props); 11329 return value(...props); 11330 } 11331 return value; 11332} 11333function isEmptyObject(value = {}) { 11334 return Object.keys(value).length === 0 && value.constructor === Object; 11335} 11336function splitExtensions(extensions) { 11337 return { 11338 baseExtensions: extensions.filter((extension) => extension.type === "extension"), 11339 nodeExtensions: extensions.filter((extension) => extension.type === "node"), 11340 markExtensions: extensions.filter((extension) => extension.type === "mark") 11341 }; 11342} 11343function getAttributesFromExtensions(extensions) { 11344 const extensionAttributes = []; 11345 const { nodeExtensions, markExtensions } = splitExtensions(extensions); 11346 const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions]; 11347 const defaultAttribute = { 11348 default: null, 11349 validate: void 0, 11350 rendered: true, 11351 renderHTML: null, 11352 parseHTML: null, 11353 keepOnSplit: true, 11354 isRequired: false 11355 }; 11356 const nodeExtensionTypes = nodeExtensions.filter((ext) => ext.name !== "text").map((ext) => ext.name); 11357 const markExtensionTypes = markExtensions.map((ext) => ext.name); 11358 const allExtensionTypes = [...nodeExtensionTypes, ...markExtensionTypes]; 11359 extensions.forEach((extension) => { 11360 const addGlobalAttributes = getExtensionField(extension, "addGlobalAttributes", { 11361 name: extension.name, 11362 options: extension.options, 11363 storage: extension.storage, 11364 extensions: nodeAndMarkExtensions 11365 }); 11366 if (!addGlobalAttributes) return;
vendor: 25,008 bytes, lines 11367-12001
11367 addGlobalAttributes().forEach((globalAttribute) => { 11368 let resolvedTypes; 11369 if (Array.isArray(globalAttribute.types)) resolvedTypes = globalAttribute.types; 11370 else if (globalAttribute.types === "*") resolvedTypes = allExtensionTypes; 11371 else if (globalAttribute.types === "nodes") resolvedTypes = nodeExtensionTypes; 11372 else if (globalAttribute.types === "marks") resolvedTypes = markExtensionTypes; 11373 else resolvedTypes = []; 11374 resolvedTypes.forEach((type) => { 11375 Object.entries(globalAttribute.attributes).forEach(([name, attribute]) => { 11376 extensionAttributes.push({ 11377 type, 11378 name, 11379 attribute: { 11380 ...defaultAttribute, 11381 ...attribute 11382 } 11383 }); 11384 }); 11385 }); 11386 }); 11387 }); 11388 nodeAndMarkExtensions.forEach((extension) => { 11389 const addAttributes = getExtensionField(extension, "addAttributes", { 11390 name: extension.name, 11391 options: extension.options, 11392 storage: extension.storage 11393 }); 11394 if (!addAttributes) return; 11395 const attributes = addAttributes(); 11396 Object.entries(attributes).forEach(([name, attribute]) => { 11397 const mergedAttr = { 11398 ...defaultAttribute, 11399 ...attribute 11400 }; 11401 if (typeof (mergedAttr === null || mergedAttr === void 0 ? void 0 : mergedAttr.default) === "function") mergedAttr.default = mergedAttr.default(); 11402 if ((mergedAttr === null || mergedAttr === void 0 ? void 0 : mergedAttr.isRequired) && (mergedAttr === null || mergedAttr === void 0 ? void 0 : mergedAttr.default) === void 0) delete mergedAttr.default; 11403 extensionAttributes.push({ 11404 type: extension.name, 11405 name, 11406 attribute: mergedAttr 11407 }); 11408 }); 11409 }); 11410 return extensionAttributes; 11411} 11412function splitStyleDeclarations(styles) { 11413 const result = []; 11414 let current = ""; 11415 let inSingleQuote = false; 11416 let inDoubleQuote = false; 11417 let parenDepth = 0; 11418 const length = styles.length; 11419 for (let i$1 = 0; i$1 < length; i$1 += 1) { 11420 const char = styles[i$1]; 11421 if (char === "'" && !inDoubleQuote) { 11422 inSingleQuote = !inSingleQuote; 11423 current += char; 11424 continue; 11425 } 11426 if (char === "\"" && !inSingleQuote) { 11427 inDoubleQuote = !inDoubleQuote; 11428 current += char; 11429 continue; 11430 } 11431 if (!inSingleQuote && !inDoubleQuote) { 11432 if (char === "(") { 11433 parenDepth += 1; 11434 current += char; 11435 continue; 11436 } 11437 if (char === ")" && parenDepth > 0) { 11438 parenDepth -= 1; 11439 current += char; 11440 continue; 11441 } 11442 if (char === ";" && parenDepth === 0) { 11443 result.push(current); 11444 current = ""; 11445 continue; 11446 } 11447 } 11448 current += char; 11449 } 11450 if (current) result.push(current); 11451 return result; 11452} 11453function parseStyleEntries(styles) { 11454 const pairs = []; 11455 const declarations = splitStyleDeclarations(styles || ""); 11456 const numDeclarations = declarations.length; 11457 for (let i$1 = 0; i$1 < numDeclarations; i$1 += 1) { 11458 const declaration = declarations[i$1]; 11459 const firstColonIndex = declaration.indexOf(":"); 11460 if (firstColonIndex === -1) continue; 11461 const property = declaration.slice(0, firstColonIndex).trim(); 11462 const value = declaration.slice(firstColonIndex + 1).trim(); 11463 if (property && value) pairs.push([property, value]); 11464 } 11465 return pairs; 11466} 11467function mergeAttributes(...objects) { 11468 return objects.filter((item) => !!item).reduce((items, item) => { 11469 const mergedAttributes = { ...items }; 11470 Object.entries(item).forEach(([key, value]) => { 11471 if (key === "__proto__") { 11472 Object.defineProperty(mergedAttributes, key, { 11473 configurable: true, 11474 enumerable: true, 11475 value, 11476 writable: true 11477 }); 11478 return; 11479 } 11480 if (!mergedAttributes[key]) { 11481 mergedAttributes[key] = value; 11482 return; 11483 } 11484 if (key === "class") { 11485 const valueClasses = value ? String(value).split(" ") : []; 11486 const existingClasses = mergedAttributes[key] ? mergedAttributes[key].split(" ") : []; 11487 const insertClasses = valueClasses.filter((valueClass) => !existingClasses.includes(valueClass)); 11488 mergedAttributes[key] = [...existingClasses, ...insertClasses].join(" "); 11489 } else if (key === "style") { 11490 const styleMap = new Map([...parseStyleEntries(mergedAttributes[key]), ...parseStyleEntries(value)]); 11491 mergedAttributes[key] = Array.from(styleMap.entries()).map(([property, val]) => `${property}: ${val}`).join("; "); 11492 } else mergedAttributes[key] = value; 11493 }); 11494 return mergedAttributes; 11495 }, {}); 11496} 11497function getRenderedAttributes(nodeOrMark, extensionAttributes) { 11498 return extensionAttributes.filter((attribute) => attribute.type === nodeOrMark.type.name).filter((item) => item.attribute.rendered).map((item) => { 11499 if (!item.attribute.renderHTML) return { [item.name]: nodeOrMark.attrs[item.name] }; 11500 return item.attribute.renderHTML(nodeOrMark.attrs) || {}; 11501 }).reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {}); 11502} 11503function fromString(value) { 11504 if (typeof value !== "string") return value; 11505 if (value.match(/^[+-]?(?:\d*\.)?\d+$/)) return Number(value); 11506 if (value === "true") return true; 11507 if (value === "false") return false; 11508 return value; 11509} 11510function injectExtensionAttributesToParseRule(parseRule, extensionAttributes) { 11511 if ("style" in parseRule) return parseRule; 11512 return { 11513 ...parseRule, 11514 getAttrs: (node) => { 11515 const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node) : parseRule.attrs; 11516 if (oldAttributes === false) return false; 11517 const newAttributes = extensionAttributes.reduce((items, item) => { 11518 const value = item.attribute.parseHTML ? item.attribute.parseHTML(node) : fromString(node.getAttribute(item.name)); 11519 if (value === null || value === void 0) return items; 11520 return { 11521 ...items, 11522 [item.name]: value 11523 }; 11524 }, {}); 11525 return { 11526 ...oldAttributes, 11527 ...newAttributes 11528 }; 11529 } 11530 }; 11531} 11532function cleanUpSchemaItem(data) { 11533 return Object.fromEntries(Object.entries(data).filter(([key, value]) => { 11534 if (key === "attrs" && isEmptyObject(value)) return false; 11535 return value !== null && value !== void 0; 11536 })); 11537} 11538function buildAttributeSpec(extensionAttribute) { 11539 var _extensionAttribute$a, _extensionAttribute$a2; 11540 const spec = {}; 11541 if (!(extensionAttribute === null || extensionAttribute === void 0 || (_extensionAttribute$a = extensionAttribute.attribute) === null || _extensionAttribute$a === void 0 ? void 0 : _extensionAttribute$a.isRequired) && "default" in ((extensionAttribute === null || extensionAttribute === void 0 ? void 0 : extensionAttribute.attribute) || {})) spec.default = extensionAttribute.attribute.default; 11542 if ((extensionAttribute === null || extensionAttribute === void 0 || (_extensionAttribute$a2 = extensionAttribute.attribute) === null || _extensionAttribute$a2 === void 0 ? void 0 : _extensionAttribute$a2.validate) !== void 0) spec.validate = extensionAttribute.attribute.validate; 11543 return [extensionAttribute.name, spec]; 11544} 11545function getSchemaByResolvedExtensions(extensions, editor) { 11546 var _nodeExtensions$find; 11547 const allAttributes = getAttributesFromExtensions(extensions); 11548 const { nodeExtensions, markExtensions } = splitExtensions(extensions); 11549 return new Schema({ 11550 topNode: (_nodeExtensions$find = nodeExtensions.find((extension) => getExtensionField(extension, "topNode"))) === null || _nodeExtensions$find === void 0 ? void 0 : _nodeExtensions$find.name, 11551 nodes: Object.fromEntries(nodeExtensions.map((extension) => { 11552 const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension.name); 11553 const context = { 11554 name: extension.name, 11555 options: extension.options, 11556 storage: extension.storage, 11557 editor 11558 }; 11559 const schema = cleanUpSchemaItem({ 11560 ...extensions.reduce((fields, e) => { 11561 const extendNodeSchema = getExtensionField(e, "extendNodeSchema", context); 11562 return { 11563 ...fields, 11564 ...extendNodeSchema ? extendNodeSchema(extension) : {} 11565 }; 11566 }, {}), 11567 content: callOrReturn(getExtensionField(extension, "content", context)), 11568 marks: callOrReturn(getExtensionField(extension, "marks", context)), 11569 group: callOrReturn(getExtensionField(extension, "group", context)), 11570 inline: callOrReturn(getExtensionField(extension, "inline", context)), 11571 atom: callOrReturn(getExtensionField(extension, "atom", context)), 11572 selectable: callOrReturn(getExtensionField(extension, "selectable", context)), 11573 draggable: callOrReturn(getExtensionField(extension, "draggable", context)), 11574 code: callOrReturn(getExtensionField(extension, "code", context)), 11575 whitespace: callOrReturn(getExtensionField(extension, "whitespace", context)), 11576 linebreakReplacement: callOrReturn(getExtensionField(extension, "linebreakReplacement", context)), 11577 defining: callOrReturn(getExtensionField(extension, "defining", context)), 11578 isolating: callOrReturn(getExtensionField(extension, "isolating", context)), 11579 attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)) 11580 }); 11581 const parseHTML = callOrReturn(getExtensionField(extension, "parseHTML", context)); 11582 if (parseHTML) schema.parseDOM = parseHTML.map((parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes)); 11583 const renderHTML = getExtensionField(extension, "renderHTML", context); 11584 if (renderHTML) schema.toDOM = (node) => renderHTML({ 11585 node, 11586 HTMLAttributes: getRenderedAttributes(node, extensionAttributes) 11587 }); 11588 const renderText = getExtensionField(extension, "renderText", context); 11589 if (renderText) schema.toText = renderText; 11590 return [extension.name, schema]; 11591 })), 11592 marks: Object.fromEntries(markExtensions.map((extension) => { 11593 const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension.name); 11594 const context = { 11595 name: extension.name, 11596 options: extension.options, 11597 storage: extension.storage, 11598 editor 11599 }; 11600 const schema = cleanUpSchemaItem({ 11601 ...extensions.reduce((fields, e) => { 11602 const extendMarkSchema = getExtensionField(e, "extendMarkSchema", context); 11603 return { 11604 ...fields, 11605 ...extendMarkSchema ? extendMarkSchema(extension) : {} 11606 }; 11607 }, {}), 11608 inclusive: callOrReturn(getExtensionField(extension, "inclusive", context)), 11609 excludes: callOrReturn(getExtensionField(extension, "excludes", context)), 11610 group: callOrReturn(getExtensionField(extension, "group", context)), 11611 spanning: callOrReturn(getExtensionField(extension, "spanning", context)), 11612 code: callOrReturn(getExtensionField(extension, "code", context)), 11613 attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)) 11614 }); 11615 const parseHTML = callOrReturn(getExtensionField(extension, "parseHTML", context)); 11616 if (parseHTML) schema.parseDOM = parseHTML.map((parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes)); 11617 const renderHTML = getExtensionField(extension, "renderHTML", context); 11618 if (renderHTML) schema.toDOM = (mark) => renderHTML({ 11619 mark, 11620 HTMLAttributes: getRenderedAttributes(mark, extensionAttributes) 11621 }); 11622 return [extension.name, schema]; 11623 })) 11624 }); 11625} 11626function findDuplicates(items) { 11627 const filtered = items.filter((el, index) => items.indexOf(el) !== index); 11628 return Array.from(new Set(filtered)); 11629} 11630function sortExtensions(extensions) { 11631 const defaultPriority = 100; 11632 return extensions.sort((a, b) => { 11633 const priorityA = getExtensionField(a, "priority") || defaultPriority; 11634 const priorityB = getExtensionField(b, "priority") || defaultPriority; 11635 if (priorityA > priorityB) return -1; 11636 if (priorityA < priorityB) return 1; 11637 return 0; 11638 }); 11639} 11640function resolveExtensions(extensions) { 11641 const resolvedExtensions = sortExtensions(flattenExtensions(extensions)); 11642 const duplicatedNames = findDuplicates(resolvedExtensions.map((extension) => extension.name)); 11643 if (duplicatedNames.length) console.warn(`[tiptap warn]: Duplicate extension names found: [${duplicatedNames.map((item) => `'${item}'`).join(", ")}]. This can lead to issues.`); 11644 return resolvedExtensions; 11645} 11646function getTextBetween(startNode, range, options) { 11647 const { from, to } = range; 11648 const { blockSeparator = "\n\n", textSerializers = {} } = options || {}; 11649 let text$1 = ""; 11650 startNode.nodesBetween(from, to, (node, pos, parent, index) => { 11651 if (node.isBlock && pos > from) text$1 += blockSeparator; 11652 const textSerializer = textSerializers === null || textSerializers === void 0 ? void 0 : textSerializers[node.type.name]; 11653 if (textSerializer) { 11654 if (parent) text$1 += textSerializer({ 11655 node, 11656 pos, 11657 parent, 11658 index, 11659 range 11660 }); 11661 return false; 11662 } 11663 if (node.isText) { 11664 var _node$text; 11665 text$1 += node === null || node === void 0 || (_node$text = node.text) === null || _node$text === void 0 ? void 0 : _node$text.slice(Math.max(from, pos) - pos, to - pos); 11666 } 11667 }); 11668 return text$1; 11669} 11670function getText(node, options) { 11671 return getTextBetween(node, { 11672 from: 0, 11673 to: node.content.size 11674 }, options); 11675} 11676function getTextSerializersFromSchema(schema) { 11677 return Object.fromEntries(Object.entries(schema.nodes).filter(([, node]) => node.spec.toText).map(([name, node]) => [name, node.spec.toText])); 11678} 11679function getNodeAttributes(state, typeOrName) { 11680 const type = getNodeType(typeOrName, state.schema); 11681 const { from, to } = state.selection; 11682 const nodes = []; 11683 state.doc.nodesBetween(from, to, (node$1) => { 11684 nodes.push(node$1); 11685 }); 11686 const node = nodes.reverse().find((nodeItem) => nodeItem.type.name === type.name); 11687 if (!node) return {}; 11688 return { ...node.attrs }; 11689} 11690function getAttributes(state, typeOrName) { 11691 const schemaType = getSchemaTypeNameByName(typeof typeOrName === "string" ? typeOrName : typeOrName.name, state.schema); 11692 if (schemaType === "node") return getNodeAttributes(state, typeOrName); 11693 if (schemaType === "mark") return getMarkAttributes(state, typeOrName); 11694 return {}; 11695} 11696function removeDuplicates(array, by = JSON.stringify) { 11697 const seen = {}; 11698 return array.filter((item) => { 11699 const key = by(item); 11700 return Object.prototype.hasOwnProperty.call(seen, key) ? false : seen[key] = true; 11701 }); 11702} 11703function simplifyChangedRanges(changes) { 11704 const uniqueChanges = removeDuplicates(changes); 11705 return uniqueChanges.length === 1 ? uniqueChanges : uniqueChanges.filter((change, index) => { 11706 return !uniqueChanges.filter((_, i$1) => i$1 !== index).some((otherChange) => { 11707 return change.oldRange.from >= otherChange.oldRange.from && change.oldRange.to <= otherChange.oldRange.to && change.newRange.from >= otherChange.newRange.from && change.newRange.to <= otherChange.newRange.to; 11708 }); 11709 }); 11710} 11711function getChangedRanges(transform) { 11712 const { mapping, steps } = transform; 11713 const changes = []; 11714 mapping.maps.forEach((stepMap, index) => { 11715 const ranges = []; 11716 if (!stepMap.ranges.length) { 11717 const { from, to } = steps[index]; 11718 if (from === void 0 || to === void 0) return; 11719 ranges.push({ 11720 from, 11721 to 11722 }); 11723 } else stepMap.forEach((from, to) => { 11724 ranges.push({ 11725 from, 11726 to 11727 }); 11728 }); 11729 ranges.forEach(({ from, to }) => { 11730 const newStart = mapping.slice(index).map(from, -1); 11731 const newEnd = mapping.slice(index).map(to); 11732 const oldStart = mapping.invert().map(newStart, -1); 11733 const oldEnd = mapping.invert().map(newEnd); 11734 changes.push({ 11735 oldRange: { 11736 from: oldStart, 11737 to: oldEnd 11738 }, 11739 newRange: { 11740 from: newStart, 11741 to: newEnd 11742 } 11743 }); 11744 }); 11745 }); 11746 return simplifyChangedRanges(changes); 11747} 11748function getMarksBetween(from, to, doc$2) { 11749 const marks = []; 11750 if (from === to) doc$2.resolve(from).marks().forEach((mark) => { 11751 const range = getMarkRange(doc$2.resolve(from), mark.type); 11752 if (!range) return; 11753 marks.push({ 11754 mark, 11755 ...range 11756 }); 11757 }); 11758 else doc$2.nodesBetween(from, to, (node, pos) => { 11759 if (!node || (node === null || node === void 0 ? void 0 : node.nodeSize) === void 0) return; 11760 marks.push(...node.marks.map((mark) => ({ 11761 from: pos, 11762 to: pos + node.nodeSize, 11763 mark 11764 }))); 11765 }); 11766 return marks; 11767} 11768var getNodeAtPosition = (state, typeOrName, pos, maxDepth = 20) => { 11769 const $pos = state.doc.resolve(pos); 11770 let currentDepth = maxDepth; 11771 let node = null; 11772 while (currentDepth > 0 && node === null) { 11773 const currentNode = $pos.node(currentDepth); 11774 if ((currentNode === null || currentNode === void 0 ? void 0 : currentNode.type.name) === typeOrName) node = currentNode; 11775 else currentDepth -= 1; 11776 } 11777 return [node, currentDepth]; 11778}; 11779var getPreviousBlockSibling = ($pos) => { 11780 const parentDepth = $pos.depth - 1; 11781 if (parentDepth < 0) return null; 11782 const index = $pos.index(parentDepth); 11783 if (index === 0) return null; 11784 return $pos.node(parentDepth).child(index - 1); 11785}; 11786function getSchemaTypeByName(name, schema) { 11787 return schema.nodes[name] || schema.marks[name] || null; 11788} 11789function getSplittedAttributes(extensionAttributes, typeName, attributes) { 11790 return Object.fromEntries(Object.entries(attributes).filter(([name]) => { 11791 const extensionAttribute = extensionAttributes.find((item) => { 11792 return item.type === typeName && item.name === name; 11793 }); 11794 if (!extensionAttribute) return false; 11795 return extensionAttribute.attribute.keepOnSplit; 11796 })); 11797} 11798var getTextContentFromNodes = ($from, maxMatch = 500) => { 11799 let textBefore = ""; 11800 const sliceEndPos = $from.parentOffset; 11801 $from.parent.nodesBetween(Math.max(0, sliceEndPos - maxMatch), sliceEndPos, (node, pos, parent, index) => { 11802 var _node$type$spec$toTex, _node$type$spec; 11803 const chunk = ((_node$type$spec$toTex = (_node$type$spec = node.type.spec).toText) === null || _node$type$spec$toTex === void 0 ? void 0 : _node$type$spec$toTex.call(_node$type$spec, { 11804 node, 11805 pos, 11806 parent, 11807 index 11808 })) || node.textContent || "%leaf%"; 11809 textBefore += node.isAtom && !node.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos)); 11810 }); 11811 return textBefore; 11812}; 11813function isMarkActive(state, typeOrName, attributes = {}) { 11814 const { empty: empty$1, ranges } = state.selection; 11815 const type = typeOrName ? getMarkType(typeOrName, state.schema) : null; 11816 if (empty$1) return !!(state.storedMarks || state.selection.$from.marks()).filter((mark) => { 11817 if (!type) return true; 11818 return type.name === mark.type.name; 11819 }).find((mark) => objectIncludes(mark.attrs, attributes, { strict: false })); 11820 let selectionRange = 0; 11821 const markRanges = []; 11822 ranges.forEach(({ $from, $to }) => { 11823 const from = $from.pos; 11824 const to = $to.pos; 11825 state.doc.nodesBetween(from, to, (node, pos) => { 11826 if (type && node.inlineContent && !node.type.allowsMarkType(type)) return false; 11827 if (!node.isText && !node.marks.length) return; 11828 const relativeFrom = Math.max(from, pos); 11829 const relativeTo = Math.min(to, pos + node.nodeSize); 11830 const range = relativeTo - relativeFrom; 11831 selectionRange += range; 11832 markRanges.push(...node.marks.map((mark) => ({ 11833 mark, 11834 from: relativeFrom, 11835 to: relativeTo 11836 }))); 11837 }); 11838 }); 11839 if (selectionRange === 0) return false; 11840 const matchedRange = markRanges.filter((markRange) => { 11841 if (!type) return true; 11842 return type.name === markRange.mark.type.name; 11843 }).filter((markRange) => objectIncludes(markRange.mark.attrs, attributes, { strict: false })).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0); 11844 const excludedRange = markRanges.filter((markRange) => { 11845 if (!type) return true; 11846 return markRange.mark.type !== type && markRange.mark.type.excludes(type); 11847 }).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0); 11848 return (matchedRange > 0 ? matchedRange + excludedRange : matchedRange) >= selectionRange; 11849} 11850function isActive(state, name, attributes = {}) { 11851 if (!name) return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes); 11852 const schemaType = getSchemaTypeNameByName(name, state.schema); 11853 if (schemaType === "node") return isNodeActive(state, name, attributes); 11854 if (schemaType === "mark") return isMarkActive(state, name, attributes); 11855 return false; 11856} 11857var isAtEndOfNode = (state, nodeType) => { 11858 const { $from, $to, $anchor } = state.selection; 11859 if (nodeType) { 11860 const parentNode$1 = findParentNode((node) => node.type.name === nodeType)(state.selection); 11861 if (!parentNode$1) return false; 11862 const $parentPos = state.doc.resolve(parentNode$1.pos + 1); 11863 if ($anchor.pos + 1 === $parentPos.end()) return true; 11864 return false; 11865 } 11866 if ($to.parentOffset < $to.parent.nodeSize - 2 || $from.pos !== $to.pos) return false; 11867 return true; 11868}; 11869var isAtStartOfNode = (state) => { 11870 const { $from, $to } = state.selection; 11871 if ($from.parentOffset > 0 || $from.pos !== $to.pos) return false; 11872 return true; 11873}; 11874function isExtensionRulesEnabled(extension, enabled) { 11875 if (Array.isArray(enabled)) return enabled.some((enabledExtension) => { 11876 return (typeof enabledExtension === "string" ? enabledExtension : enabledExtension.name) === extension.name; 11877 }); 11878 return enabled; 11879} 11880function isList(name, extensions) { 11881 const { nodeExtensions } = splitExtensions(extensions); 11882 const extension = nodeExtensions.find((item) => item.name === name); 11883 if (!extension) return false; 11884 const group = callOrReturn(getExtensionField(extension, "group", { 11885 name: extension.name, 11886 options: extension.options, 11887 storage: extension.storage 11888 })); 11889 if (typeof group !== "string") return false; 11890 return group.split(" ").includes("list"); 11891} 11892function isNodeEmpty(node, { checkChildren = true, ignoreWhitespace = false } = {}) { 11893 if (ignoreWhitespace) { 11894 if (node.type.name === "hardBreak") return true; 11895 if (node.isText) { 11896 var _node$text; 11897 return !/\S/.test((_node$text = node.text) !== null && _node$text !== void 0 ? _node$text : ""); 11898 } 11899 } 11900 if (node.isText) return !node.text; 11901 if (node.isAtom || node.isLeaf) return false; 11902 if (node.content.childCount === 0) return true; 11903 if (checkChildren) { 11904 let isContentEmpty = true; 11905 node.content.forEach((childNode) => { 11906 if (isContentEmpty === false) return; 11907 if (!isNodeEmpty(childNode, { 11908 ignoreWhitespace, 11909 checkChildren 11910 })) isContentEmpty = false; 11911 }); 11912 return isContentEmpty; 11913 } 11914 return false; 11915} 11916function isNodeSelection(value) { 11917 return value instanceof NodeSelection; 11918} 11919var MappablePosition = class MappablePosition$1 { 11920 constructor(position) { 11921 this.position = position; 11922 } 11923 static fromJSON(json) { 11924 return new MappablePosition$1(json.position); 11925 } 11926 toJSON() { 11927 return { position: this.position }; 11928 } 11929}; 11930function getUpdatedPosition(position, transaction) { 11931 const mapResult = transaction.mapping.mapResult(position.position); 11932 return { 11933 position: new MappablePosition(mapResult.pos), 11934 mapResult 11935 }; 11936} 11937function createMappablePosition(position) { 11938 return new MappablePosition(position); 11939} 11940function canSetMark(state, tr$1, newMarkType) { 11941 const { selection } = tr$1; 11942 let cursor = null; 11943 if (isTextSelection(selection)) cursor = selection.$cursor; 11944 if (cursor) { 11945 var _state$storedMarks; 11946 const currentMarks = (_state$storedMarks = state.storedMarks) !== null && _state$storedMarks !== void 0 ? _state$storedMarks : cursor.marks(); 11947 return cursor.parent.type.allowsMarkType(newMarkType) && (!!newMarkType.isInSet(currentMarks) || !currentMarks.some((mark) => mark.type.excludes(newMarkType))); 11948 } 11949 const { ranges } = selection; 11950 return ranges.some(({ $from, $to }) => { 11951 let someNodeSupportsMark = $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false; 11952 state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => { 11953 if (someNodeSupportsMark) return false; 11954 if (node.isInline) { 11955 const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType); 11956 const currentMarksAllowMarkType = !!newMarkType.isInSet(node.marks) || !node.marks.some((otherMark) => otherMark.type.excludes(newMarkType)); 11957 someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType; 11958 } 11959 return !someNodeSupportsMark; 11960 }); 11961 return someNodeSupportsMark; 11962 }); 11963} 11964var setMark = (typeOrName, attributes = {}) => ({ tr: tr$1, state, dispatch }) => { 11965 const { selection } = tr$1; 11966 const { empty: empty$1, ranges } = selection; 11967 const type = getMarkType(typeOrName, state.schema); 11968 if (dispatch) if (empty$1) { 11969 const oldAttributes = getMarkAttributes(state, type); 11970 tr$1.addStoredMark(type.create({ 11971 ...oldAttributes, 11972 ...attributes 11973 })); 11974 } else ranges.forEach((range) => { 11975 const from = range.$from.pos; 11976 const to = range.$to.pos; 11977 state.doc.nodesBetween(from, to, (node, pos) => { 11978 const trimmedFrom = Math.max(pos, from); 11979 const trimmedTo = Math.min(pos + node.nodeSize, to); 11980 if (node.marks.find((mark) => mark.type === type)) node.marks.forEach((mark) => { 11981 if (type === mark.type) tr$1.addMark(trimmedFrom, trimmedTo, type.create({ 11982 ...mark.attrs, 11983 ...attributes 11984 })); 11985 }); 11986 else tr$1.addMark(trimmedFrom, trimmedTo, type.create(attributes)); 11987 }); 11988 }); 11989 return canSetMark(state, tr$1, type); 11990}; 11991var setMeta = (key, value) => ({ tr: tr$1 }) => { 11992 tr$1.setMeta(key, value); 11993 return true; 11994}; 11995var setNode = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => { 11996 const type = getNodeType(typeOrName, state.schema); 11997 let attributesToCopy; 11998 if (state.selection.$anchor.sameParent(state.selection.$head)) attributesToCopy = state.selection.$anchor.parent.attrs; 11999 if (!type.isTextblock) { 12000 console.warn("[tiptap warn]: Currently \"setNode()\" only supports text block nodes."); 12001 return false;
vendor: 9,441 bytes, lines 12002-12227
12002 } 12003 return chain().command(({ commands }) => { 12004 if (setBlockType(type, { 12005 ...attributesToCopy, 12006 ...attributes 12007 })(state)) return true; 12008 return commands.clearNodes(); 12009 }).command(({ state: updatedState }) => { 12010 return setBlockType(type, { 12011 ...attributesToCopy, 12012 ...attributes 12013 })(updatedState, dispatch); 12014 }).run(); 12015}; 12016var setNodeSelection = (position) => ({ tr: tr$1, dispatch }) => { 12017 if (dispatch) { 12018 const { doc: doc$2 } = tr$1; 12019 const from = minMax(position, 0, doc$2.content.size); 12020 const selection = NodeSelection.create(doc$2, from); 12021 tr$1.setSelection(selection); 12022 } 12023 return true; 12024}; 12025var setTextDirection = (direction, position) => ({ tr: tr$1, state, dispatch }) => { 12026 const { selection } = state; 12027 let from; 12028 let to; 12029 if (typeof position === "number") { 12030 from = position; 12031 to = position; 12032 } else if (position && "from" in position && "to" in position) { 12033 from = position.from; 12034 to = position.to; 12035 } else { 12036 from = selection.from; 12037 to = selection.to; 12038 } 12039 if (dispatch) tr$1.doc.nodesBetween(from, to, (node, pos) => { 12040 if (node.isText) return; 12041 tr$1.setNodeMarkup(pos, void 0, { 12042 ...node.attrs, 12043 dir: direction 12044 }); 12045 }); 12046 return true; 12047}; 12048var setTextSelection = (position) => ({ tr: tr$1, dispatch }) => { 12049 if (dispatch) { 12050 const { doc: doc$2 } = tr$1; 12051 const { from, to } = typeof position === "number" ? { 12052 from: position, 12053 to: position 12054 } : position; 12055 const minPos = TextSelection.atStart(doc$2).from; 12056 const maxPos = TextSelection.atEnd(doc$2).to; 12057 const resolvedFrom = minMax(from, minPos, maxPos); 12058 const resolvedEnd = minMax(to, minPos, maxPos); 12059 const selection = TextSelection.create(doc$2, resolvedFrom, resolvedEnd); 12060 tr$1.setSelection(selection); 12061 } 12062 return true; 12063}; 12064var sinkListItem$1 = (typeOrName) => ({ state, dispatch }) => { 12065 return sinkListItem(getNodeType(typeOrName, state.schema))(state, dispatch); 12066}; 12067function ensureMarks(state, splittableMarks) { 12068 const marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks(); 12069 if (marks) { 12070 const filteredMarks = marks.filter((mark) => splittableMarks === null || splittableMarks === void 0 ? void 0 : splittableMarks.includes(mark.type.name)); 12071 state.tr.ensureMarks(filteredMarks); 12072 } 12073} 12074var splitBlock = ({ keepMarks = true } = {}) => ({ tr: tr$1, state, dispatch, editor }) => { 12075 const { selection, doc: doc$2 } = tr$1; 12076 const { $from, $to } = selection; 12077 const extensionAttributes = editor.extensionManager.attributes; 12078 const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs); 12079 if (selection instanceof NodeSelection && selection.node.isBlock) { 12080 if (!$from.parentOffset || !canSplit(doc$2, $from.pos)) return false; 12081 if (dispatch) { 12082 if (keepMarks) ensureMarks(state, editor.extensionManager.splittableMarks); 12083 tr$1.split($from.pos).scrollIntoView(); 12084 } 12085 return true; 12086 } 12087 if (!$from.parent.isBlock) return false; 12088 const atEnd = $to.parentOffset === $to.parent.content.size; 12089 const deflt = $from.depth === 0 ? void 0 : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1))); 12090 let types = atEnd && deflt ? [{ 12091 type: deflt, 12092 attrs: newAttributes 12093 }] : void 0; 12094 let can = canSplit(tr$1.doc, tr$1.mapping.map($from.pos), 1, types); 12095 if (!types && !can && canSplit(tr$1.doc, tr$1.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : void 0)) { 12096 can = true; 12097 types = deflt ? [{ 12098 type: deflt, 12099 attrs: newAttributes 12100 }] : void 0; 12101 } 12102 if (dispatch) { 12103 if (can) { 12104 if (selection instanceof TextSelection) tr$1.deleteSelection(); 12105 tr$1.split(tr$1.mapping.map($from.pos), 1, types); 12106 if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) { 12107 const first$1 = tr$1.mapping.map($from.before()); 12108 const $first = tr$1.doc.resolve(first$1); 12109 if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) tr$1.setNodeMarkup(tr$1.mapping.map($from.before()), deflt); 12110 } 12111 } 12112 if (keepMarks) ensureMarks(state, editor.extensionManager.splittableMarks); 12113 tr$1.scrollIntoView(); 12114 } 12115 return can; 12116}; 12117var splitListItem = (typeOrName, overrideAttrs = {}) => ({ tr: tr$1, state, dispatch, editor }) => { 12118 const type = getNodeType(typeOrName, state.schema); 12119 const { $from, $to } = state.selection; 12120 const node = state.selection.node; 12121 if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to)) return false; 12122 const grandParent = $from.node(-1); 12123 if (grandParent.type !== type) return false; 12124 const extensionAttributes = editor.extensionManager.attributes; 12125 if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) { 12126 if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) return false; 12127 if (dispatch) { 12128 var _type$contentMatch$de; 12129 let wrap$1 = Fragment.empty; 12130 const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3; 12131 for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) wrap$1 = Fragment.from($from.node(d).copy(wrap$1)); 12132 const depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3; 12133 const newNextTypeAttributes$1 = { 12134 ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs), 12135 ...overrideAttrs 12136 }; 12137 const nextType$1 = ((_type$contentMatch$de = type.contentMatch.defaultType) === null || _type$contentMatch$de === void 0 ? void 0 : _type$contentMatch$de.createAndFill(newNextTypeAttributes$1)) || void 0; 12138 wrap$1 = wrap$1.append(Fragment.from(type.createAndFill(null, nextType$1) || void 0)); 12139 const start = $from.before($from.depth - (depthBefore - 1)); 12140 tr$1.replace(start, $from.after(-depthAfter), new Slice(wrap$1, 4 - depthBefore, 0)); 12141 let sel = -1; 12142 tr$1.doc.nodesBetween(start, tr$1.doc.content.size, (n, pos) => { 12143 if (sel > -1) return false; 12144 if (n.isTextblock && n.content.size === 0) sel = pos + 1; 12145 }); 12146 if (sel > -1) tr$1.setSelection(TextSelection.near(tr$1.doc.resolve(sel))); 12147 tr$1.scrollIntoView(); 12148 } 12149 return true; 12150 } 12151 const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null; 12152 const newTypeAttributes = { 12153 ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs), 12154 ...overrideAttrs 12155 }; 12156 const newNextTypeAttributes = { 12157 ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs), 12158 ...overrideAttrs 12159 }; 12160 tr$1.delete($from.pos, $to.pos); 12161 const types = nextType ? [{ 12162 type, 12163 attrs: newTypeAttributes 12164 }, { 12165 type: nextType, 12166 attrs: newNextTypeAttributes 12167 }] : [{ 12168 type, 12169 attrs: newTypeAttributes 12170 }]; 12171 if (!canSplit(tr$1.doc, $from.pos, 2)) return false; 12172 if (dispatch) { 12173 const { selection, storedMarks } = state; 12174 const { splittableMarks } = editor.extensionManager; 12175 const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); 12176 tr$1.split($from.pos, 2, types).scrollIntoView(); 12177 if (!marks || !dispatch) return true; 12178 const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); 12179 tr$1.ensureMarks(filteredMarks); 12180 } 12181 return true; 12182}; 12183function normalizeListType(type) { 12184 return !type || type === "1" ? null : type; 12185} 12186function areListTypesCompatible(typeA, typeB) { 12187 return normalizeListType(typeA) === normalizeListType(typeB); 12188} 12189var joinListBackwards = (tr$1, listType) => { 12190 const list = findParentNode((node) => node.type === listType)(tr$1.selection); 12191 if (!list) return true; 12192 const before = tr$1.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth); 12193 if (before === void 0) return true; 12194 const nodeBefore = tr$1.doc.nodeAt(before); 12195 if (!(list.node.type === (nodeBefore === null || nodeBefore === void 0 ? void 0 : nodeBefore.type) && canJoin(tr$1.doc, list.pos))) return true; 12196 if (!areListTypesCompatible(list.node.attrs.type, nodeBefore === null || nodeBefore === void 0 ? void 0 : nodeBefore.attrs.type)) return true; 12197 tr$1.join(list.pos); 12198 return true; 12199}; 12200var joinListForwards = (tr$1, listType) => { 12201 const list = findParentNode((node) => node.type === listType)(tr$1.selection); 12202 if (!list) return true; 12203 const after = tr$1.doc.resolve(list.start).after(list.depth); 12204 if (after === void 0) return true; 12205 const nodeAfter = tr$1.doc.nodeAt(after); 12206 if (!(list.node.type === (nodeAfter === null || nodeAfter === void 0 ? void 0 : nodeAfter.type) && canJoin(tr$1.doc, after))) return true; 12207 if (!areListTypesCompatible(list.node.attrs.type, nodeAfter === null || nodeAfter === void 0 ? void 0 : nodeAfter.attrs.type)) return true; 12208 tr$1.join(after); 12209 return true; 12210}; 12211function createInnerSelectionForWholeDocList(tr$1) { 12212 const doc$2 = tr$1.doc; 12213 const list = doc$2.firstChild; 12214 if (!list) return null; 12215 const $start = doc$2.resolve(1); 12216 const $end = doc$2.resolve(list.nodeSize - 1); 12217 return TextSelection.between($start, $end); 12218} 12219var toggleList = (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({ editor, tr: tr$1, state, dispatch, chain, commands, can }) => { 12220 const { extensions, splittableMarks } = editor.extensionManager; 12221 const listType = getNodeType(listTypeOrName, state.schema); 12222 const itemType = getNodeType(itemTypeOrName, state.schema); 12223 const { selection, storedMarks } = state; 12224 const { $from, $to } = selection; 12225 const range = $from.blockRange($to); 12226 const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); 12227 if (!range) return false;
vendor: 8,575 bytes, lines 12228-12439
12228 const parentList = findParentNode((node) => isList(node.type.name, extensions))(selection); 12229 const isAllSelection = selection.from === 0 && selection.to === state.doc.content.size; 12230 const topLevelNodes = state.doc.content.content; 12231 const soleTopLevelNode = topLevelNodes.length === 1 ? topLevelNodes[0] : null; 12232 const allSelectionList = isAllSelection && soleTopLevelNode && isList(soleTopLevelNode.type.name, extensions) ? { 12233 node: soleTopLevelNode, 12234 pos: 0, 12235 depth: 0 12236 } : null; 12237 const currentList = parentList !== null && parentList !== void 0 ? parentList : allSelectionList; 12238 const isInsideExistingList = !!parentList && range.depth >= 1 && range.depth - parentList.depth <= 1; 12239 const hasWholeDocSelectedList = !!allSelectionList; 12240 if ((isInsideExistingList || hasWholeDocSelectedList) && currentList) { 12241 if (currentList.node.type === listType) { 12242 if (isAllSelection && hasWholeDocSelectedList) return chain().command(({ tr: trx, dispatch: disp }) => { 12243 const nextSelection = createInnerSelectionForWholeDocList(trx); 12244 if (!nextSelection) return false; 12245 trx.setSelection(nextSelection); 12246 if (disp) disp(trx); 12247 return true; 12248 }).liftListItem(itemType).run(); 12249 return commands.liftListItem(itemType); 12250 } 12251 if (isList(currentList.node.type.name, extensions) && listType.validContent(currentList.node.content)) return chain().command(() => { 12252 tr$1.setNodeMarkup(currentList.pos, listType); 12253 return true; 12254 }).command(() => joinListBackwards(tr$1, listType)).command(() => joinListForwards(tr$1, listType)).run(); 12255 } 12256 if (!keepMarks || !marks || !dispatch) return chain().command(() => { 12257 if (can().wrapInList(listType, attributes)) return true; 12258 return commands.clearNodes(); 12259 }).wrapInList(listType, attributes).command(() => joinListBackwards(tr$1, listType)).command(() => joinListForwards(tr$1, listType)).run(); 12260 return chain().command(() => { 12261 const canWrapInList = can().wrapInList(listType, attributes); 12262 const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); 12263 tr$1.ensureMarks(filteredMarks); 12264 if (canWrapInList) return true; 12265 return commands.clearNodes(); 12266 }).wrapInList(listType, attributes).command(() => joinListBackwards(tr$1, listType)).command(() => joinListForwards(tr$1, listType)).run(); 12267}; 12268var toggleMark = (typeOrName, attributes = {}, options = {}) => ({ state, commands }) => { 12269 const { extendEmptyMarkRange = false } = options; 12270 const type = getMarkType(typeOrName, state.schema); 12271 if (isMarkActive(state, type, attributes)) return commands.unsetMark(type, { extendEmptyMarkRange }); 12272 return commands.setMark(type, attributes); 12273}; 12274var toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => { 12275 const type = getNodeType(typeOrName, state.schema); 12276 const toggleType = getNodeType(toggleTypeOrName, state.schema); 12277 const isActive$1 = isNodeActive(state, type, attributes); 12278 let attributesToCopy; 12279 if (state.selection.$anchor.sameParent(state.selection.$head)) attributesToCopy = state.selection.$anchor.parent.attrs; 12280 if (isActive$1) return commands.setNode(toggleType, attributesToCopy); 12281 return commands.setNode(type, { 12282 ...attributesToCopy, 12283 ...attributes 12284 }); 12285}; 12286var toggleWrap = (typeOrName, attributes = {}) => ({ state, commands }) => { 12287 const type = getNodeType(typeOrName, state.schema); 12288 if (isNodeActive(state, type, attributes)) return commands.lift(type); 12289 return commands.wrapIn(type, attributes); 12290}; 12291var undoInputRule = () => ({ state, dispatch }) => { 12292 const plugins = state.plugins; 12293 for (let i$1 = 0; i$1 < plugins.length; i$1 += 1) { 12294 const plugin = plugins[i$1]; 12295 let undoable; 12296 if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) { 12297 if (dispatch) { 12298 const tr$1 = state.tr; 12299 const toUndo = undoable.transform; 12300 for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) tr$1.step(toUndo.steps[j].invert(toUndo.docs[j])); 12301 if (undoable.text) { 12302 const marks = tr$1.doc.resolve(undoable.from).marks(); 12303 tr$1.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks)); 12304 } else tr$1.delete(undoable.from, undoable.to); 12305 } 12306 return true; 12307 } 12308 } 12309 return false; 12310}; 12311var unsetAllMarks = (options = {}) => ({ tr: tr$1, dispatch, editor }) => { 12312 const { ignoreClearable = false } = options; 12313 const { selection } = tr$1; 12314 const { empty: empty$1, ranges } = selection; 12315 if (empty$1) return true; 12316 const { nonClearableMarks } = editor.extensionManager; 12317 if (dispatch) { 12318 const clearableMarkTypes = Object.values(editor.schema.marks).filter((markType) => ignoreClearable || !nonClearableMarks.includes(markType.name)); 12319 ranges.forEach((range) => { 12320 for (const markType of clearableMarkTypes) tr$1.removeMark(range.$from.pos, range.$to.pos, markType); 12321 }); 12322 } 12323 return true; 12324}; 12325var unsetMark = (typeOrName, options = {}) => ({ tr: tr$1, state, dispatch }) => { 12326 const { extendEmptyMarkRange = false } = options; 12327 const { selection } = tr$1; 12328 const type = getMarkType(typeOrName, state.schema); 12329 const { $from, empty: empty$1, ranges } = selection; 12330 if (!dispatch) return true; 12331 if (empty$1 && extendEmptyMarkRange) { 12332 var _$from$marks$find; 12333 let { from, to } = selection; 12334 const range = getMarkRange($from, type, (_$from$marks$find = $from.marks().find((mark) => mark.type === type)) === null || _$from$marks$find === void 0 ? void 0 : _$from$marks$find.attrs); 12335 if (range) { 12336 from = range.from; 12337 to = range.to; 12338 } 12339 tr$1.removeMark(from, to, type); 12340 } else ranges.forEach((range) => { 12341 tr$1.removeMark(range.$from.pos, range.$to.pos, type); 12342 }); 12343 tr$1.removeStoredMark(type); 12344 return true; 12345}; 12346var unsetTextDirection = (position) => ({ tr: tr$1, state, dispatch }) => { 12347 const { selection } = state; 12348 let from; 12349 let to; 12350 if (typeof position === "number") { 12351 from = position; 12352 to = position; 12353 } else if (position && "from" in position && "to" in position) { 12354 from = position.from; 12355 to = position.to; 12356 } else { 12357 from = selection.from; 12358 to = selection.to; 12359 } 12360 if (dispatch) tr$1.doc.nodesBetween(from, to, (node, pos) => { 12361 if (node.isText) return; 12362 const newAttrs = { ...node.attrs }; 12363 delete newAttrs.dir; 12364 tr$1.setNodeMarkup(pos, void 0, newAttrs); 12365 }); 12366 return true; 12367}; 12368var updateAttributes = (typeOrName, attributes = {}) => ({ tr: tr$1, state, dispatch }) => { 12369 let nodeType = null; 12370 let markType = null; 12371 const schemaType = getSchemaTypeNameByName(typeof typeOrName === "string" ? typeOrName : typeOrName.name, state.schema); 12372 if (!schemaType) return false; 12373 if (schemaType === "node") nodeType = getNodeType(typeOrName, state.schema); 12374 if (schemaType === "mark") markType = getMarkType(typeOrName, state.schema); 12375 let canUpdate = false; 12376 tr$1.selection.ranges.forEach((range) => { 12377 const from = range.$from.pos; 12378 const to = range.$to.pos; 12379 let lastPos; 12380 let lastNode; 12381 let trimmedFrom; 12382 let trimmedTo; 12383 if (tr$1.selection.empty) state.doc.nodesBetween(from, to, (node, pos) => { 12384 if (nodeType && nodeType === node.type) { 12385 canUpdate = true; 12386 trimmedFrom = Math.max(pos, from); 12387 trimmedTo = Math.min(pos + node.nodeSize, to); 12388 lastPos = pos; 12389 lastNode = node; 12390 } 12391 }); 12392 else state.doc.nodesBetween(from, to, (node, pos) => { 12393 if (pos < from && nodeType && nodeType === node.type) { 12394 canUpdate = true; 12395 trimmedFrom = Math.max(pos, from); 12396 trimmedTo = Math.min(pos + node.nodeSize, to); 12397 lastPos = pos; 12398 lastNode = node; 12399 } 12400 if (pos >= from && pos <= to) { 12401 if (nodeType && nodeType === node.type) { 12402 canUpdate = true; 12403 if (dispatch) tr$1.setNodeMarkup(pos, void 0, { 12404 ...node.attrs, 12405 ...attributes 12406 }); 12407 } 12408 if (markType && node.marks.length) node.marks.forEach((mark) => { 12409 if (markType === mark.type) { 12410 canUpdate = true; 12411 if (dispatch) { 12412 const trimmedFrom2 = Math.max(pos, from); 12413 const trimmedTo2 = Math.min(pos + node.nodeSize, to); 12414 tr$1.addMark(trimmedFrom2, trimmedTo2, markType.create({ 12415 ...mark.attrs, 12416 ...attributes 12417 })); 12418 } 12419 } 12420 }); 12421 } 12422 }); 12423 if (lastNode) { 12424 if (lastPos !== void 0 && dispatch) tr$1.setNodeMarkup(lastPos, void 0, { 12425 ...lastNode.attrs, 12426 ...attributes 12427 }); 12428 if (markType && lastNode.marks.length) lastNode.marks.forEach((mark) => { 12429 if (markType === mark.type && dispatch) tr$1.addMark(trimmedFrom, trimmedTo, markType.create({ 12430 ...mark.attrs, 12431 ...attributes 12432 })); 12433 }); 12434 } 12435 }); 12436 return canUpdate; 12437}; 12438var DECORATION_MANAGER_PLUGIN_KEY = new PluginKey("__tiptap_decorations__"); 12439var updateDecorations = (extensionName) => ({ tr: tr$1, dispatch }) => {
12440 if (dispatch) tr$1.setMeta(DECORATION_MANAGER_PLUGIN_KEY, { 12441 type: "force", 12442 name: extensionName 12443 }); 12444 return true; 12445}; 12446var wrapIn$1 = (typeOrName, attributes = {}) => ({ state, dispatch }) => { 12447 return wrapIn(getNodeType(typeOrName, state.schema), attributes)(state, dispatch); 12448}; 12449var wrapInList$1 = (typeOrName, attributes = {}) => ({ state, dispatch }) => { 12450 return wrapInList(getNodeType(typeOrName, state.schema), attributes)(state, dispatch); 12451}; 12452var commands_exports = /* @__PURE__ */ __exportAll({ 12453 blur: () => blur, 12454 clearContent: () => clearContent, 12455 clearNodes: () => clearNodes, 12456 command: () => command, 12457 createParagraphNear: () => createParagraphNear$1, 12458 cut: () => cut, 12459 deleteCurrentNode: () => deleteCurrentNode, 12460 deleteNode: () => deleteNode, 12461 deleteRange: () => deleteRange, 12462 deleteSelection: () => deleteSelection, 12463 enter: () => enter, 12464 exitCode: () => exitCode$1, 12465 extendMarkRange: () => extendMarkRange, 12466 first: () => first, 12467 focus: () => focus, 12468 forEach: () => forEach, 12469 insertContent: () => insertContent, 12470 insertContentAt: () => insertContentAt, 12471 insertDefaultBlock: () => insertDefaultBlock, 12472 joinBackward: () => joinBackward$1, 12473 joinDown: () => joinDown$1, 12474 joinForward: () => joinForward$1, 12475 joinItemBackward: () => joinItemBackward, 12476 joinItemForward: () => joinItemForward, 12477 joinTextblockBackward: () => joinTextblockBackward$1, 12478 joinTextblockForward: () => joinTextblockForward$1, 12479 joinUp: () => joinUp$1, 12480 keyboardShortcut: () => keyboardShortcut, 12481 lift: () => lift$1, 12482 liftEmptyBlock: () => liftEmptyBlock$1, 12483 liftListItem: () => liftListItem$1, 12484 newlineInCode: () => newlineInCode$1, 12485 resetAttributes: () => resetAttributes, 12486 scrollIntoView: () => scrollIntoView, 12487 selectAll: () => selectAll, 12488 selectNodeBackward: () => selectNodeBackward$1, 12489 selectNodeForward: () => selectNodeForward$1, 12490 selectParentNode: () => selectParentNode$1, 12491 selectTextblockEnd: () => selectTextblockEnd$1, 12492 selectTextblockStart: () => selectTextblockStart$1, 12493 setContent: () => setContent, 12494 setMark: () => setMark, 12495 setMeta: () => setMeta, 12496 setNode: () => setNode, 12497 setNodeSelection: () => setNodeSelection, 12498 setTextDirection: () => setTextDirection, 12499 setTextSelection: () => setTextSelection, 12500 sinkListItem: () => sinkListItem$1, 12501 splitBlock: () => splitBlock, 12502 splitListItem: () => splitListItem, 12503 toggleList: () => toggleList, 12504 toggleMark: () => toggleMark, 12505 toggleNode: () => toggleNode, 12506 toggleWrap: () => toggleWrap, 12507 undoInputRule: () => undoInputRule, 12508 unsetAllMarks: () => unsetAllMarks, 12509 unsetMark: () => unsetMark, 12510 unsetTextDirection: () => unsetTextDirection, 12511 updateAttributes: () => updateAttributes, 12512 updateDecorations: () => updateDecorations, 12513 wrapIn: () => wrapIn$1, 12514 wrapInList: () => wrapInList$1 12515}); 12516var depthByEditor = /* @__PURE__ */ new WeakMap(); 12517function runInDecorationApplyScope(editor, callback) { 12518 var _depthByEditor$get; 12519 depthByEditor.set(editor, ((_depthByEditor$get = depthByEditor.get(editor)) !== null && _depthByEditor$get !== void 0 ? _depthByEditor$get : 0) + 1); 12520 try { 12521 return callback(); 12522 } finally { 12523 var _depthByEditor$get2; 12524 const remaining = ((_depthByEditor$get2 = depthByEditor.get(editor)) !== null && _depthByEditor$get2 !== void 0 ? _depthByEditor$get2 : 1) - 1; 12525 if (remaining > 0) depthByEditor.set(editor, remaining); 12526 else depthByEditor.delete(editor); 12527 } 12528} 12529function isInDecorationApplyScope(editor) { 12530 return depthByEditor.has(editor); 12531} 12532var EventEmitter = class { 12533 constructor() { 12534 this.callbacks = {}; 12535 } 12536 on(event, fn) { 12537 if (!this.callbacks[event]) this.callbacks[event] = []; 12538 this.callbacks[event].push(fn); 12539 return this; 12540 } 12541 emit(event, ...args) { 12542 const callbacks = this.callbacks[event]; 12543 if (callbacks) callbacks.forEach((callback) => callback.apply(this, args)); 12544 return this; 12545 } 12546 off(event, fn) { 12547 const callbacks = this.callbacks[event]; 12548 if (callbacks) if (fn) this.callbacks[event] = callbacks.filter((callback) => callback !== fn); 12549 else delete this.callbacks[event]; 12550 return this; 12551 } 12552 once(event, fn) { 12553 const onceFn = (...args) => { 12554 this.off(event, onceFn); 12555 fn.apply(this, args); 12556 }; 12557 return this.on(event, onceFn); 12558 } 12559 removeAllListeners() { 12560 this.callbacks = {}; 12561 } 12562}; 12563var isDev$1 = typeof process !== "undefined" && true; 12564function isWidgetDecoration(decoration) { 12565 return decoration.kind === "widget"; 12566} 12567function decorationsToPMDecorations(decorations, extensionName) { 12568 const pmDecorations = []; 12569 const widgetKeys = /* @__PURE__ */ new Set(); 12570 for (const decoration of decorations) { 12571 if (decoration.kind === "widget") { 12572 if (isWidgetDecoration(decoration)) widgetKeys.add(decoration.key); 12573 } 12574 pmDecorations.push(decoration.toPMDecoration(extensionName)); 12575 } 12576 return { 12577 decorations: pmDecorations, 12578 widgetKeys 12579 }; 12580} 12581function buildDecorationSet(doc$2, decorations, extensionName) { 12582 const { decorations: pmDecorations, widgetKeys } = decorationsToPMDecorations(decorations, extensionName); 12583 return { 12584 set: DecorationSet.create(doc$2, pmDecorations), 12585 widgetKeys 12586 }; 12587} 12588function rangeOwnsPosition({ position, from, to, docSize }) { 12589 if (position < from) return false;
vendor: 2,047 bytes, lines 12590-12639
12590 if (position < to) return true; 12591 return position === to && to === docSize; 12592} 12593function filterOutOfRangeDecorations({ decorations, from, to, docSize, extensionName, warnedExtensions }) { 12594 return decorations.filter((decoration) => { 12595 if (rangeOwnsPosition({ 12596 position: decoration.anchor, 12597 from, 12598 to, 12599 docSize 12600 })) return true; 12601 if (decoration.anchor === to) return false; 12602 if (!warnedExtensions.has(extensionName)) { 12603 warnedExtensions.add(extensionName); 12604 console.warn(`[tiptap warn]: Extension "${extensionName}" returned a decoration outside the requested range [${from}, ${to}). It was ignored.`); 12605 } 12606 return false; 12607 }); 12608} 12609function widgetKeyOf(decoration) { 12610 var _decoration$spec; 12611 const key = (_decoration$spec = decoration.spec) === null || _decoration$spec === void 0 ? void 0 : _decoration$spec.key; 12612 return typeof key === "string" ? key : void 0; 12613} 12614function findDuplicateWidgetKeys(decorationSet) { 12615 const extensionsByKey = /* @__PURE__ */ new Map(); 12616 const counts = /* @__PURE__ */ new Map(); 12617 for (const decoration of decorationSet.find()) { 12618 var _extensionName, _extensionsByKey$get, _counts$get; 12619 const key = widgetKeyOf(decoration); 12620 if (!key) continue; 12621 const extension = (_extensionName = decoration.spec.extensionName) !== null && _extensionName !== void 0 ? _extensionName : "unknown"; 12622 const extensions = (_extensionsByKey$get = extensionsByKey.get(key)) !== null && _extensionsByKey$get !== void 0 ? _extensionsByKey$get : /* @__PURE__ */ new Set(); 12623 extensions.add(extension); 12624 extensionsByKey.set(key, extensions); 12625 counts.set(key, ((_counts$get = counts.get(key)) !== null && _counts$get !== void 0 ? _counts$get : 0) + 1); 12626 } 12627 return Array.from(extensionsByKey, ([key, extensions]) => ({ 12628 key, 12629 extensions 12630 })).filter(({ key }) => { 12631 var _counts$get2; 12632 return ((_counts$get2 = counts.get(key)) !== null && _counts$get2 !== void 0 ? _counts$get2 : 0) > 1; 12633 }); 12634} 12635function isAttrStep(step) { 12636 return step.jsonID === "attr"; 12637} 12638function hasResolvableChangedRange(step) { 12639 let hasMappedRange = false;
vendor: 15,520 bytes, lines 12640-13013
12640 step.getMap().forEach(() => { 12641 hasMappedRange = true; 12642 }); 12643 if (hasMappedRange || isAttrStep(step)) return true; 12644 const positionalStep = step; 12645 return typeof positionalStep.from === "number" && typeof positionalStep.to === "number"; 12646} 12647function blockRangeFor(doc$2, changed) { 12648 let from = null; 12649 let to = 0; 12650 let nodeStart = 0; 12651 for (let index = 0; index < doc$2.childCount; index += 1) { 12652 if (nodeStart > changed.to) break; 12653 const nodeEnd = nodeStart + doc$2.child(index).nodeSize; 12654 if (nodeEnd >= changed.from) { 12655 if (from === null) from = nodeStart; 12656 to = nodeEnd; 12657 } 12658 nodeStart = nodeEnd; 12659 } 12660 return from === null ? null : { 12661 from, 12662 to 12663 }; 12664} 12665function getRebuildRanges(tr$1, doc$2) { 12666 if (tr$1.steps.some((step) => !hasResolvableChangedRange(step))) return { type: "full" }; 12667 const newRanges = getChangedRanges(tr$1).map(({ newRange }) => newRange); 12668 tr$1.steps.forEach((step, index) => { 12669 if (!isAttrStep(step)) return; 12670 const mapping = tr$1.mapping.slice(index); 12671 newRanges.push({ 12672 from: mapping.map(step.pos, -1), 12673 to: mapping.map(step.pos + 1) 12674 }); 12675 }); 12676 const ranges = []; 12677 for (const newRange of newRanges) { 12678 const blockRange = blockRangeFor(doc$2, newRange); 12679 if (blockRange) ranges.push(blockRange); 12680 } 12681 ranges.sort((a, b) => a.from - b.from); 12682 const merged = []; 12683 for (const range of ranges) { 12684 const last = merged[merged.length - 1]; 12685 if (last && range.from <= last.to) last.to = Math.max(last.to, range.to); 12686 else merged.push({ ...range }); 12687 } 12688 return { 12689 type: "ranges", 12690 ranges: merged 12691 }; 12692} 12693function mapDecorationSet(set, mapping, doc$2, widgetKeys) { 12694 return set.map(mapping, doc$2, { onRemove: (removedSpec) => { 12695 const key = removedSpec === null || removedSpec === void 0 ? void 0 : removedSpec.key; 12696 if (typeof key === "string") widgetKeys.delete(key); 12697 } }); 12698} 12699function mapDecorations(name, previous, tr$1) { 12700 var _previous$decorationS, _previous$widgetKeysB; 12701 const previousSet = (_previous$decorationS = previous.decorationSetsByExtension[name]) !== null && _previous$decorationS !== void 0 ? _previous$decorationS : DecorationSet.empty; 12702 const widgetKeys = new Set((_previous$widgetKeysB = previous.widgetKeysByExtension[name]) !== null && _previous$widgetKeysB !== void 0 ? _previous$widgetKeysB : []); 12703 return { 12704 set: mapDecorationSet(previousSet, tr$1.mapping, tr$1.doc, widgetKeys), 12705 widgetKeys 12706 }; 12707} 12708function mergeDecorationSets(doc$2, decorationSetsByExtension) { 12709 const allDecorations = Object.values(decorationSetsByExtension).flatMap((set) => set.find()); 12710 return DecorationSet.create(doc$2, allDecorations); 12711} 12712function unionWidgetKeys(widgetKeysByExtension) { 12713 const merged = /* @__PURE__ */ new Set(); 12714 for (const keys$1 of Object.values(widgetKeysByExtension)) for (const key of keys$1) merged.add(key); 12715 return merged; 12716} 12717function validateDecorationSpec(name, spec) { 12718 var _update; 12719 switch ((_update = spec.update) !== null && _update !== void 0 ? _update : "document") { 12720 case "document": 12721 if (spec.createInRange) throw new Error(`[tiptap error]: Extension "${name}" provides createInRange() but does not use the "changedRanges" decoration update strategy.`); 12722 return; 12723 case "changedRanges": 12724 if (!spec.createInRange) throw new Error(`[tiptap error]: Extension "${name}" uses the "changedRanges" decoration update strategy but does not provide createInRange().`); 12725 return; 12726 case "manual": 12727 if (spec.createInRange) throw new Error(`[tiptap error]: Extension "${name}" uses the "manual" decoration update strategy, which is not compatible with createInRange(). createInRange() requires the "changedRanges" strategy.`); 12728 if (spec.shouldUpdate) throw new Error(`[tiptap error]: Extension "${name}" cannot combine the "manual" decoration update strategy with shouldUpdate().`); 12729 return; 12730 default: throw new Error(`[tiptap error]: Extension "${name}" uses an unknown decoration update strategy. Expected "document", "changedRanges", or "manual".`); 12731 } 12732} 12733function shouldRecomputeDecoration(spec, props, forced) { 12734 if (forced) return true; 12735 if (spec.update === "manual") return false; 12736 return spec.shouldUpdate ? spec.shouldUpdate(props) : props.tr.docChanged; 12737} 12738var EMPTY_KEYS = /* @__PURE__ */ new Set(); 12739var DecorationManager = class { 12740 constructor(options) { 12741 this.warnedWidgetKeys = /* @__PURE__ */ new Set(); 12742 this.warnedOutOfRangeExtensions = /* @__PURE__ */ new Set(); 12743 this.handleBeforeTransaction = ({ nextState }) => { 12744 const state = DECORATION_MANAGER_PLUGIN_KEY.getState(nextState); 12745 if (state) this.warnDuplicateWidgetKeys(state); 12746 }; 12747 this.editor = options.editor; 12748 this.entries = this.resolveEntries(options.entries); 12749 this.entries.forEach(({ name, spec }) => validateDecorationSpec(name, spec)); 12750 this.plugin = this.entries.length > 0 ? this.createPlugin() : null; 12751 this.editor.on("beforeTransaction", this.handleBeforeTransaction); 12752 } 12753 destroy() { 12754 this.editor.off("beforeTransaction", this.handleBeforeTransaction); 12755 } 12756 liveWidgetKeys() { 12757 var _DECORATION_MANAGER_P, _DECORATION_MANAGER_P2; 12758 return (_DECORATION_MANAGER_P = (_DECORATION_MANAGER_P2 = DECORATION_MANAGER_PLUGIN_KEY.getState(this.editor.state)) === null || _DECORATION_MANAGER_P2 === void 0 ? void 0 : _DECORATION_MANAGER_P2.widgetKeys) !== null && _DECORATION_MANAGER_P !== void 0 ? _DECORATION_MANAGER_P : EMPTY_KEYS; 12759 } 12760 get mountedView() { 12761 return this.editor.isDestroyed ? null : this.editor.view; 12762 } 12763 resolveEntries(entries$1) { 12764 const resolved = []; 12765 for (const { name, addDecorations } of entries$1) { 12766 const spec = addDecorations(); 12767 if (spec) resolved.push({ 12768 name, 12769 spec 12770 }); 12771 } 12772 return resolved; 12773 } 12774 createPlugin() { 12775 const { editor, entries: entries$1 } = this; 12776 return new Plugin({ 12777 key: DECORATION_MANAGER_PLUGIN_KEY, 12778 state: { 12779 init: (_config, state) => { 12780 const decorationSetsByExtension = {}; 12781 const widgetKeysByExtension = {}; 12782 for (const { name, spec } of entries$1) { 12783 const { set, widgetKeys } = this.buildFullSet(name, spec, state); 12784 decorationSetsByExtension[name] = set; 12785 widgetKeysByExtension[name] = widgetKeys; 12786 } 12787 const managerState = { 12788 decorationSetsByExtension, 12789 widgetKeysByExtension, 12790 mergedDecorationSet: this.buildMergedSet(state.doc, decorationSetsByExtension), 12791 widgetKeys: unionWidgetKeys(widgetKeysByExtension) 12792 }; 12793 this.warnDuplicateWidgetKeys(managerState); 12794 return managerState; 12795 }, 12796 apply: (tr$1, previous, oldState, newState) => { 12797 const meta = tr$1.getMeta(DECORATION_MANAGER_PLUGIN_KEY); 12798 const forceAll = (meta === null || meta === void 0 ? void 0 : meta.type) === "force" && !meta.name; 12799 const forceName = (meta === null || meta === void 0 ? void 0 : meta.type) === "force" ? meta.name : void 0; 12800 const decorationSetsByExtension = {}; 12801 const widgetKeysByExtension = {}; 12802 const recomputedNames = /* @__PURE__ */ new Set(); 12803 runInDecorationApplyScope(editor, () => { 12804 for (const { name, spec } of entries$1) { 12805 const forced = forceAll || forceName === name; 12806 if (!shouldRecomputeDecoration(spec, { 12807 editor, 12808 tr: tr$1, 12809 oldState, 12810 newState 12811 }, forced)) { 12812 const result = mapDecorations(name, previous, tr$1); 12813 decorationSetsByExtension[name] = result.set; 12814 widgetKeysByExtension[name] = result.widgetKeys; 12815 } else if (spec.update === "changedRanges" && tr$1.docChanged && !forced) { 12816 const result = this.applyChangedRangesRecompute(name, spec, previous, tr$1, newState); 12817 decorationSetsByExtension[name] = result.set; 12818 widgetKeysByExtension[name] = result.widgetKeys; 12819 recomputedNames.add(name); 12820 } else { 12821 const { set, widgetKeys } = this.buildFullSet(name, spec, newState); 12822 decorationSetsByExtension[name] = set; 12823 widgetKeysByExtension[name] = widgetKeys; 12824 recomputedNames.add(name); 12825 } 12826 } 12827 }); 12828 if (recomputedNames.size === 0 && !tr$1.docChanged) return previous; 12829 return { 12830 decorationSetsByExtension, 12831 widgetKeysByExtension, 12832 mergedDecorationSet: this.mergeAfterApply({ 12833 entries: entries$1, 12834 previous, 12835 tr: tr$1, 12836 decorationSetsByExtension, 12837 recomputedNames 12838 }), 12839 widgetKeys: unionWidgetKeys(widgetKeysByExtension) 12840 }; 12841 } 12842 }, 12843 props: { decorations(state) { 12844 var _DECORATION_MANAGER_P3, _DECORATION_MANAGER_P4; 12845 return (_DECORATION_MANAGER_P3 = (_DECORATION_MANAGER_P4 = DECORATION_MANAGER_PLUGIN_KEY.getState(state)) === null || _DECORATION_MANAGER_P4 === void 0 ? void 0 : _DECORATION_MANAGER_P4.mergedDecorationSet) !== null && _DECORATION_MANAGER_P3 !== void 0 ? _DECORATION_MANAGER_P3 : DecorationSet.empty; 12846 } } 12847 }); 12848 } 12849 applyChangedRangesRecompute(name, spec, previous, tr$1, newState) { 12850 const resolution = getRebuildRanges(tr$1, newState.doc); 12851 if (resolution.type === "full") return this.buildFullSet(name, spec, newState); 12852 return this.rebuildRanges(name, spec, previous, tr$1, newState, resolution.ranges); 12853 } 12854 rebuildRanges(name, spec, previous, tr$1, newState, ranges) { 12855 var _previous$decorationS, _previous$widgetKeysB; 12856 const previousSet = (_previous$decorationS = previous.decorationSetsByExtension[name]) !== null && _previous$decorationS !== void 0 ? _previous$decorationS : DecorationSet.empty; 12857 const widgetKeys = new Set((_previous$widgetKeysB = previous.widgetKeysByExtension[name]) !== null && _previous$widgetKeysB !== void 0 ? _previous$widgetKeysB : []); 12858 let set = mapDecorationSet(previousSet, tr$1.mapping, tr$1.doc, widgetKeys); 12859 const docSize = newState.doc.content.size; 12860 for (const { from, to } of ranges) { 12861 const stale = set.find(from, to).filter((decoration) => rangeOwnsPosition({ 12862 position: decoration.from, 12863 from, 12864 to, 12865 docSize 12866 })); 12867 for (const decoration of stale) { 12868 const key = widgetKeyOf(decoration); 12869 if (key) widgetKeys.delete(key); 12870 } 12871 set = set.remove(stale); 12872 const { decorations: pmDecorations, widgetKeys: addedKeys } = decorationsToPMDecorations(filterOutOfRangeDecorations({ 12873 decorations: this.runCreate(name, "createInRange", () => spec.createInRange({ 12874 editor: this.editor, 12875 state: newState, 12876 view: this.mountedView, 12877 from, 12878 to 12879 })), 12880 from, 12881 to, 12882 docSize, 12883 extensionName: name, 12884 warnedExtensions: this.warnedOutOfRangeExtensions 12885 }), name); 12886 set = set.add(newState.doc, pmDecorations); 12887 for (const key of addedKeys) widgetKeys.add(key); 12888 } 12889 return { 12890 set, 12891 widgetKeys 12892 }; 12893 } 12894 buildFullSet(name, spec, state) { 12895 const decorations = this.runCreate(name, "create", () => spec.create({ 12896 editor: this.editor, 12897 state, 12898 view: this.mountedView 12899 })); 12900 return buildDecorationSet(state.doc, decorations, name); 12901 } 12902 runCreate(name, method, create$1) { 12903 try { 12904 return create$1(); 12905 } catch (error) { 12906 console.error(`[tiptap error]: Extension "${name}" threw in \`addDecorations().${method}()\`. Its decorations were dropped for this update.`, error); 12907 return []; 12908 } 12909 } 12910 warnDuplicateWidgetKeys(state) { 12911 if (!isDev$1) return; 12912 if (state.widgetKeys.size === 0) { 12913 this.warnedWidgetKeys.clear(); 12914 return; 12915 } 12916 const duplicateKeys = findDuplicateWidgetKeys(state.mergedDecorationSet); 12917 const nextWarningKeys = new Set(duplicateKeys.map(({ key }) => key)); 12918 for (const { key, extensions } of duplicateKeys) { 12919 if (this.warnedWidgetKeys.has(key)) continue; 12920 const names = Array.from(extensions).map((name) => `"${name}"`).join(", "); 12921 console.warn(`[tiptap warn]: Duplicate widget decoration key "${key}" in extension${extensions.size === 1 ? "" : "s"} ${names}. Widget decoration keys must be globally unique, otherwise ProseMirror misplaces the widget DOM. Use a stable, unique key (e.g. \`comment-\${id}\`).`); 12922 } 12923 this.warnedWidgetKeys = nextWarningKeys; 12924 } 12925 buildMergedSet(doc$2, decorationSetsByExtension) { 12926 const names = Object.keys(decorationSetsByExtension); 12927 if (names.length === 1) return decorationSetsByExtension[names[0]]; 12928 return mergeDecorationSets(doc$2, decorationSetsByExtension); 12929 } 12930 mergeAfterApply({ entries: entries$1, previous, tr: tr$1, decorationSetsByExtension, recomputedNames }) { 12931 if (entries$1.length === 1) return decorationSetsByExtension[entries$1[0].name]; 12932 if (recomputedNames.size === 0) return previous.mergedDecorationSet.map(tr$1.mapping, tr$1.doc); 12933 return mergeDecorationSets(tr$1.doc, decorationSetsByExtension); 12934 } 12935}; 12936function canInsertNode(state, nodeType) { 12937 const { selection } = state; 12938 const { $from } = selection; 12939 if (selection instanceof NodeSelection) { 12940 const index = $from.index(); 12941 return $from.parent.canReplaceWith(index, index + 1, nodeType); 12942 } 12943 let depth = $from.depth; 12944 while (depth >= 0) { 12945 const index = $from.index(depth); 12946 if ($from.node(depth).contentMatchAt(index).matchType(nodeType)) return true; 12947 depth -= 1; 12948 } 12949 return false; 12950} 12951function createStyleTag(style$1, nonce, suffix) { 12952 const tiptapStyleTag = document.querySelector(`style[data-tiptap-style${suffix ? `-${suffix}` : ""}]`); 12953 if (tiptapStyleTag !== null) return tiptapStyleTag; 12954 const styleNode = document.createElement("style"); 12955 if (nonce) styleNode.setAttribute("nonce", nonce); 12956 styleNode.setAttribute(`data-tiptap-style${suffix ? `-${suffix}` : ""}`, ""); 12957 styleNode.innerHTML = style$1; 12958 document.getElementsByTagName("head")[0].appendChild(styleNode); 12959 return styleNode; 12960} 12961function isNumber(value) { 12962 return typeof value === "number"; 12963} 12964function getType(value) { 12965 return Object.prototype.toString.call(value).slice(8, -1); 12966} 12967function isPlainObject(value) { 12968 if (getType(value) !== "Object") return false; 12969 return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype; 12970} 12971function parseIndentedBlocks(src, config, lexer) { 12972 const lines = src.split("\n"); 12973 const items = []; 12974 let totalRaw = ""; 12975 let i$1 = 0; 12976 const baseIndentSize = config.baseIndentSize || 2; 12977 while (i$1 < lines.length) { 12978 const currentLine = lines[i$1]; 12979 const itemMatch = currentLine.match(config.itemPattern); 12980 if (!itemMatch) if (items.length > 0) break; 12981 else if (currentLine.trim() === "") { 12982 i$1 += 1; 12983 totalRaw = `${totalRaw}${currentLine}\n`; 12984 continue; 12985 } else return; 12986 const itemData = config.extractItemData(itemMatch); 12987 const { indentLevel, mainContent } = itemData; 12988 totalRaw = `${totalRaw}${currentLine}\n`; 12989 const itemContent = [mainContent]; 12990 i$1 += 1; 12991 while (i$1 < lines.length) { 12992 var _nextLine$match; 12993 const nextLine = lines[i$1]; 12994 if (nextLine.trim() === "") { 12995 var _nextNonEmpty$match; 12996 const nextNonEmptyIndex = lines.slice(i$1 + 1).findIndex((l) => l.trim() !== ""); 12997 if (nextNonEmptyIndex === -1) break; 12998 if ((((_nextNonEmpty$match = lines[i$1 + 1 + nextNonEmptyIndex].match(/^(\s*)/)) === null || _nextNonEmpty$match === void 0 || (_nextNonEmpty$match = _nextNonEmpty$match[1]) === null || _nextNonEmpty$match === void 0 ? void 0 : _nextNonEmpty$match.length) || 0) > indentLevel) { 12999 itemContent.push(nextLine); 13000 totalRaw = `${totalRaw}${nextLine}\n`; 13001 i$1 += 1; 13002 continue; 13003 } else break; 13004 } 13005 if ((((_nextLine$match = nextLine.match(/^(\s*)/)) === null || _nextLine$match === void 0 || (_nextLine$match = _nextLine$match[1]) === null || _nextLine$match === void 0 ? void 0 : _nextLine$match.length) || 0) > indentLevel) { 13006 itemContent.push(nextLine); 13007 totalRaw = `${totalRaw}${nextLine}\n`; 13008 i$1 += 1; 13009 } else break; 13010 } 13011 let nestedTokens; 13012 const nestedContent = itemContent.slice(1); 13013 if (nestedContent.length > 0) {
vendor: 4,491 bytes, lines 13014-13120
13014 const dedentedNested = nestedContent.map((nestedLine) => nestedLine.slice(indentLevel + baseIndentSize)).join("\n"); 13015 if (dedentedNested.trim()) if (config.customNestedParser) nestedTokens = config.customNestedParser(dedentedNested); 13016 else nestedTokens = lexer.blockTokens(dedentedNested); 13017 } 13018 const token = config.createToken(itemData, nestedTokens); 13019 items.push(token); 13020 } 13021 if (items.length === 0) return; 13022 return { 13023 items, 13024 raw: totalRaw 13025 }; 13026} 13027var TAB_STOP = 4; 13028function columnWidth(text$1) { 13029 let width = 0; 13030 for (const character of text$1) width = character === " " ? width + TAB_STOP - width % TAB_STOP : width + 1; 13031 return width; 13032} 13033function renderNestedMarkdownContent(node, h$1, prefixOrGenerator, ctx, options) { 13034 if (!node || !Array.isArray(node.content)) return ""; 13035 const prefix = typeof prefixOrGenerator === "function" ? prefixOrGenerator(ctx) : prefixOrGenerator; 13036 const [content, ...children] = node.content; 13037 let output = `${prefix}${h$1.renderChildren([content])}`; 13038 if (children && children.length > 0) children.forEach((child, index) => { 13039 var _h$renderChild, _h$renderChild2; 13040 const childContent = (_h$renderChild = (_h$renderChild2 = h$1.renderChild) === null || _h$renderChild2 === void 0 ? void 0 : _h$renderChild2.call(h$1, child, index + 1)) !== null && _h$renderChild !== void 0 ? _h$renderChild : h$1.renderChildren([child]); 13041 if (childContent !== void 0 && childContent !== null) { 13042 const indentLine = (line) => { 13043 if (!(options === null || options === void 0 ? void 0 : options.alignNestedToPrefix)) return h$1.indent(line); 13044 const configured = h$1.indent(""); 13045 const prefixWidth = columnWidth(prefix); 13046 return (columnWidth(configured) >= prefixWidth ? configured : " ".repeat(prefixWidth)) + line; 13047 }; 13048 const indentedChild = childContent.split("\n").map((line) => line ? indentLine(line) : indentLine("")).join("\n"); 13049 output += child.type === "paragraph" ? `\n\n${indentedChild}` : `\n${indentedChild}`; 13050 } 13051 }); 13052 return output; 13053} 13054function mergeDeep(target, source) { 13055 const output = { ...target }; 13056 if (isPlainObject(target) && isPlainObject(source)) Object.keys(source).forEach((key) => { 13057 if (isPlainObject(source[key]) && isPlainObject(target[key])) output[key] = mergeDeep(target[key], source[key]); 13058 else output[key] = source[key]; 13059 }); 13060 return output; 13061} 13062function updateMarkViewAttributes(checkMark, editor, attrs = {}) { 13063 const { state } = editor; 13064 const { doc: doc$2, tr: tr$1 } = state; 13065 const thisMark = checkMark; 13066 doc$2.descendants((node, pos) => { 13067 const from = tr$1.mapping.map(pos); 13068 const to = tr$1.mapping.map(pos) + node.nodeSize; 13069 let foundMark = null; 13070 node.marks.forEach((mark) => { 13071 if (mark !== thisMark) return false; 13072 foundMark = mark; 13073 }); 13074 if (!foundMark) return; 13075 let needsUpdate = false; 13076 Object.keys(attrs).forEach((k) => { 13077 if (attrs[k] !== foundMark.attrs[k]) needsUpdate = true; 13078 }); 13079 if (needsUpdate) { 13080 const updatedMark = checkMark.type.create({ 13081 ...checkMark.attrs, 13082 ...attrs 13083 }); 13084 tr$1.removeMark(from, to, checkMark.type); 13085 tr$1.addMark(from, to, updatedMark); 13086 } 13087 }); 13088 if (tr$1.docChanged) editor.view.dispatch(tr$1); 13089} 13090var InputRule = class { 13091 constructor(config) { 13092 var _config$undoable; 13093 this.find = config.find; 13094 this.handler = config.handler; 13095 this.undoable = (_config$undoable = config.undoable) !== null && _config$undoable !== void 0 ? _config$undoable : true; 13096 } 13097}; 13098var inputRuleMatcherHandler = (text$1, find$1) => { 13099 if (isRegExp(find$1)) return find$1.exec(text$1); 13100 const inputRuleMatch = find$1(text$1); 13101 if (!inputRuleMatch) return null; 13102 const result = [inputRuleMatch.text]; 13103 result.index = inputRuleMatch.index; 13104 result.input = text$1; 13105 result.data = inputRuleMatch.data; 13106 if (inputRuleMatch.replaceWith) { 13107 if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) console.warn("[tiptap warn]: \"inputRuleMatch.replaceWith\" must be part of \"inputRuleMatch.text\"."); 13108 result.push(inputRuleMatch.replaceWith); 13109 } 13110 return result; 13111}; 13112function run$1$1(config) { 13113 var _ref$1; 13114 const { editor, from, to, text: text$1, rules, plugin } = config; 13115 const { view } = editor; 13116 if (view.composing) return false; 13117 const $from = view.state.doc.resolve(from); 13118 if ($from.parent.type.spec.code || !!((_ref$1 = $from.nodeBefore || $from.nodeAfter) === null || _ref$1 === void 0 ? void 0 : _ref$1.marks.find((mark) => mark.type.spec.code))) return false; 13119 let matched = false; 13120 const textBefore = getTextContentFromNodes($from) + text$1;
vendor: 2,601 bytes, lines 13121-13232
13121 rules.forEach((rule) => { 13122 if (matched) return; 13123 const match = inputRuleMatcherHandler(textBefore, rule.find); 13124 if (!match) return; 13125 const matchedDocLength = match[0].length - text$1.length; 13126 if (matchedDocLength > 0) { 13127 const matchStartOffset = $from.parentOffset - matchedDocLength; 13128 if (matchStartOffset < 0 || $from.parent.textBetween(matchStartOffset, $from.parentOffset) !== match[0].slice(0, matchedDocLength)) return; 13129 } 13130 const tr$1 = view.state.tr; 13131 const state = createChainableState({ 13132 state: view.state, 13133 transaction: tr$1 13134 }); 13135 const range = { 13136 from: from - (match[0].length - text$1.length), 13137 to 13138 }; 13139 const { commands, chain, can } = new CommandManager({ 13140 editor, 13141 state 13142 }); 13143 if (rule.handler({ 13144 state, 13145 range, 13146 match, 13147 commands, 13148 chain, 13149 can 13150 }) === null || !tr$1.steps.length) return; 13151 if (rule.undoable) tr$1.setMeta(plugin, { 13152 transform: tr$1, 13153 from, 13154 to, 13155 text: text$1 13156 }); 13157 view.dispatch(tr$1); 13158 matched = true; 13159 }); 13160 return matched; 13161} 13162function inputRulesPlugin(props) { 13163 const { editor, rules } = props; 13164 const plugin = new Plugin({ 13165 state: { 13166 init() { 13167 return null; 13168 }, 13169 apply(tr$1, prev, state) { 13170 const stored = tr$1.getMeta(plugin); 13171 if (stored) return stored; 13172 const simulatedInputMeta = tr$1.getMeta("applyInputRules"); 13173 if (!!simulatedInputMeta) setTimeout(() => { 13174 let { text: text$1 } = simulatedInputMeta; 13175 if (typeof text$1 === "string") text$1 = text$1; 13176 else text$1 = getHTMLFromFragment(Fragment.from(text$1), state.schema); 13177 const { from } = simulatedInputMeta; 13178 run$1$1({ 13179 editor, 13180 from, 13181 to: from + text$1.length, 13182 text: text$1, 13183 rules, 13184 plugin 13185 }); 13186 }); 13187 return tr$1.selectionSet || tr$1.docChanged ? null : prev; 13188 } 13189 }, 13190 props: { 13191 handleTextInput(view, from, to, text$1) { 13192 return run$1$1({ 13193 editor, 13194 from, 13195 to, 13196 text: text$1, 13197 rules, 13198 plugin 13199 }); 13200 }, 13201 handleDOMEvents: { compositionend: (view) => { 13202 setTimeout(() => { 13203 const { $cursor } = view.state.selection; 13204 if ($cursor) run$1$1({ 13205 editor, 13206 from: $cursor.pos, 13207 to: $cursor.pos, 13208 text: "", 13209 rules, 13210 plugin 13211 }); 13212 }); 13213 return false; 13214 } }, 13215 handleKeyDown(view, event) { 13216 if (event.key !== "Enter") return false; 13217 const { $cursor } = view.state.selection; 13218 if ($cursor) return run$1$1({ 13219 editor, 13220 from: $cursor.pos, 13221 to: $cursor.pos, 13222 text: "\n", 13223 rules, 13224 plugin 13225 }); 13226 return false; 13227 } 13228 }, 13229 isInputRules: true 13230 }); 13231 return plugin; 13232}
vendor: 4,225 bytes, lines 13233-13349
13233var Extendable = class { 13234 constructor(config = {}) { 13235 this.type = "extendable"; 13236 this.parent = null; 13237 this.child = null; 13238 this.name = ""; 13239 this.config = { name: this.name }; 13240 this.config = { 13241 ...this.config, 13242 ...config 13243 }; 13244 this.name = this.config.name; 13245 } 13246 get options() { 13247 return { ...callOrReturn(getExtensionField(this, "addOptions", { name: this.name })) }; 13248 } 13249 get storage() { 13250 return { ...callOrReturn(getExtensionField(this, "addStorage", { 13251 name: this.name, 13252 options: this.options 13253 })) }; 13254 } 13255 configure(options = {}) { 13256 const extension = this.extend({ 13257 ...this.config, 13258 addOptions: () => { 13259 return mergeDeep(this.options, options); 13260 } 13261 }); 13262 extension.name = this.name; 13263 extension.parent = this.parent; 13264 this.child = null; 13265 return extension; 13266 } 13267 extend(extendedConfig = {}) { 13268 const extension = new this.constructor({ 13269 ...this.config, 13270 ...extendedConfig 13271 }); 13272 extension.parent = this; 13273 this.child = extension; 13274 extension.name = "name" in extendedConfig ? extendedConfig.name : extension.parent.name; 13275 return extension; 13276 } 13277}; 13278var Mark = class Mark$2 extends Extendable { 13279 constructor(..._args) { 13280 super(..._args); 13281 this.type = "mark"; 13282 } 13283 static create(config = {}) { 13284 return new Mark$2(typeof config === "function" ? config() : config); 13285 } 13286 static handleExit({ editor, mark }) { 13287 const { tr: tr$1 } = editor.state; 13288 const currentPos = editor.state.selection.$from; 13289 if (currentPos.pos === currentPos.end()) { 13290 const currentMarks = currentPos.marks(); 13291 if (!!!currentMarks.find((m) => (m === null || m === void 0 ? void 0 : m.type.name) === mark.name)) return false; 13292 const removeMark$1 = currentMarks.find((m) => (m === null || m === void 0 ? void 0 : m.type.name) === mark.name); 13293 if (removeMark$1) tr$1.removeStoredMark(removeMark$1); 13294 tr$1.insertText(" ", currentPos.pos); 13295 editor.view.dispatch(tr$1); 13296 return true; 13297 } 13298 return false; 13299 } 13300 configure(options) { 13301 return super.configure(options); 13302 } 13303 extend(extendedConfig) { 13304 const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; 13305 return super.extend(resolvedConfig); 13306 } 13307}; 13308var PasteRule = class { 13309 constructor(config) { 13310 this.find = config.find; 13311 this.handler = config.handler; 13312 } 13313}; 13314var pasteRuleMatcherHandler = (text$1, find$1, event) => { 13315 if (isRegExp(find$1)) return [...text$1.matchAll(find$1)]; 13316 const matches$1 = find$1(text$1, event); 13317 if (!matches$1) return []; 13318 return matches$1.map((pasteRuleMatch) => { 13319 const result = [pasteRuleMatch.text]; 13320 result.index = pasteRuleMatch.index; 13321 result.input = text$1; 13322 result.data = pasteRuleMatch.data; 13323 if (pasteRuleMatch.replaceWith) { 13324 if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) console.warn("[tiptap warn]: \"pasteRuleMatch.replaceWith\" must be part of \"pasteRuleMatch.text\"."); 13325 result.push(pasteRuleMatch.replaceWith); 13326 } 13327 return result; 13328 }); 13329}; 13330function run$2(config) { 13331 const { editor, state, from, to, rule, pasteEvent, dropEvent } = config; 13332 const { commands, chain, can } = new CommandManager({ 13333 editor, 13334 state 13335 }); 13336 const handlers$1 = []; 13337 state.doc.nodesBetween(from, to, (node, pos) => { 13338 var _node$type, _ref$1, _node$content$size, _node$content; 13339 if (((_node$type = node.type) === null || _node$type === void 0 || (_node$type = _node$type.spec) === null || _node$type === void 0 ? void 0 : _node$type.code) || !(node.isText || node.isTextblock || node.isInline)) return; 13340 const contentSize = (_ref$1 = (_node$content$size = (_node$content = node.content) === null || _node$content === void 0 ? void 0 : _node$content.size) !== null && _node$content$size !== void 0 ? _node$content$size : node.nodeSize) !== null && _ref$1 !== void 0 ? _ref$1 : 0; 13341 const resolvedFrom = Math.max(from, pos); 13342 const resolvedTo = Math.min(to, pos + contentSize); 13343 if (resolvedFrom >= resolvedTo) return; 13344 pasteRuleMatcherHandler(node.isText ? node.text || "" : node.textBetween(resolvedFrom - pos, resolvedTo - pos, void 0, ""), rule.find, pasteEvent).forEach((match) => { 13345 if (match.index === void 0) return; 13346 const start = resolvedFrom + match.index + 1; 13347 const end = start + match[0].length; 13348 const range = { 13349 from: state.tr.mapping.map(start),
vendor: 4,361 bytes, lines 13350-13471
13350 to: state.tr.mapping.map(end) 13351 }; 13352 const handler = rule.handler({ 13353 state, 13354 range, 13355 match, 13356 commands, 13357 chain, 13358 can, 13359 pasteEvent, 13360 dropEvent 13361 }); 13362 handlers$1.push(handler); 13363 }); 13364 }); 13365 return handlers$1.every((handler) => handler !== null); 13366} 13367var tiptapDragFromOtherEditor = null; 13368var createClipboardPasteEvent = (text$1) => { 13369 var _event$clipboardData; 13370 const event = new ClipboardEvent("paste", { clipboardData: new DataTransfer() }); 13371 (_event$clipboardData = event.clipboardData) === null || _event$clipboardData === void 0 || _event$clipboardData.setData("text/html", text$1); 13372 return event; 13373}; 13374function pasteRulesPlugin(props) { 13375 const { editor, rules } = props; 13376 let dragSourceElement = null; 13377 let isPastedFromProseMirror = false; 13378 let isDroppedFromProseMirror = false; 13379 let pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null; 13380 let dropEvent; 13381 try { 13382 dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null; 13383 } catch { 13384 dropEvent = null; 13385 } 13386 const processEvent = ({ state, from, to, rule, pasteEvt }) => { 13387 const tr$1 = state.tr; 13388 if (!run$2({ 13389 editor, 13390 state: createChainableState({ 13391 state, 13392 transaction: tr$1 13393 }), 13394 from: Math.max(from - 1, 0), 13395 to: to.b - 1, 13396 rule, 13397 pasteEvent: pasteEvt, 13398 dropEvent 13399 }) || !tr$1.steps.length) return; 13400 try { 13401 dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null; 13402 } catch { 13403 dropEvent = null; 13404 } 13405 pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null; 13406 return tr$1; 13407 }; 13408 return rules.map((rule) => { 13409 return new Plugin({ 13410 view(view) { 13411 const handleDragstart = (event) => { 13412 var _view$dom$parentEleme; 13413 dragSourceElement = ((_view$dom$parentEleme = view.dom.parentElement) === null || _view$dom$parentEleme === void 0 ? void 0 : _view$dom$parentEleme.contains(event.target)) ? view.dom.parentElement : null; 13414 if (dragSourceElement) tiptapDragFromOtherEditor = editor; 13415 }; 13416 const handleDragend = () => { 13417 if (tiptapDragFromOtherEditor) tiptapDragFromOtherEditor = null; 13418 }; 13419 window.addEventListener("dragstart", handleDragstart); 13420 window.addEventListener("dragend", handleDragend); 13421 return { destroy() { 13422 window.removeEventListener("dragstart", handleDragstart); 13423 window.removeEventListener("dragend", handleDragend); 13424 } }; 13425 }, 13426 props: { handleDOMEvents: { 13427 drop: (view, event) => { 13428 isDroppedFromProseMirror = dragSourceElement === view.dom.parentElement; 13429 dropEvent = event; 13430 if (!isDroppedFromProseMirror) { 13431 const dragFromOtherEditor = tiptapDragFromOtherEditor; 13432 if (dragFromOtherEditor === null || dragFromOtherEditor === void 0 ? void 0 : dragFromOtherEditor.isEditable) setTimeout(() => { 13433 const selection = dragFromOtherEditor.state.selection; 13434 if (selection) dragFromOtherEditor.commands.deleteRange({ 13435 from: selection.from, 13436 to: selection.to 13437 }); 13438 }, 10); 13439 } 13440 return false; 13441 }, 13442 paste: (_view, event) => { 13443 var _clipboardData; 13444 const html$2 = (_clipboardData = event.clipboardData) === null || _clipboardData === void 0 ? void 0 : _clipboardData.getData("text/html"); 13445 pasteEvent = event; 13446 isPastedFromProseMirror = !!(html$2 === null || html$2 === void 0 ? void 0 : html$2.includes("data-pm-slice")); 13447 return false; 13448 } 13449 } }, 13450 appendTransaction: (transactions, oldState, state) => { 13451 const transaction = transactions[0]; 13452 const isPaste = transaction.getMeta("uiEvent") === "paste" && !isPastedFromProseMirror; 13453 const isDrop = transaction.getMeta("uiEvent") === "drop" && !isDroppedFromProseMirror; 13454 const simulatedPasteMeta = transaction.getMeta("applyPasteRules"); 13455 const isSimulatedPaste = !!simulatedPasteMeta; 13456 if (!isPaste && !isDrop && !isSimulatedPaste) return; 13457 if (isSimulatedPaste) { 13458 let { text: text$1 } = simulatedPasteMeta; 13459 if (typeof text$1 === "string") text$1 = text$1; 13460 else text$1 = getHTMLFromFragment(Fragment.from(text$1), state.schema); 13461 const { from: from$1 } = simulatedPasteMeta; 13462 const to$1 = from$1 + text$1.length; 13463 const pasteEvt = createClipboardPasteEvent(text$1); 13464 return processEvent({ 13465 rule, 13466 state, 13467 from: from$1, 13468 to: { b: to$1 }, 13469 pasteEvt 13470 }); 13471 }
vendor: 10,379 bytes, lines 13472-13755
13472 const from = oldState.doc.content.findDiffStart(state.doc.content); 13473 const to = oldState.doc.content.findDiffEnd(state.doc.content); 13474 if (!isNumber(from) || !to || from === to.b) return; 13475 return processEvent({ 13476 rule, 13477 state, 13478 from, 13479 to, 13480 pasteEvt: pasteEvent 13481 }); 13482 } 13483 }); 13484 }); 13485} 13486var ExtensionManager = class { 13487 constructor(extensions, editor) { 13488 this.splittableMarks = []; 13489 this.nonClearableMarks = []; 13490 this.decorationManager = null; 13491 this.editor = editor; 13492 this.baseExtensions = extensions; 13493 this.extensions = resolveExtensions(extensions); 13494 this.schema = getSchemaByResolvedExtensions(this.extensions, editor); 13495 this.setupExtensions(); 13496 } 13497 get commands() { 13498 return this.extensions.reduce((commands, extension) => { 13499 const addCommands = getExtensionField(extension, "addCommands", { 13500 name: extension.name, 13501 options: extension.options, 13502 storage: this.editor.extensionStorage[extension.name], 13503 editor: this.editor, 13504 type: getSchemaTypeByName(extension.name, this.schema) 13505 }); 13506 if (!addCommands) return commands; 13507 return { 13508 ...commands, 13509 ...addCommands() 13510 }; 13511 }, {}); 13512 } 13513 get plugins() { 13514 const { editor } = this; 13515 const allPlugins = sortExtensions([...this.extensions].reverse()).flatMap((extension) => { 13516 const context = { 13517 name: extension.name, 13518 options: extension.options, 13519 storage: this.editor.extensionStorage[extension.name], 13520 editor, 13521 type: getSchemaTypeByName(extension.name, this.schema) 13522 }; 13523 const plugins = []; 13524 const addKeyboardShortcuts = getExtensionField(extension, "addKeyboardShortcuts", context); 13525 let defaultBindings = {}; 13526 if (extension.type === "mark" && getExtensionField(extension, "exitable", context)) defaultBindings.ArrowRight = () => Mark.handleExit({ 13527 editor, 13528 mark: extension 13529 }); 13530 if (addKeyboardShortcuts) { 13531 const bindings = Object.fromEntries(Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => { 13532 return [shortcut, () => method({ editor })]; 13533 })); 13534 defaultBindings = { 13535 ...defaultBindings, 13536 ...bindings 13537 }; 13538 } 13539 const keyMapPlugin = keymap(defaultBindings); 13540 plugins.push(keyMapPlugin); 13541 const addInputRules = getExtensionField(extension, "addInputRules", context); 13542 if (isExtensionRulesEnabled(extension, editor.options.enableInputRules) && addInputRules) { 13543 const rules = addInputRules(); 13544 if (rules && rules.length) { 13545 const inputResult = inputRulesPlugin({ 13546 editor, 13547 rules 13548 }); 13549 const inputPlugins = Array.isArray(inputResult) ? inputResult : [inputResult]; 13550 plugins.push(...inputPlugins); 13551 } 13552 } 13553 const addPasteRules = getExtensionField(extension, "addPasteRules", context); 13554 if (isExtensionRulesEnabled(extension, editor.options.enablePasteRules) && addPasteRules) { 13555 const rules = addPasteRules(); 13556 if (rules && rules.length) { 13557 const pasteRules = pasteRulesPlugin({ 13558 editor, 13559 rules 13560 }); 13561 plugins.push(...pasteRules); 13562 } 13563 } 13564 const addProseMirrorPlugins = getExtensionField(extension, "addProseMirrorPlugins", context); 13565 if (addProseMirrorPlugins) { 13566 const proseMirrorPlugins = addProseMirrorPlugins(); 13567 plugins.push(...proseMirrorPlugins); 13568 } 13569 return plugins; 13570 }); 13571 const decorationPlugin = this.createDecorationPlugin(); 13572 if (decorationPlugin) allPlugins.push(decorationPlugin); 13573 return allPlugins; 13574 } 13575 createDecorationPlugin() { 13576 var _this$decorationManag; 13577 const { editor } = this; 13578 (_this$decorationManag = this.decorationManager) === null || _this$decorationManag === void 0 || _this$decorationManag.destroy(); 13579 const entries$1 = []; 13580 this.extensions.forEach((extension) => { 13581 const addDecorations = getExtensionField(extension, "addDecorations", { 13582 name: extension.name, 13583 options: extension.options, 13584 storage: this.editor.extensionStorage[extension.name], 13585 editor, 13586 type: getSchemaTypeByName(extension.name, this.schema) 13587 }); 13588 if (!addDecorations) return; 13589 entries$1.push({ 13590 name: extension.name, 13591 addDecorations 13592 }); 13593 }); 13594 this.decorationManager = new DecorationManager({ 13595 editor, 13596 entries: entries$1 13597 }); 13598 return this.decorationManager.plugin; 13599 } 13600 get attributes() { 13601 return getAttributesFromExtensions(this.extensions); 13602 } 13603 get nodeViews() { 13604 const { editor } = this; 13605 const { nodeExtensions } = splitExtensions(this.extensions); 13606 return Object.fromEntries(nodeExtensions.filter((extension) => !!getExtensionField(extension, "addNodeView")).map((extension) => { 13607 const extensionAttributes = this.attributes.filter((attribute) => attribute.type === extension.name); 13608 const addNodeView = getExtensionField(extension, "addNodeView", { 13609 name: extension.name, 13610 options: extension.options, 13611 storage: this.editor.extensionStorage[extension.name], 13612 editor, 13613 type: getNodeType(extension.name, this.schema) 13614 }); 13615 if (!addNodeView) return []; 13616 const nodeViewResult = addNodeView(); 13617 if (!nodeViewResult) return []; 13618 const nodeview = (node, view, getPos, decorations, innerDecorations) => { 13619 return nodeViewResult({ 13620 node, 13621 view, 13622 getPos, 13623 decorations, 13624 innerDecorations, 13625 editor, 13626 extension, 13627 HTMLAttributes: getRenderedAttributes(node, extensionAttributes) 13628 }); 13629 }; 13630 return [extension.name, nodeview]; 13631 })); 13632 } 13633 dispatchTransaction(baseDispatch) { 13634 const { editor } = this; 13635 return sortExtensions([...this.extensions].reverse()).reduceRight((next, extension) => { 13636 const context = { 13637 name: extension.name, 13638 options: extension.options, 13639 storage: this.editor.extensionStorage[extension.name], 13640 editor, 13641 type: getSchemaTypeByName(extension.name, this.schema) 13642 }; 13643 const dispatchTransaction = getExtensionField(extension, "dispatchTransaction", context); 13644 if (!dispatchTransaction) return next; 13645 return (transaction) => { 13646 dispatchTransaction.call(context, { 13647 transaction, 13648 next 13649 }); 13650 }; 13651 }, baseDispatch); 13652 } 13653 transformPastedHTML(baseTransform) { 13654 const { editor } = this; 13655 return sortExtensions([...this.extensions]).reduce((transform, extension) => { 13656 const context = { 13657 name: extension.name, 13658 options: extension.options, 13659 storage: this.editor.extensionStorage[extension.name], 13660 editor, 13661 type: getSchemaTypeByName(extension.name, this.schema) 13662 }; 13663 const extensionTransform = getExtensionField(extension, "transformPastedHTML", context); 13664 if (!extensionTransform) return transform; 13665 return (html$2, view) => { 13666 const transformedHtml = transform(html$2, view); 13667 return extensionTransform.call(context, transformedHtml); 13668 }; 13669 }, baseTransform || ((html$2) => html$2)); 13670 } 13671 get markViews() { 13672 const { editor } = this; 13673 const { markExtensions } = splitExtensions(this.extensions); 13674 return Object.fromEntries(markExtensions.filter((extension) => !!getExtensionField(extension, "addMarkView")).map((extension) => { 13675 const extensionAttributes = this.attributes.filter((attribute) => attribute.type === extension.name); 13676 const addMarkView = getExtensionField(extension, "addMarkView", { 13677 name: extension.name, 13678 options: extension.options, 13679 storage: this.editor.extensionStorage[extension.name], 13680 editor, 13681 type: getMarkType(extension.name, this.schema) 13682 }); 13683 if (!addMarkView) return []; 13684 const markView = (mark, view, inline) => { 13685 const HTMLAttributes = getRenderedAttributes(mark, extensionAttributes); 13686 return addMarkView()({ 13687 mark, 13688 view, 13689 inline, 13690 editor, 13691 extension, 13692 HTMLAttributes, 13693 updateAttributes: (attrs) => { 13694 updateMarkViewAttributes(mark, editor, attrs); 13695 } 13696 }); 13697 }; 13698 return [extension.name, markView]; 13699 })); 13700 } 13701 destroy() { 13702 var _this$decorationManag2; 13703 (_this$decorationManag2 = this.decorationManager) === null || _this$decorationManag2 === void 0 || _this$decorationManag2.destroy(); 13704 this.extensions.forEach((extension) => { 13705 let current = extension; 13706 while (current.parent) { 13707 const parent = current.parent; 13708 if (parent.child === current) parent.child = null; 13709 current = parent; 13710 } 13711 }); 13712 this.extensions = []; 13713 this.baseExtensions = []; 13714 this.decorationManager = null; 13715 this.schema = null; 13716 this.editor = null; 13717 } 13718 setupExtensions() { 13719 const extensions = this.extensions; 13720 this.editor.extensionStorage = Object.fromEntries(extensions.map((extension) => [extension.name, extension.storage])); 13721 extensions.forEach((extension) => { 13722 const context = { 13723 name: extension.name, 13724 options: extension.options, 13725 storage: this.editor.extensionStorage[extension.name], 13726 editor: this.editor, 13727 type: getSchemaTypeByName(extension.name, this.schema) 13728 }; 13729 if (extension.type === "mark") { 13730 var _callOrReturn, _callOrReturn2; 13731 if ((_callOrReturn = callOrReturn(getExtensionField(extension, "keepOnSplit", context))) !== null && _callOrReturn !== void 0 ? _callOrReturn : true) this.splittableMarks.push(extension.name); 13732 if (!((_callOrReturn2 = callOrReturn(getExtensionField(extension, "clearable", context))) !== null && _callOrReturn2 !== void 0 ? _callOrReturn2 : true)) this.nonClearableMarks.push(extension.name); 13733 } 13734 const onBeforeCreate = getExtensionField(extension, "onBeforeCreate", context); 13735 const onCreate = getExtensionField(extension, "onCreate", context); 13736 const onUpdate = getExtensionField(extension, "onUpdate", context); 13737 const onSelectionUpdate = getExtensionField(extension, "onSelectionUpdate", context); 13738 const onTransaction = getExtensionField(extension, "onTransaction", context); 13739 const onFocus = getExtensionField(extension, "onFocus", context); 13740 const onBlur = getExtensionField(extension, "onBlur", context); 13741 const onDestroy = getExtensionField(extension, "onDestroy", context); 13742 if (onBeforeCreate) this.editor.on("beforeCreate", onBeforeCreate); 13743 if (onCreate) this.editor.on("create", onCreate); 13744 if (onUpdate) this.editor.on("update", onUpdate); 13745 if (onSelectionUpdate) this.editor.on("selectionUpdate", onSelectionUpdate); 13746 if (onTransaction) this.editor.on("transaction", onTransaction); 13747 if (onFocus) this.editor.on("focus", onFocus); 13748 if (onBlur) this.editor.on("blur", onBlur); 13749 if (onDestroy) this.editor.on("destroy", onDestroy); 13750 }); 13751 } 13752}; 13753ExtensionManager.resolve = resolveExtensions; 13754ExtensionManager.sort = sortExtensions; 13755ExtensionManager.flatten = flattenExtensions;
vendor: 20,769 bytes, lines 13756-14388
13756var Extension = class Extension$1 extends Extendable { 13757 constructor(..._args) { 13758 super(..._args); 13759 this.type = "extension"; 13760 } 13761 static create(config = {}) { 13762 return new Extension$1(typeof config === "function" ? config() : config); 13763 } 13764 configure(options) { 13765 return super.configure(options); 13766 } 13767 extend(extendedConfig) { 13768 const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; 13769 return super.extend(resolvedConfig); 13770 } 13771}; 13772var ClipboardTextSerializer = Extension.create({ 13773 name: "clipboardTextSerializer", 13774 addOptions() { 13775 return { blockSeparator: void 0 }; 13776 }, 13777 addProseMirrorPlugins() { 13778 return [new Plugin({ 13779 key: new PluginKey("clipboardTextSerializer"), 13780 props: { clipboardTextSerializer: () => { 13781 const { editor } = this; 13782 const { state, schema } = editor; 13783 const { doc: doc$2, selection } = state; 13784 const textSerializers = getTextSerializersFromSchema(schema); 13785 const { blockSeparator } = this.options; 13786 const options = { 13787 ...blockSeparator !== void 0 ? { blockSeparator } : {}, 13788 textSerializers 13789 }; 13790 return [...selection.ranges].sort((a, b) => a.$from.pos - b.$from.pos).map(({ $from, $to }) => getTextBetween(doc$2, { 13791 from: $from.pos, 13792 to: $to.pos 13793 }, options)).join(blockSeparator !== null && blockSeparator !== void 0 ? blockSeparator : "\n\n"); 13794 } } 13795 })]; 13796 } 13797}); 13798var Commands = Extension.create({ 13799 name: "commands", 13800 addCommands() { 13801 return { ...commands_exports }; 13802 } 13803}); 13804var Delete = Extension.create({ 13805 name: "delete", 13806 onUpdate({ transaction, appendedTransactions }) { 13807 var _this$editor$options$4, _this$editor$options$5; 13808 const callback = () => { 13809 var _this$editor$options$, _this$editor$options$2, _this$editor$options$3; 13810 if ((_this$editor$options$ = (_this$editor$options$2 = this.editor.options.coreExtensionOptions) === null || _this$editor$options$2 === void 0 || (_this$editor$options$2 = _this$editor$options$2.delete) === null || _this$editor$options$2 === void 0 || (_this$editor$options$3 = _this$editor$options$2.filterTransaction) === null || _this$editor$options$3 === void 0 ? void 0 : _this$editor$options$3.call(_this$editor$options$2, transaction)) !== null && _this$editor$options$ !== void 0 ? _this$editor$options$ : transaction.getMeta("y-sync$")) return; 13811 const nextTransaction = combineTransactionSteps(transaction.before, [transaction, ...appendedTransactions]); 13812 getChangedRanges(nextTransaction).forEach((change) => { 13813 if (nextTransaction.mapping.mapResult(change.oldRange.from).deletedAfter && nextTransaction.mapping.mapResult(change.oldRange.to).deletedBefore) nextTransaction.before.nodesBetween(change.oldRange.from, change.oldRange.to, (node, from) => { 13814 const to = from + node.nodeSize - 2; 13815 const isFullyWithinRange = change.oldRange.from <= from && to <= change.oldRange.to; 13816 this.editor.emit("delete", { 13817 type: "node", 13818 node, 13819 from, 13820 to, 13821 newFrom: nextTransaction.mapping.map(from), 13822 newTo: nextTransaction.mapping.map(to), 13823 deletedRange: change.oldRange, 13824 newRange: change.newRange, 13825 partial: !isFullyWithinRange, 13826 editor: this.editor, 13827 transaction, 13828 combinedTransform: nextTransaction 13829 }); 13830 }); 13831 }); 13832 const mapping = nextTransaction.mapping; 13833 nextTransaction.steps.forEach((step, index) => { 13834 if (step instanceof RemoveMarkStep) { 13835 var _nextTransaction$doc$, _nextTransaction$doc$2; 13836 const newStart = mapping.slice(index).map(step.from, -1); 13837 const newEnd = mapping.slice(index).map(step.to); 13838 const oldStart = mapping.invert().map(newStart, -1); 13839 const oldEnd = mapping.invert().map(newEnd); 13840 const foundBeforeMark = newStart > 0 ? (_nextTransaction$doc$ = nextTransaction.doc.nodeAt(newStart - 1)) === null || _nextTransaction$doc$ === void 0 ? void 0 : _nextTransaction$doc$.marks.some((mark) => mark.eq(step.mark)) : false; 13841 const foundAfterMark = (_nextTransaction$doc$2 = nextTransaction.doc.nodeAt(newEnd)) === null || _nextTransaction$doc$2 === void 0 ? void 0 : _nextTransaction$doc$2.marks.some((mark) => mark.eq(step.mark)); 13842 this.editor.emit("delete", { 13843 type: "mark", 13844 mark: step.mark, 13845 from: step.from, 13846 to: step.to, 13847 deletedRange: { 13848 from: oldStart, 13849 to: oldEnd 13850 }, 13851 newRange: { 13852 from: newStart, 13853 to: newEnd 13854 }, 13855 partial: Boolean(foundAfterMark || foundBeforeMark), 13856 editor: this.editor, 13857 transaction, 13858 combinedTransform: nextTransaction 13859 }); 13860 } 13861 }); 13862 }; 13863 if ((_this$editor$options$4 = (_this$editor$options$5 = this.editor.options.coreExtensionOptions) === null || _this$editor$options$5 === void 0 || (_this$editor$options$5 = _this$editor$options$5.delete) === null || _this$editor$options$5 === void 0 ? void 0 : _this$editor$options$5.async) !== null && _this$editor$options$4 !== void 0 ? _this$editor$options$4 : true) setTimeout(callback, 0); 13864 else callback(); 13865 } 13866}); 13867var Drop = Extension.create({ 13868 name: "drop", 13869 addProseMirrorPlugins() { 13870 return [new Plugin({ 13871 key: new PluginKey("tiptapDrop"), 13872 props: { handleDrop: (_, e, slice, moved) => { 13873 this.editor.emit("drop", { 13874 editor: this.editor, 13875 event: e, 13876 slice, 13877 moved 13878 }); 13879 } } 13880 })]; 13881 } 13882}); 13883var Editable = Extension.create({ 13884 name: "editable", 13885 addProseMirrorPlugins() { 13886 return [new Plugin({ 13887 key: new PluginKey("editable"), 13888 props: { editable: () => this.editor.options.editable } 13889 })]; 13890 } 13891}); 13892var focusEventsPluginKey = new PluginKey("focusEvents"); 13893var FocusEvents = Extension.create({ 13894 name: "focusEvents", 13895 addProseMirrorPlugins() { 13896 const { editor } = this; 13897 return [new Plugin({ 13898 key: focusEventsPluginKey, 13899 props: { handleDOMEvents: { 13900 focus: (view, event) => { 13901 editor.isFocused = true; 13902 const transaction = editor.state.tr.setMeta("focus", { event }).setMeta("addToHistory", false); 13903 view.dispatch(transaction); 13904 return false; 13905 }, 13906 blur: (view, event) => { 13907 editor.isFocused = false; 13908 const transaction = editor.state.tr.setMeta("blur", { event }).setMeta("addToHistory", false); 13909 view.dispatch(transaction); 13910 return false; 13911 } 13912 } } 13913 })]; 13914 } 13915}); 13916var Keymap = Extension.create({ 13917 name: "keymap", 13918 addKeyboardShortcuts() { 13919 const handleBackspace$2 = () => this.editor.commands.first(({ commands }) => [ 13920 () => commands.undoInputRule(), 13921 () => commands.command(({ tr: tr$1 }) => { 13922 const { selection, doc: doc$2 } = tr$1; 13923 const { empty: empty$1, $anchor } = selection; 13924 const { pos, parent } = $anchor; 13925 const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr$1.doc.resolve(pos - 1) : $anchor; 13926 const parentIsIsolating = $parentPos.parent.type.spec.isolating; 13927 const parentPos = $anchor.pos - $anchor.parentOffset; 13928 const isAtStart = parentIsIsolating && $parentPos.parent.childCount === 1 ? parentPos === $anchor.pos : Selection$1.atStart(doc$2).from === pos; 13929 if (!empty$1 || !parent.type.isTextblock || parent.textContent.length || !isAtStart || isAtStart && $anchor.parent.type.name === "paragraph") return false; 13930 return commands.clearNodes(); 13931 }), 13932 () => commands.deleteSelection(), 13933 () => commands.joinBackward(), 13934 () => commands.selectNodeBackward() 13935 ]); 13936 const handleDelete$1 = () => this.editor.commands.first(({ commands }) => [ 13937 () => commands.deleteSelection(), 13938 () => commands.deleteCurrentNode(), 13939 () => commands.joinForward(), 13940 () => commands.selectNodeForward() 13941 ]); 13942 const handleEnter = () => this.editor.commands.first(({ commands }) => [ 13943 () => commands.newlineInCode(), 13944 () => commands.createParagraphNear(), 13945 () => commands.liftEmptyBlock(), 13946 () => commands.splitBlock() 13947 ]); 13948 const baseKeymap$1 = { 13949 Enter: handleEnter, 13950 "Mod-Enter": () => this.editor.commands.exitCode(), 13951 Backspace: handleBackspace$2, 13952 "Mod-Backspace": handleBackspace$2, 13953 "Shift-Backspace": handleBackspace$2, 13954 Delete: handleDelete$1, 13955 "Mod-Delete": handleDelete$1, 13956 "Mod-a": () => this.editor.commands.selectAll() 13957 }; 13958 const pcKeymap = { ...baseKeymap$1 }; 13959 const macKeymap = { 13960 ...baseKeymap$1, 13961 "Ctrl-h": handleBackspace$2, 13962 "Alt-Backspace": handleBackspace$2, 13963 "Ctrl-d": handleDelete$1, 13964 "Ctrl-Alt-Backspace": handleDelete$1, 13965 "Alt-Delete": handleDelete$1, 13966 "Alt-d": handleDelete$1, 13967 "Ctrl-a": () => this.editor.commands.selectTextblockStart(), 13968 "Ctrl-e": () => this.editor.commands.selectTextblockEnd() 13969 }; 13970 if (isiOS() || isMacOS()) return macKeymap; 13971 return pcKeymap; 13972 }, 13973 addProseMirrorPlugins() { 13974 return [new Plugin({ 13975 key: new PluginKey("clearDocument"), 13976 appendTransaction: (transactions, oldState, newState) => { 13977 if (transactions.some((tr$2) => tr$2.getMeta("composition"))) return; 13978 const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc); 13979 const ignoreTr = transactions.some((transaction) => transaction.getMeta("preventClearDocument")); 13980 if (!docChanges || ignoreTr) return; 13981 const { empty: empty$1, from, to } = oldState.selection; 13982 const allFrom = Selection$1.atStart(oldState.doc).from; 13983 const allEnd = Selection$1.atEnd(oldState.doc).to; 13984 if (empty$1 || !(from === allFrom && to === allEnd)) return; 13985 if (!isNodeEmpty(newState.doc)) return; 13986 const tr$1 = newState.tr; 13987 const state = createChainableState({ 13988 state: newState, 13989 transaction: tr$1 13990 }); 13991 const { commands } = new CommandManager({ 13992 editor: this.editor, 13993 state 13994 }); 13995 commands.clearNodes(); 13996 if (!tr$1.steps.length) return; 13997 return tr$1; 13998 } 13999 })]; 14000 } 14001}); 14002var Paste = Extension.create({ 14003 name: "paste", 14004 addProseMirrorPlugins() { 14005 return [new Plugin({ 14006 key: new PluginKey("tiptapPaste"), 14007 props: { handlePaste: (_view, e, slice) => { 14008 this.editor.emit("paste", { 14009 editor: this.editor, 14010 event: e, 14011 slice 14012 }); 14013 } } 14014 })]; 14015 } 14016}); 14017var Tabindex = Extension.create({ 14018 name: "tabindex", 14019 addOptions() { 14020 return { value: void 0 }; 14021 }, 14022 addProseMirrorPlugins() { 14023 return [new Plugin({ 14024 key: new PluginKey("tabindex"), 14025 props: { attributes: () => { 14026 var _this$options$value; 14027 if (!this.editor.isEditable && this.options.value === void 0) return {}; 14028 return { tabindex: (_this$options$value = this.options.value) !== null && _this$options$value !== void 0 ? _this$options$value : "0" }; 14029 } } 14030 })]; 14031 } 14032}); 14033var TextDirection = Extension.create({ 14034 name: "textDirection", 14035 addOptions() { 14036 return { direction: void 0 }; 14037 }, 14038 addGlobalAttributes() { 14039 if (!this.options.direction) return []; 14040 const { nodeExtensions } = splitExtensions(this.extensions); 14041 return [{ 14042 types: nodeExtensions.filter((extension) => extension.name !== "text").map((extension) => extension.name), 14043 attributes: { dir: { 14044 default: this.options.direction, 14045 parseHTML: (element) => { 14046 const dir = element.getAttribute("dir"); 14047 if (dir && (dir === "ltr" || dir === "rtl" || dir === "auto")) return dir; 14048 return this.options.direction; 14049 }, 14050 renderHTML: (attributes) => { 14051 if (!attributes.dir) return {}; 14052 return { dir: attributes.dir }; 14053 } 14054 } } 14055 }]; 14056 }, 14057 addProseMirrorPlugins() { 14058 return [new Plugin({ 14059 key: new PluginKey("textDirection"), 14060 props: { attributes: () => { 14061 const direction = this.options.direction; 14062 if (!direction) return {}; 14063 return { dir: direction }; 14064 } } 14065 })]; 14066 } 14067}); 14068var hasChecked = false; 14069function warnOnDuplicatedProseMirrorModel(schema) { 14070 if (hasChecked) return; 14071 hasChecked = true; 14072 let content; 14073 try { 14074 content = ReplaceStep.fromJSON(schema, { 14075 from: 0, 14076 to: 0 14077 }).slice.content; 14078 } catch { 14079 return; 14080 } 14081 if (content instanceof Fragment) return; 14082 console.warn("[tiptap warn]: prosemirror-model is loaded more than once. Wrapping and splitting nodes will fail. Deduplicate it in your lock file, or alias it to a single copy in your bundler."); 14083} 14084var NodePos = class NodePos$1 { 14085 get name() { 14086 return this.node.type.name; 14087 } 14088 constructor(pos, editor, isBlock = false, node = null) { 14089 this.currentNode = null; 14090 this.actualDepth = null; 14091 this.isBlock = isBlock; 14092 this.resolvedPos = pos; 14093 this.editor = editor; 14094 this.currentNode = node; 14095 } 14096 get node() { 14097 return this.currentNode || this.resolvedPos.node(); 14098 } 14099 get element() { 14100 return this.editor.view.domAtPos(this.pos).node; 14101 } 14102 get depth() { 14103 var _this$actualDepth; 14104 return (_this$actualDepth = this.actualDepth) !== null && _this$actualDepth !== void 0 ? _this$actualDepth : this.resolvedPos.depth; 14105 } 14106 get pos() { 14107 return this.resolvedPos.pos; 14108 } 14109 get content() { 14110 return this.node.content; 14111 } 14112 set content(content) { 14113 let from = this.from; 14114 let to = this.to; 14115 if (this.isBlock) { 14116 if (this.content.size === 0) { 14117 console.error(`You canât set content on a block node. Tried to set content on ${this.name} at ${this.pos}`); 14118 return; 14119 } 14120 from = this.from + 1; 14121 to = this.to - 1; 14122 } 14123 this.editor.commands.insertContentAt({ 14124 from, 14125 to 14126 }, content); 14127 } 14128 get attributes() { 14129 return this.node.attrs; 14130 } 14131 get textContent() { 14132 return this.node.textContent; 14133 } 14134 get size() { 14135 return this.node.nodeSize; 14136 } 14137 get from() { 14138 if (this.isBlock) return this.pos; 14139 return this.resolvedPos.start(this.resolvedPos.depth); 14140 } 14141 get range() { 14142 return { 14143 from: this.from, 14144 to: this.to 14145 }; 14146 } 14147 get to() { 14148 if (this.isBlock) return this.pos + this.size; 14149 return this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1); 14150 } 14151 get parent() { 14152 if (this.depth === 0) return null; 14153 const parentPos = this.resolvedPos.start(this.resolvedPos.depth - 1); 14154 return new NodePos$1(this.resolvedPos.doc.resolve(parentPos), this.editor); 14155 } 14156 get before() { 14157 let $pos = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2)); 14158 if ($pos.depth !== this.depth) $pos = this.resolvedPos.doc.resolve(this.from - 3); 14159 return new NodePos$1($pos, this.editor); 14160 } 14161 get after() { 14162 let $pos = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1)); 14163 if ($pos.depth !== this.depth) $pos = this.resolvedPos.doc.resolve(this.to + 3); 14164 return new NodePos$1($pos, this.editor); 14165 } 14166 get children() { 14167 const children = []; 14168 this.node.content.forEach((node, offset) => { 14169 const isBlock = node.isBlock && !node.isTextblock; 14170 const isNonTextAtom = node.isAtom && !node.isText; 14171 const isInline$1 = node.isInline; 14172 const targetPos = this.pos + offset + (isNonTextAtom ? 0 : 1); 14173 if (targetPos < 0 || targetPos > this.resolvedPos.doc.nodeSize - 2) return; 14174 const $pos = this.resolvedPos.doc.resolve(targetPos); 14175 if (!isBlock && !isInline$1 && $pos.depth <= this.depth) return; 14176 const childNodePos = new NodePos$1($pos, this.editor, isBlock, isBlock || isInline$1 ? node : null); 14177 if (isBlock) childNodePos.actualDepth = this.depth + 1; 14178 children.push(childNodePos); 14179 }); 14180 return children; 14181 } 14182 get firstChild() { 14183 return this.children[0] || null; 14184 } 14185 get lastChild() { 14186 const children = this.children; 14187 return children[children.length - 1] || null; 14188 } 14189 closest(selector, attributes = {}) { 14190 let node = null; 14191 let currentNode = this.parent; 14192 while (currentNode && !node) { 14193 if (currentNode.node.type.name === selector) if (Object.keys(attributes).length > 0) { 14194 const nodeAttributes = currentNode.node.attrs; 14195 const attrKeys = Object.keys(attributes); 14196 for (let index = 0; index < attrKeys.length; index += 1) { 14197 const key = attrKeys[index]; 14198 if (nodeAttributes[key] !== attributes[key]) break; 14199 } 14200 } else node = currentNode; 14201 currentNode = currentNode.parent; 14202 } 14203 return node; 14204 } 14205 querySelector(selector, attributes = {}) { 14206 return this.querySelectorAll(selector, attributes, true)[0] || null; 14207 } 14208 querySelectorAll(selector, attributes = {}, firstItemOnly = false) { 14209 let nodes = []; 14210 if (!this.children || this.children.length === 0) return nodes; 14211 const attrKeys = Object.keys(attributes); 14212 this.children.forEach((childPos) => { 14213 if (firstItemOnly && nodes.length > 0) return; 14214 if (childPos.node.type.name === selector) { 14215 if (attrKeys.every((key) => attributes[key] === childPos.node.attrs[key])) nodes.push(childPos); 14216 } 14217 if (firstItemOnly && nodes.length > 0) return; 14218 nodes = nodes.concat(childPos.querySelectorAll(selector, attributes, firstItemOnly)); 14219 }); 14220 return nodes; 14221 } 14222 setAttribute(attributes) { 14223 const { tr: tr$1 } = this.editor.state; 14224 tr$1.setNodeMarkup(this.from, void 0, { 14225 ...this.node.attrs, 14226 ...attributes 14227 }); 14228 this.editor.view.dispatch(tr$1); 14229 } 14230}; 14231var style = `.ProseMirror { 14232 position: relative; 14233} 14234 14235.ProseMirror { 14236 word-wrap: break-word; 14237 white-space: pre-wrap; 14238 white-space: break-spaces; 14239 -webkit-font-variant-ligatures: none; 14240 font-variant-ligatures: none; 14241 font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */ 14242} 14243 14244.ProseMirror [contenteditable="false"] { 14245 white-space: normal; 14246} 14247 14248.ProseMirror [contenteditable="false"] [contenteditable="true"] { 14249 white-space: pre-wrap; 14250} 14251 14252.ProseMirror pre { 14253 white-space: pre-wrap; 14254} 14255 14256img.ProseMirror-separator { 14257 display: inline !important; 14258 border: none !important; 14259 margin: 0 !important; 14260 width: 0 !important; 14261 height: 0 !important; 14262} 14263 14264.ProseMirror-gapcursor { 14265 display: none; 14266 pointer-events: none; 14267 position: absolute; 14268 margin: 0; 14269} 14270 14271.ProseMirror-gapcursor:after { 14272 content: ""; 14273 display: block; 14274 position: absolute; 14275 top: -2px; 14276 width: 20px; 14277 border-top: 1px solid black; 14278 animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite; 14279} 14280 14281@keyframes ProseMirror-cursor-blink { 14282 to { 14283 visibility: hidden; 14284 } 14285} 14286 14287.ProseMirror-hideselection *::selection { 14288 background: transparent; 14289} 14290 14291.ProseMirror-hideselection *::-moz-selection { 14292 background: transparent; 14293} 14294 14295.ProseMirror-hideselection * { 14296 caret-color: transparent; 14297} 14298 14299.ProseMirror-focused .ProseMirror-gapcursor { 14300 display: block; 14301}`; 14302var Editor = class extends EventEmitter { 14303 constructor(options = {}) { 14304 super(); 14305 this.css = null; 14306 this.className = "tiptap"; 14307 this.editorView = null; 14308 this.isFocused = false; 14309 this.destroyed = false; 14310 this.isInitialized = false; 14311 this.extensionStorage = {}; 14312 this.instanceId = Math.random().toString(36).slice(2, 9); 14313 this.hasWarnedStaleDecorationRead = false; 14314 this.options = { 14315 element: typeof document !== "undefined" ? document.createElement("div") : null, 14316 content: "", 14317 injectCSS: true, 14318 injectNonce: void 0, 14319 extensions: [], 14320 autofocus: false, 14321 editable: true, 14322 textDirection: void 0, 14323 editorProps: {}, 14324 parseOptions: {}, 14325 coreExtensionOptions: {}, 14326 enableInputRules: true, 14327 enablePasteRules: true, 14328 enableCoreExtensions: true, 14329 enableContentCheck: false, 14330 emitContentError: false, 14331 onBeforeCreate: () => null, 14332 onCreate: () => null, 14333 onMount: () => null, 14334 onUnmount: () => null, 14335 onUpdate: () => null, 14336 onSelectionUpdate: () => null, 14337 onTransaction: () => null, 14338 onFocus: () => null, 14339 onBlur: () => null, 14340 onDestroy: () => null, 14341 onContentError: ({ error }) => { 14342 throw error; 14343 }, 14344 onPaste: () => null, 14345 onDrop: () => null, 14346 onDelete: () => null, 14347 enableExtensionDispatchTransaction: true 14348 }; 14349 this.isCapturingTransaction = false; 14350 this.capturedTransaction = null; 14351 this.utils = { 14352 getUpdatedPosition, 14353 createMappablePosition 14354 }; 14355 this.setOptions(options); 14356 this.createExtensionManager(); 14357 this.createCommandManager(); 14358 this.createSchema(); 14359 this.on("beforeCreate", this.options.onBeforeCreate); 14360 this.emit("beforeCreate", { editor: this }); 14361 this.on("mount", this.options.onMount); 14362 this.on("unmount", this.options.onUnmount); 14363 this.on("contentError", this.options.onContentError); 14364 this.on("create", this.options.onCreate); 14365 this.on("update", this.options.onUpdate); 14366 this.on("selectionUpdate", this.options.onSelectionUpdate); 14367 this.on("transaction", this.options.onTransaction); 14368 this.on("focus", this.options.onFocus); 14369 this.on("blur", this.options.onBlur); 14370 this.on("destroy", this.options.onDestroy); 14371 this.on("drop", ({ event, slice, moved }) => this.options.onDrop(event, slice, moved)); 14372 this.on("paste", ({ event, slice }) => this.options.onPaste(event, slice)); 14373 this.on("delete", this.options.onDelete); 14374 const initialDoc = this.createDoc(); 14375 if (!this.editorState) { 14376 const selection = resolveFocusPosition(initialDoc, this.options.autofocus); 14377 this.editorState = EditorState.create({ 14378 doc: initialDoc, 14379 schema: this.schema, 14380 selection: selection || void 0 14381 }); 14382 } 14383 warnOnDuplicatedProseMirrorModel(this.schema); 14384 if (this.options.element) this.mount(this.options.element); 14385 } 14386 mount(el) { 14387 if (typeof document === "undefined") throw new Error(`[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.`); 14388 this.createView(el);
vendor: 4,346 bytes, lines 14389-14504
14389 this.emit("mount", { editor: this }); 14390 if (this.css && !document.head.contains(this.css)) document.head.appendChild(this.css); 14391 window.setTimeout(() => { 14392 if (this.isDestroyed) return; 14393 if (this.options.autofocus !== false && this.options.autofocus !== null) this.commands.focus(this.options.autofocus); 14394 this.emit("create", { editor: this }); 14395 this.isInitialized = true; 14396 }, 0); 14397 } 14398 unmount() { 14399 if (this.editorView) { 14400 this.editorState = this.editorView.state; 14401 const dom = this.editorView.dom; 14402 if (dom === null || dom === void 0 ? void 0 : dom.editor) delete dom.editor; 14403 this.editorView.destroy(); 14404 } 14405 this.editorView = null; 14406 this.isInitialized = false; 14407 if (this.css && !document.querySelectorAll(`.${this.className}`).length) try { 14408 if (typeof this.css.remove === "function") this.css.remove(); 14409 else if (this.css.parentNode) this.css.parentNode.removeChild(this.css); 14410 } catch (error) { 14411 console.warn("Failed to remove CSS element:", error); 14412 } 14413 this.css = null; 14414 this.emit("unmount", { editor: this }); 14415 } 14416 get storage() { 14417 return this.extensionStorage; 14418 } 14419 get commands() { 14420 return this.commandManager.commands; 14421 } 14422 chain() { 14423 if (!this.commandManager) return CommandManager.createFakeChain(); 14424 return this.commandManager.chain(); 14425 } 14426 can() { 14427 if (!this.commandManager) return CommandManager.createFallbackCan(); 14428 return this.commandManager.can(); 14429 } 14430 injectCSS() { 14431 if (this.options.injectCSS && typeof document !== "undefined") this.css = createStyleTag(style, this.options.injectNonce); 14432 } 14433 setOptions(options = {}) { 14434 this.options = { 14435 ...this.options, 14436 ...options 14437 }; 14438 if (!this.editorView || !this.state || this.isDestroyed) return; 14439 if (this.options.editorProps) this.view.setProps(this.options.editorProps); 14440 this.view.updateState(this.state); 14441 } 14442 setEditable(editable, emitUpdate = true) { 14443 this.setOptions({ editable }); 14444 if (emitUpdate) this.emit("update", { 14445 editor: this, 14446 transaction: this.state.tr, 14447 appendedTransactions: [] 14448 }); 14449 } 14450 get isEditable() { 14451 return this.options.editable && this.view && this.view.editable; 14452 } 14453 get view() { 14454 if (this.editorView) return this.editorView; 14455 return new Proxy({ 14456 state: this.editorState, 14457 updateState: (state) => { 14458 this.editorState = state; 14459 }, 14460 dispatch: (tr$1) => { 14461 this.dispatchTransaction(tr$1); 14462 }, 14463 composing: false, 14464 dragging: null, 14465 editable: true, 14466 isDestroyed: false 14467 }, { get: (obj, key) => { 14468 if (this.editorView) return this.editorView[key]; 14469 if (key === "state") return this.editorState; 14470 if (key in obj) return Reflect.get(obj, key); 14471 throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${key}']. The editor may not be mounted yet.`); 14472 } }); 14473 } 14474 get state() { 14475 if (isDev$1 && !this.hasWarnedStaleDecorationRead && isInDecorationApplyScope(this)) { 14476 this.hasWarnedStaleDecorationRead = true; 14477 console.warn("[tiptap warn]: `editor.state` was read while decoration `create()` was running. It returns the pre-transaction document. Use the `state` argument passed to `create()` instead. Helpers like `editor.isActive()` read `editor.state` too, so pass `state` to their standalone versions instead of calling them on the editor."); 14478 } 14479 if (this.editorView) this.editorState = this.view.state; 14480 return this.editorState; 14481 } 14482 registerPlugin(plugin, handlePlugins) { 14483 const plugins = isFunction(handlePlugins) ? handlePlugins(plugin, [...this.state.plugins]) : [...this.state.plugins, plugin]; 14484 const state = this.state.reconfigure({ plugins }); 14485 this.view.updateState(state); 14486 return state; 14487 } 14488 unregisterPlugin(nameOrPluginKeyToRemove) { 14489 if (this.isDestroyed) return; 14490 const prevPlugins = this.state.plugins; 14491 let plugins = prevPlugins; 14492 [].concat(nameOrPluginKeyToRemove).forEach((nameOrPluginKey) => { 14493 const name = typeof nameOrPluginKey === "string" ? `${nameOrPluginKey}$` : nameOrPluginKey.key; 14494 plugins = plugins.filter((plugin) => !plugin.key.startsWith(name)); 14495 }); 14496 if (prevPlugins.length === plugins.length) return; 14497 const state = this.state.reconfigure({ plugins }); 14498 this.view.updateState(state); 14499 return state; 14500 } 14501 createExtensionManager() { 14502 var _this$options$coreExt, _this$options$coreExt2; 14503 this.extensionManager = new ExtensionManager([...this.options.enableCoreExtensions ? [ 14504 Editable,
vendor: 4,710 bytes, lines 14505-14615
14505 ClipboardTextSerializer.configure({ blockSeparator: (_this$options$coreExt = this.options.coreExtensionOptions) === null || _this$options$coreExt === void 0 || (_this$options$coreExt = _this$options$coreExt.clipboardTextSerializer) === null || _this$options$coreExt === void 0 ? void 0 : _this$options$coreExt.blockSeparator }), 14506 Commands, 14507 FocusEvents, 14508 Keymap, 14509 Tabindex.configure({ value: (_this$options$coreExt2 = this.options.coreExtensionOptions) === null || _this$options$coreExt2 === void 0 || (_this$options$coreExt2 = _this$options$coreExt2.tabindex) === null || _this$options$coreExt2 === void 0 ? void 0 : _this$options$coreExt2.value }), 14510 Drop, 14511 Paste, 14512 Delete, 14513 TextDirection.configure({ direction: this.options.textDirection }) 14514 ].filter((ext) => { 14515 if (typeof this.options.enableCoreExtensions === "object") return this.options.enableCoreExtensions[ext.name] !== false; 14516 return true; 14517 }) : [], ...this.options.extensions].filter((extension) => { 14518 return [ 14519 "extension", 14520 "node", 14521 "mark" 14522 ].includes(extension === null || extension === void 0 ? void 0 : extension.type); 14523 }), this); 14524 } 14525 createCommandManager() { 14526 this.commandManager = new CommandManager({ editor: this }); 14527 } 14528 createSchema() { 14529 this.schema = this.extensionManager.schema; 14530 } 14531 createDoc() { 14532 let doc$2; 14533 try { 14534 doc$2 = createDocument(this.options.content, this.schema, this.options.parseOptions, { errorOnInvalidContent: this.options.enableContentCheck }); 14535 } catch (e) { 14536 if (!(e instanceof Error) || !["[tiptap error]: Invalid JSON content", "[tiptap error]: Invalid HTML content"].includes(e.message)) throw e; 14537 const fallbackDoc = createDocument(this.options.content, this.schema, this.options.parseOptions, { errorOnInvalidContent: false }); 14538 this.editorState = EditorState.create({ 14539 doc: fallbackDoc, 14540 schema: this.schema, 14541 selection: resolveFocusPosition(fallbackDoc, this.options.autofocus) || void 0 14542 }); 14543 this.emit("contentError", { 14544 editor: this, 14545 error: e, 14546 disableCollaboration: () => { 14547 if ("collaboration" in this.storage && typeof this.storage.collaboration === "object" && this.storage.collaboration) this.storage.collaboration.isDisabled = true; 14548 this.options.extensions = this.options.extensions.filter((extension) => extension.name !== "collaboration"); 14549 this.createExtensionManager(); 14550 } 14551 }); 14552 return this.editorState.doc; 14553 } 14554 return doc$2; 14555 } 14556 createView(element) { 14557 const { editorProps, enableExtensionDispatchTransaction } = this.options; 14558 const baseDispatch = editorProps.dispatchTransaction || this.dispatchTransaction.bind(this); 14559 const dispatch = enableExtensionDispatchTransaction ? this.extensionManager.dispatchTransaction(baseDispatch) : baseDispatch; 14560 const baseTransformPastedHTML = editorProps.transformPastedHTML; 14561 const transformPastedHTML = this.extensionManager.transformPastedHTML(baseTransformPastedHTML); 14562 this.editorView = new EditorView(element, { 14563 ...editorProps, 14564 attributes: { 14565 role: "textbox", 14566 ...editorProps === null || editorProps === void 0 ? void 0 : editorProps.attributes 14567 }, 14568 dispatchTransaction: dispatch, 14569 transformPastedHTML, 14570 state: this.editorState, 14571 markViews: this.extensionManager.markViews, 14572 nodeViews: this.extensionManager.nodeViews 14573 }); 14574 const newState = this.state.reconfigure({ plugins: this.extensionManager.plugins }); 14575 this.view.updateState(newState); 14576 this.prependClass(); 14577 this.injectCSS(); 14578 const dom = this.view.dom; 14579 dom.editor = this; 14580 } 14581 createNodeViews() { 14582 if (this.view.isDestroyed) return; 14583 this.view.setProps({ 14584 markViews: this.extensionManager.markViews, 14585 nodeViews: this.extensionManager.nodeViews 14586 }); 14587 } 14588 prependClass() { 14589 this.view.dom.className = `${this.className} ${this.view.dom.className}`; 14590 } 14591 captureTransaction(fn) { 14592 this.isCapturingTransaction = true; 14593 fn(); 14594 this.isCapturingTransaction = false; 14595 const tr$1 = this.capturedTransaction; 14596 this.capturedTransaction = null; 14597 return tr$1; 14598 } 14599 dispatchTransaction(transaction) { 14600 if (this.view.isDestroyed) return; 14601 if (this.isCapturingTransaction) { 14602 if (!this.capturedTransaction) { 14603 this.capturedTransaction = transaction; 14604 return; 14605 } 14606 transaction.steps.forEach((step) => { 14607 var _this$capturedTransac; 14608 return (_this$capturedTransac = this.capturedTransaction) === null || _this$capturedTransac === void 0 ? void 0 : _this$capturedTransac.step(step); 14609 }); 14610 return; 14611 } 14612 const { state, transactions } = this.state.applyTransaction(transaction); 14613 const selectionHasChanged = !this.state.selection.eq(state.selection); 14614 const rootTrWasApplied = transactions.includes(transaction); 14615 const prevState = this.state;
vendor: 1,721 bytes, lines 14616-14666
14616 this.emit("beforeTransaction", { 14617 editor: this, 14618 transaction, 14619 nextState: state 14620 }); 14621 if (!rootTrWasApplied) return; 14622 this.view.updateState(state); 14623 this.emit("transaction", { 14624 editor: this, 14625 transaction, 14626 appendedTransactions: transactions.slice(1) 14627 }); 14628 if (selectionHasChanged) this.emit("selectionUpdate", { 14629 editor: this, 14630 transaction 14631 }); 14632 const mostRecentFocusTr = transactions.findLast((tr$1) => tr$1.getMeta("focus") || tr$1.getMeta("blur")); 14633 const focus$1 = mostRecentFocusTr === null || mostRecentFocusTr === void 0 ? void 0 : mostRecentFocusTr.getMeta("focus"); 14634 const blur$1 = mostRecentFocusTr === null || mostRecentFocusTr === void 0 ? void 0 : mostRecentFocusTr.getMeta("blur"); 14635 if (focus$1) this.emit("focus", { 14636 editor: this, 14637 event: focus$1.event, 14638 transaction: mostRecentFocusTr 14639 }); 14640 if (blur$1) this.emit("blur", { 14641 editor: this, 14642 event: blur$1.event, 14643 transaction: mostRecentFocusTr 14644 }); 14645 if (transaction.getMeta("preventUpdate") || !transactions.some((tr$1) => tr$1.docChanged) || prevState.doc.eq(state.doc)) return; 14646 this.emit("update", { 14647 editor: this, 14648 transaction, 14649 appendedTransactions: transactions.slice(1) 14650 }); 14651 } 14652 getAttributes(nameOrType) { 14653 return getAttributes(this.state, nameOrType); 14654 } 14655 isActive(nameOrAttributes, attributesOrUndefined) { 14656 const name = typeof nameOrAttributes === "string" ? nameOrAttributes : null; 14657 const attributes = typeof nameOrAttributes === "string" ? attributesOrUndefined : nameOrAttributes; 14658 return isActive(this.state, name, attributes); 14659 } 14660 getJSON() { 14661 return this.state.doc.toJSON(); 14662 } 14663 getHTML() { 14664 return getHTMLFromFragment(this.state.doc.content, this.schema); 14665 } 14666 getText(options) {
vendor: 5,563 bytes, lines 14667-14803
14667 const { blockSeparator = "\n\n", textSerializers = {} } = options || {}; 14668 return getText(this.state.doc, { 14669 blockSeparator, 14670 textSerializers: { 14671 ...getTextSerializersFromSchema(this.schema), 14672 ...textSerializers 14673 } 14674 }); 14675 } 14676 get isEmpty() { 14677 return isNodeEmpty(this.state.doc); 14678 } 14679 destroy() { 14680 if (this.destroyed) return; 14681 this.destroyed = true; 14682 this.emit("destroy"); 14683 this.unmount(); 14684 this.removeAllListeners(); 14685 this.extensionManager.destroy(); 14686 this.extensionManager = null; 14687 this.schema = null; 14688 this.commandManager = null; 14689 this.extensionStorage = {}; 14690 } 14691 get isDestroyed() { 14692 var _this$editorView$isDe, _this$editorView; 14693 return (_this$editorView$isDe = (_this$editorView = this.editorView) === null || _this$editorView === void 0 ? void 0 : _this$editorView.isDestroyed) !== null && _this$editorView$isDe !== void 0 ? _this$editorView$isDe : true; 14694 } 14695 $node(selector, attributes) { 14696 var _this$$doc; 14697 return ((_this$$doc = this.$doc) === null || _this$$doc === void 0 ? void 0 : _this$$doc.querySelector(selector, attributes)) || null; 14698 } 14699 $nodes(selector, attributes) { 14700 var _this$$doc2; 14701 return ((_this$$doc2 = this.$doc) === null || _this$$doc2 === void 0 ? void 0 : _this$$doc2.querySelectorAll(selector, attributes)) || null; 14702 } 14703 $pos(pos) { 14704 const $pos = this.state.doc.resolve(pos); 14705 const node = pos > 0 && $pos.nodeAfter && !$pos.nodeAfter.isText && $pos.nodeAfter.isAtom ? $pos.nodeAfter : null; 14706 return new NodePos($pos, this, false, node); 14707 } 14708 get $doc() { 14709 return this.$pos(0); 14710 } 14711}; 14712function markInputRule(config) { 14713 return new InputRule({ 14714 find: config.find, 14715 handler: ({ state, range, match }) => { 14716 const attributes = callOrReturn(config.getAttributes, void 0, match); 14717 if (attributes === false || attributes === null) return null; 14718 const { tr: tr$1 } = state; 14719 const captureGroup = match[match.length - 1]; 14720 const fullMatch = match[0]; 14721 if (captureGroup) { 14722 const startSpaces = fullMatch.search(/\S/); 14723 const textStart = range.from + fullMatch.indexOf(captureGroup); 14724 const textEnd = textStart + captureGroup.length; 14725 if (getMarksBetween(range.from, range.to, state.doc).filter((item) => { 14726 return item.mark.type.excluded.find((type) => type === config.type && type !== item.mark.type); 14727 }).filter((item) => item.to > textStart).length) return null; 14728 if (textEnd < range.to) tr$1.delete(textEnd, range.to); 14729 if (textStart > range.from) tr$1.delete(range.from + startSpaces, textStart); 14730 const markEnd = range.from + startSpaces + captureGroup.length; 14731 tr$1.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {})); 14732 tr$1.removeStoredMark(config.type); 14733 } 14734 }, 14735 undoable: config.undoable 14736 }); 14737} 14738function nodeInputRule(config) { 14739 return new InputRule({ 14740 find: config.find, 14741 handler: ({ state, range, match }) => { 14742 const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; 14743 const { tr: tr$1 } = state; 14744 const start = range.from; 14745 let end = range.to; 14746 const newNode = config.type.create(attributes); 14747 if (match[1]) { 14748 let matchStart = start + match[0].lastIndexOf(match[1]); 14749 if (matchStart > end) matchStart = end; 14750 else end = matchStart + match[1].length; 14751 const lastChar = match[0][match[0].length - 1]; 14752 tr$1.insertText(lastChar, start + match[0].length - 1); 14753 tr$1.replaceWith(matchStart, end, newNode); 14754 } else if (match[0]) { 14755 const insertionStart = config.type.isInline ? start : start - 1; 14756 tr$1.insert(insertionStart, config.type.create(attributes)).delete(tr$1.mapping.map(start), tr$1.mapping.map(end)); 14757 } 14758 tr$1.scrollIntoView(); 14759 }, 14760 undoable: config.undoable 14761 }); 14762} 14763function textblockTypeInputRule(config) { 14764 return new InputRule({ 14765 find: config.find, 14766 handler: ({ state, range, match }) => { 14767 const $start = state.doc.resolve(range.from); 14768 const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; 14769 if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) return null; 14770 state.tr.delete(range.from, range.to).setBlockType(range.from, range.from, config.type, attributes); 14771 }, 14772 undoable: config.undoable 14773 }); 14774} 14775function wrappingInputRule(config) { 14776 return new InputRule({ 14777 find: config.find, 14778 handler: ({ state, range, match, chain }) => { 14779 const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; 14780 const tr$1 = state.tr.delete(range.from, range.to); 14781 const blockRange = tr$1.doc.resolve(range.from).blockRange(); 14782 const wrapping = blockRange && findWrapping(blockRange, config.type, attributes); 14783 if (!wrapping) return null; 14784 tr$1.wrap(blockRange, wrapping); 14785 if (config.keepMarks && config.editor) { 14786 const { selection, storedMarks } = state; 14787 const { splittableMarks } = config.editor.extensionManager; 14788 const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); 14789 if (marks) { 14790 const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); 14791 tr$1.ensureMarks(filteredMarks); 14792 } 14793 } 14794 if (config.keepAttributes) { 14795 const nodeType = config.type.name === "bulletList" || config.type.name === "orderedList" ? "listItem" : "taskList"; 14796 chain().updateAttributes(nodeType, attributes).run(); 14797 } 14798 const before = tr$1.doc.resolve(range.from - 1).nodeBefore; 14799 if (before && before.type === config.type && canJoin(tr$1.doc, range.from - 1) && (!config.joinPredicate || config.joinPredicate(match, before))) tr$1.join(range.from - 1); 14800 }, 14801 undoable: config.undoable 14802 }); 14803}
vendor: 5,065 bytes, lines 14804-14846
14804var Node = class Node$2 extends Extendable { 14805 constructor(..._args) { 14806 super(..._args); 14807 this.type = "node"; 14808 } 14809 static create(config = {}) { 14810 return new Node$2(typeof config === "function" ? config() : config); 14811 } 14812 configure(options) { 14813 return super.configure(options); 14814 } 14815 extend(extendedConfig) { 14816 const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; 14817 return super.extend(resolvedConfig); 14818 } 14819}; 14820function markPasteRule(config) { 14821 return new PasteRule({ 14822 find: config.find, 14823 handler: ({ state, range, match, pasteEvent }) => { 14824 const attributes = callOrReturn(config.getAttributes, void 0, match, pasteEvent); 14825 if (attributes === false || attributes === null) return null; 14826 const { tr: tr$1 } = state; 14827 const captureGroup = match[match.length - 1]; 14828 const fullMatch = match[0]; 14829 let markEnd = range.to; 14830 if (captureGroup) { 14831 const startSpaces = fullMatch.search(/\S/); 14832 const textStart = range.from + fullMatch.indexOf(captureGroup); 14833 const textEnd = textStart + captureGroup.length; 14834 if (getMarksBetween(range.from, range.to, state.doc).filter((item) => { 14835 return item.mark.type.excluded.find((type) => type === config.type && type !== item.mark.type); 14836 }).filter((item) => item.to > textStart).length) return null; 14837 if (textEnd < range.to) tr$1.delete(textEnd, range.to); 14838 if (textStart > range.from) tr$1.delete(range.from + startSpaces, textStart); 14839 markEnd = range.from + startSpaces + captureGroup.length; 14840 tr$1.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {})); 14841 if (!(match.index !== void 0 && match.input !== void 0 && match.index + match[0].length >= match.input.length)) tr$1.removeStoredMark(config.type); 14842 } 14843 } 14844 }); 14845} 14846var encodedTlds = "aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2
14846ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2"; 14847var encodedUtlds = "ελ1Ï 2бг1ел3деÑи4еÑ2каÑолик6ом3мÐ
14847ºÐ´2он1Ñква6онлайн5Ñг3ÑÑÑ2Ñ2ÑайÑ3Ñб3ÑкÑ3Òаз3Õ°Õ¡Õµ3×שר××5×§××3Ø§Ø¨ÙØ¸Ø¨Ù5را٠ÙÙ5ÙØ§Ø±Ø¯Ù4Ø¨ØØ±ÙÙ5جزائر5Ø³Ø¹ÙØ¯ÙØ©6عÙÙØ§Ù5٠غرب5٠ارات5ÛØ±Ø§Ù5بارت2زار4ÙØªÙ3ھارت5تÙÙØ³4Ø³ÙØ¯Ø§Ù3Ø±ÙØ©5Ø´Ø¨ÙØ©4عراÙ2ب2٠اÙ4ÙÙØ³Ø·ÙÙ6ÙØ·Ø±3ÙØ§Ø«ÙÙÙÙ6ÙÙ 3٠صر2ÙÙØ³Ùا5ÙØ±ÙتاÙÙØ§7ÙØ¹4Ù٠راÙ5پاکستاÙ7ÚØ§Ø±Øª4à¤à¥à¤®3नà¥à¤3à¤à¤¾à¤°à¤¤0मà¥3à¥à¤¤5सà¤à¤à¤ न5বাà¦à¦²à¦¾5à¦à¦¾à¦°à¦¤2ৰত4à¨à¨¾à¨°à¨¤4àªàª¾àª°àª¤4à¬à¬¾à¬°à¬¤4à®à®¨à¯à®¤à®¿à®¯à®¾6லà®à¯à®à¯6à®à®¿à®à¯à®à®ªà¯à®ªà¯à®°à¯11à°à°¾à°°à°¤à±5à²à²¾à²°à²¤4à´à´¾à´°à´¤à´5à¶½à¶à¶à·4à¸à¸à¸¡3à¹à¸à¸¢3ລາວ3áá2ã¿ããª3ã¢ãã¾ã³4ã¯ã©ã¦ã4ã°ã¼ã°ã«4ã³ã 2ã¹ãã¢3ã»ã¼ã«3ãã¡ãã·ã§ã³6ãã¤ã³ã4ä¸ç2ä¸ä¿¡1å½1å1æç½3äºé©¬é3ä¼ä¸2ä½å±±2ä¿¡æ¯2å¥åº·2å «å¦2å ¬å¸1ç2å°æ¹¾1ç£2åå1åº1æ 2åé0大é åº5å¨çº¿2大æ¿2天主æ3娱ä¹2å®¶é»2广ä¸2å¾®å2æ å2æç±ä½ 3ææº2æè2æ¿å¡1åº2æ°å å¡2é»2æ¶å°2æ¸ç±2æºæ2淡马é¡3游æ2æ¾³é2ç¹ç2ç§»å¨2ç»ç»æºæ4ç½å1åº1ç«1ç»2èé2è°·æ2è´ç©2é販2éå¢2é»è¨çç§4é£å©æµ¦3é£å2é¤å 2馿 ¼éæ3港2ë·ë·1ì»´2ì¼ì±2íêµ2"; 14848var numeric = "numeric"; 14849var ascii = "ascii"; 14850var alpha = "alpha"; 14851var asciinumeric = "asciinumeric"; 14852var alphanumeric = "alphanumeric"; 14853var domain = "domain"; 14854var emoji = "emoji"; 14855var scheme = "scheme"; 14856var slashscheme = "slashscheme"; 14857var whitespace = "whitespace"; 14858function registerGroup(name, groups) { 14859 if (!(name in groups)) groups[name] = []; 14860 return groups[name]; 14861} 14862function addToGroups(t, flags, groups) { 14863 if (flags[numeric]) { 14864 flags[asciinumeric] = true; 14865 flags[alphanumeric] = true; 14866 } 14867 if (flags[ascii]) { 14868 flags[asciinumeric] = true; 14869 flags[alpha] = true; 14870 } 14871 if (flags[asciinumeric]) flags[alphanumeric] = true; 14872 if (flags[alpha]) flags[alphanumeric] = true; 14873 if (flags[alphanumeric]) flags[domain] = true; 14874 if (flags[emoji]) flags[domain] = true; 14875 for (const k in flags) { 14876 const group = registerGroup(k, groups); 14877 if (group.indexOf(t) < 0) group.push(t); 14878 } 14879} 14880function flagsForToken(t, groups) { 14881 const result = {}; 14882 for (const c in groups) if (groups[c].indexOf(t) >= 0) result[c] = true; 14883 return result; 14884} 14885function State(token = null) { 14886 this.j = {}; 14887 this.jr = []; 14888 this.jd = null; 14889 this.t = token; 14890} 14891State.groups = {}; 14892State.prototype = { 14893 accepts() { 14894 return !!this.t; 14895 }, 14896 go(input) { 14897 const state = this; 14898 const nextState = state.j[input]; 14899 if (nextState) return nextState; 14900 for (let i$1 = 0; i$1 < state.jr.length; i$1++) { 14901 const regex = state.jr[i$1][0]; 14902 const nextState$1 = state.jr[i$1][1]; 14903 if (nextState$1 && regex.test(input)) return nextState$1; 14904 } 14905 return state.jd; 14906 }, 14907 has(input, exactOnly = false) { 14908 return exactOnly ? input in this.j : !!this.go(input); 14909 }, 14910 ta(inputs, next, flags, groups) { 14911 for (let i$1 = 0; i$1 < inputs.length; i$1++) this.tt(inputs[i$1], next, flags, groups); 14912 }, 14913 tr(regexp, next, flags, groups) { 14914 groups = groups || State.groups; 14915 let nextState; 14916 if (next && next.j) nextState = next; 14917 else { 14918 nextState = new State(next); 14919 if (flags && groups) addToGroups(next, flags, groups); 14920 } 14921 this.jr.push([regexp, nextState]); 14922 return nextState; 14923 }, 14924 ts(input, next, flags, groups) { 14925 let state = this; 14926 const len = input.length; 14927 if (!len) return state; 14928 for (let i$1 = 0; i$1 < len - 1; i$1++) state = state.tt(input[i$1]); 14929 return state.tt(input[len - 1], next, flags, groups); 14930 }, 14931 tt(input, next, flags, groups) { 14932 groups = groups || State.groups;
14933 const state = this; 14934 if (next && next.j) { 14935 state.j[input] = next; 14936 return next; 14937 } 14938 const t = next; 14939 let nextState, templateState = state.go(input); 14940 if (templateState) { 14941 nextState = new State(); 14942 Object.assign(nextState.j, templateState.j); 14943 nextState.jr.push.apply(nextState.jr, templateState.jr); 14944 nextState.jd = templateState.jd; 14945 nextState.t = templateState.t; 14946 } else nextState = new State(); 14947 if (t) { 14948 if (groups) { 14949 if (nextState.t && typeof nextState.t === "string") addToGroups(t, Object.assign(flagsForToken(nextState.t, groups), flags), groups); 14950 else if (flags) addToGroups(t, flags, groups); 14951 } 14952 nextState.t = t; 14953 } 14954 state.j[input] = nextState; 14955 return nextState; 14956 } 14957}; 14958var ta = (state, input, next, flags, groups) => state.ta(input, next, flags, groups); 14959var tr = (state, regexp, next, flags, groups) => state.tr(regexp, next, flags, groups); 14960var ts = (state, input, next, flags, groups) => state.ts(input, next, flags, groups); 14961var tt = (state, input, next, flags, groups) => state.tt(input, next, flags, groups); 14962var WORD = "WORD"; 14963var UWORD = "UWORD"; 14964var ASCIINUMERICAL = "ASCIINUMERICAL"; 14965var ALPHANUMERICAL = "ALPHANUMERICAL"; 14966var LOCALHOST = "LOCALHOST"; 14967var TLD = "TLD"; 14968var UTLD = "UTLD"; 14969var SCHEME = "SCHEME"; 14970var SLASH_SCHEME = "SLASH_SCHEME"; 14971var NUM = "NUM"; 14972var WS = "WS"; 14973var NL = "NL"; 14974var OPENBRACE = "OPENBRACE"; 14975var CLOSEBRACE = "CLOSEBRACE"; 14976var OPENBRACKET = "OPENBRACKET"; 14977var CLOSEBRACKET = "CLOSEBRACKET"; 14978var OPENPAREN = "OPENPAREN"; 14979var CLOSEPAREN = "CLOSEPAREN"; 14980var OPENANGLEBRACKET = "OPENANGLEBRACKET"; 14981var CLOSEANGLEBRACKET = "CLOSEANGLEBRACKET"; 14982var FULLWIDTHLEFTPAREN = "FULLWIDTHLEFTPAREN"; 14983var FULLWIDTHRIGHTPAREN = "FULLWIDTHRIGHTPAREN"; 14984var LEFTCORNERBRACKET = "LEFTCORNERBRACKET"; 14985var RIGHTCORNERBRACKET = "RIGHTCORNERBRACKET"; 14986var LEFTWHITECORNERBRACKET = "LEFTWHITECORNERBRACKET"; 14987var RIGHTWHITECORNERBRACKET = "RIGHTWHITECORNERBRACKET"; 14988var FULLWIDTHLESSTHAN = "FULLWIDTHLESSTHAN"; 14989var FULLWIDTHGREATERTHAN = "FULLWIDTHGREATERTHAN"; 14990var AMPERSAND = "AMPERSAND"; 14991var APOSTROPHE = "APOSTROPHE"; 14992var ASTERISK = "ASTERISK"; 14993var AT = "AT"; 14994var BACKSLASH = "BACKSLASH"; 14995var BACKTICK = "BACKTICK"; 14996var CARET = "CARET"; 14997var COLON = "COLON"; 14998var COMMA = "COMMA"; 14999var DOLLAR = "DOLLAR"; 15000var DOT = "DOT"; 15001var EQUALS = "EQUALS"; 15002var EXCLAMATION = "EXCLAMATION"; 15003var HYPHEN = "HYPHEN"; 15004var PERCENT = "PERCENT"; 15005var PIPE = "PIPE"; 15006var PLUS = "PLUS"; 15007var POUND = "POUND"; 15008var QUERY = "QUERY"; 15009var QUOTE = "QUOTE"; 15010var FULLWIDTHMIDDLEDOT = "FULLWIDTHMIDDLEDOT"; 15011var SEMI = "SEMI"; 15012var SLASH = "SLASH"; 15013var TILDE = "TILDE"; 15014var UNDERSCORE = "UNDERSCORE"; 15015var EMOJI$1 = "EMOJI"; 15016var SYM = "SYM"; 15017var tk = /* @__PURE__ */ Object.freeze({ 15018 __proto__: null, 15019 ALPHANUMERICAL, 15020 AMPERSAND, 15021 APOSTROPHE, 15022 ASCIINUMERICAL, 15023 ASTERISK, 15024 AT, 15025 BACKSLASH, 15026 BACKTICK, 15027 CARET, 15028 CLOSEANGLEBRACKET, 15029 CLOSEBRACE, 15030 CLOSEBRACKET, 15031 CLOSEPAREN, 15032 COLON, 15033 COMMA, 15034 DOLLAR, 15035 DOT, 15036 EMOJI: EMOJI$1, 15037 EQUALS, 15038 EXCLAMATION, 15039 FULLWIDTHGREATERTHAN, 15040 FULLWIDTHLEFTPAREN, 15041 FULLWIDTHLESSTHAN, 15042 FULLWIDTHMIDDLEDOT, 15043 FULLWIDTHRIGHTPAREN, 15044 HYPHEN, 15045 LEFTCORNERBRACKET, 15046 LEFTWHITECORNERBRACKET, 15047 LOCALHOST, 15048 NL, 15049 NUM, 15050 OPENANGLEBRACKET, 15051 OPENBRACE, 15052 OPENBRACKET, 15053 OPENPAREN, 15054 PERCENT, 15055 PIPE, 15056 PLUS, 15057 POUND, 15058 QUERY, 15059 QUOTE, 15060 RIGHTCORNERBRACKET, 15061 RIGHTWHITECORNERBRACKET, 15062 SCHEME, 15063 SEMI, 15064 SLASH, 15065 SLASH_SCHEME, 15066 SYM, 15067 TILDE, 15068 TLD, 15069 UNDERSCORE, 15070 UTLD, 15071 UWORD, 15072 WORD, 15073 WS 15074}); 15075var ASCII_LETTER = /[a-z]/; 15076var LETTER = /\p{L}/u; 15077var EMOJI = /\p{Emoji}/u; 15078var DIGIT = /\d/; 15079var SPACE = /\s/; 15080var CR = "\r"; 15081var LF = "\n"; 15082var EMOJI_VARIATION = "ï¸"; 15083var EMOJI_JOINER = "â"; 15084var OBJECT_REPLACEMENT = ""; 15085var tlds = null, utlds = null; 15086function init$2(customSchemes = []) { 15087 const groups = {}; 15088 State.groups = groups; 15089 const Start = new State(); 15090 if (tlds == null) tlds = decodeTlds(encodedTlds); 15091 if (utlds == null) utlds = decodeTlds(encodedUtlds); 15092 tt(Start, "'", APOSTROPHE); 15093 tt(Start, "{", OPENBRACE); 15094 tt(Start, "}", CLOSEBRACE); 15095 tt(Start, "[", OPENBRACKET); 15096 tt(Start, "]", CLOSEBRACKET); 15097 tt(Start, "(", OPENPAREN); 15098 tt(Start, ")", CLOSEPAREN); 15099 tt(Start, "<", OPENANGLEBRACKET); 15100 tt(Start, ">", CLOSEANGLEBRACKET); 15101 tt(Start, "ï¼", FULLWIDTHLEFTPAREN); 15102 tt(Start, "ï¼", FULLWIDTHRIGHTPAREN); 15103 tt(Start, "ã", LEFTCORNERBRACKET); 15104 tt(Start, "ã", RIGHTCORNERBRACKET); 15105 tt(Start, "ã", LEFTWHITECORNERBRACKET); 15106 tt(Start, "ã", RIGHTWHITECORNERBRACKET); 15107 tt(Start, "ï¼", FULLWIDTHLESSTHAN); 15108 tt(Start, "ï¼", FULLWIDTHGREATERTHAN); 15109 tt(Start, "&", AMPERSAND); 15110 tt(Start, "*", ASTERISK); 15111 tt(Start, "@", AT); 15112 tt(Start, "`", BACKTICK); 15113 tt(Start, "^", CARET); 15114 tt(Start, ":", COLON); 15115 tt(Start, ",", COMMA); 15116 tt(Start, "$", DOLLAR); 15117 tt(Start, ".", DOT); 15118 tt(Start, "=", EQUALS); 15119 tt(Start, "!", EXCLAMATION); 15120 tt(Start, "-", HYPHEN); 15121 tt(Start, "%", PERCENT); 15122 tt(Start, "|", PIPE); 15123 tt(Start, "+", PLUS); 15124 tt(Start, "#", POUND); 15125 tt(Start, "?", QUERY); 15126 tt(Start, "\"", QUOTE); 15127 tt(Start, "/", SLASH); 15128 tt(Start, ";", SEMI); 15129 tt(Start, "~", TILDE); 15130 tt(Start, "_", UNDERSCORE); 15131 tt(Start, "\\", BACKSLASH); 15132 tt(Start, "ã»", FULLWIDTHMIDDLEDOT); 15133 const Num = tr(Start, DIGIT, NUM, { [numeric]: true }); 15134 tr(Num, DIGIT, Num); 15135 const Asciinumeric = tr(Num, ASCII_LETTER, ASCIINUMERICAL, { [asciinumeric]: true });
vendor: 4,299 bytes, lines 15136-15269
15136 const Alphanumeric = tr(Num, LETTER, ALPHANUMERICAL, { [alphanumeric]: true }); 15137 const Word = tr(Start, ASCII_LETTER, WORD, { [ascii]: true }); 15138 tr(Word, DIGIT, Asciinumeric); 15139 tr(Word, ASCII_LETTER, Word); 15140 tr(Asciinumeric, DIGIT, Asciinumeric); 15141 tr(Asciinumeric, ASCII_LETTER, Asciinumeric); 15142 const UWord = tr(Start, LETTER, UWORD, { [alpha]: true }); 15143 tr(UWord, ASCII_LETTER); 15144 tr(UWord, DIGIT, Alphanumeric); 15145 tr(UWord, LETTER, UWord); 15146 tr(Alphanumeric, DIGIT, Alphanumeric); 15147 tr(Alphanumeric, ASCII_LETTER); 15148 tr(Alphanumeric, LETTER, Alphanumeric); 15149 const Nl$1 = tt(Start, LF, NL, { [whitespace]: true }); 15150 const Cr = tt(Start, CR, WS, { [whitespace]: true }); 15151 const Ws = tr(Start, SPACE, WS, { [whitespace]: true }); 15152 tt(Start, OBJECT_REPLACEMENT, Ws); 15153 tt(Cr, LF, Nl$1); 15154 tt(Cr, OBJECT_REPLACEMENT, Ws); 15155 tr(Cr, SPACE, Ws); 15156 tt(Ws, CR); 15157 tt(Ws, LF); 15158 tr(Ws, SPACE, Ws); 15159 tt(Ws, OBJECT_REPLACEMENT, Ws); 15160 const Emoji = tr(Start, EMOJI, EMOJI$1, { [emoji]: true }); 15161 tt(Emoji, "#"); 15162 tr(Emoji, EMOJI, Emoji); 15163 tt(Emoji, EMOJI_VARIATION, Emoji); 15164 const EmojiJoiner = tt(Emoji, EMOJI_JOINER); 15165 tt(EmojiJoiner, "#"); 15166 tr(EmojiJoiner, EMOJI, Emoji); 15167 const wordjr = [[ASCII_LETTER, Word], [DIGIT, Asciinumeric]]; 15168 const uwordjr = [ 15169 [ASCII_LETTER, null], 15170 [LETTER, UWord], 15171 [DIGIT, Alphanumeric] 15172 ]; 15173 for (let i$1 = 0; i$1 < tlds.length; i$1++) fastts(Start, tlds[i$1], TLD, WORD, wordjr); 15174 for (let i$1 = 0; i$1 < utlds.length; i$1++) fastts(Start, utlds[i$1], UTLD, UWORD, uwordjr); 15175 addToGroups(TLD, { 15176 tld: true, 15177 ascii: true 15178 }, groups); 15179 addToGroups(UTLD, { 15180 utld: true, 15181 alpha: true 15182 }, groups); 15183 fastts(Start, "file", SCHEME, WORD, wordjr); 15184 fastts(Start, "mailto", SCHEME, WORD, wordjr); 15185 fastts(Start, "http", SLASH_SCHEME, WORD, wordjr); 15186 fastts(Start, "https", SLASH_SCHEME, WORD, wordjr); 15187 fastts(Start, "ftp", SLASH_SCHEME, WORD, wordjr); 15188 fastts(Start, "ftps", SLASH_SCHEME, WORD, wordjr); 15189 addToGroups(SCHEME, { 15190 scheme: true, 15191 ascii: true 15192 }, groups); 15193 addToGroups(SLASH_SCHEME, { 15194 slashscheme: true, 15195 ascii: true 15196 }, groups); 15197 customSchemes = customSchemes.sort((a, b) => a[0] > b[0] ? 1 : -1); 15198 for (let i$1 = 0; i$1 < customSchemes.length; i$1++) { 15199 const sch = customSchemes[i$1][0]; 15200 const flags = customSchemes[i$1][1] ? { [scheme]: true } : { [slashscheme]: true }; 15201 if (sch.indexOf("-") >= 0) flags[domain] = true; 15202 else if (!ASCII_LETTER.test(sch)) flags[numeric] = true; 15203 else if (DIGIT.test(sch)) flags[asciinumeric] = true; 15204 else flags[ascii] = true; 15205 ts(Start, sch, sch, flags); 15206 } 15207 ts(Start, "localhost", LOCALHOST, { ascii: true }); 15208 Start.jd = new State(SYM); 15209 return { 15210 start: Start, 15211 tokens: Object.assign({ groups }, tk) 15212 }; 15213} 15214function run$1(start, str) { 15215 const iterable = stringToArray(str.replace(/[A-Z]/g, (c) => c.toLowerCase())); 15216 const charCount = iterable.length; 15217 const tokens = []; 15218 let cursor = 0; 15219 let charCursor = 0; 15220 while (charCursor < charCount) { 15221 let state = start; 15222 let nextState = null; 15223 let tokenLength = 0; 15224 let latestAccepting = null; 15225 let sinceAccepts = -1; 15226 let charsSinceAccepts = -1; 15227 while (charCursor < charCount && (nextState = state.go(iterable[charCursor]))) { 15228 state = nextState; 15229 if (state.accepts()) { 15230 sinceAccepts = 0; 15231 charsSinceAccepts = 0; 15232 latestAccepting = state; 15233 } else if (sinceAccepts >= 0) { 15234 sinceAccepts += iterable[charCursor].length; 15235 charsSinceAccepts++; 15236 } 15237 tokenLength += iterable[charCursor].length; 15238 cursor += iterable[charCursor].length; 15239 charCursor++; 15240 } 15241 cursor -= sinceAccepts; 15242 charCursor -= charsSinceAccepts; 15243 tokenLength -= sinceAccepts; 15244 tokens.push({ 15245 t: latestAccepting.t, 15246 v: str.slice(cursor - tokenLength, cursor), 15247 s: cursor - tokenLength, 15248 e: cursor 15249 }); 15250 } 15251 return tokens; 15252} 15253function stringToArray(str) { 15254 const result = []; 15255 const len = str.length; 15256 let index = 0; 15257 while (index < len) { 15258 let first$1 = str.charCodeAt(index); 15259 let second; 15260 let char = first$1 < 55296 || first$1 > 56319 || index + 1 === len || (second = str.charCodeAt(index + 1)) < 56320 || second > 57343 ? str[index] : str.slice(index, index + 2); 15261 result.push(char); 15262 index += char.length; 15263 } 15264 return result; 15265} 15266function fastts(state, input, t, defaultt, jr) { 15267 let next; 15268 const len = input.length; 15269 for (let i$1 = 0; i$1 < len - 1; i$1++) {
15270 const char = input[i$1]; 15271 if (state.j[char]) next = state.j[char]; 15272 else { 15273 next = new State(defaultt); 15274 next.jr = jr.slice(); 15275 state.j[char] = next; 15276 } 15277 state = next; 15278 } 15279 next = new State(t); 15280 next.jr = jr.slice(); 15281 state.j[input[len - 1]] = next; 15282 return next; 15283} 15284function decodeTlds(encoded) { 15285 const words = []; 15286 const stack = []; 15287 let i$1 = 0; 15288 let digits = "0123456789"; 15289 while (i$1 < encoded.length) { 15290 let popDigitCount = 0; 15291 while (digits.indexOf(encoded[i$1 + popDigitCount]) >= 0) popDigitCount++; 15292 if (popDigitCount > 0) { 15293 words.push(stack.join("")); 15294 for (let popCount = parseInt(encoded.substring(i$1, i$1 + popDigitCount), 10); popCount > 0; popCount--) stack.pop(); 15295 i$1 += popDigitCount; 15296 } else { 15297 stack.push(encoded[i$1]); 15298 i$1++; 15299 } 15300 } 15301 return words; 15302} 15303var defaults = { 15304 defaultProtocol: "http", 15305 events: null, 15306 format: noop, 15307 formatHref: noop, 15308 nl2br: false, 15309 tagName: "a", 15310 target: null, 15311 rel: null, 15312 validate: true, 15313 truncate: Infinity, 15314 className: null, 15315 attributes: null, 15316 ignoreTags: [], 15317 render: null 15318}; 15319function Options(opts, defaultRender = null) { 15320 let o = Object.assign({}, defaults); 15321 if (opts) o = Object.assign(o, opts instanceof Options ? opts.o : opts); 15322 const ignoredTags = o.ignoreTags; 15323 const uppercaseIgnoredTags = []; 15324 for (let i$1 = 0; i$1 < ignoredTags.length; i$1++) uppercaseIgnoredTags.push(ignoredTags[i$1].toUpperCase()); 15325 this.o = o; 15326 if (defaultRender) this.defaultRender = defaultRender; 15327 this.ignoreTags = uppercaseIgnoredTags; 15328} 15329Options.prototype = { 15330 o: defaults, 15331 ignoreTags: [], 15332 defaultRender(ir) { 15333 return ir; 15334 }, 15335 check(token) { 15336 return this.get("validate", token.toString(), token); 15337 }, 15338 get(key, operator, token) { 15339 const isCallable = operator != null; 15340 let option = this.o[key]; 15341 if (!option) return option; 15342 if (typeof option === "object") { 15343 option = token.t in option ? option[token.t] : defaults[key]; 15344 if (typeof option === "function" && isCallable) option = option(operator, token); 15345 } else if (typeof option === "function" && isCallable) option = option(operator, token.t, token); 15346 return option; 15347 }, 15348 getObj(key, operator, token) { 15349 let obj = this.o[key]; 15350 if (typeof obj === "function" && operator != null) obj = obj(operator, token.t, token); 15351 return obj; 15352 }, 15353 render(token) { 15354 const ir = token.render(this); 15355 return (this.get("render", null, token) || this.defaultRender)(ir, token.t, token); 15356 } 15357}; 15358function noop(val) { 15359 return val; 15360} 15361function MultiToken(value, tokens) { 15362 this.t = "token"; 15363 this.v = value; 15364 this.tk = tokens; 15365} 15366MultiToken.prototype = { 15367 isLink: false, 15368 toString() { 15369 return this.v; 15370 }, 15371 toHref(scheme$1) { 15372 return this.toString(); 15373 }, 15374 toFormattedString(options) { 15375 const val = this.toString(); 15376 const truncate = options.get("truncate", val, this); 15377 const formatted = options.get("format", val, this); 15378 return truncate && formatted.length > truncate ? formatted.substring(0, truncate) + "â¦" : formatted; 15379 }, 15380 toFormattedHref(options) { 15381 return options.get("formatHref", this.toHref(options.get("defaultProtocol")), this); 15382 }, 15383 startIndex() { 15384 return this.tk[0].s; 15385 }, 15386 endIndex() { 15387 return this.tk[this.tk.length - 1].e; 15388 }, 15389 toObject(protocol = defaults.defaultProtocol) { 15390 return { 15391 type: this.t, 15392 value: this.toString(), 15393 isLink: this.isLink, 15394 href: this.toHref(protocol), 15395 start: this.startIndex(), 15396 end: this.endIndex() 15397 }; 15398 }, 15399 toFormattedObject(options) { 15400 return { 15401 type: this.t, 15402 value: this.toFormattedString(options), 15403 isLink: this.isLink, 15404 href: this.toFormattedHref(options), 15405 start: this.startIndex(), 15406 end: this.endIndex() 15407 }; 15408 }, 15409 validate(options) { 15410 return options.get("validate", this.toString(), this); 15411 }, 15412 render(options) { 15413 const token = this; 15414 const href = this.toHref(options.get("defaultProtocol")); 15415 const formattedHref = options.get("formatHref", href, this); 15416 const tagName = options.get("tagName", href, token); 15417 const content = this.toFormattedString(options); 15418 const attributes = {}; 15419 const className = options.get("className", href, token); 15420 const target = options.get("target", href, token); 15421 const rel = options.get("rel", href, token); 15422 const attrs = options.getObj("attributes", href, token); 15423 const eventListeners = options.getObj("events", href, token); 15424 attributes.href = formattedHref; 15425 if (className) attributes.class = className; 15426 if (target) attributes.target = target; 15427 if (rel) attributes.rel = rel; 15428 if (attrs) Object.assign(attributes, attrs); 15429 return { 15430 tagName, 15431 attributes, 15432 content, 15433 eventListeners 15434 }; 15435 } 15436}; 15437function createTokenClass(type, props) { 15438 class Token extends MultiToken { 15439 constructor(value, tokens) { 15440 super(value, tokens); 15441 this.t = type; 15442 } 15443 } 15444 for (const p in props) Token.prototype[p] = props[p]; 15445 Token.t = type; 15446 return Token; 15447} 15448var Email = createTokenClass("email", { 15449 isLink: true, 15450 toHref() { 15451 return "mailto:" + this.toString(); 15452 } 15453}); 15454var Text$1 = createTokenClass("text"); 15455var Nl = createTokenClass("nl"); 15456var Url = createTokenClass("url", { 15457 isLink: true, 15458 toHref(scheme$1 = defaults.defaultProtocol) { 15459 return this.hasProtocol() ? this.v : `${scheme$1}://${this.v}`; 15460 }, 15461 hasProtocol() { 15462 const tokens = this.tk; 15463 return tokens.length >= 2 && tokens[0].t !== LOCALHOST && tokens[1].t === COLON; 15464 } 15465}); 15466var makeState = (arg) => new State(arg); 15467function init$1({ groups }) { 15468 const qsAccepting = groups.domain.concat([ 15469 AMPERSAND, 15470 ASTERISK, 15471 AT, 15472 BACKSLASH, 15473 BACKTICK, 15474 CARET, 15475 DOLLAR, 15476 EQUALS, 15477 HYPHEN, 15478 NUM, 15479 PERCENT, 15480 PIPE, 15481 PLUS, 15482 POUND, 15483 SLASH, 15484 SYM, 15485 TILDE, 15486 UNDERSCORE 15487 ]); 15488 const qsNonAccepting = [ 15489 APOSTROPHE, 15490 COLON, 15491 COMMA, 15492 DOT, 15493 EXCLAMATION, 15494 PERCENT, 15495 QUERY, 15496 QUOTE, 15497 SEMI, 15498 OPENANGLEBRACKET, 15499 CLOSEANGLEBRACKET, 15500 OPENBRACE, 15501 CLOSEBRACE, 15502 CLOSEBRACKET, 15503 OPENBRACKET, 15504 OPENPAREN, 15505 CLOSEPAREN, 15506 FULLWIDTHLEFTPAREN, 15507 FULLWIDTHRIGHTPAREN, 15508 LEFTCORNERBRACKET, 15509 RIGHTCORNERBRACKET, 15510 LEFTWHITECORNERBRACKET, 15511 RIGHTWHITECORNERBRACKET, 15512 FULLWIDTHLESSTHAN, 15513 FULLWIDTHGREATERTHAN 15514 ]; 15515 const localpartAccepting = [ 15516 AMPERSAND, 15517 APOSTROPHE, 15518 ASTERISK, 15519 BACKSLASH, 15520 BACKTICK, 15521 CARET, 15522 DOLLAR, 15523 EQUALS, 15524 HYPHEN, 15525 OPENBRACE, 15526 CLOSEBRACE, 15527 PERCENT, 15528 PIPE, 15529 PLUS, 15530 POUND, 15531 QUERY, 15532 SLASH, 15533 SYM, 15534 TILDE, 15535 UNDERSCORE 15536 ]; 15537 const Start = makeState(); 15538 const Localpart = tt(Start, TILDE); 15539 ta(Localpart, localpartAccepting, Localpart); 15540 ta(Localpart, groups.domain, Localpart); 15541 const Domain = makeState(), Scheme = makeState(), SlashScheme = makeState(); 15542 ta(Start, groups.domain, Domain); 15543 ta(Start, groups.scheme, Scheme); 15544 ta(Start, groups.slashscheme, SlashScheme); 15545 ta(Domain, localpartAccepting, Localpart); 15546 ta(Domain, groups.domain, Domain); 15547 const LocalpartAt = tt(Domain, AT); 15548 tt(Localpart, AT, LocalpartAt); 15549 tt(Scheme, AT, LocalpartAt); 15550 tt(SlashScheme, AT, LocalpartAt); 15551 const LocalpartDot = tt(Localpart, DOT); 15552 ta(LocalpartDot, localpartAccepting, Localpart); 15553 ta(LocalpartDot, groups.domain, Localpart); 15554 const EmailDomain = makeState(); 15555 ta(LocalpartAt, groups.domain, EmailDomain); 15556 ta(EmailDomain, groups.domain, EmailDomain); 15557 const EmailDomainDot = tt(EmailDomain, DOT); 15558 ta(EmailDomainDot, groups.domain, EmailDomain); 15559 const Email$1 = makeState(Email); 15560 ta(EmailDomainDot, groups.tld, Email$1); 15561 ta(EmailDomainDot, groups.utld, Email$1); 15562 tt(LocalpartAt, LOCALHOST, Email$1); 15563 const EmailDomainHyphen = tt(EmailDomain, HYPHEN); 15564 tt(EmailDomainHyphen, HYPHEN, EmailDomainHyphen); 15565 ta(EmailDomainHyphen, groups.domain, EmailDomain); 15566 ta(Email$1, groups.domain, EmailDomain); 15567 tt(Email$1, DOT, EmailDomainDot); 15568 tt(Email$1, HYPHEN, EmailDomainHyphen); 15569 const DomainHyphen = tt(Domain, HYPHEN); 15570 const DomainDot = tt(Domain, DOT); 15571 tt(DomainHyphen, HYPHEN, DomainHyphen); 15572 ta(DomainHyphen, groups.domain, Domain); 15573 ta(DomainDot, localpartAccepting, Localpart); 15574 ta(DomainDot, groups.domain, Domain); 15575 const DomainDotTld = makeState(Url); 15576 ta(DomainDot, groups.tld, DomainDotTld); 15577 ta(DomainDot, groups.utld, DomainDotTld); 15578 ta(DomainDotTld, groups.domain, Domain); 15579 ta(DomainDotTld, localpartAccepting, Localpart); 15580 tt(DomainDotTld, DOT, DomainDot); 15581 tt(DomainDotTld, HYPHEN, DomainHyphen); 15582 tt(DomainDotTld, AT, LocalpartAt); 15583 const DomainDotTldColon = tt(DomainDotTld, COLON); 15584 const DomainDotTldColonPort = makeState(Url); 15585 ta(DomainDotTldColon, groups.numeric, DomainDotTldColonPort); 15586 const Url$1 = makeState(Url); 15587 const UrlNonaccept = makeState(); 15588 ta(Url$1, qsAccepting, Url$1); 15589 ta(Url$1, qsNonAccepting, UrlNonaccept); 15590 ta(UrlNonaccept, qsAccepting, Url$1); 15591 ta(UrlNonaccept, qsNonAccepting, UrlNonaccept); 15592 tt(DomainDotTld, SLASH, Url$1); 15593 tt(DomainDotTldColonPort, SLASH, Url$1); 15594 const SchemeColon = tt(Scheme, COLON); 15595 const UriPrefix = tt(tt(tt(SlashScheme, COLON), SLASH), SLASH); 15596 ta(Scheme, groups.domain, Domain); 15597 tt(Scheme, DOT, DomainDot); 15598 tt(Scheme, HYPHEN, DomainHyphen);
15599 ta(SlashScheme, groups.domain, Domain); 15600 tt(SlashScheme, DOT, DomainDot); 15601 tt(SlashScheme, HYPHEN, DomainHyphen); 15602 ta(SchemeColon, groups.domain, Url$1); 15603 tt(SchemeColon, SLASH, Url$1); 15604 tt(SchemeColon, QUERY, Url$1); 15605 ta(UriPrefix, groups.domain, Url$1); 15606 ta(UriPrefix, qsAccepting, Url$1); 15607 tt(UriPrefix, SLASH, Url$1); 15608 const bracketPairs = [ 15609 [OPENBRACE, CLOSEBRACE], 15610 [OPENBRACKET, CLOSEBRACKET], 15611 [OPENPAREN, CLOSEPAREN], 15612 [OPENANGLEBRACKET, CLOSEANGLEBRACKET], 15613 [FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN], 15614 [LEFTCORNERBRACKET, RIGHTCORNERBRACKET], 15615 [LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET], 15616 [FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN] 15617 ]; 15618 for (let i$1 = 0; i$1 < bracketPairs.length; i$1++) { 15619 const [OPEN, CLOSE] = bracketPairs[i$1]; 15620 const UrlOpen = tt(Url$1, OPEN); 15621 tt(UrlNonaccept, OPEN, UrlOpen); 15622 const UrlOpenQ = makeState(Url); 15623 ta(UrlOpen, qsAccepting, UrlOpenQ); 15624 const UrlOpenSyms = makeState(); 15625 ta(UrlOpen, qsNonAccepting, UrlOpenSyms); 15626 tt(UrlOpen, CLOSE, Url$1); 15627 ta(UrlOpenQ, qsAccepting, UrlOpenQ); 15628 ta(UrlOpenQ, qsNonAccepting, UrlOpenSyms); 15629 ta(UrlOpenSyms, qsAccepting, UrlOpenQ); 15630 ta(UrlOpenSyms, qsNonAccepting, UrlOpenSyms); 15631 tt(UrlOpenQ, CLOSE, Url$1); 15632 tt(UrlOpenSyms, CLOSE, Url$1); 15633 } 15634 tt(Start, LOCALHOST, DomainDotTld); 15635 tt(Start, NL, Nl); 15636 return { 15637 start: Start, 15638 tokens: tk 15639 }; 15640} 15641function run(start, input, tokens) { 15642 let len = tokens.length; 15643 let cursor = 0; 15644 let multis = []; 15645 let textTokens = []; 15646 while (cursor < len) { 15647 let state = start; 15648 let secondState = null; 15649 let nextState = null; 15650 let multiLength = 0; 15651 let latestAccepting = null; 15652 let sinceAccepts = -1; 15653 while (cursor < len && !(secondState = state.go(tokens[cursor].t))) textTokens.push(tokens[cursor++]); 15654 while (cursor < len && (nextState = secondState || state.go(tokens[cursor].t))) { 15655 secondState = null; 15656 state = nextState; 15657 if (state.accepts()) { 15658 sinceAccepts = 0; 15659 latestAccepting = state; 15660 } else if (sinceAccepts >= 0) sinceAccepts++; 15661 cursor++; 15662 multiLength++; 15663 } 15664 if (sinceAccepts < 0) { 15665 cursor -= multiLength; 15666 if (cursor < len) { 15667 textTokens.push(tokens[cursor]); 15668 cursor++; 15669 } 15670 } else { 15671 if (textTokens.length > 0) { 15672 multis.push(initMultiToken(Text$1, input, textTokens)); 15673 textTokens = []; 15674 } 15675 cursor -= sinceAccepts; 15676 multiLength -= sinceAccepts; 15677 const Multi = latestAccepting.t; 15678 const subtokens = tokens.slice(cursor - multiLength, cursor); 15679 multis.push(initMultiToken(Multi, input, subtokens)); 15680 } 15681 } 15682 if (textTokens.length > 0) multis.push(initMultiToken(Text$1, input, textTokens)); 15683 return multis; 15684} 15685function initMultiToken(Multi, input, tokens) { 15686 const startIdx = tokens[0].s; 15687 const endIdx = tokens[tokens.length - 1].e; 15688 return new Multi(input.slice(startIdx, endIdx), tokens); 15689} 15690var warn = typeof console !== "undefined" && console && console.warn || (() => {}); 15691var warnAdvice = "until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time."; 15692var INIT = { 15693 scanner: null, 15694 parser: null, 15695 tokenQueue: [], 15696 pluginQueue: [], 15697 customSchemes: [], 15698 initialized: false 15699}; 15700function reset() { 15701 State.groups = {}; 15702 INIT.scanner = null; 15703 INIT.parser = null; 15704 INIT.tokenQueue = []; 15705 INIT.pluginQueue = []; 15706 INIT.customSchemes = []; 15707 INIT.initialized = false; 15708 return INIT; 15709} 15710function registerCustomProtocol(scheme$1, optionalSlashSlash = false) { 15711 if (INIT.initialized) warn(`linkifyjs: already initialized - will not register custom scheme "${scheme$1}" ${warnAdvice}`); 15712 if (!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(scheme$1)) throw new Error(`linkifyjs: incorrect scheme format. 157131. Must only contain digits, lowercase ASCII letters or "-" 157142. Cannot start or end with "-" 157153. "-" cannot repeat`); 15716 INIT.customSchemes.push([scheme$1, optionalSlashSlash]); 15717} 15718function init() { 15719 INIT.scanner = init$2(INIT.customSchemes); 15720 for (let i$1 = 0; i$1 < INIT.tokenQueue.length; i$1++) INIT.tokenQueue[i$1][1]({ scanner: INIT.scanner }); 15721 INIT.parser = init$1(INIT.scanner.tokens); 15722 for (let i$1 = 0; i$1 < INIT.pluginQueue.length; i$1++) INIT.pluginQueue[i$1][1]({ 15723 scanner: INIT.scanner, 15724 parser: INIT.parser 15725 }); 15726 INIT.initialized = true; 15727 return INIT; 15728} 15729function tokenize(str) { 15730 if (!INIT.initialized) init(); 15731 return run(INIT.parser.start, str, run$1(INIT.scanner.start, str)); 15732} 15733tokenize.scan = run$1; 15734function find(str, type = null, opts = null) { 15735 if (type && typeof type === "object") { 15736 if (opts) throw Error(`linkifyjs: Invalid link type ${type}; must be a string`); 15737 opts = type; 15738 type = null; 15739 } 15740 const options = new Options(opts); 15741 const tokens = tokenize(str); 15742 const filtered = []; 15743 for (let i$1 = 0; i$1 < tokens.length; i$1++) { 15744 const token = tokens[i$1]; 15745 if (token.isLink && (!type || token.t === type) && options.check(token)) filtered.push(token.toFormattedObject(options)); 15746 } 15747 return filtered; 15748} 15749var UNICODE_WHITESPACE_PATTERN = "[\0- \xA0áá â-\u2029âã]"; 15750var UNICODE_WHITESPACE_REGEX = new RegExp(UNICODE_WHITESPACE_PATTERN); 15751var UNICODE_WHITESPACE_REGEX_END = /* @__PURE__ */ new RegExp(`${UNICODE_WHITESPACE_PATTERN}$`); 15752var UNICODE_WHITESPACE_REGEX_GLOBAL = new RegExp(UNICODE_WHITESPACE_PATTERN, "g"); 15753function isValidLinkStructure(tokens) { 15754 if (tokens.length === 1) return tokens[0].isLink; 15755 if (tokens.length === 3 && tokens[1].isLink) return ["()", "[]"].includes(tokens[0].value + tokens[2].value); 15756 return false;
vendor: 14,219 bytes, lines 15757-16107
15757} 15758function autolink(options) { 15759 return new Plugin({ 15760 key: new PluginKey("autolink"), 15761 appendTransaction: (transactions, oldState, newState) => { 15762 const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc); 15763 const preventAutolink = transactions.some((transaction) => transaction.getMeta("preventAutolink")); 15764 if (!docChanges || preventAutolink) return; 15765 const { tr: tr$1 } = newState; 15766 getChangedRanges(combineTransactionSteps(oldState.doc, [...transactions])).forEach(({ newRange }) => { 15767 const nodesInChangedRanges = findChildrenInRange(newState.doc, newRange, (node) => node.isTextblock); 15768 let textBlock; 15769 let textBeforeWhitespace; 15770 if (nodesInChangedRanges.length > 1) { 15771 textBlock = nodesInChangedRanges[0]; 15772 textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, textBlock.pos + textBlock.node.nodeSize, void 0, " "); 15773 } else if (nodesInChangedRanges.length) { 15774 const endText = newState.doc.textBetween(newRange.from, newRange.to, " ", " "); 15775 if (!UNICODE_WHITESPACE_REGEX_END.test(endText)) return; 15776 textBlock = nodesInChangedRanges[0]; 15777 textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, newRange.to, void 0, " "); 15778 } 15779 if (textBlock && textBeforeWhitespace) { 15780 const wordsBeforeWhitespace = textBeforeWhitespace.split(UNICODE_WHITESPACE_REGEX).filter(Boolean); 15781 if (wordsBeforeWhitespace.length <= 0) return false; 15782 const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1]; 15783 const lastWordAndBlockOffset = textBlock.pos + textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace); 15784 if (!lastWordBeforeSpace) return false; 15785 const linksBeforeSpace = tokenize(lastWordBeforeSpace).map((t) => t.toObject(options.defaultProtocol)); 15786 if (!isValidLinkStructure(linksBeforeSpace)) return false; 15787 linksBeforeSpace.filter((link) => link.isLink).map((link) => ({ 15788 ...link, 15789 from: lastWordAndBlockOffset + link.start + 1, 15790 to: lastWordAndBlockOffset + link.end + 1 15791 })).filter((link) => { 15792 if (!newState.schema.marks.code) return true; 15793 return !newState.doc.rangeHasMark(link.from, link.to, newState.schema.marks.code); 15794 }).filter((link) => options.validate(link.value)).filter((link) => options.shouldAutoLink(link.value)).forEach((link) => { 15795 if (getMarksBetween(link.from, link.to, newState.doc).some((item) => item.mark.type === options.type)) return; 15796 tr$1.addMark(link.from, link.to, options.type.create({ href: link.href })); 15797 }); 15798 } 15799 }); 15800 if (!tr$1.steps.length) return; 15801 return tr$1; 15802 } 15803 }); 15804} 15805function clickHandler(options) { 15806 return new Plugin({ 15807 key: new PluginKey("handleClickLink"), 15808 props: { handleClick: (view, pos, event) => { 15809 if (event.button !== 0) return false; 15810 if (!view.editable) return false; 15811 let link = null; 15812 if (event.target instanceof HTMLAnchorElement) link = event.target; 15813 else { 15814 const target = event.target; 15815 if (!target) return false; 15816 const root = options.editor.view.dom; 15817 link = target.closest("a"); 15818 if (link && !root.contains(link)) link = null; 15819 } 15820 if (!link) return false; 15821 let handled = false; 15822 if (options.enableClickSelection) handled = options.editor.commands.extendMarkRange(options.type.name); 15823 if (options.openOnClick) { 15824 var _link$href, _link$target; 15825 const attrs = getAttributes(view.state, options.type.name); 15826 const href = (_link$href = link.href) !== null && _link$href !== void 0 ? _link$href : attrs.href; 15827 const target = (_link$target = link.target) !== null && _link$target !== void 0 ? _link$target : attrs.target; 15828 if (href) { 15829 window.open(href, target); 15830 handled = true; 15831 } 15832 } 15833 return handled; 15834 } } 15835 }); 15836} 15837var MARKDOWN_LINK_INPUT_REGEX = /\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|â(.*?)â|â(.*?)â))?\)$/; 15838var MARKDOWN_LINK_PASTE_REGEX = /\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|â(.*?)â|â(.*?)â))?\)/g; 15839function isEscaped(text$1, index) { 15840 let backslashes = 0; 15841 for (let position = index - 1; position >= 0 && text$1[position] === "\\"; position -= 1) backslashes += 1; 15842 return backslashes % 2 === 1; 15843} 15844function isInsideCodeSpan(text$1, matchIndex) { 15845 let openRunLength = 0; 15846 let index = 0; 15847 while (index < matchIndex) { 15848 if (text$1[index] !== "`") { 15849 index += 1; 15850 continue; 15851 } 15852 if (openRunLength === 0 && isEscaped(text$1, index)) { 15853 index += 1; 15854 continue; 15855 } 15856 let runLength = 0; 15857 while (index < matchIndex && text$1[index] === "`") { 15858 runLength += 1; 15859 index += 1; 15860 } 15861 if (openRunLength === 0) openRunLength = runLength; 15862 else if (runLength === openRunLength) openRunLength = 0; 15863 } 15864 return openRunLength > 0; 15865} 15866function isConvertibleLink(text$1, match, isAllowedHref) { 15867 var _match$index, _match$index2; 15868 const [, linkText, href] = match; 15869 if ((match.index ? text$1[match.index - 1] : void 0) === "!" || isEscaped(text$1, (_match$index = match.index) !== null && _match$index !== void 0 ? _match$index : 0)) return false; 15870 if (isInsideCodeSpan(text$1, (_match$index2 = match.index) !== null && _match$index2 !== void 0 ? _match$index2 : 0)) return false; 15871 return !!linkText.trim() && isAllowedHref(href); 15872} 15873function toRuleMatch(match) { 15874 var _ref$1, _match$index3; 15875 const [linkSyntax, linkText, href, , straightQuotedTitle, curlyDoubleTitle, curlySingleTitle] = match; 15876 const title = (_ref$1 = straightQuotedTitle !== null && straightQuotedTitle !== void 0 ? straightQuotedTitle : curlyDoubleTitle) !== null && _ref$1 !== void 0 ? _ref$1 : curlySingleTitle; 15877 return { 15878 index: (_match$index3 = match.index) !== null && _match$index3 !== void 0 ? _match$index3 : 0, 15879 text: linkSyntax, 15880 replaceWith: linkText, 15881 data: { 15882 href, 15883 title: title || null, 15884 markdown: true 15885 } 15886 }; 15887} 15888function matchesOverlap(a, b) { 15889 return a.index < b.index + b.text.length && b.index < a.index + a.text.length; 15890} 15891function getMarkdownLinkAttributes(match) { 15892 var _match$data, _match$data$title, _match$data2; 15893 return { 15894 href: (_match$data = match.data) === null || _match$data === void 0 ? void 0 : _match$data.href, 15895 title: (_match$data$title = (_match$data2 = match.data) === null || _match$data2 === void 0 ? void 0 : _match$data2.title) !== null && _match$data$title !== void 0 ? _match$data$title : null 15896 }; 15897} 15898function markdownLinkInputRule(config) { 15899 const rule = markInputRule({ 15900 find: (text$1) => { 15901 const match = MARKDOWN_LINK_INPUT_REGEX.exec(text$1); 15902 if (!match || !isConvertibleLink(text$1, match, config.isAllowedHref)) return null; 15903 return toRuleMatch(match); 15904 }, 15905 type: config.type, 15906 getAttributes: getMarkdownLinkAttributes 15907 }); 15908 return new InputRule({ 15909 find: rule.find, 15910 handler: (props) => { 15911 const result = rule.handler(props); 15912 if (result !== null && props.state.tr.steps.length) props.state.tr.setMeta("preventAutolink", true); 15913 return result; 15914 } 15915 }); 15916} 15917function markdownLinkPasteRule(config) { 15918 const rule = markPasteRule({ 15919 find: (text$1) => { 15920 var _config$findPlainUrls, _config$findPlainUrls2; 15921 const markdownMatches = []; 15922 for (const match of text$1.matchAll(MARKDOWN_LINK_PASTE_REGEX)) if (isConvertibleLink(text$1, match, config.isAllowedHref)) markdownMatches.push(toRuleMatch(match)); 15923 const plainUrlMatches = ((_config$findPlainUrls = (_config$findPlainUrls2 = config.findPlainUrls) === null || _config$findPlainUrls2 === void 0 ? void 0 : _config$findPlainUrls2.call(config, text$1)) !== null && _config$findPlainUrls !== void 0 ? _config$findPlainUrls : []).filter((urlMatch) => !markdownMatches.some((markdownMatch) => matchesOverlap(markdownMatch, urlMatch))); 15924 return [...markdownMatches, ...plainUrlMatches]; 15925 }, 15926 type: config.type, 15927 getAttributes: getMarkdownLinkAttributes 15928 }); 15929 return new PasteRule({ 15930 find: rule.find, 15931 handler: (props) => { 15932 var _props$match$data; 15933 const result = rule.handler(props); 15934 if (result !== null && props.state.tr.steps.length && ((_props$match$data = props.match.data) === null || _props$match$data === void 0 ? void 0 : _props$match$data.markdown)) props.state.tr.setMeta("preventAutolink", true); 15935 return result; 15936 } 15937 }); 15938} 15939function pasteHandler(options) { 15940 return new Plugin({ 15941 key: new PluginKey("handlePasteLink"), 15942 props: { handlePaste: (view, _event, slice) => { 15943 const { shouldAutoLink } = options; 15944 const { state } = view; 15945 const { selection } = state; 15946 const { empty: empty$1 } = selection; 15947 if (empty$1) return false; 15948 let textContent = ""; 15949 slice.content.forEach((node) => { 15950 textContent += node.textContent; 15951 }); 15952 const link = find(textContent, { defaultProtocol: options.defaultProtocol }).find((item) => item.isLink && item.value === textContent); 15953 if (!textContent || !link || shouldAutoLink !== void 0 && !shouldAutoLink(link.value)) return false; 15954 return options.editor.commands.setMark(options.type, { href: link.href }); 15955 } } 15956 }); 15957} 15958function isAllowedUri(uri, protocols) { 15959 const allowedProtocols = [ 15960 "http", 15961 "https", 15962 "ftp", 15963 "ftps", 15964 "mailto", 15965 "tel", 15966 "callto", 15967 "sms", 15968 "cid", 15969 "xmpp" 15970 ]; 15971 if (protocols) protocols.forEach((protocol) => { 15972 const nextProtocol = typeof protocol === "string" ? protocol : protocol.scheme; 15973 if (nextProtocol) allowedProtocols.push(nextProtocol); 15974 }); 15975 return !uri || uri.replace(UNICODE_WHITESPACE_REGEX_GLOBAL, "").match(new RegExp(`^(?:(?:${allowedProtocols.map((protocol) => protocol.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&")).join("|")}):|[^a-z]|[a-z0-9+.\\-]+(?:[^a-z+.\\-:]|$))`, "i")); 15976} 15977var Link$2 = Mark.create({ 15978 name: "link", 15979 priority: 1e3, 15980 keepOnSplit: false, 15981 exitable: true, 15982 onCreate() { 15983 if (this.options.validate && !this.options.shouldAutoLink) { 15984 this.options.shouldAutoLink = this.options.validate; 15985 console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead."); 15986 } 15987 this.options.protocols.forEach((protocol) => { 15988 if (typeof protocol === "string") { 15989 registerCustomProtocol(protocol); 15990 return; 15991 } 15992 registerCustomProtocol(protocol.scheme, protocol.optionalSlashes); 15993 }); 15994 }, 15995 onDestroy() { 15996 reset(); 15997 }, 15998 inclusive() { 15999 return this.options.autolink; 16000 }, 16001 addOptions() { 16002 return { 16003 openOnClick: true, 16004 enableClickSelection: false, 16005 linkOnPaste: true, 16006 markdownLinks: false, 16007 autolink: true, 16008 protocols: [], 16009 defaultProtocol: "http", 16010 HTMLAttributes: { 16011 target: "_blank", 16012 rel: "noopener noreferrer nofollow", 16013 class: null 16014 }, 16015 isAllowedUri: (url, ctx) => !!isAllowedUri(url, ctx.protocols), 16016 validate: (url) => !!url, 16017 shouldAutoLink: (url) => { 16018 const hasProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(url); 16019 const hasMaybeProtocol = /^[a-z][a-z0-9+.-]*:/i.test(url); 16020 if (hasProtocol || hasMaybeProtocol && !url.includes("@")) return true; 16021 const hostname = (url.includes("@") ? url.split("@").pop() : url).split(/[/?#:]/)[0]; 16022 if (/^\d{1,3}(\.\d{1,3}){3}$/.test(hostname)) return false; 16023 if (!/\./.test(hostname)) return false; 16024 return true; 16025 } 16026 }; 16027 }, 16028 addAttributes() { 16029 var _this$options$HTMLAtt, _this$options$HTMLAtt2, _this$options$HTMLAtt3; 16030 return { 16031 href: { 16032 default: null, 16033 parseHTML(element) { 16034 return element.getAttribute("href"); 16035 } 16036 }, 16037 target: { default: (_this$options$HTMLAtt = this.options.HTMLAttributes.target) !== null && _this$options$HTMLAtt !== void 0 ? _this$options$HTMLAtt : null }, 16038 rel: { default: (_this$options$HTMLAtt2 = this.options.HTMLAttributes.rel) !== null && _this$options$HTMLAtt2 !== void 0 ? _this$options$HTMLAtt2 : null }, 16039 class: { default: (_this$options$HTMLAtt3 = this.options.HTMLAttributes.class) !== null && _this$options$HTMLAtt3 !== void 0 ? _this$options$HTMLAtt3 : null }, 16040 title: { default: null } 16041 }; 16042 }, 16043 parseHTML() { 16044 return [{ 16045 tag: "a[href]", 16046 getAttrs: (dom) => { 16047 const href = dom.getAttribute("href"); 16048 if (!href || !this.options.isAllowedUri(href, { 16049 defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols), 16050 protocols: this.options.protocols, 16051 defaultProtocol: this.options.defaultProtocol 16052 })) return false; 16053 return null; 16054 } 16055 }]; 16056 }, 16057 renderHTML({ HTMLAttributes }) { 16058 if (!this.options.isAllowedUri(HTMLAttributes.href, { 16059 defaultValidate: (href) => !!isAllowedUri(href, this.options.protocols), 16060 protocols: this.options.protocols, 16061 defaultProtocol: this.options.defaultProtocol 16062 })) return [ 16063 "a", 16064 mergeAttributes(this.options.HTMLAttributes, { 16065 ...HTMLAttributes, 16066 href: "" 16067 }), 16068 0 16069 ]; 16070 return [ 16071 "a", 16072 mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 16073 0 16074 ]; 16075 }, 16076 markdownTokenName: "link", 16077 parseMarkdown: (token, helpers) => { 16078 return helpers.applyMark("link", helpers.parseInline(token.tokens || []), { 16079 href: token.href, 16080 title: token.title || null 16081 }); 16082 }, 16083 renderMarkdown: (node, h$1) => { 16084 var _node$attrs$href, _node$attrs, _node$attrs$title, _node$attrs2; 16085 const href = (_node$attrs$href = (_node$attrs = node.attrs) === null || _node$attrs === void 0 ? void 0 : _node$attrs.href) !== null && _node$attrs$href !== void 0 ? _node$attrs$href : ""; 16086 const title = (_node$attrs$title = (_node$attrs2 = node.attrs) === null || _node$attrs2 === void 0 ? void 0 : _node$attrs2.title) !== null && _node$attrs$title !== void 0 ? _node$attrs$title : ""; 16087 const text$1 = h$1.renderChildren(node); 16088 return title ? `[${text$1}](${href} "${title}")` : `[${text$1}](${href})`; 16089 }, 16090 addCommands() { 16091 return { 16092 setLink: (attributes) => ({ chain }) => { 16093 const { href } = attributes; 16094 if (!this.options.isAllowedUri(href, { 16095 defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols), 16096 protocols: this.options.protocols, 16097 defaultProtocol: this.options.defaultProtocol 16098 })) return false; 16099 return chain().setMark(this.name, attributes).setMeta("preventAutolink", true).run(); 16100 }, 16101 toggleLink: (attributes) => ({ chain }) => { 16102 const { href } = attributes || {}; 16103 if (href && !this.options.isAllowedUri(href, { 16104 defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols), 16105 protocols: this.options.protocols, 16106 defaultProtocol: this.options.defaultProtocol 16107 })) return false;
16108 return chain().toggleMark(this.name, attributes, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run(); 16109 }, 16110 unsetLink: () => ({ chain }) => { 16111 return chain().unsetMark(this.name, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run(); 16112 } 16113 }; 16114 }, 16115 addInputRules() { 16116 if (!this.options.markdownLinks) return []; 16117 return [markdownLinkInputRule({ 16118 type: this.type, 16119 isAllowedHref: (href) => this.options.isAllowedUri(href, { 16120 defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols), 16121 protocols: this.options.protocols, 16122 defaultProtocol: this.options.defaultProtocol 16123 }) 16124 })]; 16125 }, 16126 addPasteRules() { 16127 const findPlainUrls = (text$1) => { 16128 const foundLinks = []; 16129 if (text$1) { 16130 const { protocols, defaultProtocol } = this.options; 16131 find(text$1).filter((item) => item.isLink && this.options.isAllowedUri(item.value, { 16132 defaultValidate: (href) => !!isAllowedUri(href, protocols), 16133 protocols, 16134 defaultProtocol 16135 })).forEach((link) => { 16136 if (!this.options.shouldAutoLink(link.value)) return; 16137 foundLinks.push({ 16138 text: link.value, 16139 data: { href: link.href }, 16140 index: link.start 16141 }); 16142 }); 16143 } 16144 return foundLinks; 16145 }; 16146 if (this.options.markdownLinks) return [markdownLinkPasteRule({ 16147 type: this.type, 16148 isAllowedHref: (href) => this.options.isAllowedUri(href, { 16149 defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols), 16150 protocols: this.options.protocols, 16151 defaultProtocol: this.options.defaultProtocol 16152 }), 16153 findPlainUrls 16154 })]; 16155 return [markPasteRule({ 16156 find: findPlainUrls, 16157 type: this.type, 16158 getAttributes: (match) => { 16159 var _match$data; 16160 return { href: (_match$data = match.data) === null || _match$data === void 0 ? void 0 : _match$data.href }; 16161 } 16162 })]; 16163 }, 16164 addProseMirrorPlugins() { 16165 const plugins = []; 16166 const { protocols, defaultProtocol } = this.options; 16167 if (this.options.autolink) plugins.push(autolink({ 16168 type: this.type, 16169 defaultProtocol: this.options.defaultProtocol, 16170 validate: (url) => this.options.isAllowedUri(url, { 16171 defaultValidate: (href) => !!isAllowedUri(href, protocols), 16172 protocols, 16173 defaultProtocol 16174 }), 16175 shouldAutoLink: this.options.shouldAutoLink 16176 })); 16177 plugins.push(clickHandler({ 16178 type: this.type, 16179 editor: this.editor, 16180 openOnClick: this.options.openOnClick === "whenNotEditable" ? true : this.options.openOnClick, 16181 enableClickSelection: this.options.enableClickSelection 16182 })); 16183 if (this.options.linkOnPaste) plugins.push(pasteHandler({ 16184 editor: this.editor, 16185 defaultProtocol: this.options.defaultProtocol, 16186 type: this.type, 16187 shouldAutoLink: this.options.shouldAutoLink 16188 })); 16189 return plugins; 16190 } 16191}); 16192var src_default = Link$2; 16193var import_react_dom = /* @__PURE__ */ __toESM(require_react_dom(), 1); 16194var import_shim = /* @__PURE__ */ __toESM(require_shim(), 1); 16195var import_with_selector = /* @__PURE__ */ __toESM(require_with_selector(), 1); 16196var mergeRefs = (...refs) => { 16197 return (node) => { 16198 refs.forEach((ref) => { 16199 if (typeof ref === "function") ref(node); 16200 else if (ref) ref.current = node; 16201 }); 16202 }; 16203}; 16204var Portals = ({ contentComponent }) => { 16205 const renderers = (0, import_shim.useSyncExternalStore)(contentComponent.subscribe, contentComponent.getSnapshot, contentComponent.getServerSnapshot); 16206 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: Object.values(renderers) }); 16207}; 16208function createContentComponent() { 16209 const subscribers = /* @__PURE__ */ new Set(); 16210 let renderers = {}; 16211 let isNotificationQueued = false; 16212 const notifySubscribers = () => { 16213 if (isNotificationQueued || !subscribers.size) return; 16214 isNotificationQueued = true; 16215 queueMicrotask(() => { 16216 isNotificationQueued = false; 16217 subscribers.forEach((subscriber) => subscriber()); 16218 }); 16219 }; 16220 return { 16221 subscribe(callback) { 16222 subscribers.add(callback); 16223 return () => { 16224 subscribers.delete(callback); 16225 }; 16226 }, 16227 getSnapshot() { 16228 return renderers; 16229 }, 16230 getServerSnapshot() { 16231 return renderers; 16232 }, 16233 setRenderer(id, renderer) { 16234 renderers = { 16235 ...renderers, 16236 [id]: import_react_dom.createPortal(renderer.reactElement, renderer.element, id) 16237 }; 16238 notifySubscribers(); 16239 }, 16240 removeRenderer(id) { 16241 const nextRenderers = { ...renderers }; 16242 delete nextRenderers[id]; 16243 renderers = nextRenderers; 16244 notifySubscribers(); 16245 } 16246 }; 16247} 16248var PureEditorContent = class extends import_react.Component { 16249 constructor(props) { 16250 super(props); 16251 this.editorContentRef = import_react.createRef(); 16252 } 16253 componentDidMount() { 16254 this.init(); 16255 } 16256 componentDidUpdate() { 16257 this.init(); 16258 }
16259 init() { 16260 var _editor$view$dom; 16261 const editor = this.props.editor; 16262 if (editor && !editor.isDestroyed && ((_editor$view$dom = editor.view.dom) === null || _editor$view$dom === void 0 ? void 0 : _editor$view$dom.parentNode)) { 16263 if (editor.contentComponent) return; 16264 const element = this.editorContentRef.current; 16265 element.append(...editor.view.dom.parentNode.childNodes); 16266 editor.setOptions({ element }); 16267 editor.contentComponent = createContentComponent(); 16268 editor.createNodeViews(); 16269 editor.isEditorContentInitialized = true; 16270 this.forceUpdate(); 16271 } 16272 } 16273 componentWillUnmount() { 16274 const editor = this.props.editor; 16275 if (!editor) return; 16276 editor.isEditorContentInitialized = false; 16277 if (!editor.isDestroyed) editor.view.setProps({ nodeViews: {} }); 16278 editor.contentComponent = null; 16279 try { 16280 var _editor$view$dom2; 16281 if (!((_editor$view$dom2 = editor.view.dom) === null || _editor$view$dom2 === void 0 ? void 0 : _editor$view$dom2.parentNode)) return; 16282 const newElement = document.createElement("div"); 16283 newElement.append(...editor.view.dom.parentNode.childNodes); 16284 editor.setOptions({ element: newElement }); 16285 } catch {} 16286 } 16287 render() { 16288 const { editor, innerRef,...rest } = this.props; 16289 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 16290 ref: mergeRefs(innerRef, this.editorContentRef), 16291 ...rest 16292 }), (editor === null || editor === void 0 ? void 0 : editor.contentComponent) && /* @__P
16292URE__ */ (0, import_jsx_runtime.jsx)(Portals, { contentComponent: editor.contentComponent })] }); 16293 } 16294}; 16295var EditorContentWithKey = (0, import_react.forwardRef)((props, ref) => { 16296 const key = import_react.useMemo(() => { 16297 return Math.floor(Math.random() * 4294967295).toString(); 16298 }, [props.editor]); 16299 return import_react.createElement(PureEditorContent, { 16300 key, 16301 innerRef: ref, 16302 ...props 16303 }); 16304}); 16305var EditorContent = import_react.memo(EditorContentWithKey); 16306var useIsomorphicLayoutEffect = typeof window !== "undefined" ? import_react.useLayoutEffect : import_react.useEffect; 16307var EditorStateManager = class { 16308 constructor(initialEditor) { 16309 this.transactionNumber = 0; 16310 this.lastTransactionNumber = 0; 16311 this.subscribers = /* @__PURE__ */ new Set(); 16312 this.editor = initialEditor; 16313 this.lastSnapshot = { 16314 editor: initialEditor, 16315 transactionNumber: 0 16316 }; 16317 this.getSnapshot = this.getSnapshot.bind(this); 16318 this.getServerSnapshot = this.getServerSnapshot.bind(this); 16319 this.watch = this.watch.bind(this); 16320 this.subscribe = this.subscribe.bind(this); 16321 } 16322 getSnapshot() { 16323 if (this.transactionNumber === this.lastTransactionNumber) return this.lastSnapshot; 16324 this.lastTransactionNumber = this.transactionNumber; 16325 this.lastSnapshot = { 16326 editor: this.editor, 16327 transactionNumber: this.transactionNumber 16328 }; 16329 return this.lastSnapshot; 16330 } 16331 getServerSnapshot() { 16332 return { 16333 editor: null, 16334 transactionNumber: 0 16335 }; 16336 } 16337 subscribe(callback) { 16338 this.subscribers.add(callback); 16339 return () => { 16340 this.subscribers.delete(callback); 16341 }; 16342 } 16343 watch(nextEditor) { 16344 this.editor = nextEditor; 16345 if (this.editor) { 16346 let lastTransaction; 16347 const fn = (props) => { 16348 if ((props === null || props === void 0 ? void 0 : props.transaction) !== void 0 && props.transaction === lastTransaction) return; 16349 lastTransaction = props === null || props === void 0 ? void 0 : props.transaction; 16350 this.transactionNumber += 1; 16351 this.subscribers.forEach((callback) => callback()); 16352 }; 16353 const currentEditor = this.editor; 16354 currentEditor.on("transaction", fn); 16355 currentEditor.on("update", fn); 16356 return () => { 16357 currentEditor.off("transaction", fn); 16358 currentEditor.off("update", fn); 16359 }; 16360 } 16361 } 16362}; 16363function useEditorState(options) { 16364 var _options$equalityFn; 16365 const [editorStateManager] = (0, import_react.useState)(() => new EditorStateManager(options.editor)); 16366 const selectedState = (0, import_with_selector.useSyncExternalStoreWithSelector)(editorStateManager.subscribe, editorStateManager.getSnapshot, editorStateManager.getServerSnapshot, options.selector, (_options$equalityFn = options.equalityFn) !== null && _options$equalityFn !== void 0 ? _options$equalityFn : deepEqual); 16367 useIsomorphicLayoutEffect(() => { 16368 return editorStateManager.watch(options.editor); 16369 }, [options.editor, editorStateManager]); 16370 (0, import_react.useDebugValue)(selectedState); 16371 return selectedState; 16372} 16373var isDev = true; 16374var isSSR = typeof window === "undefined"; 16375var isNext = isSSR || Boolean(typeof window !== "undefined" && window.next); 16376var EditorInstanceManager = class EditorInstanceManager$1 { 16377 constructor(options) { 16378 this.editor = null; 16379 this.subscriptions = /* @__PURE__ */ new Set(); 16380 this.isComponentMounted = false; 16381 this.previousDeps = null; 16382 this.instanceId = ""; 16383 this.options = options; 16384 this.subscriptions = /* @__PURE__ */ new Set(); 16385 this.setEditor(this.getInitialEditor()); 16386 this.scheduleDestroy(); 16387 this.getEditor = this.getEditor.bind(this); 16388 this.getServerSnapshot = this.getServerSnapshot.bind(this); 16389 this.subscribe = this.subscribe.bind(this); 16390 this.refreshEditorInstance = this.refreshEditorInstance.bind(this); 16391 this.scheduleDestroy = this.scheduleDestroy.bind(this); 16392 this.onRender = this.onRender.bind(this); 16393 this.createEditor = this.createEditor.bind(this); 16394 } 16395 setEditor(editor) { 16396 this.editor = editor; 16397 this.instanceId = Math.random().toString(36).slice(2, 9); 16398 this.subscriptions.forEach((cb) => cb()); 16399 } 16400 getInitialEditor() { 16401 const explicit = this.options.current.immediatelyRender; 16402 let immediatelyRender = explicit !== null && explicit !== void 0 ? explicit : true; 16403 if (isSSR) { 16404 if (immediatelyRender && isDev) console.warn("SSR detected. `immediatelyRender` has been set to false to avoid hydration mismatches"); 16405 immediatelyRender = false;
16406 } else if (isNext && explicit === void 0) { 16407 immediatelyRender = false; 16408 console.warn("Next.js detected. `immediatelyRender` defaults to false to avoid hydration mismatches. Pass `immediatelyRender: true` explicitly if you are rendering the editor only on the client."); 16409 } 16410 return immediatelyRender ? this.createEditor() : null; 16411 } 16412 createEditor() { 16413 return new Editor({ 16414 ...this.options.current, 16415 onBeforeCreate: (...args) => { 16416 var _this$options$current, _this$options$current2; 16417 return (_this$options$current = (_this$options$current2 = this.options.current).onBeforeCreate) === null || _this$options$current === void 0 ? void 0 : _this$options$current.call(_this$options$current2, ...args); 16418 }, 16419 onBlur: (...args) => { 16420 var _this$options$current3, _this$options$current4; 16421 return (_this$options$current3 = (_this$options$current4 = this.options.current).onBlur) === null || _this$options$current3 === void 0 ? void 0 : _this$options$current3.call(_this$options$current4, ...args); 16422 }, 16423 onCreate: (...args) => { 16424 var _this$options$current5, _this$options$current6; 16425 return (_this$options$current5 = (_this$options$current6 = this.options.current).onCreate) === null || _this$options$current5 === void 0 ? void 0 : _this$options$current5.call(_this$options$current6, ...args); 16426 }, 16427 onDestroy: (...args) => { 16428 var _this$options$current7, _this$options$current8; 16429 return (_this$options$current7 = (_this$options$current8 = this.options.current).onDestroy) === null || _this$options$current7 === void 0 ? void 0 : _this$options$current7.call(_this$options$current8, ...args); 16430 }, 16431 onFocus: (...args) => { 16432 var _this$options$current9, _this$options$current10; 16433 return (_this$options$current9 = (_this$options$current10 = this.options.current).onFocus) === null || _this$options$current9 === void 0 ? void 0 : _this$options$current9.call(_this$options$current10, ...args); 16434 }, 16435 onSelectionUpdate: (...args) => { 16436 var _this$options$current11, _this$options$current12; 16437 return (_this$options$current11 = (_this$options$current12 = this.options.current).onSelectionUpdate) === null || _this$options$current11 === void 0 ? void 0 : _this$options$current11.call(_this$options$current12, ...args); 16438 }, 16439 onTransaction: (...args) => { 16440 var _this$options$current13, _this$options$current14; 16441 return (_this$options$current13 = (_this$options$current14 = this.options.current).onTransaction) === null || _this$options$current13 === void 0 ? void 0 : _this$options$current13.call(_this$options$current14, ...args); 16442 }, 16443 onUpdate: (...args) => { 16444 var _this$options$current15, _this$options$current16; 16445 return (_this$options$current15 = (_this$options$current16 = this.options.current).onUpdate) === null || _this$options$current15 === void 0 ? void 0 : _this$options$current15.call(_this$options$current16, ...args); 16446 }, 16447 onContentError: (...args) => { 16448 var _this$options$current17, _this$options$current18; 16449 return (_this$options$current17 = (_this$options$current18 = this.options.current).onContentError) === null || _this$options$current17 === void 0 ? void 0 : _this$options$current17.call(_this$options$current18, ...args); 16450 }, 16451 onDrop: (...args) => { 16452 var _this$options$current19, _this$options$current20; 16453 return (_this$options$current19 = (_this$options$current20 = this.options.current).onDrop) === null || _this$options$current19 === void 0 ? void 0 : _this$options$current19.call(_this$options$current20, ...args); 16454 }, 16455 onPaste: (...args) => { 16456 var _this$options$current21, _this$options$current22; 16457 return (_this$options$current21 = (_this$options$current22 = this.options.current).onPaste) === null || _this$options$current21 === void 0 ? void 0 : _this$options$current21.call(_this$options$current22, ...args); 16458 }, 16459 onDelete: (...args) => { 16460 var _this$options$current23, _this$options$current24; 16461 return (_this$options$current23 = (_this$options$current24 = this.options.current).onDelete) === null || _this$options$current23 === void 0 ? void 0 : _this$options$current23.call(_this$options$current24, ...args); 16462 }, 16463 onMount: (...args) => { 16464 var _this$options$current25, _this$options$current26; 16465 return (_this$options$current25 = (_this$options$current26 = this.options.current).onMount) === null || _this$options$current25 === void 0 ? void 0 : _this$options$current25.call(_this$options$current26, ...args); 16466 }, 16467 onUnmount: (...args) => { 16468 var _this$options$current27, _this$options$current28; 16469 return (_this$options$current27 = (_this$options$current28 = this.options.current).onUnmount) === null || _this$options$current27 === void 0 ? void 0 : _this$options$current27.call(_this$options$current28, ...args); 16470 } 16471 }); 16472 } 16473 getEditor() { 16474 return this.editor; 16475 } 16476 getServerSnapshot() { 16477 return null; 16478 } 16479 subscribe(onStoreChange) { 16480 this.subscriptions.add(onStoreChange); 16481 return () => { 16482 this.subscriptions.delete(onStoreChange); 16483 }; 16484 } 16485 static compareOptions(a, b) { 16486 return Object.keys(a).every((key) => { 16487 if ([ 16488 "onCreate", 16489 "onBeforeCreate", 16490 "onDestroy", 16491 "onUpdate", 16492 "onTransaction", 16493 "onFocus", 16494 "onBlur", 16495 "onSelectionUpdate", 16496 "onContentError", 16497 "onDrop", 16498 "onPaste" 16499 ].includes(key)) return true; 16500 if (key === "extensions" && a.extensions && b.extensions) { 16501 if (a.extensions.length !== b.extensions.length) return false;
16502 return a.extensions.every((extension, index) => { 16503 var _b$extensions; 16504 if (extension !== ((_b$extensions = b.extensions) === null || _b$extensions === void 0 ? void 0 : _b$extensions[index])) return false; 16505 return true; 16506 }); 16507 } 16508 if (a[key] !== b[key]) return false; 16509 return true; 16510 }); 16511 } 16512 onRender(deps) { 16513 return () => { 16514 this.isComponentMounted = true; 16515 clearTimeout(this.scheduledDestructionTimeout); 16516 if (this.editor && !this.editor.isDestroyed && deps.length === 0) { 16517 if (!EditorInstanceManager$1.compareOptions(this.options.current, this.editor.options)) this.editor.setOptions({ 16518 ...this.options.current, 16519 editable: this.editor.isEditable 16520 }); 16521 } else this.refreshEditorInstance(deps); 16522 return () => { 16523 this.isComponentMounted = false; 16524 this.scheduleDestroy(); 16525 }; 16526 }; 16527 } 16528 refreshEditorInstance(deps) { 16529 if (this.editor && !this.editor.isDestroyed) { 16530 if (this.previousDeps === null) { 16531 this.previousDeps = deps; 16532 return; 16533 } 16534 if (this.previousDeps.length === deps.length && this.previousDeps.every((dep, index) => dep === deps[index])) return; 16535 } 16536 if (this.editor && !this.editor.isDestroyed) this.editor.destroy(); 16537 this.setEditor(this.createEditor()); 16538 this.previousDeps = deps; 16539 } 16540 scheduleDestroy() { 16541 const currentInstanceId = this.instanceId; 16542 const currentEditor = this.editor; 16543 this.scheduledDestructionTimeout = setTimeout(() => { 16544 if (this.isComponentMounted && this.instanceId === currentInstanceId) { 16545 if (currentEditor) currentEditor.setOptions(this.options.current); 16546 return; 16547 } 16548 if (currentEditor && !currentEditor.isDestroyed) { 16549 currentEditor.destroy(); 16550 if (this.instanceId === currentInstanceId) this.setEditor(null); 16551 } 16552 }, 1); 16553 } 16554}; 16555function useEditor(options = {}, deps = []) { 16556 const mostRecentOptions = (0, import_react.useRef)(options); 16557 mostRecentOptions.current = options; 16558 const [instanceManager] = (0, import_react.useState)(() => new EditorInstanceManager(mostRecentOptions)); 16559 const editor = (0, import_shim.useSyncExternalStore)(instanceManager.subscribe, instanceManager.getEditor, instanceManager.getServerSnapshot); 16560 (0, import_react.useDebugValue)(editor); 16561 (0, import_react.useEffect)(instanceManager.onRender(deps)); 16562 useEditorState({ 16563 editor, 16564 selector: ({ transactionNumber }) => { 16565 if (options.shouldRerenderOnTransaction === false || options.shouldRerenderOnTransaction === void 0) return null; 16566 if (options.immediatelyRender && transactionNumber === 0) return 0; 16567 return transactionNumber + 1; 16568 } 16569 }); 16570 return editor; 16571} 16572var EditorContext = (0, import_react.createContext)({ editor: null }); 16573EditorContext.Consumer; 16574var ReactNodeViewContext = (0, import_react.createContext)({ 16575 onDragStart: () => {}, 16576 nodeViewContentChildren: void 0, 16577 nodeViewContentRef: () => {} 16578}); 16579var useReactNodeView = () => (0, import_react.useContext)(ReactNodeViewContext); 16580import_react.forwardRef((props, ref) => { 16581 const { onDragStart } = useReactNodeView(); 16582 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(props.as || "div", { 16583 ...props, 16584 ref, 16585 "data-node-view-wrapper": "", 16586 onDragStart, 16587 style: { 16588 whiteSpace: "normal", 16589 ...props.style 16590 } 16591 }); 16592}); 16593import_react.createContext({ markViewContentRef: () => {} }); 16594var TiptapContext = (0, import_react.createContext)({ get editor() { 16595 throw new Error("useTiptap must be used within a <Tiptap> provider"); 16596} }); 16597TiptapContext.displayName = "TiptapContext"; 16598var useTiptap = () => (0, import_react.useContext)(TiptapContext); 16599function TiptapWrapper({ children,...props }) { 16600 const resolvedEditor = "editor" in props ? props.editor : props.instance; 16601 if (!resolvedEditor) throw new Error("Tiptap: An editor instance is required. Pass a non-null `editor` prop."); 16602 const tiptapContextValue = (0, import_react.useMemo)(() => ({ editor: resolvedEditor }), [resolvedEditor]); 16603 const legacyContextValue = (0, import_react.useMemo)(() => ({ editor: resolvedEditor }), [resolvedEditor]); 16604 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EditorContext.Provider, { 16605 value: legacyContextValue, 16606 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TiptapContext.Provider, { 16607 value: tiptapContextValue, 16608 children 16609 }) 16610 }); 16611} 16612TiptapWrapper.displayName = "Tiptap"; 16613function TiptapContent({ ...rest }) { 16614 const { editor } = useTiptap(); 16615 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EditorContent, { 16616 editor, 16617 ...rest 16618 }); 16619} 16620TiptapContent.displayName = "Tiptap.Content"; 16621Object.assign(TiptapWrapper, { Content: TiptapContent }); 16622var jsxElements = /* @__PURE__ */ new WeakSet(); 16623var jsxFragments = /* @__PURE__ */ new WeakSet(); 16624function createJSXElement(spec) { 16625 const element = spec; 16626 jsxElements.add(element); 16627 return element; 16628} 16629function isJSXElement(value) { 16630 return Array.isArray(value) && jsxElements.has(value); 16631} 16632function flattenFragmentChildren(children) { 16633 return children.flatMap((child) => { 16634 if (child == null) return []; 16635 if (Array.isArray(child) && jsxFragments.has(child) && !isJSXElement(child)) return flattenFragmentChildren(child); 16636 return [child]; 16637 }); 16638} 16639function render(tag, attributes) { 16640 if (tag === "slot") return 0; 16641 if (tag instanceof Function) { 16642 const result = tag(attributes); 16643 if (Array.isArray(result) && !isJSXElement(result) && !jsxFragments.has(result)) return createJSXElement(result); 16644 return result; 16645 } 16646 const { children,...rest } = attributes !== null && attributes !== void 0 ? attributes : {}; 16647 if (tag === "svg") throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead"); 16648 if (Array.isArray(children)) { 16649 if (isJSXElement(children)) return createJSXElement([ 16650 tag, 16651 rest, 16652 children 16653 ]); 16654 if (children.length === 0) return createJSXElement([tag, rest]); 16655 const flattenedChildren = flattenFragmentChildren(children); 16656 if (flattenedChildren.length === 0) return createJSXElement([tag, rest]); 16657 return createJSXElement([ 16658 tag, 16659 rest, 16660 ...flattenedChildren 16661 ]); 16662 } 16663 if (children !== void 0 && children !== null) return createJSXElement([ 16664 tag, 16665 rest, 16666 children 16667 ]); 16668 return createJSXElement([tag, rest]); 16669} 16670var h = (tag, attributes) => render(tag, attributes); 16671var handleBackspace$1 = (editor, type) => { 16672 var _previous$lastChild; 16673 const { state } = editor; 16674 const { selection } = state; 16675 if (!selection.empty) return false;
16676 const { $from } = selection; 16677 if ($from.parentOffset !== 0) return false; 16678 const parentDepth = $from.depth - 1; 16679 if (parentDepth < 0) return false; 16680 const parent = $from.node(parentDepth); 16681 const index = $from.index(parentDepth); 16682 if (index === 0) return false; 16683 if (parent.type === type) return editor.commands.lift(type.name); 16684 const previous = parent.child(index - 1); 16685 if (previous.type !== type || !((_previous$lastChild = previous.lastChild) === null || _previous$lastChild === void 0 ? void 0 : _previous$lastChild.isTextblock)) return false; 16686 const targetPos = $from.before() - 1 - 1; 16687 return editor.commands.command(({ tr: tr$1, dispatch }) => { 16688 if (!dispatch) return true; 16689 const content = $from.parent.content; 16690 const slice = new Slice(content, 0, 0); 16691 tr$1.replace(targetPos, $from.after(), slice); 16692 tr$1.setSelection(TextSelection.create(tr$1.doc, targetPos + content.size)); 16693 tr$1.scrollIntoView(); 16694 dispatch(tr$1); 16695 return true; 16696 }); 16697}; 16698var inputRegex$2 = /^\s*>\s$/; 16699var Blockquote = Node.create({ 16700 name: "blockquote", 16701 addOptions() { 16702 return { HTMLAttributes: {} }; 16703 }, 16704 content: "block+", 16705 group: "block", 16706 defining: true, 16707 parseHTML() { 16708 return [{ tag: "blockquote" }]; 16709 }, 16710 renderHTML({ HTMLAttributes }) { 16711 return /* @__PURE__ */ h("blockquote", { 16712 ...mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 16713 children: /* @__PURE__ */ h("slot", {}) 16714 }); 16715 }, 16716 parseMarkdown: (token, helpers) => { 16717 var _helpers$parseBlockCh; 16718 const parseBlockChildren = (_helpers$parseBlockCh = helpers.parseBlockChildren) !== null && _helpers$parseBlockCh !== void 0 ? _helpers$parseBlockCh : helpers.parseChildren; 16719 return helpers.createNode("blockquote", void 0, parseBlockChildren(token.tokens || [])); 16720 }, 16721 renderMarkdown: (node, h$1) => { 16722 if (!node.content) return ""; 16723 const prefix = ">"; 16724 const result = []; 16725 node.content.forEach((child, index) => { 16726 var _h$renderChild, _h$renderChild2; 16727 const linesWithPrefix = ((_h$renderChild = (_h$renderChild2 = h$1.renderChild) === null || _h$renderChild2 === void 0 ? void 0 : _h$renderChild2.call(h$1, child, index)) !== null && _h$renderChild !== void 0 ? _h$renderChild : h$1.renderChildren([child])).split("\n").map((line) => { 16728 if (line.trim() === "") return prefix; 16729 return `${prefix} ${line}`; 16730 }); 16731 result.push(linesWithPrefix.join("\n")); 16732 }); 16733 return result.join(`\n${prefix}\n`); 16734 }, 16735 addCommands() { 16736 return { 16737 setBlockquote: () => ({ commands }) => { 16738 return commands.wrapIn(this.name); 16739 }, 16740 toggleBlockquote: () => ({ commands }) => { 16741 return commands.toggleWrap(this.name); 16742 }, 16743 unsetBlockquote: () => ({ commands }) => { 16744 return commands.lift(this.name); 16745 } 16746 }; 16747 }, 16748 addKeyboardShortcuts() { 16749 return { 16750 "Mod-Shift-b": () => this.editor.commands.toggleBlockquote(), 16751 Backspace: () => handleBackspace$1(this.editor, this.type) 16752 }; 16753 }, 16754 addInputRules() { 16755 return [wrappingInputRule({ 16756 find: inputRegex$2, 16757 type: this.type 16758 })]; 16759 } 16760}); 16761var starInputRegex$1 = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/; 16762var starPasteRegex$1 = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g; 16763var underscoreInputRegex$1 = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/; 16764var underscorePasteRegex$1 = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g; 16765var Bold$1 = Mark.create({ 16766 name: "bold", 16767 addOptions() { 16768 return { HTMLAttributes: {} }; 16769 }, 16770 parseHTML() { 16771 return [ 16772 { tag: "strong" }, 16773 { 16774 tag: "b", 16775 getAttrs: (node) => node.style.fontWeight !== "normal" && null 16776 }, 16777 { 16778 style: "font-weight=400", 16779 clearMark: (mark) => mark.type.name === this.name 16780 }, 16781 { 16782 style: "font-weight", 16783 getAttrs: (value) => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null 16784 } 16785 ]; 16786 }, 16787 renderHTML({ HTMLAttributes }) { 16788 return /* @__PURE__ */ h("strong", { 16789 ...mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 16790 children: /* @__PURE__ */ h("slot", {}) 16791 }); 16792 }, 16793 markdownTokenName: "strong", 16794 parseMarkdown: (token, helpers) => { 16795 return helpers.applyMark("bold", helpers.parseInline(token.tokens || [])); 16796 }, 16797 markdownOptions: { htmlReopen: { 16798 open: "<strong>",
16799 close: "</strong>" 16800 } }, 16801 renderMarkdown: (node, h$1) => { 16802 return `**${h$1.renderChildren(node)}**`; 16803 }, 16804 addCommands() { 16805 return { 16806 setBold: () => ({ commands }) => { 16807 return commands.setMark(this.name); 16808 }, 16809 toggleBold: () => ({ commands }) => { 16810 return commands.toggleMark(this.name); 16811 }, 16812 unsetBold: () => ({ commands }) => { 16813 return commands.unsetMark(this.name); 16814 } 16815 }; 16816 }, 16817 addKeyboardShortcuts() { 16818 return { 16819 "Mod-b": () => this.editor.commands.toggleBold(), 16820 "Mod-B": () => this.editor.commands.toggleBold() 16821 }; 16822 }, 16823 addInputRules() { 16824 return [markInputRule({ 16825 find: starInputRegex$1, 16826 type: this.type 16827 }), markInputRule({ 16828 find: underscoreInputRegex$1, 16829 type: this.type 16830 })]; 16831 }, 16832 addPasteRules() { 16833 return [markPasteRule({ 16834 find: starPasteRegex$1, 16835 type: this.type 16836 }), markPasteRule({ 16837 find: underscorePasteRegex$1, 16838 type: this.type 16839 })]; 16840 } 16841}); 16842var inputRegexMatch = (text$1) => { 16843 const match = /`([^`]+)`(?!`)$/.exec(text$1); 16844 if (!match) return null; 16845 if (match.index > 0 && text$1[match.index - 1] === "`") return null; 16846 return { 16847 index: match.index, 16848 text: match[0], 16849 replaceWith: match[1] 16850 }; 16851}; 16852var pasteRegexMatch = (text$1) => { 16853 const regex = /`([^`]+)`(?!`)/g; 16854 const matches$1 = []; 16855 let match; 16856 while ((match = regex.exec(text$1)) !== null) { 16857 if (match.index > 0 && text$1[match.index - 1] === "`") continue; 16858 matches$1.push({ 16859 index: match.index, 16860 text: match[0], 16861 replaceWith: match[1] 16862 }); 16863 } 16864 return matches$1; 16865}; 16866var Code = Mark.create({ 16867 name: "code", 16868 addOptions() { 16869 return { HTMLAttributes: {} }; 16870 }, 16871 excludes: "_", 16872 code: true, 16873 exitable: true, 16874 parseHTML() { 16875 return [{ tag: "code" }]; 16876 }, 16877 renderHTML({ HTMLAttributes }) { 16878 return [ 16879 "code", 16880 mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 16881 0 16882 ]; 16883 }, 16884 markdownTokenName: "codespan", 16885 parseMarkdown: (token, helpers) => { 16886 return helpers.applyMark("code", [{ 16887 type: "text", 16888 text: token.text || "" 16889 }]); 16890 }, 16891 renderMarkdown: (node, h$1) => { 16892 if (!node.content) return ""; 16893 return `\`${h$1.renderChildren(node.content)}\``; 16894 }, 16895 addCommands() { 16896 return { 16897 setCode: () => ({ commands }) => { 16898 return commands.setMark(this.name); 16899 }, 16900 toggleCode: () => ({ commands }) => { 16901 return commands.toggleMark(this.name); 16902 }, 16903 unsetCode: () => ({ commands }) => { 16904 return commands.unsetMark(this.name); 16905 } 16906 }; 16907 }, 16908 addKeyboardShortcuts() { 16909 return { "Mod-e": () => this.editor.commands.toggleCode() }; 16910 }, 16911 addInputRules() { 16912 return [markInputRule({ 16913 find: inputRegexMatch, 16914 type: this.type 16915 })]; 16916 }, 16917 addPasteRules() { 16918 return [markPasteRule({ 16919 find: pasteRegexMatch, 16920 type: this.type 16921 })]; 16922 } 16923}); 16924var DEFAULT_TAB_SIZE = 4; 16925var backtickInputRegex = /^```([a-z]+)?[\s\n]$/; 16926var tildeInputRegex = /^~~~([a-z]+)?[\s\n]$/; 16927var CodeBlock = Node.create({ 16928 name: "codeBlock", 16929 addOptions() { 16930 return { 16931 languageClassPrefix: "language-", 16932 exitOnTripleEnter: true, 16933 exitOnArrowDown: true, 16934 exitOnArrowUp: true, 16935 defaultLanguage: null, 16936 enableTabIndentation: false, 16937 tabSize: DEFAULT_TAB_SIZE, 16938 HTMLAttributes: {} 16939 }; 16940 }, 16941 content: "text*", 16942 marks: "", 16943 group: "block", 16944 code: true, 16945 defining: true, 16946 addAttributes() { 16947 return { language: { 16948 default: this.options.defaultLanguage, 16949 parseHTML: (element) => { 16950 var _element$firstElement; 16951 const { languageClassPrefix } = this.options; 16952 if (!languageClassPrefix) return null; 16953 const language = [...((_element$firstElement = element.firstElementChild) === null || _element$firstElement === void 0 ? void 0 : _element$firstElement.classList) || []].filter((className) => className.startsWith(languageClassPrefix)).map((className) => className.replace(languageClassPrefix, ""))[0]; 16954 if (!language) return null; 16955 return language; 16956 }, 16957 rendered: false 16958 } }; 16959 }, 16960 parseHTML() { 16961 return [{ 16962 tag: "pre", 16963 preserveWhitespace: "full" 16964 }]; 16965 }, 16966 renderHTML({ node, HTMLAttributes }) { 16967 return [ 16968 "pre", 16969 mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 16970 [ 16971 "code", 16972 { class: node.attrs.language ? this.options.languageClassPrefix + n
vendor: 3,259 bytes, lines 16972-17045
16972ode.attrs.language : null }, 16973 0 16974 ] 16975 ]; 16976 }, 16977 markdownTokenName: "code", 16978 parseMarkdown: (token, helpers) => { 16979 var _token$raw, _token$raw2; 16980 if (((_token$raw = token.raw) === null || _token$raw === void 0 ? void 0 : _token$raw.startsWith("```")) === false && ((_token$raw2 = token.raw) === null || _token$raw2 === void 0 ? void 0 : _token$raw2.startsWith("~~~")) === false && token.codeBlockStyle !== "indented") return []; 16981 return helpers.createNode("codeBlock", { language: token.lang || null }, token.text ? [helpers.createTextNode(token.text)] : []); 16982 }, 16983 renderMarkdown: (node, h$1) => { 16984 var _node$attrs; 16985 let output = ""; 16986 const language = ((_node$attrs = node.attrs) === null || _node$attrs === void 0 ? void 0 : _node$attrs.language) || ""; 16987 if (!node.content) output = `\`\`\`${language}\n\n\`\`\``; 16988 else output = [ 16989 `\`\`\`${language}`, 16990 h$1.renderChildren(node.content), 16991 "```" 16992 ].join("\n"); 16993 return output; 16994 }, 16995 addCommands() { 16996 return { 16997 setCodeBlock: (attributes) => ({ commands }) => { 16998 return commands.setNode(this.name, attributes); 16999 }, 17000 toggleCodeBlock: (attributes) => ({ commands }) => { 17001 return commands.toggleNode(this.name, "paragraph", attributes); 17002 } 17003 }; 17004 }, 17005 addKeyboardShortcuts() { 17006 return { 17007 "Mod-Alt-c": () => this.editor.commands.toggleCodeBlock(), 17008 Backspace: () => { 17009 const { empty: empty$1, $anchor } = this.editor.state.selection; 17010 const isAtStart = $anchor.pos === 1; 17011 if (!empty$1 || $anchor.parent.type.name !== this.name) return false; 17012 if (isAtStart || !$anchor.parent.textContent.length) return this.editor.commands.clearNodes(); 17013 return false; 17014 }, 17015 Tab: ({ editor }) => { 17016 var _this$options$tabSize; 17017 if (!this.options.enableTabIndentation) return false; 17018 const tabSize = (_this$options$tabSize = this.options.tabSize) !== null && _this$options$tabSize !== void 0 ? _this$options$tabSize : DEFAULT_TAB_SIZE; 17019 const { state } = editor; 17020 const { selection } = state; 17021 const { $from, empty: empty$1 } = selection; 17022 if ($from.parent.type !== this.type) return false; 17023 const indent = " ".repeat(tabSize); 17024 if (empty$1) return editor.commands.insertContent(indent); 17025 return editor.commands.command(({ tr: tr$1 }) => { 17026 const { from, to } = selection; 17027 const indentedText = state.doc.textBetween(from, to, "\n", "\n").split("\n").map((line) => indent + line).join("\n"); 17028 tr$1.replaceWith(from, to, state.schema.text(indentedText)); 17029 return true; 17030 }); 17031 }, 17032 "Shift-Tab": ({ editor }) => { 17033 var _this$options$tabSize2; 17034 if (!this.options.enableTabIndentation) return false; 17035 const tabSize = (_this$options$tabSize2 = this.options.tabSize) !== null && _this$options$tabSize2 !== void 0 ? _this$options$tabSize2 : DEFAULT_TAB_SIZE; 17036 const { state } = editor; 17037 const { selection } = state; 17038 const { $from, empty: empty$1 } = selection; 17039 if ($from.parent.type !== this.type) return false; 17040 if (empty$1) return editor.commands.command(({ tr: tr$1 }) => { 17041 var _currentLine$match; 17042 const { pos } = $from; 17043 const codeBlockStart = $from.start(); 17044 const codeBlockEnd = $from.end(); 17045 const lines = state.doc.textBetween(codeBlockStart, codeBlockEnd, "\n", "\n").split("\n");
vendor: 4,119 bytes, lines 17046-17140
17046 let currentLineIndex = 0; 17047 let charCount = 0; 17048 const relativeCursorPos = pos - codeBlockStart; 17049 for (let i$1 = 0; i$1 < lines.length; i$1 += 1) { 17050 if (charCount + lines[i$1].length >= relativeCursorPos) { 17051 currentLineIndex = i$1; 17052 break; 17053 } 17054 charCount += lines[i$1].length + 1; 17055 } 17056 const leadingSpaces = ((_currentLine$match = lines[currentLineIndex].match(/^ */)) === null || _currentLine$match === void 0 ? void 0 : _currentLine$match[0]) || ""; 17057 const spacesToRemove = Math.min(leadingSpaces.length, tabSize); 17058 if (spacesToRemove === 0) return true; 17059 let lineStartPos = codeBlockStart; 17060 for (let i$1 = 0; i$1 < currentLineIndex; i$1 += 1) lineStartPos += lines[i$1].length + 1; 17061 tr$1.delete(lineStartPos, lineStartPos + spacesToRemove); 17062 if (pos - lineStartPos <= spacesToRemove) tr$1.setSelection(TextSelection.create(tr$1.doc, lineStartPos)); 17063 return true; 17064 }); 17065 return editor.commands.command(({ tr: tr$1 }) => { 17066 const { from, to } = selection; 17067 const reverseIndentText = state.doc.textBetween(from, to, "\n", "\n").split("\n").map((line) => { 17068 var _line$match; 17069 const leadingSpaces = ((_line$match = line.match(/^ */)) === null || _line$match === void 0 ? void 0 : _line$match[0]) || ""; 17070 const spacesToRemove = Math.min(leadingSpaces.length, tabSize); 17071 return line.slice(spacesToRemove); 17072 }).join("\n"); 17073 tr$1.replaceWith(from, to, state.schema.text(reverseIndentText)); 17074 return true; 17075 }); 17076 }, 17077 Enter: ({ editor }) => { 17078 if (!this.options.exitOnTripleEnter) return false; 17079 const { state } = editor; 17080 const { selection } = state; 17081 const { $from, empty: empty$1 } = selection; 17082 if (!empty$1 || $from.parent.type !== this.type) return false; 17083 const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2; 17084 const endsWithDoubleNewline = $from.parent.textContent.endsWith("\n\n"); 17085 if (!isAtEnd || !endsWithDoubleNewline) return false; 17086 return editor.chain().command(({ tr: tr$1 }) => { 17087 tr$1.delete($from.pos - 2, $from.pos); 17088 return true; 17089 }).exitCode().run(); 17090 }, 17091 ArrowUp: ({ editor }) => { 17092 if (!this.options.exitOnArrowUp) return false; 17093 const { state } = editor; 17094 const { selection } = state; 17095 const { $from, empty: empty$1 } = selection; 17096 if (!empty$1 || $from.parent.type !== this.type) return false; 17097 if ($from.parentOffset !== 0) return false; 17098 const before = $from.before(); 17099 if (before > 0) return false; 17100 return editor.commands.insertDefaultBlock({ pos: before }); 17101 }, 17102 ArrowDown: ({ editor }) => { 17103 if (!this.options.exitOnArrowDown) return false; 17104 const { state } = editor; 17105 const { selection, doc: doc$2 } = state; 17106 const { $from, empty: empty$1 } = selection; 17107 if (!empty$1 || $from.parent.type !== this.type) return false; 17108 if (!($from.parentOffset === $from.parent.nodeSize - 2)) return false; 17109 const after = $from.after(); 17110 if (after === void 0) return false; 17111 if (doc$2.nodeAt(after)) return editor.commands.command(({ tr: tr$1 }) => { 17112 tr$1.setSelection(Selection$1.near(doc$2.resolve(after))); 17113 return true; 17114 }); 17115 return editor.commands.exitCode(); 17116 } 17117 }; 17118 }, 17119 addInputRules() { 17120 return [textblockTypeInputRule({ 17121 find: backtickInputRegex, 17122 type: this.type, 17123 getAttributes: (match) => ({ language: match[1] }) 17124 }), textblockTypeInputRule({ 17125 find: tildeInputRegex, 17126 type: this.type, 17127 getAttributes: (match) => ({ language: match[1] }) 17128 })]; 17129 }, 17130 addProseMirrorPlugins() { 17131 return [new Plugin({ 17132 key: new PluginKey("codeBlockVSCodeHandler"), 17133 props: { handlePaste: (view, event) => { 17134 if (!event.clipboardData) return false; 17135 if (this.editor.isActive(this.type.name)) return false; 17136 const text$1 = event.clipboardData.getData("text/plain"); 17137 const vscode = event.clipboardData.getData("vscode-editor-data"); 17138 const vscodeData = vscode ? JSON.parse(vscode) : void 0; 17139 const language = vscodeData === null || vscodeData === void 0 ? void 0 : vscodeData.mode; 17140 if (!text$1 || !language) return false;
17141 const { tr: tr$1, schema } = view.state; 17142 const textNode = schema.text(text$1.replace(/\r\n?/g, "\n")); 17143 tr$1.replaceSelectionWith(this.type.create({ language }, textNode)); 17144 if (tr$1.selection.$from.parent.type !== this.type) tr$1.setSelection(TextSelection.near(tr$1.doc.resolve(Math.max(0, tr$1.selection.from - 2)))); 17145 tr$1.setMeta("paste", true); 17146 view.dispatch(tr$1); 17147 return true; 17148 } } 17149 })]; 17150 } 17151}); 17152var Document = Node.create({ 17153 name: "doc", 17154 topNode: true, 17155 content: "block+", 17156 renderMarkdown: (node, h$1) => { 17157 if (!node.content) return ""; 17158 return h$1.renderChildren(node.content, "\n\n"); 17159 } 17160}); 17161var HardBreak = Node.create({ 17162 name: "hardBreak", 17163 markdownTokenName: "br", 17164 addOptions() { 17165 return { 17166 keepMarks: true, 17167 HTMLAttributes: {} 17168 }; 17169 }, 17170 inline: true, 17171 group: "inline", 17172 selectable: false, 17173 linebreakReplacement: true, 17174 parseHTML() { 17175 return [{ tag: "br" }]; 17176 }, 17177 renderHTML({ HTMLAttributes }) { 17178 return ["br", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]; 17179 }, 17180 renderText() { 17181 return "\n"; 17182 }, 17183 renderMarkdown: () => ` \n`, 17184 parseMarkdown: () => { 17185 return { type: "hardBreak" }; 17186 }, 17187 addCommands() { 17188 return { setHardBreak: () => ({ commands, chain, state, editor }) => { 17189 return commands.first([() => commands.exitCode(), () => commands.command(() => { 17190 const { selection, storedMarks } = state; 17191 if (selection.$from.parent.type.spec.isolating) return false; 17192 const { keepMarks } = this.options; 17193 const { splittableMarks } = editor.extensionManager; 17194 const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); 17195 return chain().insertContent({ type: this.name }).command(({ tr: tr$1, dispatch }) => { 17196 if (dispatch && marks && keepMarks) { 17197 const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); 17198 tr$1.ensureMarks(filteredMarks); 17199 } 17200 return true; 17201 }).scrollIntoView().run(); 17202 })]); 17203 } }; 17204 }, 17205 addKeyboardShortcuts() { 17206 return { 17207 "Mod-Enter": () => this.editor.commands.setHardBreak(), 17208 "Shift-Enter": () => this.editor.commands.setHardBreak() 17209 }; 17210 } 17211}); 17212var Heading = Node.create({ 17213 name: "heading", 17214 addOptions() { 17215 return { 17216 levels: [ 17217 1, 17218 2, 17219 3, 17220 4, 17221 5, 17222 6 17223 ], 17224 HTMLAttributes: {} 17225 }; 17226 }, 17227 content: "inline*", 17228 group: "block", 17229 defining: true, 17230 addAttributes() { 17231 return { level: { 17232 default: 1, 17233 rendered: false 17234 } }; 17235 }, 17236 parseHTML() { 17237 return this.options.levels.map((level) => ({ 17238 tag: `h${level}`, 17239 attrs: { level } 17240 })); 17241 }, 17242 renderHTML({ node, HTMLAttributes }) { 17243 return [ 17244 `h${this.options.levels.includes(node.attrs.level) ? node.attrs.level : this.options.levels[0]}`, 17245 mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 17246 0 17247 ]; 17248 }, 17249 parseMarkdown: (token, helpers) => { 17250 return helpers.createNode("heading", { level: token.depth || 1 }, helpers.parseInline(token.tokens || [])); 17251 }, 17252 renderMarkdown: (node, h$1) => { 17253 var _node$attrs; 17254 const level = ((_node$attrs = node.attrs) === null || _node$attrs === void 0 ? void 0 : _node$attrs.level) ? parseInt(node.attrs.level, 10) : 1; 17255 const headingChars = "#".repeat(level); 17256 if (!node.content) return ""; 17257 return `${headingChars} ${h$1.renderChildren(node.content)}`; 17258 }, 17259 addCommands() { 17260 return { 17261 setHeading: (attributes) => ({ commands }) => { 17262 if (!this.options.levels.includes(attributes.level)) return false; 17263 return commands.setNode(this.name, attributes); 17264 }, 17265 toggleHeading: (attributes) => ({ commands }) => { 17266 if (!this.options.levels.includes(attributes.level)) return false; 17267 return commands.toggleNode(this.name, "paragraph", attributes); 17268 } 17269 }; 17270 }, 17271 addKeyboardShortcuts() { 17272 return this.options.levels.reduce((items, level) => ({ 17273 ...items, 17274 [`Mod-Alt-${level}`]: () => this.editor.commands.toggleHeading({ level }) 17275 }), {}); 17276 }, 17277 addInputRules() { 17278 return this.options.levels.map((level) => { 17279 return textblockTypeInputRule({ 17280 find: /* @__PURE__ */ new RegExp(`^(#{${Math.min(...this.options.levels)},${level}})\\s$`), 17281 type: this.type, 17282 getAttributes: { level } 17283 }); 17284 }); 17285 } 17286}); 17287var HorizontalRule = Node.create({ 17288 name: "horizontalRule", 17289 addOptions() { 17290 return { 17291 HTMLAttributes: {}, 17292 nextNodeType: "paragraph" 17293 }; 17294 }, 17295 group: "block", 17296 parseHTML() { 17297 return [{ tag: "hr" }]; 17298 }, 17299 renderHTML({ HTMLAttributes }) { 17300 return ["hr", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]; 17301 }, 17302 markdownTokenName: "hr", 17303 parseMarkdown: (token, helpers) => { 17304 return helpers.createNode("horizontalRule"); 17305 }, 17306 renderMarkdown: () => { 17307 return "---"; 17308 }, 17309 addCommands() { 17310 return { setHorizontalRule: () => ({ chain, state }) => { 17311 if (!canInsertNode(state, state.schema.nodes[this.name])) return false;
17312 const { selection } = state; 17313 const { $to: $originTo } = selection; 17314 const currentChain = chain(); 17315 if (isNodeSelection(selection)) currentChain.insertContentAt($originTo.pos, { type: this.name }); 17316 else currentChain.insertContent({ type: this.name }); 17317 return currentChain.command(({ state: chainState, tr: tr$1, dispatch }) => { 17318 if (dispatch) { 17319 const { $to } = tr$1.selection; 17320 const posAfter = $to.end(); 17321 if ($to.nodeAfter) if ($to.nodeAfter.isTextblock) tr$1.setSelection(TextSelection.create(tr$1.doc, $to.pos + 1)); 17322 else if ($to.nodeAfter.isBlock) tr$1.setSelection(NodeSelection.create(tr$1.doc, $to.pos)); 17323 else tr$1.setSelection(TextSelection.create(tr$1.doc, $to.pos)); 17324 else { 17325 const nodeType = chainState.schema.nodes[this.options.nextNodeType] || $to.parent.type.contentMatch.defaultType; 17326 const node = nodeType === null || nodeType === void 0 ? void 0 : nodeType.create(); 17327 if (node) { 17328 tr$1.insert(posAfter, node); 17329 tr$1.setSelection(TextSelection.create(tr$1.doc, posAfter + 1)); 17330 } 17331 } 17332 tr$1.scrollIntoView(); 17333 } 17334 return true; 17335 }).run(); 17336 } }; 17337 }, 17338 addInputRules() { 17339 return [nodeInputRule({ 17340 find: /^(?:---|â-|___\s|\*\*\*\s)$/, 17341 type: this.type 17342 })]; 17343 } 17344}); 17345var starInputRegex = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/; 17346var starPasteRegex = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g; 17347var underscoreInputRegex = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/; 17348var underscorePasteRegex = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g; 17349var Italic$1 = Mark.create({ 17350 name: "italic", 17351 addOptions() { 17352 return { HTMLAttributes: {} }; 17353 }, 17354 parseHTML() { 17355 return [ 17356 { tag: "em" }, 17357 { 17358 tag: "i", 17359 getAttrs: (node) => node.style.fontStyle !== "normal" && null 17360 }, 17361 { 17362 style: "font-style=normal", 17363 clearMark: (mark) => mark.type.name === this.name 17364 }, 17365 { style: "font-style=italic" } 17366 ]; 17367 }, 17368 renderHTML({ HTMLAttributes }) { 17369 return [ 17370 "em", 17371 mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 17372 0 17373 ]; 17374 }, 17375 addCommands() { 17376 return { 17377 setItalic: () => ({ commands }) => { 17378 return commands.setMark(this.name); 17379 }, 17380 toggleItalic: () => ({ commands }) => { 17381 return commands.toggleMark(this.name); 17382 }, 17383 unsetItalic: () => ({ commands }) => { 17384 return commands.unsetMark(this.name); 17385 } 17386 }; 17387 }, 17388 markdownTokenName: "em", 17389 parseMarkdown: (token, helpers) => { 17390 return helpers.applyMark("italic", helpers.parseInline(token.tokens || [])); 17391 }, 17392 markdownOptions: { htmlReopen: { 17393 open: "<em>", 17394 close: "</em>" 17395 } }, 17396 renderMarkdown: (node, h$1) => { 17397 return `*${h$1.renderChildren(node)}*`; 17398 }, 17399 addKeyboardShortcuts() { 17400 return { 17401 "Mod-i": () => this.editor.commands.toggleItalic(), 17402 "Mod-I": () => this.editor.commands.toggleItalic() 17403 }; 17404 }, 17405 addInputRules() { 17406 return [markInputRule({ 17407 find: starInputRegex, 17408 type: this.type 17409 }), markInputRule({ 17410 find: underscoreInputRegex, 17411 type: this.type 17412 })]; 17413 }, 17414 addPasteRules() { 17415 return [markPasteRule({ 17416 find: starPasteRegex, 17417 type: this.type 17418 }), markPasteRule({ 17419 find: underscorePasteRegex, 17420 type: this.type 17421 })]; 17422 } 17423}); 17424var ListItemName$1 = "listItem"; 17425var TextStyleName$1 = "textStyle"; 17426var bulletListInputRegex = /^\s*([-+*])\s$/; 17427var BulletList = Node.create({ 17428 name: "bulletList", 17429 addOptions() { 17430 return { 17431 itemTypeName: "listItem", 17432 HTMLAttributes: {}, 17433 keepMarks: false, 17434 keepAttributes: false 17435 }; 17436 }, 17437 group: "block list", 17438 content() { 17439 return `${this.options.itemTypeName}+`; 17440 }, 17441 parseHTML() { 17442 return [{ tag: "ul" }]; 17443 }, 17444 renderHTML({ HTMLAttributes }) { 17445 return [ 17446 "ul", 17447 mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 17448 0 17449 ]; 17450 }, 17451 markdownTokenName: "list", 17452 parseMarkdown: (token, helpers) => { 17453 if (token.type !== "list" || token.ordered) return []; 17454 return { 17455 type: "bulletList", 17456 content: token.items ? helpers.parseChildren(token.items) : [] 17457 }; 17458 }, 17459 renderMarkdown: (node, h$1) => { 17460 if (!node.content) return ""; 17461 return h$1.renderChildren(node.content, "\n"); 17462 }, 17463 markdownOptions: { indentsContent: true }, 17464 addCommands() { 17465 return { toggleBulletList: () => ({ commands, chain }) => { 17466 if (this.options.keepAttributes) return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName$1, this.editor.getAttributes(TextStyleName$1)).run(); 17467 return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks); 17468 } }; 17469 }, 17470 addKeyboardShortcuts() {
17471 return { "Mod-Shift-8": () => this.editor.commands.toggleBulletList() }; 17472 }, 17473 addInputRules() { 17474 let inputRule = wrappingInputRule({ 17475 find: bulletListInputRegex, 17476 type: this.type 17477 }); 17478 if (this.options.keepMarks || this.options.keepAttributes) inputRule = wrappingInputRule({ 17479 find: bulletListInputRegex, 17480 type: this.type, 17481 keepMarks: this.options.keepMarks, 17482 keepAttributes: this.options.keepAttributes, 17483 getAttributes: () => { 17484 return this.editor.getAttributes(TextStyleName$1); 17485 }, 17486 editor: this.editor 17487 }); 17488 return [inputRule]; 17489 } 17490}); 17491var getBranchingNestedListAtCursor = (state, itemName, wrapperNames) => { 17492 const { selection } = state; 17493 if (!selection.empty) return null; 17494 const { $from } = selection; 17495 if (!$from.parent.isTextblock) return null; 17496 if ($from.parentOffset !== $from.parent.content.size) return null; 17497 let listItemDepth = -1; 17498 for (let depth = $from.depth; depth > 0; depth -= 1) if ($from.node(depth).type.name === itemName) { 17499 listItemDepth = depth; 17500 break; 17501 } 17502 if (listItemDepth < 0) return null; 17503 const listItem = $from.node(listItemDepth); 17504 const indexInListItem = $from.index(listItemDepth); 17505 if (indexInListItem + 1 >= listItem.childCount) return null; 17506 const nextChild = listItem.child(indexInListItem + 1); 17507 if (!wrapperNames.includes(nextChild.type.name)) return null; 17508 const itemType = state.schema.nodes[itemName]; 17509 let hasBranching = false; 17510 nextChild.forEach((child) => { 17511 if (child.type === itemType && child.childCount > 1) hasBranching = true; 17512 }); 17513 if (!hasBranching) return null; 17514 const nodeAfter = state.doc.resolve($from.after()).nodeAfter; 17515 if (!nodeAfter || !wrapperNames.includes(nodeAfter.type.name)) return null; 17516 const items = []; 17517 nodeAfter.forEach((child) => { 17518 items.push(child); 17519 }); 17520 if (items.length === 0) return null; 17521 return { 17522 listItemDepth, 17523 nestedList: nodeAfter, 17524 nestedListPos: $from.after(), 17525 insertPos: $from.after(listItemDepth), 17526 items 17527 }; 17528}; 17529var hoistBranchingNestedList = (state, dispatch, itemName, wrapperNames) => { 17530 const context = getBranchingNestedListAtCursor(state, itemName, wrapperNames); 17531 if (!context) return false; 17532 const { selection } = state; 17533 const { nestedList, nestedListPos, insertPos, items } = context; 17534 const tr$1 = state.tr; 17535 tr$1.delete(nestedListPos, nestedListPos + nestedList.nodeSize); 17536 const mappedInsertPos = tr$1.mapping.map(insertPos); 17537 tr$1.insert(mappedInsertPos, Fragment.from(items)); 17538 tr$1.setSelection(selection.map(tr$1.doc, tr$1.mapping)); 17539 if (dispatch) dispatch(tr$1); 17540 return true; 17541}; 17542var handleDeleteBranchingNestedList = (editor, itemName, wrapperNames) => { 17543 return hoistBranchingNestedList(editor.state, editor.view.dispatch, itemName, wrapperNames); 17544}; 17545var createBranchingListDeleteKeymap = (itemName, wrapperNames) => { 17546 return Extension.create({ 17547 name: `${itemName}BranchingDeleteKeymap`, 17548 priority: 101, 17549 addKeyboardShortcuts() { 17550 const handleDelete$1 = () => handleDeleteBranchingNestedList(this.editor, itemName, wrapperNames); 17551 return { 17552 Delete: handleDelete$1, 17553 "Mod-Delete": handleDelete$1 17554 }; 17555 } 17556 }); 17557}; 17558var ROMAN_NUMERALS = [ 17559 [1e3, "m"], 17560 [900, "cm"], 17561 [500, "d"], 17562 [400, "cd"], 17563 [100, "c"], 17564 [90, "xc"], 17565 [50, "l"], 17566 [40, "xl"], 17567 [10, "x"], 17568 [9, "ix"], 17569 [5, "v"], 17570 [4, "iv"], 17571 [1, "i"] 17572]; 17573var ALPHA_NUMERALS = "abcdefghijklmnopqrstuvwxyz"; 17574var ORDERED_LIST_MARKER_PATTERN = String.raw`\d+|[ivxlcdmIVXLCDM]+|${"[a-zA-Z]{1,2}"}`; 17575function toRoman(num) { 17576 let remaining = num; 17577 let result = ""; 17578 for (const [value, numeral] of ROMAN_NUMERALS) while (remaining >= value) { 17579 result += numeral; 17580 remaining -= value; 17581 } 17582 return result; 17583} 17584function toRomanUpper(num) { 17585 return toRoman(num).toUpperCase(); 17586} 17587function fromRoman(roman) { 17588 const lower = roman.toLowerCase(); 17589 let index = 0; 17590 let result = 0; 17591 while (index < lower.length) { 17592 let matched = false; 17593 for (const [value, numeral] of ROMAN_NUMERALS) if (lower.startsWith(numeral, index)) { 17594 result += value; 17595 index += numeral.length; 17596 matched = true; 17597 break; 17598 } 17599 if (!matched) return 0; 17600 } 17601 return result; 17602} 17603function isValidRoman(marker) { 17604 if (!/^[ivxlcdmIVXLCDM]+$/.test(marker)) return false;
17605 const value = fromRoman(marker); 17606 if (value <= 0) return false; 17607 return (marker === marker.toLowerCase() ? toRoman(value) : toRomanUpper(value)) === marker; 17608} 17609function fromAlpha(marker) { 17610 const lower = marker.toLowerCase(); 17611 if (lower.length === 1) return lower.charCodeAt(0) - "a".charCodeAt(0) + 1; 17612 if (lower.length === 2) { 17613 const first$1 = lower.charCodeAt(0) - "a".charCodeAt(0); 17614 const second = lower.charCodeAt(1) - "a".charCodeAt(0); 17615 return (first$1 + 1) * 26 + second + 1; 17616 } 17617 return 0; 17618} 17619function toRomanAlpha(num) { 17620 if (num <= 26) return ALPHA_NUMERALS[num - 1]; 17621 const first$1 = Math.floor((num - 1) / 26) - 1; 17622 const second = (num - 1) % 26; 17623 if (first$1 < 0) return ALPHA_NUMERALS[second]; 17624 return ALPHA_NUMERALS[first$1] + ALPHA_NUMERALS[second]; 17625} 17626function detectMarkerType(marker) { 17627 if (!marker || /^\d+$/.test(marker)) return; 17628 if (isValidRoman(marker)) return marker === marker.toLowerCase() ? "i" : "I"; 17629 if (/^[a-z]{1,2}$/.test(marker)) return "a"; 17630 if (/^[A-Z]{1,2}$/.test(marker)) return "A"; 17631} 17632function markerToStart(marker) { 17633 if (/^\d+$/.test(marker)) return parseInt(marker, 10); 17634 const type = detectMarkerType(marker); 17635 if (type === "i" || type === "I") return fromRoman(marker); 17636 if (type === "a" || type === "A") { 17637 const start = fromAlpha(marker); 17638 return start > 0 ? start : 1; 17639 } 17640 const parsed = parseInt(marker, 10); 17641 return Number.isNaN(parsed) ? 1 : parsed; 17642} 17643function startToMarker(type, start) { 17644 if (type === "numeric") return String(start); 17645 switch (type) { 17646 case "a": return toRomanAlpha(start); 17647 case "A": return toRomanAlpha(start).toUpperCase(); 17648 case "i": return toRoman(start); 17649 case "I": return toRomanUpper(start); 17650 default: return String(start); 17651 } 17652} 17653function areOrderedListMarkersSequential(markers) { 17654 var _detectMarkerType; 17655 if (markers.length === 0) return false; 17656 const firstType = (_detectMarkerType = detectMarkerType(markers[0])) !== null && _detectMarkerType !== void 0 ? _detectMarkerType : "numeric"; 17657 const firstStart = markerToStart(markers[0]); 17658 if (firstStart < 1) return false; 17659 for (let i$1 = 0; i$1 < markers.length; i$1++) { 17660 const expected = startToMarker(firstType, firstStart + i$1); 17661 if (markers[i$1] !== expected) return false; 17662 } 17663 return true; 17664} 17665function parseListMarker(marker) { 17666 return { 17667 type: detectMarkerType(marker), 17668 start: markerToStart(marker) 17669 }; 17670} 17671function buildOrderedListAttrsFromMarker(marker) { 17672 const { type, start } = parseListMarker(marker); 17673 const attrs = {}; 17674 if (type) attrs.type = type; 17675 if (start !== 1) attrs.start = start; 17676 return attrs; 17677} 17678function getListMarker(type, index, separator = ". ") { 17679 const position = index + 1; 17680 if (!type || type === "1") return `${position}${separator}`; 17681 switch (type) { 17682 case "a": return `${toRomanAlpha(position)}${separator}`; 17683 case "A": return `${toRomanAlpha(position).toUpperCase()}${separator}`; 17684 case "i": return `${toRoman(position)}${separator}`; 17685 case "I": return `${toRomanUpper(position)}${separator}`; 17686 default: return `${position}${separator}`; 17687 } 17688} 17689function isSameLineOrderedListToken(token) { 17690 var _token$tokens, _token$tokens2; 17691 const nestedToken = (_token$tokens = token.tokens) === null || _token$tokens === void 0 ? void 0 : _token$tokens[0]; 17692 return Boolean(token.text && ((_token$tokens2 = token.tokens) === null || _token$tokens2 === void 0 ? void 0 : _token$tokens2.length) === 1 && (nestedToken === null || nestedToken === void 0 ? void 0 : nestedToken.type) === "list" && nestedToken.ordered && nestedToken.raw === token.text); 17693} 17694function parseSameLineOrderedListText(text$1, helpers) { 17695 if (helpers.tokenizeInline) return helpers.parseInline(helpers.tokenizeInline(text$1)); 17696 return helpers.parseInline([{ 17697 type: "text", 17698 raw: text$1, 17699 text: text$1 17700 }]); 17701} 17702var ListItem = Node.create({ 17703 name: "listItem", 17704 addOptions() { 17705 return { 17706 HTMLAttributes: {}, 17707 bulletListTypeName: "bulletList", 17708 orderedListTypeName: "orderedList" 17709 }; 17710 }, 17711 content: "paragraph block*", 17712 defining: true, 17713 parseHTML() { 17714 return [{ tag: "li" }]; 17715 }, 17716 renderHTML({ HTMLAttributes }) { 17717 return [ 17718 "li", 17719 mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 17720 0 17721 ]; 17722 }, 17723 markdownTokenName: "list_item", 17724 parseMarkdown: (token, helpers) => { 17725 var _helpers$parseBlockCh; 17726 if (token.type !== "list_item") return []; 17727 const parseBlockChildren = (_helpers$parseBlockCh = helpers.parseBlockChildren) !== null && _helpers$parseBlockCh !== void 0 ? _helpers$parseBlockCh : helpers.parseChildren; 17728 let content = []; 17729 if (token.tokens && token.tokens.length > 0) { 17730 if (isSameLineOrderedListToken(token)) return { 17731 type: "listItem", 17732 content: [{ 17733 type: "paragraph", 17734 content: parseSameLineOrderedListText(token.text || "", helpers) 17735 }] 17736 }; 17737 if (token.tokens.some((t) => t.type === "paragraph")) content = parseBlockChildren(token.tokens); 17738 else { 17739 const firstToken = token.tokens[0]; 17740 if (firstToken && firstToken.type === "text" && firstToken.tokens && firstToken.tokens.length > 0) { 17741 content = [{ 17742 type: "paragraph", 17743 content: helpers.parseInline(firstToken.tokens) 17744 }]; 17745 if (token.tokens.length > 1) { 17746 const additionalContent = parseBlockChildren(token.tokens.slice(1)); 17747 content.push(...additionalContent); 17748 } 17749 } else content = parseBlockChildren(token.tokens); 17750 } 17751 } 17752 if (content.length === 0) content = [{ 17753 type: "paragraph", 17754 content: [] 17755 }]; 17756 return { 17757 type: "listItem", 17758 content 17759 }; 17760 }, 17761 renderMarkdown: (node, h$1, ctx) => { 17762 return renderNestedMarkdownContent(node, h$1, (context) => { 17763 if (context.parentType === "bulletList") return "- "; 17764 if (context.parentType === "orderedList") { 17765 var _context$meta, _context$meta2; 17766 const start = ((_context$meta = context.meta) === null || _context$meta === void 0 || (_context$meta = _context$meta.parentAttrs) === null || _context$meta === void 0 ? void 0 : _context$meta.start) || 1; 17767 return getListMarker((_context$meta2 = context.meta) === null || _context$meta2 === void 0 || (_context$meta2 = _context$meta2.parentAttrs) === null || _context$meta2 === void 0 ? void 0 : _context$meta2.type, start - 1 + (context.index || 0), ". "); 17768 } 17769 return "- "; 17770 }, ctx, { alignNestedToPrefix: (ctx === null || ctx === void 0 ? void 0 : ctx.parentType) === "orderedList" }); 17771 }, 17772 addExtensions() { 17773 return [createBranchingListDeleteKeymap(this.name, [this.options.bulletListTypeName, this.options.orderedListTypeName])]; 17774 }, 17775 addKeyboardShortcuts() { 17776 return { 17777 Enter: () => this.editor.commands.splitListItem(this.name), 17778 Tab: () => this.editor.commands.sinkListItem(this.name), 17779 "Shift-Tab": () => this.editor.commands.liftListItem(this.name) 17780 }; 17781 } 17782});
17783var findListItemPos = (typeOrName, state) => { 17784 const { $from } = state.selection; 17785 const nodeType = getNodeType(typeOrName, state.schema); 17786 let currentNode = null; 17787 let currentDepth = $from.depth; 17788 let currentPos = $from.pos; 17789 let targetDepth = null; 17790 while (currentDepth > 0 && targetDepth === null) { 17791 currentNode = $from.node(currentDepth); 17792 if (currentNode.type === nodeType) targetDepth = currentDepth; 17793 else { 17794 currentDepth -= 1; 17795 currentPos -= 1; 17796 } 17797 } 17798 if (targetDepth === null) return null; 17799 return { 17800 $pos: state.doc.resolve(currentPos), 17801 depth: targetDepth 17802 }; 17803}; 17804var getNextListDepth = (typeOrName, state) => { 17805 const listItemPos = findListItemPos(typeOrName, state); 17806 if (!listItemPos) return false; 17807 const [, depth] = getNodeAtPosition(state, typeOrName, listItemPos.$pos.pos + 4); 17808 return depth; 17809}; 17810var hasListBefore = (editorState, name, parentListTypes) => { 17811 const { $anchor } = editorState.selection; 17812 const previousNodePos = Math.max(0, $anchor.pos - 2); 17813 const previousNode = editorState.doc.resolve(previousNodePos).node(); 17814 if (!previousNode || !parentListTypes.includes(previousNode.type.name)) return false; 17815 return true; 17816}; 17817var handleBackspace = (editor, name, parentListTypes) => { 17818 if (editor.commands.undoInputRule()) return true; 17819 if (editor.state.selection.from !== editor.state.selection.to) return false; 17820 if (!isNodeActive(editor.state, name) && hasListBefore(editor.state, name, parentListTypes)) { 17821 const { $anchor } = editor.state.selection; 17822 const $listPos = editor.state.doc.resolve($anchor.before() - 1); 17823 const listDescendants = []; 17824 $listPos.node().descendants((node, pos) => { 17825 if (node.type.name === name) listDescendants.push({ 17826 node, 17827 pos 17828 }); 17829 }); 17830 const lastItem = listDescendants.at(-1); 17831 if (!lastItem) return false; 17832 const $lastItemPos = editor.state.doc.resolve($listPos.start() + lastItem.pos + 1); 17833 return editor.chain().cut({ 17834 from: $anchor.start() - 1, 17835 to: $anchor.end() + 1 17836 }, $lastItemPos.end()).joinForward().run(); 17837 } 17838 if (!isNodeActive(editor.state, name)) return false; 17839 if (!isAtStartOfNode(editor.state)) return false; 17840 const { $from } = editor.state.selection; 17841 const itemDepth = $from.depth - 1; 17842 if ($from.node(itemDepth).type !== editor.schema.nodes[name] || $from.index(itemDepth) !== 0) return false; 17843 return editor.chain().liftListItem(name).run(); 17844}; 17845var nextListIsDeeper = (typeOrName, state) => { 17846 const listDepth = getNextListDepth(typeOrName, state); 17847 const listItemPos = findListItemPos(typeOrName, state); 17848 if (!listItemPos || !listDepth) return false; 17849 if (listDepth > listItemPos.depth) return true; 17850 return false; 17851}; 17852var nextListIsHigher = (typeOrName, state) => { 17853 const listDepth = getNextListDepth(typeOrName, state); 17854 const listItemPos = findListItemPos(typeOrName, state); 17855 if (!listItemPos || !listDepth) return false; 17856 if (listDepth < listItemPos.depth) return true; 17857 return false; 17858}; 17859var handleDelete = (editor, name) => { 17860 if (!isNodeActive(editor.state, name)) return false; 17861 if (!isAtEndOfNode(editor.state, name)) return false; 17862 const { selection } = editor.state; 17863 const { $from, $to } = selection; 17864 if (!selection.empty && $from.sameParent($to)) return false; 17865 if (nextListIsDeeper(name, editor.state)) return editor.chain().focus(editor.state.selection.from + 4).lift(name).joinBackward().run(); 17866 if (nextListIsHigher(name, editor.state)) return editor.chain().joinForward().joinBackward().run(); 17867 return editor.commands.joinItemForward(); 17868}; 17869var handleTab = (editor, name, parentListTypes) => { 17870 const { state } = editor; 17871 const { selection } = state; 17872 if (!selection.empty) return false; 17873 const { $from } = selection; 17874 if ($from.parentOffset !== 0) return false; 17875 if (!$from.parent.isTextblock) return false; 17876 if (isNodeActive(state, name)) return false; 17877 const previous = getPreviousBlockSibling($from); 17878 if (!previous || !parentListTypes.includes(previous.type.name)) return false; 17879 const lastItem = previous.lastChild; 17880 if (!lastItem || lastItem.type.name !== name) return false; 17881 const block = $from.parent; 17882 if (!lastItem.canReplace(lastItem.childCount, lastItem.childCount, Fragment.from(block))) return false;
17883 const blockStart = $from.before(); 17884 const blockEnd = $from.after(); 17885 const insideLastItemEnd = blockStart - 2; 17886 return editor.commands.command(({ tr: tr$1, dispatch }) => { 17887 if (dispatch) { 17888 tr$1.delete(blockStart, blockEnd).insert(insideLastItemEnd, Fragment.from(block)); 17889 tr$1.setSelection(TextSelection.create(tr$1.doc, insideLastItemEnd + 1)); 17890 tr$1.scrollIntoView(); 17891 } 17892 return true; 17893 }); 17894}; 17895var ListKeymap = Extension.create({ 17896 name: "listKeymap", 17897 addOptions() { 17898 return { listTypes: [{ 17899 itemName: "listItem", 17900 wrapperNames: ["bulletList", "orderedList"] 17901 }, { 17902 itemName: "taskItem", 17903 wrapperNames: ["taskList"] 17904 }] }; 17905 }, 17906 addKeyboardShortcuts() { 17907 return { 17908 Delete: ({ editor }) => { 17909 let handled = false; 17910 this.options.listTypes.forEach(({ itemName }) => { 17911 if (editor.state.schema.nodes[itemName] === void 0) return; 17912 if (handleDelete(editor, itemName)) handled = true; 17913 }); 17914 return handled; 17915 }, 17916 "Mod-Delete": ({ editor }) => { 17917 let handled = false; 17918 this.options.listTypes.forEach(({ itemName }) => { 17919 if (editor.state.schema.nodes[itemName] === void 0) return; 17920 if (handleDelete(editor, itemName)) handled = true; 17921 }); 17922 return handled; 17923 }, 17924 Backspace: ({ editor }) => { 17925 let handled = false; 17926 this.options.listTypes.forEach(({ itemName, wrapperNames }) => { 17927 if (editor.state.schema.nodes[itemName] === void 0) return; 17928 if (handleBackspace(editor, itemName, wrapperNames)) handled = true; 17929 }); 17930 return handled; 17931 }, 17932 "Mod-Backspace": ({ editor }) => { 17933 let handled = false; 17934 this.options.listTypes.forEach(({ itemName, wrapperNames }) => { 17935 if (editor.state.schema.nodes[itemName] === void 0) return; 17936 if (handleBackspace(editor, itemName, wrapperNames)) handled = true; 17937 }); 17938 return handled; 17939 }, 17940 Tab: ({ editor }) => { 17941 for (const { itemName, wrapperNames } of this.options.listTypes) { 17942 if (editor.state.schema.nodes[itemName] === void 0) continue; 17943 if (handleTab(editor, itemName, wrapperNames)) return true; 17944 } 17945 return false; 17946 } 17947 }; 17948 } 17949}); 17950var ORDERED_LIST_ITEM_REGEX = /* @__PURE__ */ new RegExp(`^(\\s*)(${ORDERED_LIST_MARKER_PATTERN})([.)])\\s+(.*)$`); 17951var INDENTED_LINE_REGEX = /^\s/; 17952var PARAGRAPH_INTERRUPTERS = { 17953 heading: /^#{1,6}(?:\s|$)/, 17954 bulletItem: /^[-+*]\s+/, 17955 codeFence: /^(?:```|~~~)/, 17956 blockMath: /^\$\$/, 17957 thematicBreak: /^(?:(?:-[ \t]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})$/ 17958}; 17959function isOrderedListMarkerLine(line) { 17960 return ORDERED_LIST_ITEM_REGEX.test(line.trimStart()); 17961} 17962function isBlockContentLine(line) { 17963 const trimmedLine = line.trimStart(); 17964 return PARAGRAPH_INTERRUPTERS.bulletItem.test(trimmedLine) || isOrderedListMarkerLine(trimmedLine) || PARAGRAPH_INTERRUPTERS.heading.test(trimmedLine) || PARAGRAPH_INTERRUPTERS.thematicBreak.test(trimmedLine) && !trimmedLine.startsWith("-") || /^>\s?/.test(trimmedLine) || PARAGRAPH_INTERRUPTERS.codeFence.test(trimmedLine) || PARAGRAPH_INTERRUPTERS.blockMath.test(trimmedLine); 17965} 17966function interruptsLazyContinuation(line) { 17967 return Object.values(PARAGRAPH_INTERRUPTERS).some((pattern) => pattern.test(line)); 17968} 17969function splitItemContent(contentLines) { 17970 const paragraphLines = []; 17971 const blockLines = []; 17972 let reachedBlockBoundary = false; 17973 contentLines.forEach((line) => { 17974 if (reachedBlockBoundary) { 17975 blockLines.push(line); 17976 return; 17977 } 17978 if (line.trim() === "") { 17979 reachedBlockBoundary = true; 17980 blockLines.push(line); 17981 return; 17982 } 17983 if (paragraphLines.length > 0 && isBlockContentLine(line)) { 17984 reachedBlockBoundary = true; 17985 blockLines.push(line); 17986 return; 17987 } 17988 paragraphLines.push(line); 17989 }); 17990 return { 17991 paragraphLines, 17992 blockLines 17993 }; 17994} 17995function collectOrderedListItems(lines) { 17996 const listItems = []; 17997 let currentLineIndex = 0; 17998 let consumed = 0; 17999 while (currentLineIndex < lines.length) { 18000 const line = lines[currentLineIndex]; 18001 const match = line.match(ORDERED_LIST_ITEM_REGEX); 18002 if (!match) break; 18003 const [, indent, marker, _separator, content] = match; 18004 const indentLevel = indent.length; 18005 const number = parseInt(marker, 10); 18006 const markerType = isNaN(number) ? detectMarkerType(marker) : void 0; 18007 const itemNumber = isNaN(number) ? markerToStart(marker) : number; 18008 const itemContentLines = [content]; 18009 let nextLineIndex = currentLineIndex + 1; 18010 const itemLines = [line]; 18011 let sawBlankLine = false;
18012 while (nextLineIndex < lines.length) { 18013 const nextLine = lines[nextLineIndex]; 18014 if (nextLine.match(ORDERED_LIST_ITEM_REGEX)) break; 18015 if (nextLine.trim() === "") { 18016 itemLines.push(nextLine); 18017 itemContentLines.push(""); 18018 sawBlankLine = true; 18019 nextLineIndex += 1; 18020 } else if (nextLine.match(INDENTED_LINE_REGEX)) { 18021 const leadingWhitespace = nextLine.length - nextLine.trimStart().length; 18022 const contentIndent = indentLevel + marker.length + 1; 18023 itemLines.push(nextLine); 18024 itemContentLines.push(nextLine.slice(Math.min(leadingWhitespace, contentIndent))); 18025 nextLineIndex += 1; 18026 } else { 18027 if (sawBlankLine || interruptsLazyContinuation(nextLine)) break; 18028 itemLines.push(nextLine); 18029 itemContentLines.push(nextLine); 18030 nextLineIndex += 1; 18031 } 18032 } 18033 listItems.push({ 18034 indent: indentLevel, 18035 number: itemNumber, 18036 type: markerType, 18037 content: itemContentLines.join("\n").trim(), 18038 contentLines: itemContentLines, 18039 raw: itemLines.join("\n") 18040 }); 18041 consumed = nextLineIndex; 18042 currentLineIndex = nextLineIndex; 18043 } 18044 return [listItems, consumed]; 18045} 18046var PLAIN_TEXT_ORDERED_LIST_LINE_REGEX = /* @__PURE__ */ new RegExp(`^(${ORDERED_LIST_MARKER_PATTERN})([.)])\\s+(.+)$`); 18047function parsePlainTextOrderedListPaste(text$1) { 18048 const lines = text$1.split("\n").filter((l) => l.trim().length > 0); 18049 if (lines.length === 0) return null; 18050 const parsedItems = []; 18051 for (const line of lines) { 18052 const match = line.trim().match(PLAIN_TEXT_ORDERED_LIST_LINE_REGEX); 18053 if (!match) return null; 18054 parsedItems.push({ 18055 marker: match[1], 18056 content: match[3] 18057 }); 18058 } 18059 if (!areOrderedListMarkersSequential(parsedItems.map((item) => item.marker))) return null; 18060 return { 18061 type: "orderedList", 18062 attrs: buildOrderedListAttrsFromMarker(parsedItems[0].marker), 18063 content: parsedItems.map((item) => ({ 18064 type: "listItem", 18065 content: [{ 18066 type: "paragraph", 18067 content: [{ 18068 type: "text", 18069 text: item.content 18070 }] 18071 }] 18072 })) 18073 }; 18074} 18075function buildNestedStructure(items, baseIndent, lexer) { 18076 const result = []; 18077 let currentIndex = 0; 18078 while (currentIndex < items.length) { 18079 const item = items[currentIndex]; 18080 if (item.indent === baseIndent) { 18081 const { paragraphLines, blockLines } = splitItemContent(item.contentLines); 18082 const mainText = paragraphLines.join("\n").trim(); 18083 const tokens = []; 18084 if (mainText) tokens.push({ 18085 type: "paragraph", 18086 raw: mainText, 18087 tokens: lexer.inlineTokens(mainText) 18088 }); 18089 const additionalContent = blockLines.join("\n").trim(); 18090 if (additionalContent) { 18091 const blockTokens = lexer.blockTokens(additionalContent); 18092 tokens.push(...blockTokens); 18093 } 18094 let lookAheadIndex = currentIndex + 1; 18095 const nestedItems = []; 18096 while (lookAheadIndex < items.length && items[lookAheadIndex].indent > baseIndent) { 18097 nestedItems.push(items[lookAheadIndex]); 18098 lookAheadIndex += 1; 18099 } 18100 if (nestedItems.length > 0) { 18101 const nestedListItems = buildNestedStructure(nestedItems, Math.min(...nestedItems.map((nestedItem) => nestedItem.indent)), lexer); 18102 tokens.push({ 18103 type: "list", 18104 ordered: true, 18105 start: nestedItems[0].number, 18106 typeMarker: nestedItems[0].type, 18107 items: nestedListItems, 18108 raw: nestedItems.map((nestedItem) => nestedItem.raw).join("\n") 18109 }); 18110 } 18111 result.push({ 18112 type: "list_item", 18113 raw: item.raw, 18114 tokens 18115 }); 18116 currentIndex = lookAheadIndex; 18117 } else currentIndex += 1; 18118 } 18119 return result; 18120} 18121function parseListItems(items, helpers) { 18122 return items.map((item) => { 18123 if (item.type !== "list_item") return helpers.parseChildren([item])[0]; 18124 const content = []; 18125 if (item.tokens && item.tokens.length > 0) item.tokens.forEach((itemToken) => { 18126 if (itemToken.type === "paragraph" || itemToken.type === "list" || itemToken.type === "blockquote" || itemToken.type === "code") content.push(...helpers.parseChildren([itemToken])); 18127 else if (itemToken.type === "text" && itemToken.tokens) { 18128 const inlineContent = helpers.parseChildren([itemToken]); 18129 content.push({ 18130 type: "paragraph", 18131 content: inlineContent 18132 }); 18133 } else { 18134 const parsed = helpers.parseChildren([itemToken]); 18135 if (parsed.length > 0) content.push(...parsed); 18136 } 18137 }); 18138 return { 18139 type: "listItem", 18140 content 18141 }; 18142 }); 18143} 18144var ListItemName = "listItem"; 18145var TextStyleName = "textStyle"; 18146var orderedListInputRegex = /^(\d+)\.\s$/; 18147function cssListStyleTypeToHtmlType(style$1) { 18148 const match = style$1.match(/list-style-type\s*:\s*([^;]+)/i); 18149 if (!match) return null; 18150 switch (match[1].trim().toLowerCase()) { 18151 case "upper-roman": return "I"; 18152 case "lower-roman": return "i"; 18153 case "upper-alpha": 18154 case "upper-latin": return "A"; 18155 case "lower-alpha": 18156 case "lower-latin": return "a"; 18157 default: return null; 18158 } 18159} 18160var OrderedList = Node.create({ 18161 name: "orderedList", 18162 addOptions() { 18163 return { 18164 itemTypeName: "listItem", 18165 HTMLAttributes: {}, 18166 keepMarks: false, 18167 keepAttributes: false 18168 }; 18169 }, 18170 group: "block list", 18171 content() { 18172 return `${this.options.itemTypeName}+`; 18173 }, 18174 addAttributes() { 18175 return { 18176 start: { 18177 default: 1, 18178 parseHTML: (element) => { 18179 return element.hasAttribute("start") ? parseInt(element.getAttribute("start") || "", 10) : 1; 18180 } 18181 }, 18182 type: { 18183 default: null, 18184 parseHTML: (element) => { 18185 const htmlType = element.getAttribute("type"); 18186 if (htmlType) return htmlType; 18187 const style$1 = element.getAttribute("style"); 18188 if (style$1) { 18189 const mappedFromOl = cssListStyleTypeToHtmlType(style$1); 18190 if (mappedFromOl) return mappedFromOl; 18191 } 18192 const firstLi = element.querySelector("li"); 18193 if (firstLi) { 18194 const liStyle = firstLi.getAttribute("style"); 18195 if (liStyle) { 18196 const mappedFromLi = cssListStyleTypeToHtmlType(liStyle); 18197 if (mappedFromLi) return mappedFromLi; 18198 } 18199 } 18200 return null; 18201 } 18202 } 18203 }; 18204 }, 18205 parseHTML() { 18206 return [{ tag: "ol" }]; 18207 }, 18208 renderHTML({ HTMLAttributes }) { 18209 const { start, type,...attributesWithoutType } = HTMLAttributes; 18210 const attrs = mergeAttributes(this.options.HTMLAttributes, attributesWithoutType); 18211 if (start !== 1) attrs.start = start; 18212 if (type && type !== "1") attrs.type = type; 18213 return [ 18214 "ol", 18215 attrs, 18216 0 18217 ]; 18218 }, 18219 markdownTokenName: "list", 18220 parseMarkdown: (token, helpers) => { 18221 if (token.type !== "list" || !token.ordered) return []; 18222 const startValue = token.start || 1; 18223 const typeValue = token.typeMarker; 18224 const content = token.items ? parseListItems(token.items, helpers) : []; 18225 const attrs = {}; 18226 if (startValue !== 1) attrs.start = startValue; 18227 if (typeValue) attrs.type = typeValue; 18228 if (Object.keys(attrs).length > 0) return { 18229 type: "orderedList", 18230 attrs, 18231 content 18232 }; 18233 return { 18234 type: "orderedList", 18235 content 18236 }; 18237 }, 18238 renderMarkdown: (node, h$1) => { 18239 if (!node.content) return ""; 18240 return h$1.renderChildren(node.content, "\n"); 18241 }, 18242 markdownTokenizer: { 18243 name: "orderedList", 18244 level: "block", 18245 start: () => -1, 18246 tokenize: (src, _tokens, lexer) => { 18247 var _listItems$, _listItems$2; 18248 const lines = src.split("\n"); 18249 const [listItems, consumed] = collectOrderedListItems(lines); 18250 if (listItems.length === 0) return;
18251 const items = buildNestedStructure(listItems, listItems[0].indent, lexer); 18252 if (items.length === 0) return; 18253 return { 18254 type: "list", 18255 ordered: true, 18256 start: ((_listItems$ = listItems[0]) === null || _listItems$ === void 0 ? void 0 : _listItems$.number) || 1, 18257 typeMarker: (_listItems$2 = listItems[0]) === null || _listItems$2 === void 0 ? void 0 : _listItems$2.type, 18258 items, 18259 raw: lines.slice(0, consumed).join("\n") 18260 }; 18261 } 18262 }, 18263 markdownOptions: { indentsContent: true }, 18264 addCommands() { 18265 return { toggleOrderedList: () => ({ commands, chain }) => { 18266 if (this.options.keepAttributes) return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName, this.editor.getAttributes(TextStyleName)).run(); 18267 return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks); 18268 } }; 18269 }, 18270 addKeyboardShortcuts() { 18271 return { "Mod-Shift-7": () => this.editor.commands.toggleOrderedList() }; 18272 }, 18273 addProseMirrorPlugins() { 18274 return [new Plugin({ props: { handlePaste: (view, event) => { 18275 var _event$clipboardData, _event$clipboardData2; 18276 const html$2 = (_event$clipboardData = event.clipboardData) === null || _event$clipboardData === void 0 ? void 0 : _event$clipboardData.getData("text/html"); 18277 if (html$2 === null || html$2 === void 0 ? void 0 : html$2.trim()) return false; 18278 const text$1 = (_event$clipboardData2 = event.clipboardData) === null || _event$clipboardData2 === void 0 ? void 0 : _event$clipboardData2.getData("text/plain"); 18279 if (!text$1) return false; 18280 const orderedListContent = parsePlainTextOrderedListPaste(text$1); 18281 if (!orderedListContent) return false; 18282 try { 18283 const orderedListNode = view.state.schema.nodeFromJSON(orderedListContent); 18284 const tr$1 = view.state.tr.replaceSelectionWith(orderedListNode); 18285 view.dispatch(tr$1); 18286 return true; 18287 } catch { 18288 return false; 18289 } 18290 } } })]; 18291 }, 18292 addInputRules() { 18293 const joinPredicate = (match, node) => { 18294 return (!node.attrs.type || node.attrs.type === "1") && node.childCount + node.attrs.start === +match[1]; 18295 }; 18296 let inputRule = wrappingInputRule({ 18297 find: orderedListInputRegex, 18298 type: this.type, 18299 getAttributes: (match) => ({ start: +match[1] }), 18300 joinPredicate 18301 }); 18302 if (this.options.keepMarks || this.options.keepAttributes) inputRule = wrappingInputRule({ 18303 find: orderedListInputRegex, 18304 type: this.type, 18305 keepMarks: this.options.keepMarks, 18306 keepAttributes: this.options.keepAttributes, 18307 getAttributes: (match) => ({ 18308 start: +match[1], 18309 ...this.editor.getAttributes(TextStyleName) 18310 }), 18311 joinPredicate, 18312 editor: this.editor 18313 }); 18314 return [inputRule]; 18315 } 18316}); 18317var inputRegex$1 = /^\s*(\[([( |x])?\])\s$/; 18318var visuallyHiddenStyle = "position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0"; 18319var getCheckboxLabel = (node, checked, a11y) => { 18320 var _a11y$checkboxLabel; 18321 return (a11y === null || a11y === void 0 || (_a11y$checkboxLabel = a11y.checkboxLabel) === null || _a11y$checkboxLabel === void 0 ? void 0 : _a11y$checkboxLabel.call(a11y, node, checked)) || `Task item checkbox for ${node.textContent || "empty task item"}`; 18322}; 18323var TaskItem = Node.create({ 18324 name: "taskItem", 18325 addOptions() { 18326 return { 18327 nested: false, 18328 HTMLAttributes: {}, 18329 taskListTypeName: "taskList", 18330 a11y: void 0 18331 }; 18332 }, 18333 content() { 18334 return this.options.nested ? "paragraph block*" : "paragraph+"; 18335 }, 18336 defining: true, 18337 addAttributes() { 18338 return { checked: { 18339 default: false, 18340 keepOnSplit: false, 18341 parseHTML: (element) => { 18342 const dataChecked = element.getAttribute("data-checked"); 18343 return dataChecked === "" || dataChecked === "true"; 18344 }, 18345 renderHTML: (attributes) => ({ "data-checked": attributes.checked }) 18346 } }; 18347 }, 18348 parseHTML() { 18349 return [{ 18350 tag: `li[data-type="${this.name}"]`, 18351 priority: 51, 18352 contentElement: (element) => { 18353 var _element$querySelecto; 18354 return (_element$querySelecto = element.querySelector("div")) !== null && _element$querySelecto !== void 0 ? _element$querySelecto : element; 18355 } 18356 }]; 18357 }, 18358 renderHTML({ node, HTMLAttributes }) { 18359 return [ 18360 "li", 18361 mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { "data-type": this.name }), 18362 [ 18363 "label", 18364 ["input", { 18365 type: "checkbox", 18366 checked: node.attrs.checked ? "checked" : null 18367 }], 18368 ["span"] 18369 ], 18370 ["div", 0] 18371 ]; 18372 }, 18373 parseMarkdown: (token, h$1) => { 18374 const content = []; 18375 if (token.tokens && token.tokens.length > 0) content.push(h$1.createNode("paragraph", {}, h$1.parseInline(token.tokens))); 18376 else if (token.text) content.push(h$1.createNode("paragraph", {}, [h$1.createNode("text", { text: token.text })])); 18377 else content.push(h$1.createNode("paragraph", {}, [])); 18378 if (token.nestedTokens && token.nestedTokens.length > 0) { 18379 const nestedContent = h$1.parseChildren(token.nestedTokens); 18380 content.push(...nestedContent); 18381 } 18382 return h$1.createNode("taskItem", { checked: token.checked || false }, content); 18383 }, 18384 renderMarkdown: (node, h$1) => { 18385 var _node$attrs; 18386 return renderNestedMarkdownContent(node, h$1, `- [${((_node$attrs = node.attrs) === null || _node$attrs === void 0 ? void 0 : _node$attrs.checked) ? "x" : " "}] `); 18387 }, 18388 addExtensions() { 18389 if (!this.options.nested) return []; 18390 return [createBranchingListDeleteKeymap(this.name, [this.options.taskListTypeName])]; 18391 }, 18392 addKeyboardShortcuts() { 18393 const shortcuts = { 18394 Enter: () => this.editor.commands.splitListItem(this.name), 18395 "Shift-Tab": () => this.editor.commands.liftListItem(this.name) 18396 }; 18397 if (!this.options.nested) return shortcuts; 18398 return { 18399 ...shortcuts, 18400 Tab: () => this.editor.commands.sinkListItem(this.name) 18401 }; 18402 }, 18403 addNodeView() { 18404 return ({ node, HTMLAttributes, getPos, editor }) => { 18405 const listItem = document.createElement("li"); 18406 const checkboxWrapper = document.createElement("label"); 18407 const checkboxStyler = document.createElement("span"); 18408 const checkbox = document.createElement("input"); 18409 const content = document.createElement("div"); 18410 checkboxStyler.style.cssText = visuallyHiddenStyle; 18411 const updateA11Y = (currentNode) => { 18412 const label = getCheckboxLabel(currentNode, currentNode.attrs.checked, this.options.a11y); 18413 checkbox.setAttribute("aria-label", label); 18414 checkboxStyler.textContent = label; 18415 }; 18416 updateA11Y(node); 18417 checkboxWrapper.contentEditable = "false"; 18418 checkbox.type = "checkbox"; 18419 checkbox.addEventListener("mousedown", (event) => event.preventDefault()); 18420 checkbox.addEventListener("change", (event) => { 18421 if (!editor.isEditable && !this.options.onReadOnlyChecked) { 18422 checkbox.checked = !checkbox.checked; 18423 return; 18424 } 18425 const { checked } = event.target; 18426 if (editor.isEditable && typeof getPos === "function") editor.chain().focus(void 0, { scrollIntoView: false }).command(({ tr: tr$1 }) => { 18427 const position = getPos(); 18428 if (typeof position !== "number") return false;
18429 const currentNode = tr$1.doc.nodeAt(position); 18430 tr$1.setNodeMarkup(position, void 0, { 18431 ...currentNode === null || currentNode === void 0 ? void 0 : currentNode.attrs, 18432 checked 18433 }); 18434 return true; 18435 }).run(); 18436 if (!editor.isEditable && this.options.onReadOnlyChecked) { 18437 if (!this.options.onReadOnlyChecked(node, checked)) checkbox.checked = !checkbox.checked; 18438 } 18439 }); 18440 Object.entries(this.options.HTMLAttributes).forEach(([key, value]) => { 18441 listItem.setAttribute(key, value); 18442 }); 18443 listItem.dataset.checked = node.attrs.checked; 18444 checkbox.checked = node.attrs.checked; 18445 checkboxWrapper.append(checkbox, checkboxStyler); 18446 listItem.append(checkboxWrapper, content); 18447 Object.entries(HTMLAttributes).forEach(([key, value]) => { 18448 listItem.setAttribute(key, value); 18449 }); 18450 let prevRenderedAttributeKeys = new Set(Object.keys(HTMLAttributes)); 18451 return { 18452 dom: listItem, 18453 contentDOM: content, 18454 update: (updatedNode) => { 18455 if (updatedNode.type !== this.type) return false; 18456 listItem.dataset.checked = updatedNode.attrs.checked; 18457 checkbox.checked = updatedNode.attrs.checked; 18458 updateA11Y(updatedNode); 18459 const extensionAttributes = editor.extensionManager.attributes; 18460 const newHTMLAttributes = getRenderedAttributes(updatedNode, extensionAttributes); 18461 const newKeys = new Set(Object.keys(newHTMLAttributes)); 18462 const staticAttrs = this.options.HTMLAttributes; 18463 prevRenderedAttributeKeys.forEach((key) => { 18464 if (!newKeys.has(key)) if (key in staticAttrs) listItem.setAttribute(key, staticAttrs[key]); 18465 else listItem.removeAttribute(key); 18466 }); 18467 Object.entries(newHTMLAttributes).forEach(([key, value]) => { 18468 if (value === null || value === void 0) if (key in staticAttrs) listItem.setAttribute(key, staticAttrs[key]); 18469 else listItem.removeAttribute(key); 18470 else listItem.setAttribute(key, value); 18471 }); 18472 prevRenderedAttributeKeys = newKeys; 18473 return true; 18474 } 18475 }; 18476 }; 18477 }, 18478 addInputRules() { 18479 return [wrappingInputRule({ 18480 find: inputRegex$1, 18481 type: this.type, 18482 getAttributes: (match) => ({ checked: match[match.length - 1] === "x" }) 18483 })]; 18484 } 18485}); 18486var TaskList = Node.create({ 18487 name: "taskList", 18488 addOptions() { 18489 return { 18490 itemTypeName: "taskItem", 18491 HTMLAttributes: {} 18492 }; 18493 }, 18494 group: "block list", 18495 content() { 18496 return `${this.options.itemTypeName}+`; 18497 }, 18498 parseHTML() { 18499 return [{ 18500 tag: `ul[data-type="${this.name}"]`, 18501 priority: 51 18502 }]; 18503 }, 18504 renderHTML({ HTMLAttributes }) { 18505 return [ 18506 "ul", 18507 mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { "data-type": this.name }), 18508 0 18509 ]; 18510 }, 18511 parseMarkdown: (token, h$1) => { 18512 return h$1.createNode("taskList", {}, h$1.parseChildren(token.items || [])); 18513 }, 18514 renderMarkdown: (node, h$1) => { 18515 if (!node.content) return ""; 18516 return h$1.renderChildren(node.content, "\n"); 18517 }, 18518 markdownTokenizer: { 18519 name: "taskList", 18520 level: "block", 18521 start(src) { 18522 var _src$match; 18523 const index = (_src$match = src.match(/^\s*[-+*]\s+\[([ xX])\]\s+/)) === null || _src$match === void 0 ? void 0 : _src$match.index; 18524 return index !== void 0 ? index : -1; 18525 }, 18526 tokenize(src, tokens, lexer) { 18527 const parseTaskListContent = (content) => { 18528 const nestedResult = parseIndentedBlocks(content, { 18529 itemPattern: /^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/, 18530 extractItemData: (match) => ({ 18531 indentLevel: match[1].length, 18532 mainContent: match[4], 18533 checked: match[3].toLowerCase() === "x" 18534 }), 18535 createToken: (data, nestedTokens) => ({ 18536 type: "taskItem", 18537 raw: "", 18538 mainContent: data.mainContent, 18539 indentLevel: data.indentLevel, 18540 checked: data.checked, 18541 text: data.mainContent, 18542 tokens: lexer.inlineTokens(data.mainContent), 18543 nestedTokens 18544 }), 18545 customNestedParser: parseTaskListContent 18546 }, lexer); 18547 if (nestedResult) { 18548 const taskListToken = { 18549 type: "taskList", 18550 raw: nestedResult.raw, 18551 items: nestedResult.items 18552 }; 18553 const remainder = content.slice(nestedResult.raw.length); 18554 if (remainder.trim()) return [taskListToken, ...lexer.blockTokens(remainder)]; 18555 return [taskListToken]; 18556 } 18557 return lexer.blockTokens(content); 18558 }; 18559 const result = parseIndentedBlocks(src, { 18560 itemPattern: /^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/, 18561 extractItemData: (match) => ({ 18562 indentLevel: match[1].length, 18563 mainContent: match[4], 18564 checked: match[3].toLowerCase() === "x" 18565 }), 18566 createToken: (data, nestedTokens) => ({ 18567 type: "taskItem", 18568 raw: "", 18569 mainContent: data.mainContent, 18570 indentLevel: data.indentLevel, 18571 checked: data.checked, 18572 text: data.mainContent, 18573 tokens: lexer.inlineTokens(data.mainContent), 18574 nestedTokens 18575 }), 18576 customNestedParser: parseTaskListContent 18577 }, lexer); 18578 if (!result) return; 18579 return { 18580 type: "taskList", 18581 raw: result.raw, 18582 items: result.items 18583 }; 18584 } 18585 }, 18586 markdownOptions: { indentsContent: true }, 18587 addCommands() { 18588 return { toggleTaskList: () => ({ commands }) => { 18589 return commands.toggleList(this.name, this.options.itemTypeName); 18590 } }; 18591 }, 18592 addKeyboardShortcuts() {
18593 return { "Mod-Shift-9": () => this.editor.commands.toggleTaskList() }; 18594 } 18595}); 18596Extension.create({ 18597 name: "listKit", 18598 addExtensions() { 18599 const extensions = []; 18600 if (this.options.bulletList !== false) extensions.push(BulletList.configure(this.options.bulletList)); 18601 if (this.options.listItem !== false) extensions.push(ListItem.configure(this.options.listItem)); 18602 if (this.options.listKeymap !== false) extensions.push(ListKeymap.configure(this.options.listKeymap)); 18603 if (this.options.orderedList !== false) extensions.push(OrderedList.configure(this.options.orderedList)); 18604 if (this.options.taskItem !== false) extensions.push(TaskItem.configure(this.options.taskItem)); 18605 if (this.options.taskList !== false) extensions.push(TaskList.configure(this.options.taskList)); 18606 return extensions; 18607 } 18608}); 18609var EMPTY_PARAGRAPH_MARKDOWN = " "; 18610var NBSP_CHAR = "\xA0"; 18611var Paragraph = Node.create({ 18612 name: "paragraph", 18613 priority: 1e3, 18614 addOptions() { 18615 return { HTMLAttributes: {} }; 18616 }, 18617 group: "block", 18618 content: "inline*", 18619 parseHTML() { 18620 return [{ tag: "p" }]; 18621 }, 18622 renderHTML({ HTMLAttributes }) { 18623 return [ 18624 "p", 18625 mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 18626 0 18627 ]; 18628 }, 18629 parseMarkdown: (token, helpers) => { 18630 const tokens = token.tokens || []; 18631 if (tokens.length === 1 && tokens[0].type === "image") return helpers.parseChildren([tokens[0]]); 18632 const content = helpers.parseInline(tokens); 18633 if (tokens.length === 1 && tokens[0].type === "text" && (tokens[0].raw === EMPTY_PARAGRAPH_MARKDOWN || tokens[0].text === EMPTY_PARAGRAPH_MARKDOWN || tokens[0].raw === NBSP_CHAR || tokens[0].text === NBSP_CHAR) && content.length === 1 && content[0].type === "text" && (content[0].text === EMPTY_PARAGRAPH_MARKDOWN || content[0].text === NBSP_CHAR)) return helpers.createNode("paragraph", void 0, []); 18634 return helpers.createNode("paragraph", void 0, content); 18635 }, 18636 renderMarkdown: (node, h$1, ctx) => { 18637 if (!node) return ""; 18638 const content = Array.isArray(node.content) ? node.content : []; 18639 if (content.length === 0) { 18640 var _ctx$previousNode, _ctx$previousNode2;
18641 const previousContent = Array.isArray(ctx === null || ctx === void 0 || (_ctx$previousNode = ctx.previousNode) === null || _ctx$previousNode === void 0 ? void 0 : _ctx$previousNode.content) ? ctx.previousNode.content : []; 18642 return (ctx === null || ctx === void 0 || (_ctx$previousNode2 = ctx.previousNode) === null || _ctx$previousNode2 === void 0 ? void 0 : _ctx$previousNode2.type) === "paragraph" && previousContent.length === 0 ? EMPTY_PARAGRAPH_MARKDOWN : ""; 18643 } 18644 return h$1.renderChildren(content); 18645 }, 18646 addCommands() { 18647 return { setParagraph: () => ({ commands }) => { 18648 return commands.setNode(this.name); 18649 } }; 18650 }, 18651 addKeyboardShortcuts() { 18652 return { "Mod-Alt-0": () => this.editor.commands.setParagraph() }; 18653 } 18654}); 18655var inputRegex = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/; 18656var pasteRegex = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g; 18657var Strike = Mark.create({ 18658 name: "strike", 18659 addOptions() { 18660 return { HTMLAttributes: {} }; 18661 }, 18662 parseHTML() { 18663 return [ 18664 { tag: "s" }, 18665 { tag: "del" }, 18666 { tag: "strike" }, 18667 { 18668 style: "text-decoration", 18669 consuming: false, 18670 getAttrs: (style$1) => style$1.includes("line-through") ? {} : false 18671 } 18672 ]; 18673 }, 18674 renderHTML({ HTMLAttributes }) { 18675 return [ 18676 "s", 18677 mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 18678 0 18679 ]; 18680 }, 18681 markdownTokenName: "del", 18682 parseMarkdown: (token, helpers) => { 18683 return helpers.applyMark("strike", helpers.parseInline(token.tokens || [])); 18684 }, 18685 renderMarkdown: (node, h$1) => { 18686 return `~~${h$1.renderChildren(node)}~~`; 18687 }, 18688 addCommands() { 18689 return { 18690 setStrike: () => ({ commands }) => { 18691 return commands.setMark(this.name); 18692 }, 18693 toggleStrike: () => ({ commands }) => { 18694 return commands.toggleMark(this.name); 18695 }, 18696 unsetStrike: () => ({ commands }) => { 18697 return commands.unsetMark(this.name); 18698 } 18699 }; 18700 }, 18701 addKeyboardShortcuts() {
18702 return { "Mod-Shift-s": () => this.editor.commands.toggleStrike() }; 18703 }, 18704 addInputRules() { 18705 return [markInputRule({ 18706 find: inputRegex, 18707 type: this.type 18708 })]; 18709 }, 18710 addPasteRules() { 18711 return [markPasteRule({ 18712 find: pasteRegex, 18713 type: this.type 18714 })]; 18715 } 18716}); 18717var Text = Node.create({ 18718 name: "text", 18719 group: "inline", 18720 parseMarkdown: (token) => { 18721 return { 18722 type: "text", 18723 text: token.text || "" 18724 }; 18725 }, 18726 renderMarkdown: (node) => node.text || "" 18727}); 18728var Underline$1 = Mark.create({ 18729 name: "underline", 18730 addOptions() { 18731 return { HTMLAttributes: {} }; 18732 }, 18733 parseHTML() { 18734 return [{ tag: "u" }, { 18735 style: "text-decoration", 18736 consuming: false, 18737 getAttrs: (style$1) => style$1.includes("underline") ? {} : false 18738 }]; 18739 }, 18740 renderHTML({ HTMLAttributes }) { 18741 return [ 18742 "u", 18743 mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 18744 0 18745 ]; 18746 }, 18747 parseMarkdown(token, helpers) { 18748 return helpers.applyMark(this.name || "underline", helpers.parseInline(token.tokens || [])); 18749 }, 18750 renderMarkdown(node, helpers) { 18751 return `++${helpers.renderChildren(node)}++`; 18752 }, 18753 markdownTokenizer: { 18754 name: "underline", 18755 level: "inline", 18756 start(src) { 18757 return src.indexOf("++"); 18758 }, 18759 tokenize(src, _tokens, lexer) { 18760 const match = /^(\+\+)([\s\S]+?)(\+\+)/.exec(src); 18761 if (!match) return; 18762 const innerContent = match[2].trim(); 18763 return { 18764 type: "underline", 18765 raw: match[0], 18766 text: innerContent, 18767 tokens: lexer.inlineTokens(innerContent) 18768 }; 18769 } 18770 }, 18771 addCommands() { 18772 return { 18773 setUnderline: () => ({ commands }) => { 18774 return commands.setMark(this.name); 18775 }, 18776 toggleUnderline: () => ({ commands }) => { 18777 return commands.toggleMark(this.name); 18778 }, 18779 unsetUnderline: () => ({ commands }) => { 18780 return commands.unsetMark(this.name); 18781 } 18782 }; 18783 }, 18784 addKeyboardShortcuts() { 18785 return { 18786 "Mod-u": () => this.editor.commands.toggleUnderline(), 18787 "Mod-U": () => this.editor.commands.toggleUnderline() 18788 }; 18789 } 18790}); 18791function dropCursor(options = {}) { 18792 return new Plugin({ view(editorView) { 18793 return new DropCursorView(editorView, options); 18794 } }); 18795} 18796var DropCursorView = class { 18797 constructor(editorView, options) { 18798 var _a; 18799 this.editorView = editorView;
18800 this.cursorPos = null; 18801 this.element = null; 18802 this.timeout = -1; 18803 this.lastDragEvent = null; 18804 this.width = (_a = options.width) !== null && _a !== void 0 ? _a : 1; 18805 this.color = options.color === false ? void 0 : options.color || "black"; 18806 this.class = options.class; 18807 this.handlers = [ 18808 "dragover", 18809 "dragend", 18810 "drop", 18811 "dragleave" 18812 ].map((name) => { 18813 let handler = (e) => { 18814 this[name](e); 18815 }; 18816 editorView.dom.addEventListener(name, handler); 18817 return { 18818 name, 18819 handler 18820 }; 18821 }); 18822 } 18823 destroy() { 18824 this.handlers.forEach(({ name, handler }) => this.editorView.dom.removeEventListener(name, handler)); 18825 } 18826 update(editorView, prevState) { 18827 if (this.cursorPos != null && prevState.doc != editorView.state.doc) if (this.lastDragEvent) { 18828 let target = this.computeTarget(this.lastDragEvent); 18829 if (target == this.cursorPos) this.updateOverlay(); 18830 else this.setCursor(target); 18831 } else this.updateOverlay(); 18832 } 18833 setCursor(pos) { 18834 if (pos == this.cursorPos) return; 18835 this.cursorPos = pos; 18836 if (pos == null) { 18837 this.element.parentNode.removeChild(this.element); 18838 this.element = null; 18839 } else this.updateOverlay(); 18840 } 18841 updateOverlay() { 18842 let $pos = this.editorView.state.doc.resolve(this.cursorPos); 18843 let isBlock = !$pos.parent.inlineContent, rect; 18844 let editorDOM = this.editorView.dom, editorRect = editorDOM.getBoundingClientRect(); 18845 let scaleX = editorRect.width / editorDOM.offsetWidth, scaleY = editorRect.height / editorDOM.offsetHeight; 18846 if (isBlock) { 18847 let before = $pos.nodeBefore, after = $pos.nodeAfter; 18848 if (before || after) { 18849 let node = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0)); 18850 if (node) { 18851 let nodeRect = node.getBoundingClientRect(); 18852 let top = before ? nodeRect.bottom : nodeRect.top; 18853 if (before && after) top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2; 18854 let halfWidth = this.width / 2 * scaleY; 18855 rect = { 18856 left: nodeRect.left, 18857 right: nodeRect.right, 18858 top: top - halfWidth, 18859 bottom: top + halfWidth 18860 }; 18861 } 18862 } 18863 } 18864 if (!rect) { 18865 let coords = this.editorView.coordsAtPos(this.cursorPos); 18866 let halfWidth = this.width / 2 * scaleX; 18867 rect = { 18868 left: coords.left - halfWidth, 18869 right: coords.left + halfWidth, 18870 top: coords.top, 18871 bottom: coords.bottom 18872 }; 18873 } 18874 let parent = this.editorView.dom.offsetParent; 18875 if (!this.element) { 18876 this.element = parent.appendChild(document.createElement("div")); 18877 if (this.class) this.element.className = this.class; 18878 this.element.style.cssText = "position: absolute; z-index: 50; pointer-events: none;"; 18879 if (this.color) this.element.style.backgroundColor = this.color; 18880 } 18881 this.element.classList.toggle("prosemirror-dropcursor-block", isBlock); 18882 this.element.classList.toggle("prosemirror-dropcursor-inline", !isBlock); 18883 let parentLeft, parentTop; 18884 if (!parent || parent == document.body && getComputedStyle(parent).position == "static") { 18885 parentLeft = -pageXOffset; 18886 parentTop = -pageYOffset; 18887 } else { 18888 let rect$1 = parent.getBoundingClientRect(); 18889 let parentScaleX = rect$1.width / parent.offsetWidth, parentScaleY = rect$1.height / parent.offsetHeight; 18890 parentLeft = rect$1.left - parent.scrollLeft * parentScaleX; 18891 parentTop = rect$1.top - parent.scrollTop * parentScaleY; 18892 } 18893 this.element.style.left = (rect.left - parentLeft) / scaleX + "px"; 18894 this.element.style.top = (rect.top - parentTop) / scaleY + "px"; 18895 this.element.style.width = (rect.right - rect.left) / scaleX + "px"; 18896 this.element.style.height = (rect.bottom - rect.top) / scaleY + "px"; 18897 } 18898 scheduleRemoval(timeout) { 18899 clearTimeout(this.timeout); 18900 this.timeout = setTimeout(() => this.setCursor(null), timeout); 18901 } 18902 computeTarget(event) { 18903 let pos = this.editorView.posAtCoords({ 18904 left: event.clientX, 18905 top: event.clientY 18906 }); 18907 let node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside); 18908 let disableDropCursor = node && node.type.spec.disableDropCursor; 18909 let disabled = typeof disableDropCursor == "function" ? disableDropCursor(this.editorView, pos, event) : disableDropCursor; 18910 if (!pos || disabled) return null; 18911 let target = pos.pos; 18912 if (this.editorView.dragging && this.editorView.dragging.slice) { 18913 let point = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice); 18914 if (point != null) target = point; 18915 } 18916 return target; 18917 } 18918 dragover(event) { 18919 if (!this.editorView.editable) return; 18920 this.lastDragEvent = event; 18921 let target = this.computeTarget(event); 18922 if (target != null) { 18923 this.setCursor(target); 18924 this.scheduleRemoval(5e3); 18925 } 18926 } 18927 dragend() { 18928 this.scheduleRemoval(20); 18929 } 18930 drop() { 18931 this.scheduleRemoval(20); 18932 } 18933 dragleave(event) { 18934 if (!this.editorView.dom.contains(event.relatedTarget)) this.setCursor(null); 18935 } 18936}; 18937var GapCursor = class GapCursor extends Selection$1 { 18938 constructor($pos) { 18939 super($pos, $pos); 18940 } 18941 map(doc$2, mapping) { 18942 let $pos = doc$2.resolve(mapping.map(this.head)); 18943 return GapCursor.valid($pos) ? new GapCursor($pos) : Selection$1.near($pos); 18944 } 18945 content() { 18946 return Slice.empty; 18947 } 18948 eq(other) { 18949 return other instanceof GapCursor && other.head == this.head; 18950 } 18951 toJSON() { 18952 return { 18953 type: "gapcursor", 18954 pos: this.head 18955 }; 18956 } 18957 static fromJSON(doc$2, json) { 18958 if (typeof json.pos != "number") throw new RangeError("Invalid input for GapCursor.fromJSON"); 18959 return new GapCursor(doc$2.resolve(json.pos)); 18960 } 18961 getBookmark() { 18962 return new GapBookmark(this.anchor); 18963 } 18964 static valid($pos) { 18965 let parent = $pos.parent; 18966 if (parent.inlineContent || !closedBefore($pos) || !closedAfter($pos)) return false;
vendor: 4,109 bytes, lines 18967-19092
18967 let override = parent.type.spec.allowGapCursor; 18968 if (override != null) return override; 18969 let deflt = parent.contentMatchAt($pos.index()).defaultType; 18970 return deflt && deflt.isTextblock; 18971 } 18972 static findGapCursorFrom($pos, dir, mustMove = false) { 18973 search: for (;;) { 18974 if (!mustMove && GapCursor.valid($pos)) return $pos; 18975 let pos = $pos.pos, next = null; 18976 for (let d = $pos.depth;; d--) { 18977 let parent = $pos.node(d); 18978 if (dir > 0 ? $pos.indexAfter(d) < parent.childCount : $pos.index(d) > 0) { 18979 next = parent.child(dir > 0 ? $pos.indexAfter(d) : $pos.index(d) - 1); 18980 break; 18981 } else if (d == 0) return null; 18982 pos += dir; 18983 let $cur = $pos.doc.resolve(pos); 18984 if (GapCursor.valid($cur)) return $cur; 18985 } 18986 for (;;) { 18987 let inside = dir > 0 ? next.firstChild : next.lastChild; 18988 if (!inside) { 18989 if (next.isAtom && !next.isText && !NodeSelection.isSelectable(next)) { 18990 $pos = $pos.doc.resolve(pos + next.nodeSize * dir); 18991 mustMove = false; 18992 continue search; 18993 } 18994 break; 18995 } 18996 next = inside; 18997 pos += dir; 18998 let $cur = $pos.doc.resolve(pos); 18999 if (GapCursor.valid($cur)) return $cur; 19000 } 19001 return null; 19002 } 19003 } 19004}; 19005GapCursor.prototype.visible = false; 19006GapCursor.findFrom = GapCursor.findGapCursorFrom; 19007Selection$1.jsonID("gapcursor", GapCursor); 19008var GapBookmark = class GapBookmark { 19009 constructor(pos) { 19010 this.pos = pos; 19011 } 19012 map(mapping) { 19013 return new GapBookmark(mapping.map(this.pos)); 19014 } 19015 resolve(doc$2) { 19016 let $pos = doc$2.resolve(this.pos); 19017 return GapCursor.valid($pos) ? new GapCursor($pos) : Selection$1.near($pos); 19018 } 19019}; 19020function needsGap(type) { 19021 return type.isAtom || type.spec.isolating || type.spec.createGapCursor; 19022} 19023function closedBefore($pos) { 19024 for (let d = $pos.depth; d >= 0; d--) { 19025 let index = $pos.index(d), parent = $pos.node(d); 19026 if (index == 0) { 19027 if (parent.type.spec.isolating) return true; 19028 continue; 19029 } 19030 for (let before = parent.child(index - 1);; before = before.lastChild) { 19031 if (before.childCount == 0 && !before.inlineContent || needsGap(before.type)) return true; 19032 if (before.inlineContent) return false; 19033 } 19034 } 19035 return true; 19036} 19037function closedAfter($pos) { 19038 for (let d = $pos.depth; d >= 0; d--) { 19039 let index = $pos.indexAfter(d), parent = $pos.node(d); 19040 if (index == parent.childCount) { 19041 if (parent.type.spec.isolating) return true; 19042 continue; 19043 } 19044 for (let after = parent.child(index);; after = after.firstChild) { 19045 if (after.childCount == 0 && !after.inlineContent || needsGap(after.type)) return true; 19046 if (after.inlineContent) return false; 19047 } 19048 } 19049 return true; 19050} 19051function gapCursor() { 19052 return new Plugin({ props: { 19053 decorations: drawGapCursor, 19054 createSelectionBetween(_view, $anchor, $head) { 19055 return $anchor.pos == $head.pos && GapCursor.valid($head) ? new GapCursor($head) : null; 19056 }, 19057 handleClick, 19058 handleKeyDown, 19059 handleDOMEvents: { beforeinput } 19060 } }); 19061} 19062var handleKeyDown = keydownHandler({ 19063 "ArrowLeft": arrow("horiz", -1), 19064 "ArrowRight": arrow("horiz", 1), 19065 "ArrowUp": arrow("vert", -1), 19066 "ArrowDown": arrow("vert", 1) 19067}); 19068function arrow(axis, dir) { 19069 const dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left"; 19070 return function(state, dispatch, view) { 19071 let sel = state.selection; 19072 let $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty; 19073 if (sel instanceof TextSelection) { 19074 if (!view.endOfTextblock(dirStr) || $start.depth == 0) return false; 19075 mustMove = false; 19076 $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before()); 19077 } 19078 let $found = GapCursor.findGapCursorFrom($start, dir, mustMove); 19079 if (!$found) return false; 19080 if (dispatch) dispatch(state.tr.setSelection(new GapCursor($found))); 19081 return true; 19082 }; 19083} 19084function handleClick(view, pos, event) { 19085 if (!view || !view.editable) return false; 19086 let $pos = view.state.doc.resolve(pos); 19087 if (!GapCursor.valid($pos)) return false; 19088 let clickPos = view.posAtCoords({ 19089 left: event.clientX, 19090 top: event.clientY 19091 }); 19092 if (clickPos && clickPos.inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(clickPos.inside))) return false;
19093 view.dispatch(view.state.tr.setSelection(new GapCursor($pos))); 19094 return true; 19095} 19096function beforeinput(view, event) { 19097 if (event.inputType != "insertCompositionText" || !(view.state.selection instanceof GapCursor)) return false; 19098 let { $from } = view.state.selection; 19099 let insert = $from.parent.contentMatchAt($from.index()).findWrapping(view.state.schema.nodes.text); 19100 if (!insert) return false; 19101 let frag = Fragment.empty; 19102 for (let i$1 = insert.length - 1; i$1 >= 0; i$1--) frag = Fragment.from(insert[i$1].createAndFill(null, frag)); 19103 let tr$1 = view.state.tr.replace($from.pos, $from.pos, new Slice(frag, 0, 0)); 19104 tr$1.setSelection(TextSelection.near(tr$1.doc.resolve($from.pos + 1))); 19105 view.dispatch(tr$1); 19106 return false; 19107} 19108function drawGapCursor(state) { 19109 if (!(state.selection instanceof GapCursor)) return null; 19110 let node = document.createElement("div"); 19111 node.className = "ProseMirror-gapcursor"; 19112 return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node, { key: "gapcursor" })]); 19113} 19114var GOOD_LEAF_SIZE = 200; 19115var RopeSequence = function RopeSequence$1() {}; 19116RopeSequence.prototype.append = function append(other) { 19117 if (!other.length) return this; 19118 other = RopeSequence.from(other); 19119 return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other); 19120}; 19121RopeSequence.prototype.prepend = function prepend(other) { 19122 if (!other.length) return this; 19123 return RopeSequence.from(other).append(this); 19124}; 19125RopeSequence.prototype.appendInner = function appendInner(other) { 19126 return new Append(this, other); 19127}; 19128RopeSequence.prototype.slice = function slice(from, to) { 19129 if (from === void 0) from = 0; 19130 if (to === void 0) to = this.length; 19131 if (from >= to) return RopeSequence.empty; 19132 return this.sliceInner(Math.max(0, from), Math.min(this.length, to)); 19133}; 19134RopeSequence.prototype.get = function get(i$1) { 19135 if (i$1 < 0 || i$1 >= this.length) return; 19136 return this.getInner(i$1); 19137}; 19138RopeSequence.prototype.forEach = function forEach$1(f, from, to) { 19139 if (from === void 0) from = 0; 19140 if (to === void 0) to = this.length; 19141 if (from <= to) this.forEachInner(f, from, to, 0); 19142 else this.forEachInvertedInner(f, from, to, 0); 19143}; 19144RopeSequence.prototype.map = function map(f, from, to) { 19145 if (from === void 0) from = 0; 19146 if (to === void 0) to = this.length; 19147 var result = []; 19148 this.forEach(function(elt, i$1) { 19149 return result.push(f(elt, i$1)); 19150 }, from, to); 19151 return result; 19152}; 19153RopeSequence.from = function from(values) { 19154 if (values instanceof RopeSequence) return values; 19155 return values && values.length ? new Leaf(values) : RopeSequence.empty; 19156}; 19157var Leaf = /* @__PURE__ */ function(RopeSequence$1) { 19158 function Leaf$1(values) { 19159 RopeSequence$1.call(this); 19160 this.values = values; 19161 } 19162 if (RopeSequence$1) Leaf$1.__proto__ = RopeSequence$1; 19163 Leaf$1.prototype = Object.create(RopeSequence$1 && RopeSequence$1.prototype); 19164 Leaf$1.prototype.constructor = Leaf$1; 19165 var prototypeAccessors = { 19166 length: { configurable: true }, 19167 depth: { configurable: true } 19168 }; 19169 Leaf$1.prototype.flatten = function flatten() { 19170 return this.values; 19171 }; 19172 Leaf$1.prototype.sliceInner = function sliceInner(from, to) { 19173 if (from == 0 && to == this.length) return this; 19174 return new Leaf$1(this.values.slice(from, to)); 19175 }; 19176 Leaf$1.prototype.getInner = function getInner(i$1) { 19177 return this.values[i$1]; 19178 }; 19179 Leaf$1.prototype.forEachInner = function forEachInner(f, from, to, start) { 19180 for (var i$1 = from; i$1 < to; i$1++) if (f(this.values[i$1], start + i$1) === false) return false; 19181 }; 19182 Leaf$1.prototype.forEachInvertedInner = function forEachInvertedInner(f, from, to, start) { 19183 for (var i$1 = from - 1; i$1 >= to; i$1--) if (f(this.values[i$1], start + i$1) === false) return false; 19184 }; 19185 Leaf$1.prototype.leafAppend = function leafAppend(other) { 19186 if (this.length + other.length <= GOOD_LEAF_SIZE) return new Leaf$1(this.values.concat(other.flatten())); 19187 }; 19188 Leaf$1.prototype.leafPrepend = function leafPrepend(other) { 19189 if (this.length + other.length <= GOOD_LEAF_SIZE) return new Leaf$1(other.flatten().concat(this.values)); 19190 }; 19191 prototypeAccessors.length.get = function() { 19192 return this.values.length; 19193 }; 19194 prototypeAccessors.depth.get = function() { 19195 return 0; 19196 }; 19197 Object.defineProperties(Leaf$1.prototype, prototypeAccessors); 19198 return Leaf$1; 19199}(RopeSequence); 19200RopeSequence.empty = new Leaf([]); 19201var Append = /* @__PURE__ */ function(RopeSequence$1) { 19202 function Append$1(left, right) { 19203 RopeSequence$1.call(this); 19204 this.left = left; 19205 this.right = right; 19206 this.length = left.length + right.length; 19207 this.depth = Math.max(left.depth, right.depth) + 1; 19208 } 19209 if (RopeSequence$1) Append$1.__proto__ = RopeSequence$1; 19210 Append$1.prototype = Object.create(RopeSequence$1 && RopeSequence$1.prototype); 19211 Append$1.prototype.constructor = Append$1; 19212 Append$1.prototype.flatten = function flatten() { 19213 return this.left.flatten().concat(this.right.flatten()); 19214 }; 19215 Append$1.prototype.getInner = function getInner(i$1) { 19216 return i$1 < this.left.length ? this.left.get(i$1) : this.right.get(i$1 - this.left.length); 19217 }; 19218 Append$1.prototype.forEachInner = function forEachInner(f, from, to, start) { 19219 var leftLen = this.left.length; 19220 if (from < leftLen && this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false) return false;
19221 if (to > leftLen && this.right.forEachInner(f, Math.max(from - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false) return false; 19222 }; 19223 Append$1.prototype.forEachInvertedInner = function forEachInvertedInner(f, from, to, start) { 19224 var leftLen = this.left.length; 19225 if (from > leftLen && this.right.forEachInvertedInner(f, from - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false) return false; 19226 if (to < leftLen && this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false) return false; 19227 }; 19228 Append$1.prototype.sliceInner = function sliceInner(from, to) { 19229 if (from == 0 && to == this.length) return this; 19230 var leftLen = this.left.length; 19231 if (to <= leftLen) return this.left.slice(from, to); 19232 if (from >= leftLen) return this.right.slice(from - leftLen, to - leftLen); 19233 return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen)); 19234 }; 19235 Append$1.prototype.leafAppend = function leafAppend(other) { 19236 var inner = this.right.leafAppend(other); 19237 if (inner) return new Append$1(this.left, inner); 19238 }; 19239 Append$1.prototype.leafPrepend = function leafPrepend(other) { 19240 var inner = this.left.leafPrepend(other); 19241 if (inner) return new Append$1(inner, this.right); 19242 }; 19243 Append$1.prototype.appendInner = function appendInner(other) { 19244 if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1) return new Append$1(this.left, new Append$1(this.right, other)); 19245 return new Append$1(this, other); 19246 }; 19247 return Append$1; 19248}(RopeSequence); 19249var dist_default = RopeSequence; 19250var max_empty_items = 500; 19251var Branch = class Branch { 19252 constructor(items, eventCount) { 19253 this.items = items; 19254 this.eventCount = eventCount; 19255 } 19256 popEvent(state, preserveItems) { 19257 if (this.eventCount == 0) return null; 19258 let end = this.items.length; 19259 for (;; end--) if (this.items.get(end - 1).selection) { 19260 --end; 19261 break; 19262 } 19263 let remap, mapFrom; 19264 if (preserveItems) { 19265 remap = this.remapping(end, this.items.length); 19266 mapFrom = remap.maps.length; 19267 } 19268 let transform = state.tr; 19269 let selection, remaining; 19270 let addAfter = [], addBefore = []; 19271 this.items.forEach((item, i$1) => { 19272 if (!item.step) { 19273 if (!remap) { 19274 remap = this.remapping(end, i$1 + 1); 19275 mapFrom = remap.maps.length; 19276 } 19277 mapFrom--; 19278 addBefore.push(item); 19279 return; 19280 } 19281 if (remap) { 19282 addBefore.push(new Item(item.map)); 19283 let step = item.step.map(remap.slice(mapFrom)), map; 19284 if (step && transform.maybeStep(step).doc) { 19285 map = transform.mapping.maps[transform.mapping.maps.length - 1]; 19286 addAfter.push(new Item(map, void 0, void 0, addAfter.length + addBefore.length)); 19287 } 19288 mapFrom--; 19289 if (map) remap.appendMap(map, mapFrom); 19290 } else transform.maybeStep(item.step); 19291 if (item.selection) { 19292 selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection; 19293 remaining = new Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1); 19294 return false; 19295 } 19296 }, this.items.length, 0); 19297 return { 19298 remaining, 19299 transform, 19300 selection 19301 }; 19302 } 19303 addTransform(transform, selection, histOptions, preserveItems) { 19304 let newItems = [], eventCount = this.eventCount; 19305 let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null; 19306 for (let i$1 = 0; i$1 < transform.steps.length; i$1++) { 19307 let step = transform.steps[i$1].invert(transform.docs[i$1]); 19308 let item = new Item(transform.mapping.maps[i$1], step, selection), merged; 19309 if (merged = lastItem && lastItem.merge(item)) { 19310 item = merged; 19311 if (i$1) newItems.pop(); 19312 else oldItems = oldItems.slice(0, oldItems.length - 1); 19313 } 19314 newItems.push(item); 19315 if (selection) { 19316 eventCount++; 19317 selection = void 0; 19318 } 19319 if (!preserveItems) lastItem = item; 19320 } 19321 let overflow = eventCount - histOptions.depth; 19322 if (overflow > DEPTH_OVERFLOW) { 19323 oldItems = cutOffEvents(oldItems, overflow); 19324 eventCount -= overflow; 19325 } 19326 return new Branch(oldItems.append(newItems), eventCount); 19327 } 19328 remapping(from, to) { 19329 let maps = new Mapping();
19330 this.items.forEach((item, i$1) => { 19331 let mirrorPos = item.mirrorOffset != null && i$1 - item.mirrorOffset >= from ? maps.maps.length - item.mirrorOffset : void 0; 19332 maps.appendMap(item.map, mirrorPos); 19333 }, from, to); 19334 return maps; 19335 } 19336 addMaps(array) { 19337 if (this.eventCount == 0) return this; 19338 return new Branch(this.items.append(array.map((map) => new Item(map))), this.eventCount); 19339 } 19340 rebased(rebasedTransform, rebasedCount) { 19341 if (!this.eventCount) return this; 19342 let rebasedItems = [], start = Math.max(0, this.items.length - rebasedCount); 19343 let mapping = rebasedTransform.mapping; 19344 let newUntil = rebasedTransform.steps.length; 19345 let eventCount = this.eventCount; 19346 this.items.forEach((item) => { 19347 if (item.selection) eventCount--; 19348 }, start); 19349 let iRebased = rebasedCount; 19350 this.items.forEach((item) => { 19351 let pos = mapping.getMirror(--iRebased); 19352 if (pos == null) return; 19353 newUntil = Math.min(newUntil, pos); 19354 let map = mapping.maps[pos]; 19355 if (item.step) { 19356 let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]); 19357 let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos)); 19358 if (selection) eventCount++; 19359 rebasedItems.push(new Item(map, step, selection)); 19360 } else rebasedItems.push(new Item(map)); 19361 }, start); 19362 let newMaps = []; 19363 for (let i$1 = rebasedCount; i$1 < newUntil; i$1++) newMaps.push(new Item(mapping.maps[i$1])); 19364 let branch = new Branch(this.items.slice(0, start).append(newMaps).append(rebasedItems), eventCount); 19365 if (branch.emptyItemCount() > max_empty_items) branch = branch.compress(this.items.length - rebasedItems.length); 19366 return branch; 19367 } 19368 emptyItemCount() { 19369 let count = 0; 19370 this.items.forEach((item) => { 19371 if (!item.step) count++; 19372 }); 19373 return count; 19374 } 19375 compress(upto = this.items.length) { 19376 let remap = this.remapping(0, upto), mapFrom = remap.maps.length; 19377 let items = [], events = 0; 19378 this.items.forEach((item, i$1) => { 19379 if (i$1 >= upto) { 19380 items.push(item); 19381 if (item.selection) events++; 19382 } else if (item.step) { 19383 let step = item.step.map(remap.slice(mapFrom)), map = step && step.getMap(); 19384 mapFrom--; 19385 if (map) remap.appendMap(map, mapFrom); 19386 if (step) { 19387 let selection = item.selection && item.selection.map(remap.slice(mapFrom)); 19388 if (selection) events++; 19389 let newItem = new Item(map.invert(), step, selection), merged, last = items.length - 1; 19390 if (merged = items.length && items[last].merge(newItem)) items[last] = merged; 19391 else items.push(newItem); 19392 } 19393 } else if (item.map) mapFrom--; 19394 }, this.items.length, 0); 19395 return new Branch(dist_default.from(items.reverse()), events); 19396 } 19397}; 19398Branch.empty = new Branch(dist_default.empty, 0); 19399function cutOffEvents(items, n) { 19400 let cutPoint; 19401 items.forEach((item, i$1) => { 19402 if (item.selection && n-- == 0) { 19403 cutPoint = i$1; 19404 return false; 19405 } 19406 }); 19407 return items.slice(cutPoint); 19408} 19409var Item = class Item { 19410 constructor(map, step, selection, mirrorOffset) { 19411 this.map = map; 19412 this.step = step; 19413 this.selection = selection; 19414 this.mirrorOffset = mirrorOffset; 19415 } 19416 merge(other) { 19417 if (this.step && other.step && !other.selection) { 19418 let step = other.step.merge(this.step); 19419 if (step) return new Item(step.getMap().invert(), step, this.selection); 19420 } 19421 } 19422}; 19423var HistoryState = class { 19424 constructor(done, undone, prevRanges, prevTime, prevComposition) { 19425 this.done = done; 19426 this.undone = undone; 19427 this.prevRanges = prevRanges; 19428 this.prevTime = prevTime; 19429 this.prevComposition = prevComposition; 19430 } 19431}; 19432var DEPTH_OVERFLOW = 20; 19433function applyTransaction(history$1, state, tr$1, options) { 19434 let historyTr = tr$1.getMeta(historyKey), rebased; 19435 if (historyTr) return historyTr.historyState; 19436 if (tr$1.getMeta(closeHistoryKey)) history$1 = new HistoryState(history$1.done, history$1.undone, null, 0, -1); 19437 let appended = tr$1.getMeta("appendedTransaction"); 19438 if (tr$1.steps.length == 0) return history$1; 19439 else if (appended && appended.getMeta(historyKey)) if (appended.getMeta(historyKey).redo) return new HistoryState(history$1.done.addTransform(tr$1, void 0, options, mustPreserveItems(state)), history$1.undone, rangesFor(tr$1.mapping.maps), history$1.prevTime, history$1.prevComposition); 19440 else return new HistoryState(history$1.done, history$1.undone.addTransform(tr$1, void 0, options, mustPreserveItems(state)), null, history$1.prevTime, history$1.prevComposition); 19441 else if (tr$1.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) { 19442 let composition = tr$1.getMeta("composition"); 19443 let newGroup = history$1.prevTime == 0 || !appended && history$1.prevComposition != composition && (history$1.prevTime < (tr$1.time || 0) - options.newGroupDelay || !isAdjacentTo(tr$1, history$1.prevRanges)); 19444 let prevRanges = appended ? mapRanges(history$1.prevRanges, tr$1.mapping) : rangesFor(tr$1.mapping.maps); 19445 return new HistoryState(history$1.done.addTransform(tr$1, newGroup ? state.selection.getBookmark() : void 0, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr$1.time, composition == null ? history$1.prevComposition : composition); 19446 } else if (rebased = tr$1.getMeta("rebased")) return new HistoryState(history$1.done.rebased(tr$1, rebased), history$1.undone.rebased(tr$1, rebased), mapRanges(history$1.prevRanges, tr$1.mapping), history$1.prevTime, history$1.prevComposition); 19447 else return new HistoryState(history$1.done.addMaps(tr$1.mapping.maps), history$1.undone.addMaps(tr$1.mapping.maps), mapRanges(history$1.prevRanges, tr$1.mapping), history$1.prevTime, history$1.prevComposition); 19448} 19449function isAdjacentTo(transform, prevRanges) { 19450 if (!prevRanges) return false;
19451 if (!transform.docChanged) return true; 19452 let adjacent = false; 19453 transform.mapping.maps[0].forEach((start, end) => { 19454 for (let i$1 = 0; i$1 < prevRanges.length; i$1 += 2) if (start <= prevRanges[i$1 + 1] && end >= prevRanges[i$1]) adjacent = true; 19455 }); 19456 return adjacent; 19457} 19458function rangesFor(maps) { 19459 let result = []; 19460 for (let i$1 = maps.length - 1; i$1 >= 0 && result.length == 0; i$1--) maps[i$1].forEach((_from, _to, from, to) => result.push(from, to)); 19461 return result; 19462} 19463function mapRanges(ranges, mapping) { 19464 if (!ranges) return null; 19465 let result = []; 19466 for (let i$1 = 0; i$1 < ranges.length; i$1 += 2) { 19467 let from = mapping.map(ranges[i$1], 1), to = mapping.map(ranges[i$1 + 1], -1); 19468 if (from <= to) result.push(from, to); 19469 } 19470 return result; 19471} 19472function histTransaction(history$1, state, redo$1) { 19473 let preserveItems = mustPreserveItems(state); 19474 let histOptions = historyKey.get(state).spec.config; 19475 let pop = (redo$1 ? history$1.undone : history$1.done).popEvent(state, preserveItems); 19476 if (!pop) return null; 19477 let selection = pop.selection.resolve(pop.transform.doc); 19478 let added = (redo$1 ? history$1.done : history$1.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems); 19479 let newHist = new HistoryState(redo$1 ? added : pop.remaining, redo$1 ? pop.remaining : added, null, 0, -1); 19480 return pop.transform.setSelection(selection).setMeta(historyKey, { 19481 redo: redo$1, 19482 historyState: newHist 19483 }); 19484} 19485var cachedPreserveItems = false, cachedPreserveItemsPlugins = null; 19486function mustPreserveItems(state) { 19487 let plugins = state.plugins; 19488 if (cachedPreserveItemsPlugins != plugins) { 19489 cachedPreserveItems = false; 19490 cachedPreserveItemsPlugins = plugins; 19491 for (let i$1 = 0; i$1 < plugins.length; i$1++) if (plugins[i$1].spec.historyPreserveItems) { 19492 cachedPreserveItems = true; 19493 break; 19494 } 19495 } 19496 return cachedPreserveItems; 19497} 19498var historyKey = new PluginKey("history"); 19499var closeHistoryKey = new PluginKey("closeHistory"); 19500function history(config = {}) { 19501 config = { 19502 depth: config.depth || 100, 19503 newGroupDelay: config.newGroupDelay || 500 19504 }; 19505 return new Plugin({ 19506 key: historyKey, 19507 state: { 19508 init() { 19509 return new HistoryState(Branch.empty, Branch.empty, null, 0, -1); 19510 }, 19511 apply(tr$1, hist, state) { 19512 return applyTransaction(hist, state, tr$1, config); 19513 } 19514 }, 19515 config, 19516 props: { handleDOMEvents: { beforeinput(view, e) { 19517 let inputType = e.inputType; 19518 let command$1 = inputType == "historyUndo" ? undo : inputType == "historyRedo" ? redo : null; 19519 if (!command$1 || !view.editable) return false; 19520 e.preventDefault(); 19521 return command$1(view.state, view.dispatch); 19522 } } } 19523 }); 19524} 19525function buildCommand(redo$1, scroll) { 19526 return (state, dispatch) => { 19527 let hist = historyKey.getState(state); 19528 if (!hist || (redo$1 ? hist.undone : hist.done).eventCount == 0) return false; 19529 if (dispatch) { 19530 let tr$1 = histTransaction(hist, state, redo$1); 19531 if (tr$1) dispatch(scroll ? tr$1.scrollIntoView() : tr$1); 19532 } 19533 return true; 19534 }; 19535} 19536var undo = buildCommand(false, true); 19537var redo = buildCommand(true, true); 19538buildCommand(false, false); 19539buildCommand(true, false); 19540Extension.create({ 19541 name: "characterCount", 19542 addOptions() { 19543 return { 19544 limit: null, 19545 autoTrim: true, 19546 mode: "textSize", 19547 textCounter: (text$1) => text$1.length, 19548 wordCounter: (text$1) => text$1.split(" ").filter((word) => word !== "").length 19549 }; 19550 }, 19551 addStorage() { 19552 return { 19553 characters: () => 0, 19554 words: () => 0 19555 }; 19556 }, 19557 onBeforeCreate() { 19558 this.storage.characters = (options) => { 19559 const node = (options === null || options === void 0 ? void 0 : options.node) || this.editor.state.doc; 19560 if (((options === null || options === void 0 ? void 0 : options.mode) || this.options.mode) === "textSize") { 19561 const text$1 = node.textBetween(0, node.content.size, void 0, " "); 19562 return this.options.textCounter(text$1); 19563 } 19564 return node.nodeSize; 19565 }; 19566 this.storage.words = (options) => { 19567 const node = (options === null || options === void 0 ? void 0 : options.node) || this.editor.state.doc; 19568 const text$1 = node.textBetween(0, node.content.size, " ", " "); 19569 return this.options.wordCounter(text$1); 19570 }; 19571 }, 19572 addProseMirrorPlugins() { 19573 let initialEvaluationDone = false;
19574 return [new Plugin({ 19575 key: new PluginKey("characterCount"), 19576 appendTransaction: (transactions, oldState, newState) => { 19577 if (initialEvaluationDone) return; 19578 const limit = this.options.limit; 19579 const autoTrim = this.options.autoTrim; 19580 if (limit === null || limit === void 0 || limit === 0 || autoTrim === false) { 19581 initialEvaluationDone = true; 19582 return; 19583 } 19584 const initialContentSize = this.storage.characters({ node: newState.doc }); 19585 if (initialContentSize > limit) { 19586 const over = initialContentSize - limit; 19587 const from = 0; 19588 const to = over; 19589 console.warn(`[CharacterCount] Initial content exceeded limit of ${limit} characters. Content was automatically trimmed.`); 19590 const tr$1 = newState.tr.deleteRange(from, to); 19591 initialEvaluationDone = true; 19592 return tr$1; 19593 } 19594 initialEvaluationDone = true; 19595 }, 19596 filterTransaction: (transaction, state) => { 19597 const limit = this.options.limit; 19598 if (!transaction.docChanged || limit === 0 || limit === null || limit === void 0) return true; 19599 const oldSize = this.storage.characters({ node: state.doc }); 19600 const newSize = this.storage.characters({ node: transaction.doc }); 19601 if (newSize <= limit) return true; 19602 if (oldSize > limit && newSize > limit && newSize <= oldSize) return true; 19603 if (oldSize > limit && newSize > limit && newSize > oldSize) return false; 19604 if (!transaction.getMeta("paste")) return false; 19605 const pos = transaction.selection.$head.pos; 19606 const from = pos - (newSize - limit); 19607 const to = pos; 19608 transaction.deleteRange(from, to); 19609 if (this.storage.characters({ node: transaction.doc }) > limit) return false; 19610 return true; 19611 } 19612 })]; 19613 } 19614}); 19615var Dropcursor = Extension.create({ 19616 name: "dropCursor", 19617 addOptions() { 19618 return { 19619 color: "currentColor", 19620 width: 1, 19621 class: void 0 19622 }; 19623 }, 19624 addProseMirrorPlugins() { 19625 return [dropCursor(this.options)]; 19626 } 19627}); 19628Extension.create({ 19629 name: "focus", 19630 addOptions() { 19631 return { 19632 className: "has-focus", 19633 mode: "all" 19634 }; 19635 }, 19636 addProseMirrorPlugins() { 19637 return [new Plugin({ 19638 key: new PluginKey("focus"), 19639 props: { decorations: ({ doc: doc$2, selection }) => { 19640 const { isEditable, isFocused } = this.editor; 19641 const { anchor } = selection; 19642 const decorations = []; 19643 if (!isEditable || !isFocused) return DecorationSet.create(doc$2, []); 19644 let maxLevels = 0; 19645 if (this.options.mode === "deepest") doc$2.descendants((node, pos) => { 19646 if (node.isText) return; 19647 if (!(anchor >= pos && anchor <= pos + node.nodeSize - 1)) return false; 19648 maxLevels += 1; 19649 }); 19650 let currentLevel = 0; 19651 doc$2.descendants((node, pos) => { 19652 if (node.isText) return false; 19653 if (!(anchor >= pos && anchor <= pos + node.nodeSize - 1)) return false; 19654 currentLevel += 1; 19655 if (this.options.mode === "deepest" && maxLevels - currentLevel > 0 || this.options.mode === "shallowest" && currentLevel > 1) return this.options.mode === "deepest"; 19656 decorations.push(Decoration.node(pos, pos + node.nodeSize, { class: this.options.className })); 19657 }); 19658 return DecorationSet.create(doc$2, decorations); 19659 } } 19660 })]; 19661 } 19662}); 19663var Gapcursor = Extension.create({ 19664 name: "gapCursor", 19665 addProseMirrorPlugins() { 19666 return [gapCursor()]; 19667 }, 19668 extendNodeSchema(extension) { 19669 var _callOrReturn; 19670 return { allowGapCursor: (_callOrReturn = callOrReturn(getExtensionField(extension, "allowGapCursor", { 19671 name: extension.name, 19672 options: extension.options, 19673 storage: extension.storage 19674 }))) !== null && _callOrReturn !== void 0 ? _callOrReturn : null }; 19675 } 19676}); 19677var DEFAULT_DATA_ATTRIBUTE = "placeholder"; 19678var PLUGIN_KEY = new PluginKey("tiptap__placeholder"); 19679function createPlaceholderDecoration(options) { 19680 const { editor, placeholder, dataAttribute, pos, node, isEmptyDoc, hasAnchor, classes: { emptyNode, emptyEditor } } = options; 19681 const classes = [emptyNode]; 19682 if (isEmptyDoc) classes.push(emptyEditor); 19683 return Decoration.node(pos, pos + node.nodeSize, { 19684 class: classes.join(" "), 19685 [dataAttribute]: typeof placeholder === "function" ? placeholder({ 19686 editor, 19687 node, 19688 pos, 19689 hasAnchor 19690 }) : placeholder 19691 }); 19692} 19693function resolveEmptyNodeClass(emptyNodeClass, props) { 19694 return typeof emptyNodeClass === "function" ? emptyNodeClass(props) : emptyNodeClass; 19695} 19696function scanRangeForDecorations({ editor, options, dataAttribute, doc: doc$2, selection, from, to }) { 19697 const { anchor } = selection; 19698 const decorations = []; 19699 const isEmptyDoc = editor.isEmpty; 19700 doc$2.nodesBetween(from, to, (node, pos) => { 19701 const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize; 19702 const isEmpty = !node.isLeaf && isNodeEmpty(node); 19703 if (!node.type.isTextblock) return options.includeChildren; 19704 if ((hasAnchor || !options.showOnlyCurrent) && isEmpty) decorations.push(createPlaceholderDecoration({ 19705 editor, 19706 isEmptyDoc, 19707 dataAttribute, 19708 hasAnchor, 19709 placeholder: options.placeholder, 19710 classes: { 19711 emptyEditor: options.emptyEditorClass, 19712 emptyNode: resolveEmptyNodeClass(options.emptyNodeClass, { 19713 editor, 19714 node, 19715 pos, 19716 hasAnchor 19717 }) 19718 }, 19719 node, 19720 pos 19721 })); 19722 return options.includeChildren; 19723 }); 19724 return decorations; 19725} 19726function buildPlaceholderDecorations({ editor, options, dataAttribute, doc: doc$2, selection }) { 19727 if (!(editor.isEditable || !options.showOnlyWhenEditable)) return null; 19728 const { anchor } = selection; 19729 const decorations = []; 19730 const isEmptyDoc = editor.isEmpty; 19731 if (options.showOnlyCurrent && !options.includeChildren) { 19732 const resolved = doc$2.resolve(anchor); 19733 const node = resolved.depth > 0 ? resolved.node(1) : resolved.nodeAfter; 19734 const nodeStart = resolved.depth > 0 ? resolved.before(1) : anchor; 19735 if (node && node.type.isTextblock && isNodeEmpty(node)) { 19736 const hasAnchor = anchor >= nodeStart && anchor <= nodeStart + node.nodeSize; 19737 decorations.push(createPlaceholderDecoration({ 19738 editor, 19739 isEmptyDoc, 19740 dataAttribute, 19741 hasAnchor, 19742 placeholder: options.placeholder, 19743 classes: { 19744 emptyEditor: options.emptyEditorClass, 19745 emptyNode: resolveEmptyNodeClass(options.emptyNodeClass, { 19746 editor, 19747 node, 19748 pos: nodeStart, 19749 hasAnchor 19750 }) 19751 }, 19752 node, 19753 pos: nodeStart 19754 })); 19755 } 19756 } else decorations.push(...scanRangeForDecorations({ 19757 editor, 19758 options, 19759 dataAttribute, 19760 doc: doc$2, 19761 selection, 19762 from: 0, 19763 to: doc$2.content.size 19764 })); 19765 return DecorationSet.create(doc$2, decorations); 19766} 19767function resolveTopLevelRange(doc$2, pos) { 19768 const resolved = doc$2.resolve(pos); 19769 if (resolved.depth === 0) { 19770 var _resolved$nodeAfter; 19771 const node = (_resolved$nodeAfter = resolved.nodeAfter) !== null && _resolved$nodeAfter !== void 0 ? _resolved$nodeAfter : resolved.nodeBefore; 19772 if (!node) return { 19773 from: pos, 19774 to: pos 19775 }; 19776 const nodePos = resolved.nodeAfter ? pos : pos - node.nodeSize; 19777 return { 19778 from: nodePos, 19779 to: nodePos + node.nodeSize 19780 }; 19781 } 19782 const topLevelPos = resolved.before(1); 19783 return { 19784 from: topLevelPos, 19785 to: topLevelPos + resolved.node(1).nodeSize 19786 }; 19787} 19788function toContentRelativeRange(doc$2, range) { 19789 return { 19790 from: Math.max(0, range.from - 1), 19791 to: Math.min(doc$2.content.size, range.to - 1) 19792 }; 19793} 19794function getTopLevelBlocksInRange(doc$2, from, to) { 19795 const ranges = []; 19796 doc$2.forEach((node, offset) => { 19797 const nodeStart = offset; 19798 const nodeEnd = nodeStart + node.nodeSize; 19799 const absNodeStart = nodeStart + 1; 19800 const absNodeEnd = nodeEnd + 1; 19801 if (absNodeStart < to && absNodeEnd > from) ranges.push({ 19802 from: nodeStart, 19803 to: nodeEnd 19804 }); 19805 }); 19806 return ranges; 19807} 19808function mergeRanges(ranges) { 19809 if (ranges.length === 0) return []; 19810 const sorted = [...ranges].sort((a, b) => a.from - b.from); 19811 const merged = [{ ...sorted[0] }]; 19812 for (let i$1 = 1; i$1 < sorted.length; i$1 += 1) { 19813 const last = merged[merged.length - 1]; 19814 const current = sorted[i$1]; 19815 if (current.from <= last.to) last.to = Math.max(last.to, current.to); 19816 else merged.push({ ...current }); 19817 } 19818 return merged; 19819} 19820function collectBlocksForChange(doc$2, change) { 19821 const ranges = getTopLevelBlocksInRange(doc$2, change.from, change.to); 19822 ranges.push(toContentRelativeRange(doc$2, resolveTopLevelRange(doc$2, change.from))); 19823 if (change.to > change.from) ranges.push(toContentRelativeRange(doc$2, resolveTopLevelRange(doc$2, Math.min(change.to, doc$2.content.size + 1) - 1))); 19824 else if (change.from < doc$2.content.size + 1) ranges.push(toContentRelativeRange(doc$2, resolveTopLevelRange(doc$2, Math.min(change.from + 1, doc$2.content.size)))); 19825 return ranges; 19826} 19827function collectRescanRanges(tr$1, oldState, newState) { 19828 const ranges = []; 19829 if (tr$1.docChanged) { 19830 const changes = getChangedRanges(tr$1); 19831 for (const change of changes) ranges.push(...collectBlocksForChange(newState.doc, change.newRange)); 19832 } 19833 if (tr$1.selectionSet) { 19834 ranges.push(toContentRelativeRange(newState.doc, resolveTopLevelRange(newState.doc, tr$1.mapping.map(oldState.selection.anchor)))); 19835 ranges.push(toContentRelativeRange(newState.doc, resolveTopLevelRange(newState.doc, newState.selection.anchor))); 19836 } 19837 return mergeRanges(ranges); 19838} 19839function clampRange(from, to, doc$2) { 19840 const clampedFrom = Math.max(0, Math.min(from, doc$2.content.size)); 19841 return { 19842 from: clampedFrom, 19843 to: Math.max(clampedFrom, Math.min(to, doc$2.content.size)) 19844 }; 19845} 19846function updateDecorationsInRanges({ decorations, ranges, editor, options, dataAttribute, doc: doc$2, selection }) { 19847 let next = decorations; 19848 for (const range of ranges) { 19849 const { from, to } = clampRange(range.from, range.to, doc$2); 19850 const existing = next.find(from, to).filter((decoration) => decoration.from >= from && decoration.to <= to); 19851 if (existing.length) next = next.remove(existing); 19852 const newDecos = scanRangeForDecorations({ 19853 editor, 19854 options, 19855 dataAttribute, 19856 doc: doc$2, 19857 selection, 19858 from, 19859 to 19860 }); 19861 if (newDecos.length) next = next.add(doc$2, newDecos); 19862 } 19863 return next; 19864} 19865function createPlaceholderStateField({ editor, options, dataAttribute }) { 19866 return { 19867 init(_config, state) { 19868 const decorations = buildPlaceholderDecorations({ 19869 editor, 19870 options, 19871 dataAttribute, 19872 doc: state.doc, 19873 selection: state.selection 19874 }); 19875 return decorations !== null && decorations !== void 0 ? decorations : DecorationSet.empty; 19876 }, 19877 apply(tr$1, prev, oldState, newState) { 19878 if (!tr$1.docChanged && !tr$1.selectionSet) return prev; 19879 return updateDecorationsInRanges({ 19880 decorations: prev.map(tr$1.mapping, tr$1.doc), 19881 ranges: collectRescanRanges(tr$1, oldState, newState), 19882 editor, 19883 options, 19884 dataAttribute, 19885 doc: newState.doc, 19886 selection: newState.selection 19887 }); 19888 } 19889 }; 19890} 19891function preparePlaceholderAttribute(attr) { 19892 return attr.replace(/\s+/g, "-").replace(/[^a-zA-Z0-9-]/g, "").replace(/^[0-9-]+/, "").replace(/^-+/, "").toLowerCase(); 19893} 19894function createPlaceholderPlugin({ editor, options }) { 19895 const dataAttribute = options.dataAttribute ? `data-${preparePlaceholderAttribute(options.dataAttribute)}` : `data-${DEFAULT_DATA_ATTRIBUTE}`; 19896 const useResolvedPath = options.showOnlyCurrent && !options.includeChildren; 19897 return new Plugin({ 19898 key: PLUGIN_KEY, 19899 ...useResolvedPath ? {} : { state: createPlaceholderStateField({ 19900 editor, 19901 options, 19902 dataAttribute 19903 }) }, 19904 props: { decorations: useResolvedPath ? ({ doc: doc$2, selection }) => buildPlaceholderDecorations({ 19905 editor, 19906 options, 19907 dataAttribute, 19908 doc: doc$2, 19909 selection 19910 }) : (state) => { 19911 var _PLUGIN_KEY$getState; 19912 if (options.showOnlyWhenEditable && !editor.isEditable) return DecorationSet.empty; 19913 return (_PLUGIN_KEY$getState = PLUGIN_KEY.getState(state)) !== null && _PLUGIN_KEY$getState !== void 0 ? _PLUGIN_KEY$getState : DecorationSet.empty; 19914 } } 19915 }); 19916} 19917Extension.create({ 19918 name: "placeholder", 19919 addOptions() { 19920 return { 19921 emptyEditorClass: "is-editor-empty", 19922 emptyNodeClass: "is-empty", 19923 dataAttribute: DEFAULT_DATA_ATTRIBUTE, 19924 placeholder: "Write something â¦", 19925 showOnlyWhenEditable: true, 19926 showOnlyCurrent: true, 19927 includeChildren: false 19928 }; 19929 }, 19930 addProseMirrorPlugins() { 19931 return [createPlaceholderPlugin({ 19932 editor: this.editor, 19933 options: this.options 19934 })]; 19935 } 19936}); 19937function shouldSyncDomSelection(state, editor) { 19938 return !state.selection.empty && !isNodeSelection(state.selection) && editor.isEditable; 19939} 19940function shouldPreserveSelection(state, editor) { 19941 return shouldSyncDomSelection(state, editor) && !editor.isFocused && !editor.view.dragging; 19942} 19943function clearDomSelection() { 19944 var _window$getSelection; 19945 (_window$getSelection = window.getSelection()) === null || _window$getSelection === void 0 || _window$getSelection.removeAllRanges(); 19946} 19947function restoreDomSelection(view) { 19948 view.focus(); 19949} 19950Extension.create({ 19951 name: "selection", 19952 addOptions() { 19953 return { className: "selection" }; 19954 }, 19955 addProseMirrorPlugins() { 19956 const { editor, options } = this; 19957 return [new Plugin({ 19958 key: new PluginKey("selection"), 19959 props: { 19960 decorations(state) { 19961 if (!shouldPreserveSelection(state, editor)) return null; 19962 return DecorationSet.create(state.doc, [Decoration.inline(state.selection.from, state.selection.to, { class: options.className })]); 19963 }, 19964 handleDOMEvents: { 19965 blur(view) { 19966 if (!shouldSyncDomSelection(view.state, editor)) return false;
19967 clearDomSelection(); 19968 return false; 19969 }, 19970 focus(view) { 19971 if (!shouldSyncDomSelection(view.state, editor)) return false; 19972 requestAnimationFrame(() => { 19973 if (!editor.isDestroyed && view.hasFocus()) restoreDomSelection(view); 19974 }); 19975 return false; 19976 } 19977 } 19978 } 19979 })]; 19980 } 19981}); 19982function nodeEqualsType({ types, node }) { 19983 return node && Array.isArray(types) && types.includes(node.type) || (node === null || node === void 0 ? void 0 : node.type) === types; 19984} 19985var TrailingNode = Extension.create({ 19986 name: "trailingNode", 19987 addOptions() { 19988 return { 19989 node: void 0, 19990 notAfter: [] 19991 }; 19992 }, 19993 addProseMirrorPlugins() { 19994 var _this$editor$schema$t; 19995 const plugin = new PluginKey(this.name); 19996 const defaultNode = this.options.node || ((_this$editor$schema$t = this.editor.schema.topNodeType.contentMatch.defaultType) === null || _this$editor$schema$t === void 0 ? void 0 : _this$editor$schema$t.name) || "paragraph"; 19997 const disabledNodes = Object.entries(this.editor.schema.nodes).map(([, value]) => value).filter((node) => (this.options.notAfter || []).concat(defaultNode).includes(node.name)); 19998 return [new Plugin({ 19999 key: plugin, 20000 appendTransaction: (transactions, __, state) => { 20001 const { doc: doc$2, tr: tr$1, schema } = state; 20002 const shouldInsertNodeAtEnd = plugin.getState(state); 20003 const endPosition = doc$2.content.size; 20004 const type = schema.nodes[defaultNode]; 20005 if (transactions.some((transaction) => transaction.getMeta("skipTrailingNode"))) return; 20006 if (!shouldInsertNodeAtEnd) return; 20007 return tr$1.insert(endPosition, type.create()); 20008 }, 20009 state: { 20010 init: (_, state) => { 20011 const lastNode = state.tr.doc.lastChild; 20012 return !nodeEqualsType({ 20013 node: lastNode, 20014 types: disabledNodes 20015 }); 20016 }, 20017 apply: (tr$1, value) => { 20018 if (!tr$1.docChanged) return value; 20019 if (tr$1.getMeta("__uniqueIDTransaction")) return value; 20020 const lastNode = tr$1.doc.lastChild; 20021 return !nodeEqualsType({ 20022 node: lastNode, 20023 types: disabledNodes 20024 }); 20025 } 20026 } 20027 })]; 20028 } 20029}); 20030var UndoRedo = Extension.create({ 20031 name: "undoRedo", 20032 addOptions() { 20033 return { 20034 depth: 100, 20035 newGroupDelay: 500 20036 }; 20037 }, 20038 addCommands() { 20039 return { 20040 undo: () => ({ state, dispatch }) => { 20041 return undo(state, dispatch); 20042 }, 20043 redo: () => ({ state, dispatch }) => { 20044 return redo(state, dispatch); 20045 } 20046 }; 20047 }, 20048 addProseMirrorPlugins() { 20049 return [history(this.options)]; 20050 }, 20051 addKeyboardShortcuts() { 20052 return { 20053 "Mod-z": () => this.editor.commands.undo(), 20054 "Shift-Mod-z": () => this.editor.commands.redo(), 20055 "Mod-y": () => this.editor.commands.redo(), 20056 "Mod-Ñ": () => this.editor.commands.undo(), 20057 "Shift-Mod-Ñ": () => this.editor.commands.redo() 20058 }; 20059 } 20060}); 20061var src_default$1 = Extension.create({ 20062 name: "starterKit", 20063 addExtensions() { 20064 const extensions = []; 20065 if (this.options.bold !== false) extensions.push(Bold$1.configure(this.options.bold)); 20066 if (this.options.blockquote !== false) extensions.push(Blockquote.configure(this.options.blockquote)); 20067 if (this.options.bulletList !== false) extensions.push(BulletList.configure(this.options.bulletList)); 20068 if (this.options.code !== false) extensions.push(Code.configure(this.options.code)); 20069 if (this.options.codeBlock !== false) extensions.push(CodeBlock.configure(this.options.codeBlock)); 20070 if (this.options.document !== false) extensions.push(Document.configure(this.options.document)); 20071 if (this.options.dropcursor !== false) extensions.push(Dropcursor.configure(this.options.dropcursor)); 20072 if (this.options.gapcursor !== false) extensions.push(Gapcursor.configure(this.options.gapcursor)); 20073 if (this.options.hardBreak !== false) extensions.push(HardBreak.configure(this.options.hardBreak)); 20074 if (this.options.heading !== false) extensions.push(Heading.configure(this.options.heading)); 20075 if (this.options.undoRedo !== false) extensions.push(UndoRedo.configure(this.options.undoRedo)); 20076 if (this.options.horizontalRule !== false) extensions.push(HorizontalRule.configure(this.options.horizontalRule)); 20077 if (this.options.italic !== false) extensions.push(Italic$1.configure(this.options.italic)); 20078 if (this.options.listItem !== false) extensions.push(ListItem.configure(this.options.listItem)); 20079 if (this.options.listKeymap !== false) { 20080 var _this$options; 20081 extensions.push(ListKeymap.configure((_this$options = this.options) === null || _this$options === void 0 ? void 0 : _this$options.listKeymap)); 20082 } 20083 if (this.options.link !== false) { 20084 var _this$options2; 20085 extensions.push(Link$2.configure((_this$options2 = this.options) === null || _this$options2 === void 0 ? void 0 : _this$options2.link)); 20086 } 20087 if (this.options.orderedList !== false) extensions.push(OrderedList.configure(this.options.orderedList)); 20088 if (this.options.paragraph !== false) extensions.push(Paragraph.configure(this.options.paragraph)); 20089 if (this.options.strike !== false) extensions.push(Strike.configure(this.options.strike)); 20090 if (this.options.text !== false) extensions.push(Text.configure(this.options.text)); 20091 if (this.options.underline !== false) { 20092 var _this$options3; 20093 extensions.push(Underline$1.configure((_this$options3 = this.options) === null || _this$options3 === void 0 ? void 0 : _this$options3.underline)); 20094 } 20095 if (this.options.trailingNode !== false) { 20096 var _this$options4; 20097 extensions.push(TrailingNode.configure((_this$options4 = this.options) === null || _this$options4 === void 0 ? void 0 : _this$options4.trailingNode)); 20098 } 20099 return extensions; 20100 } 20101}); 20102function ToolbarButton({ label, isActive: isActive$1, onClick, children }) { 20103 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { 20104 type: "button", 20105 variant: "ghost", 20106 size: "icon-mini", 20107 "aria-label": label, 20108 "aria-pressed": isActive$1, 20109 onClick, 20110 className: cn("h-7 w-7 text-zinc-600 hover:bg-zinc-100 hover:text-zinc-900", isActive$1 && "bg-zinc-200 text-zinc-900"), 20111 children 20112 }); 20113} 20114function normalizeHref(raw) { 20115 const href = raw.trim(); 20116 if (!href) return null; 20117 if (/^(javascript|data|vbscript):/i.test(href)) return null; 20118 if (/^(https?:\/\/|\/|#)/i.test(href)) return href; 20119 return `https://${href}`; 20120} 20121function LinkControl({ editor }) { 20122 const [open, setOpen] = import_react.useState(false); 20123 const [href, setHref] = import_react.useState(""); 20124 import_react.useEffect(() => { 20125 if (!open) return; 20126 setHref(editor.getAttributes("link").href ?? ""); 20127 }, [editor, open]); 20128 function applyLink() { 20129 const next = normalizeHref(href); 20130 if (!next) editor.chain().focus().extendMarkRange("link").unsetLink().run(); 20131 else editor.chain().focus().extendMarkRange("link").setLink({ href: next }).run(); 20132 setOpen(false); 20133 } 20134 function removeLink() { 20135 editor.chain().focus().extendMarkRange("link").unsetLink().run(); 20136 setOpen(false); 20137 } 20138 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Popover, { 20139 open, 20140 onOpenChange: setOpen, 20141 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(PopoverTrigger, { 20142 asChild: true, 20143 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { 20144 type: "button", 20145 variant: "ghost", 20146 size: "icon-mini", 20147 "aria-label": "Link", 20148 "aria-pressed": editor.isActive("link"), 20149 className: cn("h-7 w-7 text-zinc-600 hover:bg-zinc-100 hover:text-zinc-900", editor.isActive("link") && "bg-zinc-200 text-zinc-900"), 20150 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link$1, { className: "h-4 w-4" }) 20151 }) 20152 }
20152), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(PopoverContent, { 20153 className: "w-72 space-y-2 p-3", 20154 align: "start", 20155 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { 20156 "aria-label": "Link URL", 20157 placeholder: "https://", 20158 value: href, 20159 onChange: (event) => setHref(event.target.value), 20160 onKeyDown: (event) => { 20161 if (event.key === "Enter") { 20162 event.preventDefault(); 20163 applyLink(); 20164 } 20165 } 20166 }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 20167 className: "flex justify-end gap-2", 20168 children: [editor.isActive("link") ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { 20169 type: "button", 20170 variant: "outline", 20171 size: "sm", 20172 onClick: removeLink, 20173 children: "Remove" 20174 }) : null, /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { 20175 type: "button", 20176 size: "sm", 20177 onClick: applyLink, 20178 children: "Apply" 20179 })] 20180 })] 20181 })] 20182 }); 20183} 20184function RichEditorToolbar({ editor }) { 20185 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 20186 className: "flex flex-wrap items-center gap-0.5 border-b border-zinc-200 bg-zinc-50 px-2 py-1", 20187 children: [ 20188 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ToolbarButton, { 20189 label: "Bold", 20190 isActive: editor.isActive("bold"), 20191 onClick: () => editor.chain().focus().toggleBold().run(), 20192 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Bold, { className: "h-4 w-4" }) 20193 }), 20194 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ToolbarButton, { 20195 label: "Italic", 20196 isActive: editor.isActive("italic"), 20197 onClick: () => editor.chain().focus().toggleItalic().run(), 20198 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Italic, { className: "h-4 w-4" }) 20199 }), 20200 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ToolbarButton, { 20201 label: "Underline", 20202 isActive: editor.isActive("underline"), 20203 onClick: () => editor.chain().focus().toggleUnderline().run(), 20204 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Underline, { className: "h-4 w-4" }) 20205 }), 20206 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ToolbarButton, { 20207 label: "Bulleted list", 20208 isActive: editor.isActive("bulletList"), 20209 onClick: () => editor.chain().focus().toggleBulletList().run(), 20210 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(List, { className: "h-4 w-4" }) 20211 }), 20212 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ToolbarButton, { 20213 label: "Numbered list", 20214 isActive: editor.isActive("orderedList"), 20215 onClick: () => editor.chain().focus().toggleOrderedList().run(), 20216 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ListOrdered, { className: "h-4 w-4" }) 20217 }), 20218 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LinkControl, { editor }) 20219 ] 20220 }); 20221} 20222/*! @license DOMPurify 3.4.15 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.15/LICENSE */ 20223function _arrayLikeToArray(r, a) { 20224 (null == a || a > r.length) && (a = r.length); 20225 for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; 20226 return n; 20227} 20228function _arrayWithHoles(r) { 20229 if (Array.isArray(r)) return r; 20230} 20231function _iterableToArrayLimit(r, l) { 20232 var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; 20233 if (null != t) { 20234 var e, n, i$1, u, a = [], f = true, o = false; 20235 try { 20236 if (i$1 = (t = t.call(r)).next, 0 === l); 20237 else for (; !(f = (e = i$1.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); 20238 } catch (r$1) { 20239 o = true, n = r$1; 20240 } finally { 20241 try { 20242 if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; 20243 } finally { 20244 if (o) throw n; 20245 } 20246 } 20247 return a; 20248 } 20249} 20250function _nonIterableRest() { 20251 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); 20252} 20253function _slicedToArray(r, e) { 20254 return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); 20255} 20256function _unsupportedIterableToArray(r, a) { 20257 if (r) { 20258 if ("string" == typeof r) return _arrayLikeToArray(r, a); 20259 var t = {}.toString.call(r).slice(8, -1); 20260 return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; 20261 } 20262} 20263var entries = Object.entries, setPrototypeOf = Object.setPrototypeOf, isFrozen = Object.isFrozen, getPrototypeOf = Object.getPrototypeOf, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; 20264var freeze = Object.freeze, seal = Object.seal, create = Object.create; 20265var _ref = typeof Reflect !== "undefined" && Reflect, apply = _ref.apply, construct = _ref.construct; 20266if (!freeze) freeze = function freeze$1(x) { 20267 return x; 20268}; 20269if (!seal) seal = function seal$1(x) { 20270 return x; 20271}; 20272if (!apply) apply = function apply$2(func, thisArg) { 20273 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) args[_key - 2] = arguments[_key]; 20274 return func.apply(thisArg, args); 20275}; 20276if (!construct) construct = function construct$1(Func) { 20277 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) args[_key2 - 1] = arguments[_key2]; 20278 return new Func(...args); 20279}; 20280var arrayForEach = unapply(Array.prototype.forEach); 20281var arrayLastIndexOf = unapply(Array.prototype.lastIndexOf); 20282var arrayPop = unapply(Array.prototype.pop); 20283var arrayPush = unapply(Array.prototype.push); 20284var arraySplice = unapply(Array.prototype.splice); 20285var arrayIsArray = Array.isArray; 20286var stringToLowerCase = unapply(String.prototype.toLowerCase); 20287var stringToString = unapply(String.prototype.toString); 20288var stringMatch = unapply(String.prototype.match); 20289var stringReplace = unapply(String.prototype.replace); 20290var stringIndexOf = unapply(String.prototype.indexOf); 20291var stringTrim = unapply(String.prototype.trim); 20292var numberToString = unapply(Number.prototype.toString); 20293var booleanToString = unapply(Boolean.prototype.toString); 20294var bigintToString = typeof BigInt === "undefined" ? null : unapply(BigInt.prototype.toString); 20295var symbolToString = typeof Symbol === "undefined" ? null : unapply(Symbol.prototype.toString); 20296var objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty); 20297var objectToString = unapply(Object.prototype.toString); 20298var regExpTest = unapply(RegExp.prototype.test); 20299var typeErrorCreate = unconstruct(TypeError); 20300function unapply(func) { 20301 return function(thisArg) { 20302 if (thisArg instanceof RegExp) thisArg.lastIndex = 0; 20303 for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) args[_key3 - 1] = arguments[_key3]; 20304 return apply(func, thisArg, args); 20305 }; 20306} 20307function unconstruct(Func) { 20308 return function() { 20309 for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4;
vendor: 4,245 bytes, lines 20309-20554
20309 _key4++) args[_key4] = arguments[_key4]; 20310 return construct(Func, args); 20311 }; 20312} 20313function addToSet(set, array) { 20314 let transformCaseFunc = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : stringToLowerCase; 20315 if (setPrototypeOf) setPrototypeOf(set, null); 20316 if (!arrayIsArray(array)) return set; 20317 let l = array.length; 20318 while (l--) { 20319 let element = array[l]; 20320 if (typeof element === "string") { 20321 const lcElement = transformCaseFunc(element); 20322 if (lcElement !== element) { 20323 if (!isFrozen(array)) array[l] = lcElement; 20324 element = lcElement; 20325 } 20326 } 20327 set[element] = true; 20328 } 20329 return set; 20330} 20331function cleanArray(array) { 20332 for (let index = 0; index < array.length; index++) if (!objectHasOwnProperty(array, index)) array[index] = null; 20333 return array; 20334} 20335function clone(object) { 20336 const newObject = create(null); 20337 for (const _ref2 of entries(object)) { 20338 var _ref3 = _slicedToArray(_ref2, 2); 20339 const property = _ref3[0]; 20340 const value = _ref3[1]; 20341 if (objectHasOwnProperty(object, property)) if (arrayIsArray(value)) newObject[property] = cleanArray(value); 20342 else if (value && typeof value === "object" && value.constructor === Object) newObject[property] = clone(value); 20343 else newObject[property] = value; 20344 } 20345 return newObject; 20346} 20347function stringifyValue(value) { 20348 switch (typeof value) { 20349 case "string": return value; 20350 case "number": return numberToString(value); 20351 case "boolean": return booleanToString(value); 20352 case "bigint": return bigintToString ? bigintToString(value) : "0"; 20353 case "symbol": return symbolToString ? symbolToString(value) : "Symbol()"; 20354 case "undefined": return objectToString(value); 20355 case "function": 20356 case "object": { 20357 if (value === null) return objectToString(value); 20358 const valueAsRecord = value; 20359 const valueToString = lookupGetter(valueAsRecord, "toString"); 20360 if (typeof valueToString === "function") { 20361 const stringified = valueToString(valueAsRecord); 20362 return typeof stringified === "string" ? stringified : objectToString(stringified); 20363 } 20364 return objectToString(value); 20365 } 20366 default: return objectToString(value); 20367 } 20368} 20369function lookupGetter(object, prop) { 20370 while (object !== null) { 20371 const desc = getOwnPropertyDescriptor(object, prop); 20372 if (desc) { 20373 if (desc.get) return unapply(desc.get); 20374 if (typeof desc.value === "function") return unapply(desc.value); 20375 } 20376 object = getPrototypeOf(object); 20377 } 20378 function fallbackValue() { 20379 return null; 20380 } 20381 return fallbackValue; 20382} 20383function isRegex(value) { 20384 try { 20385 regExpTest(value, ""); 20386 return true; 20387 } catch (_unused) { 20388 return false; 20389 } 20390} 20391var html$1 = freeze([ 20392 "a", 20393 "abbr", 20394 "acronym", 20395 "address", 20396 "area", 20397 "article", 20398 "aside", 20399 "audio", 20400 "b", 20401 "bdi", 20402 "bdo", 20403 "big", 20404 "blink", 20405 "blockquote", 20406 "body", 20407 "br", 20408 "button", 20409 "canvas", 20410 "caption", 20411 "center", 20412 "cite", 20413 "code", 20414 "col", 20415 "colgroup", 20416 "content", 20417 "data", 20418 "datalist", 20419 "dd", 20420 "decorator", 20421 "del", 20422 "details", 20423 "dfn", 20424 "dialog", 20425 "dir", 20426 "div", 20427 "dl", 20428 "dt", 20429 "element", 20430 "em", 20431 "fieldset", 20432 "figcaption", 20433 "figure", 20434 "font", 20435 "footer", 20436 "form", 20437 "h1", 20438 "h2", 20439 "h3", 20440 "h4", 20441 "h5", 20442 "h6", 20443 "head", 20444 "header", 20445 "hgroup", 20446 "hr", 20447 "html", 20448 "i", 20449 "img", 20450 "input", 20451 "ins", 20452 "kbd", 20453 "label", 20454 "legend", 20455 "li", 20456 "main", 20457 "map", 20458 "mark", 20459 "marquee", 20460 "menu", 20461 "menuitem", 20462 "meter", 20463 "nav", 20464 "nobr", 20465 "ol", 20466 "optgroup", 20467 "option", 20468 "output", 20469 "p", 20470 "picture", 20471 "pre", 20472 "progress", 20473 "q", 20474 "rp", 20475 "rt", 20476 "ruby", 20477 "s", 20478 "samp", 20479 "search", 20480 "section", 20481 "select", 20482 "shadow", 20483 "slot", 20484 "small", 20485 "source", 20486 "spacer", 20487 "span", 20488 "strike", 20489 "strong", 20490 "style", 20491 "sub", 20492 "summary", 20493 "sup", 20494 "table", 20495 "tbody", 20496 "td", 20497 "template", 20498 "textarea", 20499 "tfoot", 20500 "th", 20501 "thead", 20502 "time", 20503 "tr", 20504 "track", 20505 "tt", 20506 "u", 20507 "ul", 20508 "var", 20509 "video", 20510 "wbr" 20511]); 20512var svg$1 = freeze([ 20513 "svg", 20514 "a", 20515 "altglyph", 20516 "altglyphdef", 20517 "altglyphitem", 20518 "animatecolor", 20519 "animatemotion", 20520 "animatetransform", 20521 "circle", 20522 "clippath", 20523 "defs", 20524 "desc", 20525 "ellipse", 20526 "enterkeyhint", 20527 "exportparts", 20528 "filter", 20529 "font", 20530 "g", 20531 "glyph", 20532 "glyphref", 20533 "hkern", 20534 "image", 20535 "inputmode", 20536 "line", 20537 "lineargradient", 20538 "marker", 20539 "mask", 20540 "metadata", 20541 "mpath", 20542 "part", 20543 "path", 20544 "pattern", 20545 "polygon", 20546 "polyline", 20547 "radialgradient", 20548 "rect", 20549 "stop", 20550 "style", 20551 "switch", 20552 "symbol", 20553 "text", 20554 "textpath",
20555 "title", 20556 "tref", 20557 "tspan", 20558 "view", 20559 "vkern" 20560]); 20561var svgFilters = freeze([ 20562 "feBlend", 20563 "feColorMatrix", 20564 "feComponentTransfer", 20565 "feComposite", 20566 "feConvolveMatrix", 20567 "feDiffuseLighting", 20568 "feDisplacementMap", 20569 "feDistantLight", 20570 "feDropShadow", 20571 "feFlood", 20572 "feFuncA", 20573 "feFuncB", 20574 "feFuncG", 20575 "feFuncR", 20576 "feGaussianBlur", 20577 "feImage", 20578 "feMerge", 20579 "feMergeNode", 20580 "feMorphology", 20581 "feOffset", 20582 "fePointLight", 20583 "feSpecularLighting", 20584 "feSpotLight", 20585 "feTile", 20586 "feTurbulence" 20587]); 20588var svgDisallowed = freeze([ 20589 "animate", 20590 "color-profile", 20591 "cursor", 20592 "discard", 20593 "font-face", 20594 "font-face-format", 20595 "font-face-name", 20596 "font-face-src", 20597 "font-face-uri", 20598 "foreignobject", 20599 "hatch", 20600 "hatchpath", 20601 "mesh", 20602 "meshgradient", 20603 "meshpatch", 20604 "meshrow", 20605 "missing-glyph", 20606 "script", 20607 "set", 20608 "solidcolor", 20609 "unknown", 20610 "use" 20611]); 20612var mathMl$1 = freeze([ 20613 "math", 20614 "menclose", 20615 "merror", 20616 "mfenced", 20617 "mfrac", 20618 "mglyph", 20619 "mi", 20620 "mlabeledtr", 20621 "mmultiscripts", 20622 "mn", 20623 "mo", 20624 "mover", 20625 "mpadded", 20626 "mphantom", 20627 "mroot", 20628 "mrow", 20629 "ms", 20630 "mspace", 20631 "msqrt", 20632 "mstyle", 20633 "msub", 20634 "msup", 20635 "msubsup", 20636 "mtable", 20637 "mtd", 20638 "mtext", 20639 "mtr", 20640 "munder", 20641 "munderover", 20642 "mprescripts" 20643]); 20644var mathMlDisallowed = freeze([ 20645 "maction", 20646 "maligngroup", 20647 "malignmark", 20648 "mlongdiv", 20649 "mscarries", 20650 "mscarry", 20651 "msgroup", 20652 "mstack", 20653 "msline", 20654 "msrow", 20655 "semantics", 20656 "annotation", 20657 "annotation-xml", 20658 "mprescripts", 20659 "none" 20660]); 20661var text = freeze(["#text"]); 20662var html = freeze([ 20663 "accept", 20664 "action", 20665 "align", 20666 "alt", 20667 "autocapitalize", 20668 "autocomplete", 20669 "autopictureinpicture", 20670 "autoplay", 20671 "background", 20672 "bgcolor", 20673 "border", 20674 "capture", 20675 "cellpadding", 20676 "cellspacing", 20677 "checked", 20678 "cite", 20679 "class", 20680 "clear", 20681 "color", 20682 "cols", 20683 "colspan", 20684 "command", 20685 "commandfor", 20686 "controls", 20687 "controlslist", 20688 "coords", 20689 "crossorigin", 20690 "datetime", 20691 "decoding", 20692 "default", 20693 "dir", 20694 "disabled", 20695 "disablepictureinpicture", 20696 "disableremoteplayback", 20697 "download", 20698 "draggable", 20699 "enctype", 20700 "enterkeyhint", 20701 "exportparts", 20702 "face", 20703 "for", 20704 "headers", 20705 "height", 20706 "hidden", 20707 "high", 20708 "href", 20709 "hreflang", 20710 "id", 20711 "inert", 20712 "inputmode", 20713 "integrity", 20714 "ismap", 20715 "kind", 20716 "label", 20717 "lang", 20718 "list", 20719 "loading", 20720 "loop", 20721 "low", 20722 "max", 20723 "maxlength", 20724 "media", 20725 "method", 20726 "min", 20727 "minlength", 20728 "multiple", 20729 "muted", 20730 "name", 20731 "nonce", 20732 "noshade", 20733 "novalidate", 20734 "nowrap", 20735 "open", 20736 "optimum", 20737 "part", 20738 "pattern", 20739 "placeholder", 20740 "playsinline", 20741 "popover", 20742 "popovertarget", 20743 "popovertargetaction", 20744 "poster", 20745 "preload", 20746 "pubdate", 20747 "radiogroup", 20748 "readonly", 20749 "rel", 20750 "required", 20751 "rev", 20752 "reversed", 20753 "role", 20754 "rows", 20755 "rowspan", 20756 "spellcheck", 20757 "scope", 20758 "selected", 20759 "shape", 20760 "size", 20761 "sizes", 20762 "slot", 20763 "span", 20764 "srclang", 20765 "start", 20766 "src", 20767 "srcset", 20768 "step", 20769 "style", 20770 "summary", 20771 "tabindex", 20772 "title", 20773 "translate", 20774 "type", 20775 "usemap", 20776 "valign", 20777 "value", 20778 "width", 20779 "wrap", 20780 "xmlns" 20781]); 20782var svg = freeze([ 20783 "accent-height", 20784 "accumulate", 20785 "additive", 20786 "alignment-baseline", 20787 "amplitude", 20788 "ascent", 20789 "attributename", 20790 "attributetype", 20791 "azimuth", 20792 "basefrequency", 20793 "baseline-shift", 20794 "begin", 20795 "bias", 20796 "by", 20797 "class", 20798 "clip", 20799 "clippathunits", 20800 "clip-path", 20801 "clip-rule", 20802 "color", 20803 "color-interpolation", 20804 "color-interpolation-filters", 20805 "color-profile", 20806 "color-rendering", 20807 "cx", 20808 "cy", 20809 "d", 20810 "dx", 20811 "dy", 20812 "diffuseconstant", 20813 "direction", 20814 "display", 20815 "divisor", 20816 "dominant-baseline", 20817 "dur", 20818 "edgemode", 20819 "elevation", 20820 "end", 20821 "exponent", 20822 "fill", 20823 "fill-opacity", 20824 "fill-rule", 20825 "filter", 20826 "filterunits", 20827 "flood-color", 20828 "flood-opacity", 20829 "font-family", 20830 "font-size", 20831 "font-size-adjust", 20832 "font-stretch", 20833 "font-style", 20834 "font-variant", 20835 "font-weight", 20836 "fx", 20837 "fy", 20838 "g1", 20839 "g2", 20840 "glyph-name", 20841 "glyphref", 20842 "gradientunits", 20843 "gradienttransform", 20844 "height", 20845 "href", 20846 "id", 20847 "image-rendering", 20848 "in", 20849 "in2", 20850 "intercept", 20851 "k", 20852 "k1", 20853 "k2", 20854 "k3", 20855 "k4", 20856 "kerning", 20857 "keypoints", 20858 "keysplines", 20859 "keytimes", 20860 "lang", 20861 "lengthadjust", 20862 "letter-spacing", 20863 "kernelmatrix", 20864 "kernelunitlength", 20865 "lighting-color", 20866 "local", 20867 "marker-end", 20868 "marker-mid", 20869 "marker-start", 20870 "markerheight", 20871 "markerunits", 20872 "markerwidth", 20873 "maskcontentunits", 20874 "maskunits", 20875 "max", 20876 "mask", 20877 "mask-type", 20878 "media", 20879 "method", 20880 "mode", 20881 "min", 20882 "name", 20883 "numoctaves", 20884 "offset", 20885 "operator", 20886 "opacity", 20887 "order", 20888 "orient", 20889 "orientation", 20890 "origin", 20891 "overflow", 20892 "paint-order", 20893 "path", 20894 "pathlength", 20895 "patterncontentunits", 20896 "patterntransform", 20897 "patternunits", 20898 "pointer-events", 20899 "points", 20900 "preservealpha", 20901 "preserveaspectratio", 20902 "primitiveunits", 20903 "r", 20904 "rx", 20905 "ry", 20906 "radius", 20907 "refx", 20908 "refy", 20909 "repeatcount", 20910 "repeatdur", 20911 "restart", 20912 "result", 20913 "rotate", 20914 "scale", 20915 "seed", 20916 "shape-rendering", 20917 "slope", 20918 "specularconstant", 20919 "specularexponent", 20920 "spreadmethod", 20921 "startoffset", 20922 "stddeviation", 20923 "stitchtiles", 20924 "stop-color", 20925 "stop-opacity", 20926 "stroke-dasharray", 20927 "stroke-dashoffset", 20928 "stroke-linecap", 20929 "stroke-linejoin", 20930 "stroke-miterlimit", 20931 "stroke-opacity", 20932 "stroke", 20933 "stroke-width", 20934 "style", 20935 "surfacescale", 20936 "systemlanguage", 20937 "tabindex", 20938 "tablevalues", 20939 "targetx", 20940 "targety", 20941 "transform", 20942 "transform-origin", 20943 "text-anchor", 20944 "text-decoration", 20945 "text-orientation", 20946 "text-rendering", 20947 "textlength", 20948 "type", 20949 "u1", 20950 "u2", 20951 "unicode", 20952 "values", 20953 "vector-effect", 20954 "viewbox", 20955 "visibility",
20956 "version", 20957 "vert-adv-y", 20958 "vert-origin-x", 20959 "vert-origin-y", 20960 "width", 20961 "word-spacing", 20962 "wrap", 20963 "writing-mode", 20964 "xchannelselector", 20965 "ychannelselector", 20966 "x", 20967 "x1", 20968 "x2", 20969 "xmlns", 20970 "y", 20971 "y1", 20972 "y2", 20973 "z", 20974 "zoomandpan" 20975]); 20976var mathMl = freeze([ 20977 "accent", 20978 "accentunder", 20979 "align", 20980 "bevelled", 20981 "close", 20982 "columnalign", 20983 "columnlines", 20984 "columnspacing", 20985 "columnspan", 20986 "denomalign", 20987 "depth", 20988 "dir", 20989 "display", 20990 "displaystyle", 20991 "encoding", 20992 "fence", 20993 "frame", 20994 "height", 20995 "href", 20996 "id", 20997 "largeop", 20998 "length", 20999 "linethickness", 21000 "lquote", 21001 "lspace", 21002 "mathbackground", 21003 "mathcolor", 21004 "mathsize", 21005 "mathvariant", 21006 "maxsize", 21007 "minsize", 21008 "movablelimits", 21009 "notation", 21010 "numalign", 21011 "open", 21012 "rowalign", 21013 "rowlines", 21014 "rowspacing", 21015 "rowspan", 21016 "rspace", 21017 "rquote", 21018 "scriptlevel", 21019 "scriptminsize", 21020 "scriptsizemultiplier", 21021 "selection", 21022 "separator", 21023 "separators", 21024 "stretchy", 21025 "subscriptshift", 21026 "supscriptshift", 21027 "symmetric", 21028 "voffset", 21029 "width", 21030 "xmlns" 21031]); 21032var xml = freeze([ 21033 "xlink:href", 21034 "xml:id", 21035 "xlink:title", 21036 "xml:space", 21037 "xmlns:xlink" 21038]); 21039var MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g); 21040var ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g); 21041var TMPLIT_EXPR = seal(/\${[\w\W]*/g); 21042var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); 21043var ARIA_ATTR = seal(/^aria-[\-\w]+$/); 21044var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i); 21045var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); 21046var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g); 21047var DOCTYPE_NAME = seal(/^html$/i); 21048var CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); 21049var ELEMENT_MARKUP_PROBE = seal(/<[/\w!]/g); 21050var COMMENT_MARKUP_PROBE = seal(/<[/\w]/g); 21051var FALLBACK_TAG_CLOSE = seal(/<\/no(script|embed|frames)/i); 21052var SELF_CLOSING_TAG = seal(/\/>/i); 21053var NODE_TYPE = { 21054 element: 1, 21055 attribute: 2, 21056 text: 3, 21057 cdataSection: 4, 21058 entityReference: 5, 21059 entityNode: 6, 21060 processingInstruction: 7, 21061 comment: 8, 21062 document: 9, 21063 documentType: 10, 21064 documentFragment: 11, 21065 notation: 12 21066}; 21067var LITERAL_TEXT_ELEMENT_NAMES = [ 21068 "style", 21069 "script", 21070 "xmp", 21071 "iframe", 21072 "noembed", 21073 "noframes", 21074 "plaintext", 21075 "noscript" 21076]; 21077var LITERAL_TEXT_ELEMENTS = freeze(addToSet({}, LITERAL_TEXT_ELEMENT_NAMES)); 21078var LITERAL_TEXT_CLOSE = function() { 21079 const map = {}; 21080 arrayForEach(LITERAL_TEXT_ELEMENT_NAMES, (name) => { 21081 map[name] = seal(new RegExp("</" + name + "(?=[\\t\\n\\f\\r />])", "i")); 21082 }); 21083 return freeze(map); 21084}(); 21085var getGlobal = function getGlobal$1() { 21086 return typeof window === "undefined" ? null : window; 21087}; 21088var _createTrustedTypesPolicy = function _createTrustedTypesPolicy$1(trustedTypes, purifyHostElement) { 21089 if (typeof trustedTypes !== "object" || typeof trustedTypes.createPolicy !== "function") return null; 21090 let suffix = null; 21091 const ATTR_NAME = "data-tt-policy-suffix"; 21092 if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) suffix = purifyHostElement.getAttribute(ATTR_NAME); 21093 const policyName = "dompurify" + (suffix ? "#" + suffix : ""); 21094 try { 21095 return trustedTypes.createPolicy(policyName, { 21096 createHTML(html$2) { 21097 return html$2; 21098 }, 21099 createScriptURL(scriptUrl) { 21100 return scriptUrl; 21101 } 21102 }); 21103 } catch (_) { 21104 console.warn("TrustedTypes policy " + policyName + " could not be created."); 21105 return null; 21106 } 21107}; 21108var _createHooksMap = function _createHooksMap$1() { 21109 return { 21110 afterSanitizeAttributes: [], 21111 afterSanitizeElements: [], 21112 afterSanitizeShadowDOM: [], 21113 beforeSanitizeAttributes: [], 21114 beforeSanitizeElements: [], 21115 beforeSanitizeShadowDOM: [], 21116 uponSanitizeAttribute: [], 21117 uponSanitizeElement: [], 21118 uponSanitizeShadowNode: [] 21119 }; 21120}; 21121var _resolveSetOption = function _resolveSetOption$1(cfg, key, fallback, options) { 21122 return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback; 21123}; 21124var _resolveObjectOption = function _resolveObjectOption$1(cfg, key, makeFallback) { 21125 const value = objectHasOwnProperty(cfg, key) ? cfg[key] : void 0; 21126 return value && typeof value === "object" ? clone(value) : makeFallback(); 21127}; 21128function createDOMPurify() { 21129 let window$1 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal(); 21130 const DOMPurify = (root) => createDOMPurify(root); 21131 DOMPurify.version = "3.4.15"; 21132 DOMPurify.removed = []; 21133 if (!window$1 || !window$1.document || window$1.document.nodeType !== NODE_TYPE.document || !window$1.Element) { 21134 DOMPurify.isSupported = false;
vendor: 4,234 bytes, lines 21135-21214
21135 return DOMPurify; 21136 } 21137 let document$1 = window$1.document; 21138 const originalDocument = document$1; 21139 const currentScript = originalDocument.currentScript; 21140 window$1.DocumentFragment; 21141 const HTMLTemplateElement = window$1.HTMLTemplateElement, Node$2 = window$1.Node, Element = window$1.Element, NodeFilter = window$1.NodeFilter; 21142 window$1.NamedNodeMap === void 0 && (window$1.NamedNodeMap || window$1.MozNamedAttrMap); 21143 window$1.HTMLFormElement; 21144 const DOMParser$1 = window$1.DOMParser, trustedTypes = window$1.trustedTypes; 21145 const ElementPrototype = Element.prototype; 21146 const cloneNode = lookupGetter(ElementPrototype, "cloneNode"); 21147 const remove = lookupGetter(ElementPrototype, "remove"); 21148 const removeAttributeNode = lookupGetter(ElementPrototype, "removeAttributeNode"); 21149 const getNextSibling = lookupGetter(ElementPrototype, "nextSibling"); 21150 const getChildNodes = lookupGetter(ElementPrototype, "childNodes"); 21151 const getParentNode = lookupGetter(ElementPrototype, "parentNode"); 21152 const getShadowRoot = lookupGetter(ElementPrototype, "shadowRoot"); 21153 const getAttributes$1 = lookupGetter(ElementPrototype, "attributes"); 21154 const getNodeType$1 = Node$2 && Node$2.prototype ? lookupGetter(Node$2.prototype, "nodeType") : null; 21155 const getNodeName = Node$2 && Node$2.prototype ? lookupGetter(Node$2.prototype, "nodeName") : null; 21156 const getOwnerDocument = Node$2 && Node$2.prototype ? lookupGetter(Node$2.prototype, "ownerDocument") : null; 21157 const _readNodeType = function _readNodeType$1(node) { 21158 return getNodeType$1 ? getNodeType$1(node) : node.nodeType; 21159 }; 21160 const _readNodeName = function _readNodeName$1(node) { 21161 return getNodeName ? getNodeName(node) : node.nodeName; 21162 }; 21163 if (typeof HTMLTemplateElement === "function") { 21164 const template = document$1.createElement("template"); 21165 if (template.content && template.content.ownerDocument) document$1 = template.content.ownerDocument; 21166 } 21167 let trustedTypesPolicy; 21168 let emptyHTML = ""; 21169 let defaultTrustedTypesPolicy; 21170 let defaultTrustedTypesPolicyResolved = false; 21171 let IN_TRUSTED_TYPES_POLICY = 0; 21172 const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy$1() { 21173 if (IN_TRUSTED_TYPES_POLICY > 0) throw typeErrorCreate("A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the \"DOMPurify and Trusted Types\" section of the README."); 21174 }; 21175 const _createTrustedHTML = function _createTrustedHTML$1(html$2) { 21176 _assertNotInTrustedTypesPolicy(); 21177 IN_TRUSTED_TYPES_POLICY++; 21178 try { 21179 return trustedTypesPolicy.createHTML(html$2); 21180 } finally { 21181 IN_TRUSTED_TYPES_POLICY--; 21182 } 21183 }; 21184 const _createTrustedScriptURL = function _createTrustedScriptURL$1(scriptUrl) { 21185 _assertNotInTrustedTypesPolicy(); 21186 IN_TRUSTED_TYPES_POLICY++; 21187 try { 21188 return trustedTypesPolicy.createScriptURL(scriptUrl); 21189 } finally { 21190 IN_TRUSTED_TYPES_POLICY--; 21191 } 21192 }; 21193 const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy$1() { 21194 if (!defaultTrustedTypesPolicyResolved) { 21195 defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript); 21196 defaultTrustedTypesPolicyResolved = true; 21197 } 21198 return defaultTrustedTypesPolicy; 21199 }; 21200 const _document = document$1, implementation = _document.implementation, createNodeIterator = _document.createNodeIterator, createDocumentFragment = _document.createDocumentFragment, getElementsByTagName = _document.getElementsByTagName; 21201 const importNode = originalDocument.importNode; 21202 let hooks = _createHooksMap(); 21203 DOMPurify.isSupported = typeof entries === "function" && typeof getParentNode === "function" && implementation && implementation.createHTMLDocument !== void 0; 21204 const MUSTACHE_EXPR$1 = MUSTACHE_EXPR, ERB_EXPR$1 = ERB_EXPR, TMPLIT_EXPR$1 = TMPLIT_EXPR, DATA_ATTR$1 = DATA_ATTR, ARIA_ATTR$1 = ARIA_ATTR, IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA, ATTR_WHITESPACE$1 = ATTR_WHITESPACE, CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT; 21205 let IS_ALLOWED_URI$1 = IS_ALLOWED_URI; 21206 let ALLOWED_TAGS$1 = null; 21207 const DEFAULT_ALLOWED_TAGS = addToSet({}, [ 21208 ...html$1, 21209 ...svg$1, 21210 ...svgFilters, 21211 ...mathMl$1, 21212 ...text 21213 ]); 21214 let ALLOWED_ATTR$1
vendor: 3,301 bytes, lines 21214-21365
21214 = null; 21215 const DEFAULT_ALLOWED_ATTR = addToSet({}, [ 21216 ...html, 21217 ...svg, 21218 ...mathMl, 21219 ...xml 21220 ]); 21221 let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, { 21222 tagNameCheck: { 21223 writable: true, 21224 configurable: false, 21225 enumerable: true, 21226 value: null 21227 }, 21228 attributeNameCheck: { 21229 writable: true, 21230 configurable: false, 21231 enumerable: true, 21232 value: null 21233 }, 21234 allowCustomizedBuiltInElements: { 21235 writable: true, 21236 configurable: false, 21237 enumerable: true, 21238 value: false 21239 } 21240 })); 21241 let FORBID_TAGS = null; 21242 let FORBID_ATTR = null; 21243 const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, { 21244 tagCheck: { 21245 writable: true, 21246 configurable: false, 21247 enumerable: true, 21248 value: null 21249 }, 21250 attributeCheck: { 21251 writable: true, 21252 configurable: false, 21253 enumerable: true, 21254 value: null 21255 } 21256 })); 21257 let ALLOW_ARIA_ATTR = true; 21258 let ALLOW_DATA_ATTR = true; 21259 let ALLOW_UNKNOWN_PROTOCOLS = false; 21260 let ALLOW_SELF_CLOSE_IN_ATTR = true; 21261 let SAFE_FOR_TEMPLATES = false; 21262 let SAFE_FOR_XML = true; 21263 let WHOLE_DOCUMENT = false; 21264 let SET_CONFIG = false; 21265 let SET_CONFIG_ALLOWED_TAGS = null; 21266 let SET_CONFIG_ALLOWED_ATTR = null; 21267 let FORCE_BODY = false; 21268 let RETURN_DOM = false; 21269 let RETURN_DOM_FRAGMENT = false; 21270 let RETURN_TRUSTED_TYPE = false; 21271 let SANITIZE_DOM = true; 21272 let SANITIZE_NAMED_PROPS = false; 21273 const SANITIZE_NAMED_PROPS_PREFIX = "user-content-"; 21274 let KEEP_CONTENT = true; 21275 let IN_PLACE = false; 21276 let USE_PROFILES = {}; 21277 let FORBID_CONTENTS = null; 21278 const DEFAULT_FORBID_CONTENTS = addToSet({}, [ 21279 "annotation-xml", 21280 "audio", 21281 "colgroup", 21282 "desc", 21283 "foreignobject", 21284 "head", 21285 "iframe", 21286 "math", 21287 "mi", 21288 "mn", 21289 "mo", 21290 "ms", 21291 "mtext", 21292 "noembed", 21293 "noframes", 21294 "noscript", 21295 "plaintext", 21296 "script", 21297 "selectedcontent", 21298 "style", 21299 "svg", 21300 "template", 21301 "thead", 21302 "title", 21303 "video", 21304 "xmp" 21305 ]); 21306 let DATA_URI_TAGS = null; 21307 const DEFAULT_DATA_URI_TAGS = addToSet({}, [ 21308 "audio", 21309 "video", 21310 "img", 21311 "source", 21312 "image", 21313 "track" 21314 ]); 21315 let URI_SAFE_ATTRIBUTES = null; 21316 const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, [ 21317 "alt", 21318 "class", 21319 "for", 21320 "id", 21321 "label", 21322 "name", 21323 "pattern", 21324 "placeholder", 21325 "role", 21326 "summary", 21327 "title", 21328 "value", 21329 "style", 21330 "xmlns" 21331 ]); 21332 const MATHML_NAMESPACE = "http://www.w3.org/1998/Math/MathML"; 21333 const SVG_NAMESPACE = "http://www.w3.org/2000/svg"; 21334 const HTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; 21335 let NAMESPACE = HTML_NAMESPACE; 21336 let IS_EMPTY_INPUT = false; 21337 let ALLOWED_NAMESPACES = null; 21338 const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [ 21339 MATHML_NAMESPACE, 21340 SVG_NAMESPACE, 21341 HTML_NAMESPACE 21342 ], stringToString); 21343 const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze([ 21344 "mi", 21345 "mo", 21346 "mn", 21347 "ms", 21348 "mtext" 21349 ]); 21350 let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS); 21351 const DEFAULT_HTML_INTEGRATION_POINTS = freeze(["annotation-xml"]); 21352 let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS); 21353 const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, [ 21354 "title", 21355 "style", 21356 "font", 21357 "a", 21358 "script" 21359 ]); 21360 let PARSER_MEDIA_TYPE = null; 21361 const SUPPORTED_PARSER_MEDIA_TYPES = ["application/xhtml+xml", "text/html"]; 21362 const DEFAULT_PARSER_MEDIA_TYPE = "text/html"; 21363 let transformCaseFunc = null; 21364 let CONFIG = null; 21365 const formElement = document
vendor: 26,580 bytes, lines 21365-21900
21365$1.createElement("form"); 21366 const isRegexOrFunction = function isRegexOrFunction$1(testValue) { 21367 return testValue instanceof RegExp || testValue instanceof Function; 21368 }; 21369 const _parseConfig = function _parseConfig$1() { 21370 let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; 21371 if (CONFIG && CONFIG === cfg) return; 21372 if (!cfg || typeof cfg !== "object") cfg = {}; 21373 cfg = clone(cfg); 21374 PARSER_MEDIA_TYPE = SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE; 21375 transformCaseFunc = PARSER_MEDIA_TYPE === "application/xhtml+xml" ? stringToString : stringToLowerCase; 21376 ALLOWED_TAGS$1 = _resolveSetOption(cfg, "ALLOWED_TAGS", DEFAULT_ALLOWED_TAGS, { transform: transformCaseFunc }); 21377 ALLOWED_ATTR$1 = _resolveSetOption(cfg, "ALLOWED_ATTR", DEFAULT_ALLOWED_ATTR, { transform: transformCaseFunc }); 21378 ALLOWED_NAMESPACES = _resolveSetOption(cfg, "ALLOWED_NAMESPACES", DEFAULT_ALLOWED_NAMESPACES, { transform: stringToString }); 21379 URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, "ADD_URI_SAFE_ATTR", DEFAULT_URI_SAFE_ATTRIBUTES, { 21380 transform: transformCaseFunc, 21381 base: DEFAULT_URI_SAFE_ATTRIBUTES 21382 }); 21383 DATA_URI_TAGS = _resolveSetOption(cfg, "ADD_DATA_URI_TAGS", DEFAULT_DATA_URI_TAGS, { 21384 transform: transformCaseFunc, 21385 base: DEFAULT_DATA_URI_TAGS 21386 }); 21387 FORBID_CONTENTS = _resolveSetOption(cfg, "FORBID_CONTENTS", DEFAULT_FORBID_CONTENTS, { transform: transformCaseFunc }); 21388 FORBID_TAGS = _resolveSetOption(cfg, "FORBID_TAGS", clone({}), { transform: transformCaseFunc }); 21389 FORBID_ATTR = _resolveSetOption(cfg, "FORBID_ATTR", clone({}), { transform: transformCaseFunc }); 21390 USE_PROFILES = objectHasOwnProperty(cfg, "USE_PROFILES") ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === "object" ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false; 21391 ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; 21392 ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; 21393 ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; 21394 ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; 21395 SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; 21396 SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; 21397 WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; 21398 RETURN_DOM = cfg.RETURN_DOM || false; 21399 RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; 21400 RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; 21401 FORCE_BODY = cfg.FORCE_BODY || false; 21402 SANITIZE_DOM = cfg.SANITIZE_DOM !== false; 21403 SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; 21404 KEEP_CONTENT = cfg.KEEP_CONTENT !== false; 21405 IN_PLACE = cfg.IN_PLACE || false; 21406 IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; 21407 NAMESPACE = typeof cfg.NAMESPACE === "string" ? cfg.NAMESPACE : HTML_NAMESPACE; 21408 MATHML_TEXT_INTEGRATION_POINTS = _resolveObjectOption(cfg, "MATHML_TEXT_INTEGRATION_POINTS", () => addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS)); 21409 HTML_INTEGRATION_POINTS = _resolveObjectOption(cfg, "HTML_INTEGRATION_POINTS", () => addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS)); 21410 const customElementHandling = _resolveObjectOption(cfg, "CUSTOM_ELEMENT_HANDLING", () => create(null)); 21411 CUSTOM_ELEMENT_HANDLING = create(null); 21412 if (objectHasOwnProperty(customElementHandling, "tagNameCheck") && isRegexOrFunction(customElementHandling.tagNameCheck)) CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; 21413 if (objectHasOwnProperty(customElementHandling, "attributeNameCheck") && isRegexOrFunction(customElementHandling.attributeNameCheck)) CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; 21414 if (objectHasOwnProperty(customElementHandling, "allowCustomizedBuiltInElements") && typeof customElementHandling.allowCustomizedBuiltInElements === "boolean") CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; 21415 seal(CUSTOM_ELEMENT_HANDLING); 21416 if (SAFE_FOR_TEMPLATES) ALLOW_DATA_ATTR = false; 21417 if (RETURN_DOM_FRAGMENT) RETURN_DOM = true; 21418 if (USE_PROFILES) { 21419 ALLOWED_TAGS$1 = addToSet({}, text); 21420 ALLOWED_ATTR$1 = create(null); 21421 if (USE_PROFILES.html === true) { 21422 addToSet(ALLOWED_TAGS$1, html$1); 21423 addToSet(ALLOWED_ATTR$1, html); 21424 } 21425 if (USE_PROFILES.svg === true) { 21426 addToSet(ALLOWED_TAGS$1, svg$1); 21427 addToSet(ALLOWED_ATTR$1, svg); 21428 addToSet(ALLOWED_ATTR$1, xml); 21429 } 21430 if (USE_PROFILES.svgFilters === true) { 21431 addToSet(ALLOWED_TAGS$1, svgFilters); 21432 addToSet(ALLOWED_ATTR$1, svg); 21433 addToSet(ALLOWED_ATTR$1, xml); 21434 } 21435 if (USE_PROFILES.mathMl === true) { 21436 addToSet(ALLOWED_TAGS$1, mathMl$1); 21437 addToSet(ALLOWED_ATTR$1, mathMl); 21438 addToSet(ALLOWED_ATTR$1, xml); 21439 } 21440 } 21441 EXTRA_ELEMENT_HANDLING.tagCheck = null; 21442 EXTRA_ELEMENT_HANDLING.attributeCheck = null; 21443 if (objectHasOwnProperty(cfg, "ADD_TAGS")) { 21444 if (typeof cfg.ADD_TAGS === "function") EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS; 21445 else if (arrayIsArray(cfg.ADD_TAGS)) { 21446 if (ALLOWED_TAGS$1 === DEFAULT_ALLOWED_TAGS) ALLOWED_TAGS$1 = clone(ALLOWED_TAGS$1); 21447 addToSet(ALLOWED_TAGS$1, cfg.ADD_TAGS, transformCaseFunc); 21448 } 21449 } 21450 if (objectHasOwnProperty(cfg, "ADD_ATTR")) { 21451 if (typeof cfg.ADD_ATTR === "function") EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR; 21452 else if (arrayIsArray(cfg.ADD_ATTR)) { 21453 if (ALLOWED_ATTR$1 === DEFAULT_ALLOWED_ATTR) ALLOWED_ATTR$1 = clone(ALLOWED_ATTR$1); 21454 addToSet(ALLOWED_ATTR$1, cfg.ADD_ATTR, transformCaseFunc); 21455 } 21456 } 21457 if (objectHasOwnProperty(cfg, "ADD_FORBID_CONTENTS") && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) { 21458 if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) FORBID_CONTENTS = clone(FORBID_CONTENTS); 21459 addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc); 21460 } 21461 if (KEEP_CONTENT) ALLOWED_TAGS$1["#text"] = true; 21462 if (WHOLE_DOCUMENT) addToSet(ALLOWED_TAGS$1, [ 21463 "html", 21464 "head", 21465 "body" 21466 ]); 21467 if (ALLOWED_TAGS$1.table) { 21468 addToSet(ALLOWED_TAGS$1, ["tbody"]); 21469 delete FORBID_TAGS.tbody; 21470 } 21471 if (cfg.TRUSTED_TYPES_POLICY) { 21472 if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== "function") throw typeErrorCreate("TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook."); 21473 if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== "function") throw typeErrorCreate("TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook."); 21474 const previousTrustedTypesPolicy = trustedTypesPolicy; 21475 trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; 21476 try { 21477 emptyHTML = _createTrustedHTML(""); 21478 } catch (error) { 21479 trustedTypesPolicy = previousTrustedTypesPolicy; 21480 throw error; 21481 } 21482 } else if (cfg.TRUSTED_TYPES_POLICY === null) { 21483 trustedTypesPolicy = void 0; 21484 emptyHTML = ""; 21485 } else { 21486 if (trustedTypesPolicy === void 0) trustedTypesPolicy = _getDefaultTrustedTypesPolicy(); 21487 if (trustedTypesPolicy && typeof emptyHTML === "string") emptyHTML = _createTrustedHTML(""); 21488 } 21489 if (freeze) freeze(cfg); 21490 CONFIG = cfg; 21491 }; 21492 const ALL_SVG_TAGS = addToSet({}, [ 21493 ...svg$1, 21494 ...svgFilters, 21495 ...svgDisallowed 21496 ]); 21497 const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]); 21498 const _checkSvgNamespace = function _checkSvgNamespace$1(tagName, parent, parentTagName) { 21499 if (parent.namespaceURI === HTML_NAMESPACE) return tagName === "svg"; 21500 if (parent.namespaceURI === MATHML_NAMESPACE) return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); 21501 return Boolean(ALL_SVG_TAGS[tagName]); 21502 }; 21503 const _checkMathMlNamespace = function _checkMathMlNamespace$1(tagName, parent, parentTagName) { 21504 if (parent.namespaceURI === HTML_NAMESPACE) return tagName === "math"; 21505 if (parent.namespaceURI === SVG_NAMESPACE) return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName]; 21506 return Boolean(ALL_MATHML_TAGS[tagName]); 21507 }; 21508 const _checkHtmlNamespace = function _checkHtmlNamespace$1(tagName, parent, parentTagName) { 21509 if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) return false; 21510 if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) return false; 21511 return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]); 21512 }; 21513 const _checkValidNamespace = function _checkValidNamespace$1(element) { 21514 let parent = getParentNode(element); 21515 if (!parent || !parent.tagName) parent = { 21516 namespaceURI: NAMESPACE, 21517 tagName: "template" 21518 }; 21519 const tagName = stringToLowerCase(element.tagName); 21520 const parentTagName = stringToLowerCase(parent.tagName); 21521 if (!ALLOWED_NAMESPACES[element.namespaceURI]) return false; 21522 if (element.namespaceURI === SVG_NAMESPACE) return _checkSvgNamespace(tagName, parent, parentTagName); 21523 if (element.namespaceURI === MATHML_NAMESPACE) return _checkMathMlNamespace(tagName, parent, parentTagName); 21524 if (element.namespaceURI === HTML_NAMESPACE) return _checkHtmlNamespace(tagName, parent, parentTagName); 21525 if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && ALLOWED_NAMESPACES[element.namespaceURI]) return true; 21526 return false; 21527 }; 21528 const _forceRemove = function _forceRemove$1(node) { 21529 arrayPush(DOMPurify.removed, { element: node }); 21530 try { 21531 getParentNode(node).removeChild(node); 21532 } catch (_) { 21533 remove(node); 21534 if (!getParentNode(node)) throw typeErrorCreate("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place"); 21535 } 21536 }; 21537 const _stripAttributeNode = function _stripAttributeNode$1(element, attribute, name) { 21538 try { 21539 removeAttributeNode(element, attribute); 21540 } catch (_) { 21541 try { 21542 element.removeAttribute(name); 21543 } catch (_$1) {} 21544 } 21545 }; 21546 const _neutralizeRoot = function _neutralizeRoot$1(root) { 21547 _neutralizeSubtree(root); 21548 const childNodes = getChildNodes(root); 21549 if (childNodes) { 21550 const snapshot = []; 21551 arrayForEach(childNodes, (child) => { 21552 arrayPush(snapshot, child); 21553 }); 21554 arrayForEach(snapshot, (child) => { 21555 try { 21556 remove(child); 21557 } catch (_) {} 21558 }); 21559 } 21560 const attributes = getAttributes$1(root); 21561 if (attributes) for (let i$1 = attributes.length - 1; i$1 >= 0; --i$1) { 21562 const attribute = attributes[i$1]; 21563 const name = attribute && attribute.name; 21564 if (typeof name === "string") _stripAttributeNode(root, attribute, name); 21565 } 21566 }; 21567 const _removeAttribute = function _removeAttribute$1(name, element, attr) { 21568 if (!attr) try { 21569 attr = element.getAttributeNode(name); 21570 } catch (_) { 21571 attr = null; 21572 } 21573 arrayPush(DOMPurify.removed, { 21574 attribute: attr || null, 21575 from: element 21576 }); 21577 try { 21578 if (attr) removeAttributeNode(element, attr); 21579 else element.removeAttribute(name); 21580 } catch (_) { 21581 try { 21582 element.removeAttribute(name); 21583 } catch (_$1) {} 21584 } 21585 if (name === "is") if (RETURN_DOM || RETURN_DOM_FRAGMENT) try { 21586 _forceRemove(element); 21587 } catch (_) {} 21588 else try { 21589 element.setAttribute(name, ""); 21590 } catch (_) {} 21591 }; 21592 const _stripDisallowedAttributes = function _stripDisallowedAttributes$1(element) { 21593 const attributes = getAttributes$1(element); 21594 if (!attributes) return; 21595 for (let i$1 = attributes.length - 1; i$1 >= 0; --i$1) { 21596 const attribute = attributes[i$1]; 21597 const name = attribute && attribute.name; 21598 if (typeof name !== "string" || ALLOWED_ATTR$1[transformCaseFunc(name)]) continue; 21599 _stripAttributeNode(element, attribute, name); 21600 } 21601 }; 21602 const _neutralizeSubtree = function _neutralizeSubtree$1(root) { 21603 const stack = [root]; 21604 while (stack.length > 0) { 21605 const node = stack.pop(); 21606 if (_readNodeType(node) === NODE_TYPE.element) _stripDisallowedAttributes(node); 21607 const childNodes = getChildNodes(node); 21608 if (childNodes) for (let i$1 = childNodes.length - 1; i$1 >= 0; --i$1) stack.push(childNodes[i$1]); 21609 } 21610 }; 21611 const _isPatchLinkageAttribute = function _isPatchLinkageAttribute$1(lcName, lcTag) { 21612 if (!SAFE_FOR_XML) return false; 21613 if (lcName === "patchsrc") return true; 21614 return lcName === "for" && lcTag !== "label" && lcTag !== "output"; 21615 }; 21616 const _neutralizePatchLinkage = function _neutralizePatchLinkage$1(root) { 21617 if (!SAFE_FOR_XML) return; 21618 const stack = [root]; 21619 while (stack.length > 0) { 21620 const node = stack.pop(); 21621 const nodeType = _readNodeType(node); 21622 if (nodeType === NODE_TYPE.processingInstruction || nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, node.data)) { 21623 try { 21624 remove(node); 21625 } catch (_) {} 21626 continue; 21627 } 21628 if (nodeType === NODE_TYPE.element) { 21629 const element = node; 21630 const lcTag = transformCaseFunc(_readNodeName(node)); 21631 try { 21632 if (element.hasAttribute && element.hasAttribute("patchsrc")) element.removeAttribute("patchsrc"); 21633 if (element.hasAttribute && element.hasAttribute("for") && _isPatchLinkageAttribute("for", lcTag)) element.removeAttribute("for"); 21634 } catch (_) {} 21635 } 21636 const childNodes = getChildNodes(node); 21637 if (childNodes) for (let i$1 = childNodes.length - 1; i$1 >= 0; --i$1) stack.push(childNodes[i$1]); 21638 } 21639 }; 21640 const _initDocument = function _initDocument$1(dirty) { 21641 let doc$2 = null; 21642 let leadingWhitespace = null; 21643 if (FORCE_BODY) dirty = "<remove></remove>" + dirty; 21644 else { 21645 const matches$1 = stringMatch(dirty, /^[\r\n\t ]+/); 21646 leadingWhitespace = matches$1 && matches$1[0]; 21647 } 21648 if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && NAMESPACE === HTML_NAMESPACE) dirty = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body>" + dirty + "</body></html>"; 21649 const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty; 21650 if (NAMESPACE === HTML_NAMESPACE) try { 21651 doc$2 = new DOMParser$1().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE); 21652 } catch (_) {} 21653 if (!doc$2 || !doc$2.documentElement) { 21654 doc$2 = implementation.createDocument(NAMESPACE, "template", null); 21655 try { 21656 doc$2.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload; 21657 } catch (_) {} 21658 } 21659 const body = doc$2.body || doc$2.documentElement; 21660 if (dirty && leadingWhitespace) body.insertBefore(document$1.createTextNode(leadingWhitespace), body.childNodes[0] || null); 21661 if (NAMESPACE === HTML_NAMESPACE) return getElementsByTagName.call(doc$2, WHOLE_DOCUMENT ? "html" : "body")[0]; 21662 return WHOLE_DOCUMENT ? doc$2.documentElement : body; 21663 }; 21664 const _createNodeIterator = function _createNodeIterator$1(root) { 21665 const doc$2 = getOwnerDocument ? getOwnerDocument(root) : root.ownerDocument; 21666 return createNodeIterator.call(doc$2 || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null); 21667 }; 21668 const _stripTemplateExpressions = function _stripTemplateExpressions$1(value) { 21669 value = stringReplace(value, MUSTACHE_EXPR$1, " "); 21670 value = stringReplace(value, ERB_EXPR$1, " "); 21671 value = stringReplace(value, TMPLIT_EXPR$1, " "); 21672 return value; 21673 }; 21674 const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) { 21675 var _node$querySelectorAl; 21676 node.normalize(); 21677 const doc$2 = getOwnerDocument ? getOwnerDocument(node) : node.ownerDocument; 21678 const walker = createNodeIterator.call(doc$2 || node, node, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null); 21679 let currentNode = walker.nextNode(); 21680 while (currentNode) { 21681 currentNode.data = _stripTemplateExpressions(currentNode.data); 21682 currentNode = walker.nextNode(); 21683 } 21684 const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, "template"); 21685 if (templates) arrayForEach(templates, (tmpl) => { 21686 if (_isDocumentFragment(tmpl.content)) _scrubTemplateExpressions2(tmpl.content); 21687 }); 21688 }; 21689 const _isClobbered = function _isClobbered$1(element) { 21690 const realTagName = getNodeName ? getNodeName(element) : null; 21691 if (typeof realTagName !== "string") return false; 21692 if (transformCaseFunc(realTagName) !== "form") return false; 21693 return typeof element.nodeName !== "string" || typeof element.textContent !== "string" || typeof element.removeChild !== "function" || element.attributes !== getAttributes$1(element) || typeof element.removeAttribute !== "function" || typeof element.removeAttributeNode !== "function" || typeof element.getAttributeNode !== "function" || typeof element.setAttribute !== "function" || typeof element.namespaceURI !== "string" || typeof element.insertBefore !== "function" || typeof element.hasChildNodes !== "function" || element.nodeType !== getNodeType$1(element) || element.childNodes !== getChildNodes(element); 21694 }; 21695 const _isDocumentFragment = function _isDocumentFragment$1(value) { 21696 if (!getNodeType$1 || typeof value !== "object" || value === null) return false; 21697 try { 21698 return getNodeType$1(value) === NODE_TYPE.documentFragment; 21699 } catch (_) { 21700 return false; 21701 } 21702 }; 21703 const _isNode = function _isNode$1(value) { 21704 if (!getNodeType$1 || typeof value !== "object" || value === null) return false; 21705 try { 21706 return typeof getNodeType$1(value) === "number"; 21707 } catch (_) { 21708 return false; 21709 } 21710 }; 21711 function _executeHooks(hooks$1, currentNode, data) { 21712 if (hooks$1.length === 0) return; 21713 arrayForEach(hooks$1, (hook) => { 21714 hook.call(DOMPurify, currentNode, data, CONFIG); 21715 }); 21716 } 21717 const _isUnsafeNode = function _isUnsafeNode$1(currentNode, tagName) { 21718 if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) return true; 21719 if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && LITERAL_TEXT_ELEMENTS[tagName] && (_isNode(currentNode.firstElementChild) || typeof currentNode.textContent === "string" && regExpTest(LITERAL_TEXT_CLOSE[tagName], currentNode.textContent))) return true; 21720 if (currentNode.nodeType === NODE_TYPE.processingInstruction) return true; 21721 if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) return true; 21722 return false; 21723 }; 21724 const _matchesNameCheck = function _matchesNameCheck$1(check, name) { 21725 if (check instanceof RegExp) return regExpTest(check, name); 21726 if (check instanceof Function) { 21727 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) args[_key - 2] = arguments[_key]; 21728 return Boolean(check(name, ...args)); 21729 } 21730 return false; 21731 }; 21732 const _sanitizeDisallowedNode = function _sanitizeDisallowedNode$1(currentNode, tagName, root) { 21733 if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) return false; 21734 if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) { 21735 const parentNode$1 = getParentNode(currentNode); 21736 const childNodes = getChildNodes(currentNode); 21737 if (childNodes && parentNode$1) { 21738 const childCount = childNodes.length; 21739 for (let i$1 = childCount - 1; i$1 >= 0; --i$1) { 21740 const hoisted = currentNode === root ? cloneNode(childNodes[i$1], true) : childNodes[i$1]; 21741 parentNode$1.insertBefore(hoisted, getNextSibling(currentNode)); 21742 } 21743 } 21744 } 21745 _forceRemove(currentNode); 21746 return true; 21747 }; 21748 const _forkSharedAllowlist = function _forkSharedAllowlist$1(hookList, set, defaultSet, setConfigSet) { 21749 if (hookList.length === 0) return set; 21750 return set === defaultSet || set === setConfigSet ? clone(set) : set; 21751 }; 21752 const _handleHookDetachedNode = function _handleHookDetachedNode$1(currentNode, root) { 21753 if (currentNode === root || getParentNode(currentNode) !== null) return false; 21754 if (IN_PLACE) _neutralizeSubtree(currentNode); 21755 return true; 21756 }; 21757 const _sanitizeElements = function _sanitizeElements$1(currentNode, root) { 21758 _executeHooks(hooks.beforeSanitizeElements, currentNode, null); 21759 if (_handleHookDetachedNode(currentNode, root)) return true; 21760 if (_isClobbered(currentNode)) { 21761 _forceRemove(currentNode); 21762 return true; 21763 } 21764 const tagName = transformCaseFunc(_readNodeName(currentNode)); 21765 ALLOWED_TAGS$1 = _forkSharedAllowlist(hooks.uponSanitizeElement, ALLOWED_TAGS$1, DEFAULT_ALLOWED_TAGS, SET_CONFIG_ALLOWED_TAGS); 21766 _executeHooks(hooks.uponSanitizeElement, currentNode, { 21767 tagName, 21768 allowedTags: ALLOWED_TAGS$1 21769 }); 21770 if (_handleHookDetachedNode(currentNode, root)) return true; 21771 if (_isUnsafeNode(currentNode, tagName)) { 21772 _forceRemove(currentNode); 21773 return true; 21774 } 21775 if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS$1[tagName]) { 21776 const removed$1 = _sanitizeDisallowedNode(currentNode, tagName, root); 21777 if (removed$1 === false) _executeHooks(hooks.afterSanitizeElements, currentNode, null); 21778 return removed$1; 21779 } 21780 if (_readNodeType(currentNode) === NODE_TYPE.element && !_checkValidNamespace(currentNode)) { 21781 _forceRemove(currentNode); 21782 return true; 21783 } 21784 if ((tagName === "noscript" || tagName === "noembed" || tagName === "noframes") && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) { 21785 _forceRemove(currentNode); 21786 return true; 21787 } 21788 if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) { 21789 const content = _stripTemplateExpressions(currentNode.textContent); 21790 if (currentNode.textContent !== content) { 21791 arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() }); 21792 currentNode.textContent = content; 21793 } 21794 } 21795 _executeHooks(hooks.afterSanitizeElements, currentNode, null); 21796 return false; 21797 }; 21798 const _isValidAttribute = function _isValidAttribute$1(lcTag, lcName, value) { 21799 if (FORBID_ATTR[lcName]) return false; 21800 if (_isPatchLinkageAttribute(lcName, lcTag)) return false; 21801 if (SANITIZE_DOM && (lcName === "id" || lcName === "name") && (value in document$1 || value in formElement)) return false; 21802 const nameIsPermitted = ALLOWED_ATTR$1[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag); 21803 if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) return true; 21804 if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) return true; 21805 if (!nameIsPermitted) return _isBasicCustomElement(lcTag) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName, lcTag) || lcName === "is" && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value); 21806 if (URI_SAFE_ATTRIBUTES[lcName]) return true; 21807 if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ""))) return true; 21808 if ((lcName === "src" || lcName === "xlink:href" || lcName === "href") && lcTag !== "script" && stringIndexOf(value, "data:") === 0 && DATA_URI_TAGS[lcTag]) return true; 21809 if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ""))) return true; 21810 return !value; 21811 }; 21812 const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, [ 21813 "annotation-xml", 21814 "color-profile", 21815 "font-face", 21816 "font-face-format", 21817 "font-face-name", 21818 "font-face-src", 21819 "font-face-uri", 21820 "missing-glyph" 21821 ]); 21822 const _isBasicCustomElement = function _isBasicCustomElement$1(tagName) { 21823 return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName); 21824 }; 21825 const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute$1(lcTag, lcName, namespaceURI, value) { 21826 if (trustedTypesPolicy && typeof trustedTypes === "object" && typeof trustedTypes.getAttributeType === "function" && !namespaceURI) switch (trustedTypes.getAttributeType(lcTag, lcName)) { 21827 case "TrustedHTML": return _createTrustedHTML(value); 21828 case "TrustedScriptURL": return _createTrustedScriptURL(value); 21829 } 21830 return value; 21831 }; 21832 const _setAttributeValue = function _setAttributeValue$1(currentNode, name, namespaceURI, value) { 21833 try { 21834 if (namespaceURI) currentNode.setAttributeNS(namespaceURI, name, value); 21835 else currentNode.setAttribute(name, value); 21836 if (_isClobbered(currentNode)) { 21837 _forceRemove(currentNode); 21838 return false; 21839 } 21840 return true; 21841 } catch (_) { 21842 _removeAttribute(name, currentNode); 21843 return false; 21844 } 21845 }; 21846 const _sanitizeAttributes = function _sanitizeAttributes$1(currentNode) { 21847 _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null); 21848 const attributes = currentNode.attributes; 21849 if (!attributes || _isClobbered(currentNode)) return; 21850 ALLOWED_ATTR$1 = _forkSharedAllowlist(hooks.uponSanitizeAttribute, ALLOWED_ATTR$1, DEFAULT_ALLOWED_ATTR, SET_CONFIG_ALLOWED_ATTR); 21851 const hookEvent = { 21852 attrName: "", 21853 attrValue: "", 21854 keepAttr: true, 21855 allowedAttributes: ALLOWED_ATTR$1, 21856 forceKeepAttr: void 0 21857 }; 21858 let l = attributes.length; 21859 const lcTag = transformCaseFunc(currentNode.nodeName); 21860 while (l--) { 21861 const attr = attributes[l]; 21862 const name = attr.name, namespaceURI = attr.namespaceURI, attrValue = attr.value; 21863 const lcName = transformCaseFunc(name); 21864 const initValue = attrValue; 21865 let value = name === "value" ? initValue : stringTrim(initValue); 21866 let recreatedNamedProp = false; 21867 hookEvent.attrName = lcName; 21868 hookEvent.attrValue = value; 21869 hookEvent.keepAttr = true; 21870 hookEvent.forceKeepAttr = void 0; 21871 _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent); 21872 value = hookEvent.attrValue; 21873 if (SANITIZE_NAMED_PROPS && (lcName === "id" || lcName === "name") && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) { 21874 _removeAttribute(name, currentNode, attr); 21875 value = SANITIZE_NAMED_PROPS_PREFIX + value; 21876 recreatedNamedProp = true; 21877 } 21878 if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) { 21879 _removeAttribute(name, currentNode, attr); 21880 continue; 21881 } 21882 if (lcName === "attributename" && stringMatch(value, "href")) { 21883 _removeAttribute(name, currentNode, attr); 21884 continue; 21885 } 21886 if (hookEvent.forceKeepAttr) continue; 21887 if (!hookEvent.keepAttr) { 21888 _removeAttribute(name, currentNode, attr); 21889 continue; 21890 } 21891 if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) { 21892 _removeAttribute(name, currentNode, attr); 21893 continue; 21894 } 21895 if (SAFE_FOR_TEMPLATES) value = _stripTemplateExpressions(value); 21896 if (!_isValidAttribute(lcTag, lcName, value)) { 21897 _removeAttribute(name, currentNode, attr); 21898 continue; 21899 } 21900 value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);
vendor: 5,101 bytes, lines 21901-22040
21901 if (value !== initValue) { 21902 if (_setAttributeValue(currentNode, name, namespaceURI, value) && recreatedNamedProp) arrayPop(DOMPurify.removed); 21903 } 21904 } 21905 _executeHooks(hooks.afterSanitizeAttributes, currentNode, null); 21906 }; 21907 const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) { 21908 let shadowNode = null; 21909 const shadowIterator = _createNodeIterator(fragment); 21910 _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null); 21911 while (shadowNode = shadowIterator.nextNode()) { 21912 _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null); 21913 _sanitizeElements(shadowNode, fragment); 21914 _sanitizeAttributes(shadowNode); 21915 if (_isDocumentFragment(shadowNode.content)) _sanitizeShadowDOM2(shadowNode.content); 21916 if (_readNodeType(shadowNode) === NODE_TYPE.element) { 21917 const innerSr = getShadowRoot(shadowNode); 21918 if (_isDocumentFragment(innerSr)) { 21919 _sanitizeAttachedShadowRoots(innerSr); 21920 _sanitizeShadowDOM2(innerSr); 21921 } 21922 } 21923 } 21924 _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null); 21925 }; 21926 const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots$1(root) { 21927 const stack = [{ 21928 node: root, 21929 shadow: null 21930 }]; 21931 while (stack.length > 0) { 21932 const item = stack.pop(); 21933 if (item.shadow) { 21934 _sanitizeShadowDOM2(item.shadow); 21935 continue; 21936 } 21937 const node = item.node; 21938 const isElement = _readNodeType(node) === NODE_TYPE.element; 21939 const childNodes = getChildNodes(node); 21940 if (childNodes) for (let i$1 = childNodes.length - 1; i$1 >= 0; --i$1) stack.push({ 21941 node: childNodes[i$1], 21942 shadow: null 21943 }); 21944 if (isElement) { 21945 const rootName = getNodeName ? getNodeName(node) : null; 21946 if (typeof rootName === "string" && transformCaseFunc(rootName) === "template") { 21947 const content = node.content; 21948 if (_isDocumentFragment(content)) stack.push({ 21949 node: content, 21950 shadow: null 21951 }); 21952 } 21953 } 21954 if (isElement) { 21955 const sr = getShadowRoot(node); 21956 if (_isDocumentFragment(sr)) stack.push({ 21957 node: null, 21958 shadow: sr 21959 }, { 21960 node: sr, 21961 shadow: null 21962 }); 21963 } 21964 } 21965 }; 21966 DOMPurify.sanitize = function(dirty) { 21967 let cfg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; 21968 let body = null; 21969 let importedNode = null; 21970 let currentNode = null; 21971 let returnNode = null; 21972 IS_EMPTY_INPUT = !dirty; 21973 if (IS_EMPTY_INPUT) dirty = "<!-->"; 21974 if (typeof dirty !== "string" && !_isNode(dirty)) { 21975 dirty = stringifyValue(dirty); 21976 if (typeof dirty !== "string") throw typeErrorCreate("dirty is not a string, aborting"); 21977 } 21978 if (!DOMPurify.isSupported) return dirty; 21979 if (SET_CONFIG) { 21980 ALLOWED_TAGS$1 = SET_CONFIG_ALLOWED_TAGS; 21981 ALLOWED_ATTR$1 = SET_CONFIG_ALLOWED_ATTR; 21982 } else _parseConfig(cfg); 21983 if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) ALLOWED_TAGS$1 = clone(ALLOWED_TAGS$1); 21984 if (hooks.uponSanitizeAttribute.length > 0) ALLOWED_ATTR$1 = clone(ALLOWED_ATTR$1); 21985 DOMPurify.removed = []; 21986 const inPlace = IN_PLACE && typeof dirty !== "string" && _isNode(dirty); 21987 if (inPlace) { 21988 _neutralizePatchLinkage(dirty); 21989 const nn = _readNodeName(dirty); 21990 if (typeof nn === "string") { 21991 const tagName = transformCaseFunc(nn); 21992 if (!ALLOWED_TAGS$1[tagName] || FORBID_TAGS[tagName]) { 21993 _neutralizeRoot(dirty); 21994 throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place"); 21995 } 21996 } 21997 if (_isClobbered(dirty)) { 21998 _neutralizeRoot(dirty); 21999 throw typeErrorCreate("root node is clobbered and cannot be sanitized in-place"); 22000 } 22001 try { 22002 _sanitizeAttachedShadowRoots(dirty); 22003 } catch (error) { 22004 _neutralizeRoot(dirty); 22005 throw error; 22006 } 22007 } else if (_isNode(dirty)) { 22008 body = _initDocument("<!---->"); 22009 importedNode = body.ownerDocument.importNode(dirty, true); 22010 if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === "BODY") body = importedNode; 22011 else if (importedNode.nodeName === "HTML") body = importedNode; 22012 else body.appendChild(importedNode); 22013 _sanitizeAttachedShadowRoots(body); 22014 } else { 22015 if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && dirty.indexOf("<") === -1) return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty; 22016 body = _initDocument(dirty); 22017 if (!body) return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : ""; 22018 } 22019 if (body && FORCE_BODY) _forceRemove(body.firstChild); 22020 const walkRoot = inPlace ? dirty : body; 22021 try { 22022 const nodeIterator = _createNodeIterator(walkRoot); 22023 while (currentNode = nodeIterator.nextNode()) { 22024 _sanitizeElements(currentNode, walkRoot); 22025 _sanitizeAttributes(currentNode); 22026 if (_isDocumentFragment(currentNode.content)) _sanitizeShadowDOM2(currentNode.content); 22027 } 22028 } catch (error) { 22029 if (inPlace) { 22030 _neutralizeRoot(dirty); 22031 arrayForEach(DOMPurify.removed, (entry) => { 22032 if (entry.element) _neutralizeSubtree(entry.element); 22033 }); 22034 } 22035 throw error; 22036 } 22037 if (inPlace) { 22038 arrayForEach(DOMPurify.removed, (entry) => { 22039 if (entry.element) _neutralizeSubtree(entry.element); 22040 });
22041 if (SAFE_FOR_TEMPLATES) _scrubTemplateExpressions2(dirty); 22042 return dirty; 22043 } 22044 if (RETURN_DOM) { 22045 if (SAFE_FOR_TEMPLATES) _scrubTemplateExpressions2(body); 22046 if (RETURN_DOM_FRAGMENT) { 22047 returnNode = createDocumentFragment.call(body.ownerDocument); 22048 while (body.firstChild) returnNode.appendChild(body.firstChild); 22049 } else returnNode = body; 22050 if (ALLOWED_ATTR$1.shadowroot || ALLOWED_ATTR$1.shadowrootmode) returnNode = importNode.call(originalDocument, returnNode, true); 22051 return returnNode; 22052 } 22053 let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; 22054 if (WHOLE_DOCUMENT && ALLOWED_TAGS$1["!doctype"] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) serializedHTML = "<!DOCTYPE " + body.ownerDocument.doctype.name + ">\n" + serializedHTML; 22055 if (SAFE_FOR_TEMPLATES) serializedHTML = _stripTemplateExpressions(serializedHTML); 22056 return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML; 22057 }; 22058 DOMPurify.setConfig = function() { 22059 _parseConfig(arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}); 22060 SET_CONFIG = true; 22061 SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS$1; 22062 SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR$1; 22063 }; 22064 DOMPurify.clearConfig = function() { 22065 CONFIG = null; 22066 SET_CONFIG = false; 22067 SET_CONFIG_ALLOWED_TAGS = null; 22068 SET_CONFIG_ALLOWED_ATTR = null; 22069 trustedTypesPolicy = defaultTrustedTypesPolicy; 22070 emptyHTML = ""; 22071 }; 22072 DOMPurify.isValidAttribute = function(tag, attr, value) { 22073 if (!CONFIG) _parseConfig({}); 22074 return _isValidAttribute(transformCaseFunc(tag), transformCaseFunc(attr), value); 22075 }; 22076 DOMPurify.addHook = function(entryPoint, hookFunction) { 22077 if (typeof hookFunction !== "function") return; 22078 if (!objectHasOwnProperty(hooks, entryPoint)) return; 22079 arrayPush(hooks[entryPoint], hookFunction); 22080 }; 22081 DOMPurify.removeHook = function(entryPoint, hookFunction) { 22082 if (!objectHasOwnProperty(hooks, entryPoint)) return; 22083 if (hookFunction !== void 0) { 22084 const index = arrayLastIndexOf(hooks[entryPoint], hookFunction); 22085 return index === -1 ? void 0 : arraySplice(hooks[entryPoint], index, 1)[0]; 22086 } 22087 return arrayPop(hooks[entryPoint]); 22088 }; 22089 DOMPurify.removeHooks = function(entryPoint) { 22090 if (!objectHasOwnProperty(hooks, entryPoint)) return; 22091 hooks[entryPoint] = []; 22092 }; 22093 DOMPurify.removeAllHooks = function() { 22094 hooks = _createHooksMap(); 22095 }; 22096 return DOMPurify; 22097} 22098var purify = createDOMPurify(); 22099var browser_default = purify; 22100purify.sanitize.bind(purify); 22101purify.isSupported; 22102purify.addHook.bind(purify); 22103purify.removeHook.bind(purify); 22104purify.removeHooks.bind(purify); 22105purify.removeAllHooks.bind(purify); 22106purify.setConfig.bind(purify); 22107purify.clearConfig.bind(purify); 22108purify.isValidAttribute.bind(purify); 22109purify.version; 22110purify.removed; 22111var ALLOWED_TAGS = [...[ 22112 "a", 22113 "b", 22114 "br", 22115 "em", 22116 "i", 22117 "li", 22118 "ol", 22119 "p", 22120 "strong", 22121 "u", 22122 "ul" 22123]]; 22124var ALLOWED_ATTR = [ 22125 "href", 22126 "rel", 22127 "target" 22128]; 22129var UNSAFE_HREF = /^(javascript|data|vbscript):/i; 22130var SAFE_HREF = /^(https?:\/\/|\/|#)/i;
22131var hooksRegistered = false; 22132function isSafeHref(href) { 22133 const trimmed = href.trim(); 22134 if (!trimmed || UNSAFE_HREF.test(trimmed)) return false; 22135 return SAFE_HREF.test(trimmed); 22136} 22137function registerHooks() { 22138 if (hooksRegistered) return; 22139 hooksRegistered = true; 22140 browser_default.addHook("afterSanitizeAttributes", (node) => { 22141 if (node.nodeName !== "A") return; 22142 const href = node.getAttribute("href"); 22143 if (!href || !isSafeHref(href)) node.removeAttribute("href"); 22144 node.setAttribute("rel", "noopener noreferrer"); 22145 node.setAttribute("target", "_blank"); 22146 }); 22147} 22148function sanitizeRichHtml(html$2) { 22149 registerHooks(); 22150 if (!html$2) return ""; 22151 return browser_default.sanitize(html$2, { 22152 ALLOWED_TAGS, 22153 ALLOWED_ATTR, 22154 ALLOW_DATA_ATTR: false, 22155 FORBID_TAGS: [ 22156 "script", 22157 "style", 22158 "iframe", 22159 "object", 22160 "embed" 22161 ], 22162 FORBID_CONTENTS: [ 22163 "script", 22164 "style", 22165 "iframe" 22166 ] 22167 }).trim(); 22168} 22169function isEmptyRichHtml(html$2) { 22170 const sanitized = sanitizeRichHtml(html$2); 22171 if (!sanitized) return true; 22172 return sanitized.replace(/<br\s*\/?>/gi, "").replace(/<[^>]+>/g, "").replace(/ /gi, " ").trim().length === 0; 22173} 22174const richHtmlClassName = cn("text-sm leading-6 text-zinc-900", "[&_p:last-child]:mb-0 [&_p]:mb-3", "[&_ul]:mb-3 [&_ul]:list-disc [&_ul]:pl-6", "[&_ol]:mb-3 [&_ol]:list-decimal [&_ol]:pl-6", "[&_li]:my-1", "[&_a]:text-blue-600 [&_a]:underline"); 22175function RichHtml({ html: html$2, className, emptyLabel }) { 22176 const sanitized = sanitizeRichHtml(html$2); 22177 if (isEmptyRichHtml(sanitized)) { 22178 if (!emptyLabel) return null; 22179 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { 22180 className: cn("text-sm text-zinc-500", className), 22181 children: emptyLabel 22182 }); 22183 } 22184 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 22185 className: cn(richHtmlClassName, className), 22186 dangerouslySetInnerHTML: { __html: sanitized } 22187 }); 22188} 22189const richEditorExtensions = [src_default$1.configure({ 22190 heading: false, 22191 code: false, 22192 codeBlock: false, 22193 strike: false, 22194 blockquote: false, 22195 horizontalRule: false, 22196 link: false 22197}), src_default.extend({ inclusive: false }).configure({ 22198 openOnClick: false, 22199 autolink: true, 22200 defaultProtocol: "https", 22201 HTMLAttributes: { 22202 rel: "noopener noreferrer", 22203 target: "_blank" 22204 } 22205})]; 22206function RichEditor({ content = "", onChange, editable = true, placeholder = "Write hereâ¦", className }) { 22207 const editor = useEditor({ 22208 immediatelyRender: false, 22209 shouldRerenderOnTransaction: true, 22210 extensions: richEditorExtensions, 22211 content: content ?? "", 22212 editable, 22213 editorProps: { attributes: { class: cn("min-h-[8rem] px-3 py-3 outline-none", richHtmlClassName) } }, 22214 onUpdate: ({ editor: nextEditor }) => { 22215 onChange?.(nextEditor.getHTML()); 22216 } 22217 }); 22218 import_react.useEffect(() => { 22219 if (!editor) return; 22220 editor.setEditable(editable); 22221 }, [editor, editable]); 22222 if (!editor) return null; 22223 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 22224 className: cn("overflow-hidden rounded-md border border-zinc-200 bg-white", className),
22225 children: [editable ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(RichEditorToolbar, { editor }) : null, /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 22226 className: "relative", 22227 children: [editor.isEmpty ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { 22228 className: "pointer-events-none absolute left-3 top-3 text-sm text-zinc-400", 22229 children: placeholder 22230 }) : null, /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EditorContent, { editor })] 22231 })] 22232 }); 22233} 22234function formatStrategyUpdatedAt(value) { 22235 const date = value instanceof Date ? value : new Date(value); 22236 if (Number.isNaN(date.getTime())) return ""; 22237 return date.toLocaleDateString("en-US", { 22238 weekday: "long", 22239 month: "long", 22240 day: "numeric", 22241 year: "numeric" 22242 }); 22243} 22244function lastUpdatedLabel(updatedBy, updatedAt) { 22245 const dateLabel = updatedAt ? formatStrategyUpdatedAt(updatedAt) : ""; 22246 if (updatedBy && dateLabel) return `Last Updated by ${updatedBy} ⢠${dateLabel}`; 22247 if (updatedBy) return `Last Updated by ${updatedBy}`; 22248 if (dateLabel) return `Last Updated ⢠${dateLabel}`; 22249 return null; 22250} 22251function InternalStrategy({ onUnsavedChangesChange } = {}) { 22252 const event = useEventDetails()?.event; 22253 const { data: canEdit } = useDisruptionBootstrapQuery((bootstrap) => bootstrap.allowed_to_edit_events); 22254 const revalidator = useRevalidator(); 22255 const savedHtml = event?.internal_strategy ?? ""; 22256 const [isEditing, setIsEditing] = import_react.useState(false); 22257 const [draft, setDraft] = import_react.useState(savedHtml); 22258 const [isSaving, setIsSaving] = import_react.useState(false); 22259 import_react.useEffect(() => { 22260 if (!isEditing) setDraft(savedHtml); 22261 }, [isEditing, savedHtml]); 22262 if (!event) return null; 22263 const eventId = event.event_id; 22264 const footerLabel = lastUpdatedLabel(event.internal_strategy_updated_by, event.internal_strategy_updated_at); 22265 function startEditing() { 22266 setDraft(savedHtml); 22267 setIsEditing(true); 22268 } 22269 function handleDraftChange(html$2) { 22270 setDraft(html$2); 22271 onUnsavedChangesChange?.(true); 22272 } 22273 function cancelEditing() { 22274 setDraft(savedHtml); 22275 setIsEditing(false); 22276 onUnsavedChangesChange?.(false); 22277 } 22278 async function save() { 22279 if (isSaving) return; 22280 const sanitized = sanitizeRichHtml(draft); 22281 const nextValue = isEmptyRichHtml(sanitized) ? "" : sanitized; 22282 setIsSaving(true); 22283 try { 22284 const response = await updateUpstreamEventInternalStrategy({ 22285 path: { event_uuid: eventId }, 22286 body: { internal_strategy: nextValue } 22287 }); 22288 if (response.error) throw response.error; 22289 setIsEditing(false); 22290 onUnsavedChangesChange?.(false); 22291 revalidator.revalidate(); 22292 } catch { 22293 toast({ 22294 title: "Failed to update Internal Strategy", 22295 variant: "destructive" 22296 }); 22297 } finally { 22298 setIsSaving(false); 22299 } 22300 } 22301 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventOverviewCard, { 22302 icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Notebook, { size: 16 }), 22303 title: "Internal Strategy",
22304 actions: canEdit ? isEditing ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 22305 className: "flex items-center gap-2", 22306 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { 22307 type: "button", 22308 variant: "outline", 22309 size: "sm", 22310 className: "bg-white", 22311 onClick: cancelEditing, 22312 disabled: isSaving, 22313 children: "Cancel" 22314 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { 22315 type: "button", 22316 size: "sm", 22317 onClick: () => void save(), 22318 disabled: isSaving, 22319 children: isSaving ? "Saving..." : "Save" 22320 })] 22321 }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { 22322 type: "button", 22323 variant: "outline", 22324 size: "sm", 22325 className: "bg-white", 22326 onClick: startEditing, 22327 children: "Edit" 22328 }) : null, 22329 footer: !isEditing && footerLabel ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 22330 className: "flex items-center gap-1.5 border-t border-zinc-200 px-4 py-2.5 text-xs text-zinc-500", 22331 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Edit, { size: 14 }), footerLabel] 22332 }) : null,
22333 children: isEditing ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(RichEditor, { 22334 content: savedHtml, 22335 onChange: handleDraftChange, 22336 placeholder: "Add an internal strategy..." 22337 }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(RichHtml, { 22338 html: savedHtml, 22339 emptyLabel: "No internal strategy yet" 22340 }) 22341 }); 22342} 22343function UnsavedChangesDialog({ open, onKeepEditing, onDiscard }) { 22344 const discardingRef = import_react.useRef(false); 22345 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AlertDialog, { 22346 open, 22347 onOpenChange: (nextOpen) => { 22348 if (!nextOpen && !discardingRef.current) onKeepEditing(); 22349 discardingRef.current = false; 22350 }, 22351 children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(AlertDialogContent, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(AlertDialogHeader, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(AlertDialogTitle, { children: "Discard unsaved changes?" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AlertDialogDescription, { children: "You have unsaved Internal Strategy changes. Leaving this page will discard them." })] }
22351), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(AlertDialogFooter, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(AlertDialogCancel, { children: "Keep editing" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AlertDialogAction, { 22352 variant: "destructive", 22353 onClick: () => { 22354 discardingRef.current = true; 22355 onDiscard(); 22356 }, 22357 children: "Discard changes" 22358 })] })] }) 22359 }); 22360} 22361function EventDetails() { 22362 const { eventMitigationProject } = ie(); 22363 const event = useEventDetails()?.event; 22364 const [activeTab, setActiveTab] = import_react.useState("overview"); 22365 const [hasUnsavedChanges, setHasUnsavedChanges] = import_react.useState(false); 22366 const { confirmIfDirty, keepEditing, discard, isPromptOpen } = useUnsavedChangesWarning(hasUnsavedChanges, () => setHasUnsavedChanges(false)); 22367 function handleTabChange(tab) { 22368 if (tab === activeTab) return; 22369 confirmIfDirty(() => setActiveTab(tab)); 22370 } 22371 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 22372 className: "h-full bg-background", 22373 children: [ 22374 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 22375 className: "w-full border-b border-border bg-white", 22376 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(containers_default, { 22377 variant: "header", 22378 className: "pt-0", 22379 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 22380 className: "flex flex-row flex-wrap items-center justify-between gap-2 py-4", 22381 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HeaderBreadcrumb, { 22382 breadcrumbItems: [{ 22383 backToLink: `/disruptions/events`, 22384 breadcrumbText: "Events" 22385 }, { 22386 backToLink: null, 22387 breadcrumbText: "Event Details" 22388 }], 22389 classNames: "p-0 border-none" 22390 }) 22391 }) 22392 }) 22393 }), 22394 !event ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(containers_default, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: "Event not found" }) }) : eventMitigationProject ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
22395 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(containers_default, { 22396 className: "pb-0", 22397 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventDetailsTitle, {}) 22398 }), 22399 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 22400 className: "border-b border-border", 22401 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(containers_default, { 22402 className: "py-0", 22403 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventDetailTabs, { 22404 activeTab, 22405 onTabChange: handleTabChange, 22406 itemsCount: event.products_affected 22407 }) 22408 }) 22409 }), 22410 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(containers_default, { 22411 className: "flex flex-col gap-4", 22412 children: activeTab === "overview" ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(InternalStrategy, { onUnsavedChangesChange: setHasUnsavedChanges }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventUpdates, {})] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventItems, {}) 22413 }) 22414 ] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(containers_default, { 22415 className: "flex flex-col gap-4", 22416 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventDetailsTitle, {}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventUpdates, {})] 22417 }), 22418 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(UnsavedChangesDialog, { 22419 open: isPromptOpen, 22420 onKeepEditing: keepEditing, 22421 onDiscard: discard 22422 }) 22423 ] 22424 }); 22425} 22426let EventSeverity = /* @__PURE__ */ function(EventSeverity$1) { 22427 EventSeverity$1[EventSeverity$1["LOW"] = 0] = "LOW"; 22428 EventSeverity$1[EventSeverity$1["MODERATE"] = 1] = "MODERATE"; 22429 EventSeverity$1[EventSeverity$1["MAJOR"] = 2] = "MAJOR"; 22430 EventSeverity$1[EventSeverity$1["CRITICAL"] = 3] = "CRITICAL"; 22431 return EventSeverity$1; 22432}({}); 22433const EVENT_SEVERITY_EXPLANATION = { 22434 [EventSeverity.LOW]: "Potential risk only, forward-looking plans, resolved issues, or financial announcements without immediate supply impact", 22435 [EventSeverity.MODERATE]: "Class III recall; regional shortage; warning letter that could escalate; price increase 2-10%", 22436 [EventSeverity.MAJOR]: "Class II recall; FDA shortage list; multi-state hospital impact; >10% price spike or prolonged rationing", 22437 [EventSeverity.CRITICAL]: "Class I recall; national shortage of life-support products; >50% U.S. supply lost; any event causing deaths or surgery cancellations" 22438}; 22439const EVENT_SEVERITY_NAME = { 22440 [EventSeverity.LOW]: "Low", 22441 [EventSeverity.MODERATE]: "Moderate", 22442 [EventSeverity.MAJOR]: "Major", 22443 [EventSeverity.CRITICAL]: "Critical" 22444}; 22445function EventSeverityBadge() { 22446 const event = useEventDetails()?.event; 22447 if (!event) return null; 22448 switch (event.severity) { 22449 case EventSeverity.LOW: return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BadgeWithTooltip, { 22450 severity: event.severity, 22451 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, { 22452 variant: "secondary", 22453 className: "cursor-default", 22454 children: "Low" 22455 }) 22456 }); 22457 case EventSeverity.MODERATE: return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BadgeWithTooltip, { 22458 severity: event.severity, 22459 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, { 22460 variant: "yellow", 22461 className: "cursor-default text-red-950", 22462 children: "Moderate" 22463 }) 22464 }); 22465 case EventSeverity.MAJOR: return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BadgeWithTooltip, { 22466 severity: event.severity, 22467 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, { 22468 variant: "warningMuted", 22469 className: "cursor-default", 22470 children: "Major" 22471 }) 22472 }); 22473 case EventSeverity.CRITICAL: return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BadgeWithTooltip, { 22474 severity: event.severity, 22475 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, { 22476 variant: "destructiveMuted", 22477 className: "cursor-default", 22478 children: "Critical" 22479 }) 22480 }); 22481 default: return null; 22482 } 22483} 22484function BadgeWithTooltip({ children, severity }) { 22485 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TooltipProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Tooltip, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TooltipTrigger, { 22486 asChild: true, 22487 children 22488 }
22488), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TooltipContent, { 22489 className: "flex w-[300px] flex-col gap-1 text-wrap p-2", 22490 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 22491 className: "type-body-xs pl-1 pt-1 font-medium", 22492 children: EVENT_SEVERITY_NAME[severity] 22493 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 22494 className: "type-body-2xs pl-1 font-medium leading-normal", 22495 children: EVENT_SEVERITY_EXPLANATION[severity] 22496 })] 22497 })] }) }); 22498} 22499function EventStatusBadge() { 22500 const event = useEventDetails()?.event; 22501 if (!event) return null; 22502 switch (event.status) { 22503 case EventStatus.ANNOUNCED: return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, { 22504 className: "bg-violet-200 text-violet-950", 22505 children: event.status 22506 }); 22507 case EventStatus.ONGOING: return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, { 22508 className: "bg-cyan-100 text-cyan-950", 22509 children: event.status 22510 }); 22511 case EventStatus.RESOLVED: return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, { 22512 className: "bg-zinc-200 text-zinc-800", 22513 children: event.status 22514 }); 22515 default: return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, { 22516 variant: "informative", 22517 children: event.status 22518 }); 22519 } 22520} 22521var EventStatus = { 22522 ANNOUNCED: "Announced", 22523 ONGOING: "Ongoing", 22524 RESOLVED: "Resolved" 22525}; 22526function EventSidebar() { 22527 const { eventMitigationProject, hasDrmV2 } = ie(); 22528 const data = useEventDetails(); 22529 if (!data?.event) return null; 22530 const { event } = data; 22531 const legacyDefaultDisruptionQueueParams = { 22532 ...DEFAULT_DISRUPTION_PARAMS, 22533 for_event: [event.event_id] 22534 }; 22535 const disruptionQueueLink = hasDrmV2 ? `/disruptions?page=1&page_size=25&days_calculated=30&for_event=${event.event_id}` : `/disruptions?${new URLSearchParams(convertFiltersToSearchParams(legacyDefaultDisruptionQueueParams)).toString()}`; 22536 const formattedPublishedDate = event.published_at && typeof event.published_at === "string" ? formatDate(event.published_at, "numeric", "2-digit", "2-digit") : "Unknown"; 22537 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(SideBarPaddingWrapper, { children: [ 22538 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SideBarSectionContainer, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarDetailContent, { 22539 label: "Event Type", 22540 classNames: "text-nowrap", 22541 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 22542 className: "flex flex-wrap justify-end gap-1", 22543 children: event.types.map((type) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, { 22544 variant: "informative", 22545 className: "text-nowrap", 22546 children: type 22547 }, type)) 22548 }) 22549 }) }), 22550 /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(SideBarSectionContainer, { children: [ 22551 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarDetailContent, { 22552 label: "Announced", 22553 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 22554 className: "type-body-xs text-zinc-500", 22555 children: formattedPublishedDate 22556 }) 22557 }), 22558 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarDetailContent, { 22559 label: "Status", 22560 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventStatusBadge, {}) 22561 }), 22562 eventMitigationProject ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarDetailContent, { 22563 label: "Your Status", 22564 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CustomerStatusField, { 22565 eventId: event.event_id, 22566 status: event.customer_status, 22567 display: event.customer_status_display 22568 }) 22569 }) : null, 22570 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarDetailContent, { 22571 label: "Severity", 22572 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventSeverityBadge, {}) 22573 }), 22574 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarDetailContent, { 22575 label: "Affected Items", 22576 children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 22577 className: "type-body-xs text-zinc-500", 22578 children: [event.products_affected, " items"] 22579 }) 22580 }), 22581 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarDetailContent, { 22582 label: "Impacted Locations", 22583 children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 22584 className: "type-body-xs text-zinc-500", 22585 children: [event.locations_impacted, " Locations"] 22586 }) 22587 }) 22588 ] }),
22589 !eventMitigationProject ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link, { 22590 to: disruptionQueueLink, 22591 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { 22592 className: "mt-3 w-full", 22593 children: "View Affected Items" 22594 }) 22595 }) : null 22596 ] }); 22597} 22598async function loader({ params }) { 22599 const { eventId } = params; 22600 invariant(eventId, "eventId is required"); 22601 const event = (await getUpstreamEventDetail({ path: { event_uuid: eventId } })).data; 22602 return { 22603 event, 22604 ...createBreadcrumbConfig({ 22605 label: event?.title || "Event Details", 22606 module: "DISRUPTION_MONITOR" 22607 }) 22608 }; 22609} 22610const useEventDetails = () => { 22611 return useRouteLoaderData("drm-event-details"); 22612}; 22613function Component() { 22614 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(PageLayoutRoot, { 22615 style: { "--sidebar-width": "340px" }, 22616 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(PageLayoutMain, { 22617 className: "bg-background", 22618 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventDetails, {}) 22619 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PageLayoutSidebar, { 22620 className: "relative overflow-hidden", 22621 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EventSidebar, {}) 22622 })] 22623 }); 22624} 22625export { Component, loader, useEventDetails }; 22626 22627//# sourceMappingURL=event-detail.route-C_BbJZKZ.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.