@koeroesi86/canvas-grid 26.11.8 → 26.11.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/build/types/types.d.ts +64 -0
- package/build/types/utils/cell-editors.d.ts +5 -0
- package/build/types/utils/data-store.d.ts +5 -0
- package/build/types/utils/edit-value.d.ts +18 -0
- package/build/types/utils/selection-navigation.d.ts +5 -0
- package/build/types/web-component.d.ts +49 -2
- package/build/web-component.js +2 -2
- package/build/web-component.js.map +1 -1
- package/build/web-component.mjs +420 -127
- package/build/web-component.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"web-component.js","names":["styles","throttle","debounce","factory","global","__create","__defProp","__getOwnPropDesc","__getOwnPropNames","__getProtoOf","__hasOwnProp","__commonJSMin","mod","cb","__copyProps","from","keys","i","n","key","to","except","k","desc","__toESM","isNodeMode","target","require_lodash_throttle","FUNC_ERROR_TEXT","NAN","reTrim","reIsBadHex","reIsBinary","reIsOctal","freeParseInt","freeGlobal","freeSelf","root","objectToString","nativeMax","nativeMin","now","debounce","lastArgs","lastThis","maxWait","result","timerId","lastCallTime","lastInvokeTime","leading","maxing","trailing","func","toNumber","wait","isObject","options","invokeFunc","args","thisArg","time","leadingEdge","timerExpired","remainingWait","timeSinceLastCall","timeSinceLastInvoke","shouldInvoke","trailingEdge","cancel","flush","debounced","isInvoking","throttle","\"leading\"","\"maxWait\"","\"trailing\"","type","value","isObjectLike","isSymbol","other","isBinary","require_lodash_debounce","import_lodash_throttle","import_lodash_debounce","Collection","entry","existing","matcher","id","fn","ColumnStore","length","slot","updatedAt","slots","MIN_HOLES_TO_COMPACT","RowStore","row","index","offset","low","high","middle","previous","replacement","added","height","heightOf","below","above","tolerance","removed","ids","indexes","a","b","holes","live","renumbered","rank","compare","moving","oldIndexes","inserts","positions","settledLength","end","at","items","write","read","removedIndex","rows","top","getNow","getRowId","collator","INCREMENTAL_SORT_RATIO","typeRank","compareValues","createDefaultKey","ranks","values","textIds","text","sorted","position","DataStore","environment","model","rowId","columnKey","data","changes","removals","moved","applyRemovals","column","kept","rowData","columnId","cached","only","rest","onlyColumn","precompute","sign","order","direction","sortKeys","changed","LruCache","limit","oldest","component_default","isNode","child","primitive","paint","ctx","props","x","y","Group","children","originX","originY","React","component","Renderer","getContext2d","canvas","Loading","color","Layer","name","width","pixelRatio","RendererRegistry","renderer","ref","Rect","w","h","alpha","HOVER_DURATION","REDUCED_MOTION_ALPHA","reducedMotionQuery","smoothstep","t","CellBackground","fade","duration","progress","eased","age","flashInDuration","flashOutDuration","remaining","flash","hover","background","zebraColor","hoverColor","flashColor","borderRightWidth","borderRightColor","borderBottomWidth","borderBottomColor","joiningCharacters","FIRST_COMPLEX_CODE","segmenter","toGraphemes","segment","toUnits","hasComplexCharacters","countFitting","used","units","widthOf","available","ellipsisWidth","ellipsis","sumWidths","total","MAX_CACHED_TEXTS","remember","cache","fitted","fitExactly","exact","whole","measure","scale","keep","unit","prefix","count","fitKerned","ellipsisHead","next","kerning","fitText","defaultTextStyle","FIRST_COMPLEX_CHARACTER","rightToLeftLetter","TextRenderer","font","style","known","measures","character","left","right","state","textRendering","fontKerning","letterSpacing","totalWidth","cellPadding","clip","rightToLeft","textX","ARROW_WIDTH","ARROW_HEIGHT","ARROW_ALPHA","SortIndicator","ascending","HeaderRenderer","selected","formatted","CellValueRenderer","valueChanged","forced","resolveFont","fallback","THEME_TOKENS","shared","THEME_DEFAULTS","PIXEL_KEYS","FONT_KEYS","toPixels","pixels","readTheme","defaults","parse","isFont","isColor","isSameTheme","createColorCheck","onBlack","isCssFont","clampWidth","minWidth","maxWidth","buildOffsets","offsets","widths","columnAt","last","borderAt","rightOfPrevious","rightOfCurrent","span","makeRange","columns","rangeBetween","rangeFor","mode","normalizeSpan","normalizeRange","range","copySpan","copyRange","resolve","bottom","rowCount","columnCount","within","coversAll","contains","columnLevel","level","ranges","rowLevel","shapeOf","lineRange","axis","linePosition","cross","lineIndex","crossIndex","sameSpan","sameRange","samePosition","clampSpan","clampPosition","SelectionModel","active","focus","normalized","start","dragScrollSpeed","min","max","clamp","moveTarget","lastRow","lastColumn","ctrl","pageRows","stepWithin","backwards","alongFirst","alongLast","crossFirst","crossLast","bounds","along","crossCount","wrapped","revealOffset","scroll","size","MAX_COPY_CELLS","escapeField","toTsv","maxCells","textAt","ContextMenu","host","onPick","menu","entries","clientX","clientY","item","event","label","disabled","step","classes","RESIZE_GRAB","RESIZE_EVENT_INTERVAL_MS","AUTO_SIZE_SAMPLE_ROWS","TAP_SLOP","builtIn","BUILT_IN_LAYERS","STYLE_ELEMENT_ID","injectStyles","parentOf","element","ancestorsOf","chain","current","FRAME_JITTER_MS","DEFAULT_FONT","DEFAULT_HEADER_FONT","CanvasGridComponent","prevSize","getId","layer","before","candidate","scrollArea","debounceAfterScroll","attribute","token","sizeChanged","theme","delta","overrides","refs","redrawAll","keepDrawing","fakeRowIndex","header","xOffset","firstRow","visibleColumns","rowIndex","currentY","cellRow","store","animating","visible","columnOffsets","columnList","rectOf","rect","cell","scrollTop","padding","widest","texts","content","grab","pointerType","rowNumbers","headers","resizeDrag","horizontal","resizeGuide","drag","free","touch","change","selecting","contentX","contentY","inHeader","inRowNumbers","selectionModel","extend","additive","hit","modifiers","anchor","touchTap","selectDrag","dx","dy","scrollLeft","shape","shiftKey","copied","byPointer","detail","add","update","remove","v"],"sources":["../node_modules/lodash.throttle/index.js","../node_modules/lodash.debounce/index.js","../components/utils/collection.ts","../components/utils/column-store.ts","../components/utils/row-store.ts","../components/utils/selectors.ts","../components/utils/data-store.ts","../components/utils/lru-cache.ts","../components/utils/jsx.ts","../components/utils/renderer.ts","../components/utils/canvas.ts","../components/utils/loading.ts","../components/utils/layer.ts","../components/utils/renderer-registry.ts","../components/rectangle/index.ts","../components/cell-background/index.tsx","../components/utils/fit-text.ts","../components/text/index.ts","../components/sort-indicator/index.ts","../components/header/index.tsx","../components/cell-value/index.tsx","../components/utils/inherited-font.ts","../components/utils/theme.ts","../components/utils/column-layout.ts","../components/utils/selection.ts","../components/utils/selection-navigation.ts","../components/utils/clipboard.ts","../components/utils/context-menu.ts","../components/web-component.ts"],"sourcesContent":["/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the `TypeError` message for \"Functions\" methods. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n return root.Date.now();\n};\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n result = wait - timeSinceLastCall;\n\n return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\n/**\n * Creates a throttled function that only invokes `func` at most once per\n * every `wait` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `func` invocations and a `flush` method to\n * immediately invoke them. Provide `options` to indicate whether `func`\n * should be invoked on the leading and/or trailing edge of the `wait`\n * timeout. The `func` is invoked with the last arguments provided to the\n * throttled function. Subsequent calls to the throttled function return the\n * result of the last `func` invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the throttled function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.throttle` and `_.debounce`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=true]\n * Specify invoking on the leading edge of the timeout.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // Avoid excessively updating the position while scrolling.\n * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n *\n * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });\n * jQuery(element).on('click', throttled);\n *\n * // Cancel the trailing throttled invocation.\n * jQuery(window).on('popstate', throttled.cancel);\n */\nfunction throttle(func, wait, options) {\n var leading = true,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (isObject(options)) {\n leading = 'leading' in options ? !!options.leading : leading;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n return debounce(func, wait, {\n 'leading': leading,\n 'maxWait': wait,\n 'trailing': trailing\n });\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && objectToString.call(value) == symbolTag);\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = throttle;\n","/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the `TypeError` message for \"Functions\" methods. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n return root.Date.now();\n};\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n result = wait - timeSinceLastCall;\n\n return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && objectToString.call(value) == symbolTag);\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = debounce;\n","import type { Key } from '../types';\n\ninterface Entry<T> {\n key: Key;\n value: T;\n}\n\n/**\n * Insertion-ordered map. Keys are compared as strings (1 and '1' are the same entry),\n * and every operation is O(1) apart from iteration.\n */\nclass Collection<T> {\n private entries = new Map<string, Entry<T>>();\n\n constructor() {\n this.get = this.get.bind(this);\n this.set = this.set.bind(this);\n this.clear = this.clear.bind(this);\n this.forEach = this.forEach.bind(this);\n }\n\n get keys(): Key[] {\n return Array.from(this.entries.values(), entry => entry.key);\n }\n\n get(key: Key): T | undefined {\n return this.entries.get(String(key))?.value;\n }\n\n set(key: Key, value: T) {\n const existing = this.entries.get(String(key));\n if (existing) {\n existing.value = value;\n return;\n }\n this.entries.set(String(key), { key, value });\n }\n\n add(value: T) {\n this.set(this.entries.size, value);\n }\n\n delete(key: Key) {\n this.entries.delete(String(key));\n }\n\n clear(matcher?: (item: T, key: Key) => boolean) {\n if (typeof matcher !== 'function') {\n this.entries.clear();\n return;\n }\n this.entries.forEach(({ key, value }, id) => {\n if (matcher(value, key)) this.entries.delete(id);\n });\n }\n\n forEach(fn: (item: T, key: Key) => void) {\n this.entries.forEach(({ key, value }) => fn(value, key));\n }\n\n get length() {\n return this.entries.size;\n }\n}\n\nexport default Collection;\n","/**\n * Values of one column for all rows, indexed by row slot. Two flat arrays instead of an object per cell.\n * `undefined` means the row has no value in this column.\n */\nclass ColumnStore {\n values: unknown[];\n\n /** Changes whenever a value is set, cleared or moved, so results computed from the values can be reused while it stays the same. */\n version = 0;\n\n /** When each value last changed, 0 when unknown; only allocated once a value changes after loading. */\n private updatedAt: number[] | undefined = undefined;\n\n constructor(length = 0) {\n this.values = new Array(length).fill(undefined);\n }\n\n get(slot: number) {\n return this.values[slot];\n }\n\n getUpdatedAt(slot: number): number | undefined {\n return this.updatedAt?.[slot] || undefined;\n }\n\n set(slot: number, value: unknown, updatedAt?: number) {\n this.version++;\n while (this.values.length < slot) this.values.push(undefined);\n this.values[slot] = value;\n if (updatedAt === undefined && this.updatedAt === undefined) return;\n\n this.updatedAt ??= new Array(this.values.length).fill(0);\n while (this.updatedAt.length < this.values.length) this.updatedAt.push(0);\n this.updatedAt[slot] = updatedAt ?? 0;\n }\n\n /** Empties the given slots, leaving holes; the other slots keep their place. */\n clearSlots(slots: readonly number[]) {\n this.version++;\n slots.forEach(slot => {\n if (slot < this.values.length) this.values[slot] = undefined;\n if (this.updatedAt && slot < this.updatedAt.length) this.updatedAt[slot] = 0;\n });\n }\n\n /** Keeps only the given slots (ascending), renumbering them 0, 1, 2... in that order. */\n compact(slots: ArrayLike<number>) {\n this.version++;\n this.values = Array.from(slots, slot => this.values[slot]);\n const { updatedAt } = this;\n if (updatedAt) this.updatedAt = Array.from(slots, slot => updatedAt[slot] ?? 0);\n }\n}\n\nexport default ColumnStore;\n","import type { Key, RowData, RowId } from '../types';\n\nexport type Row = RowData;\n\n/** Holes below this are not worth a pass over every column. */\nconst MIN_HOLES_TO_COMPACT = 1024;\n\n/**\n * Rows in display order: a dense array with an id lookup and each row's top offset,\n * so appends, lookups and finding the row at a scroll offset never scan every row.\n * Removing rows renumbers the positions after the first removed one (once per call).\n * Rows keep a `slot` into the column stores that does not change when the rows are sorted or others removed;\n * removed rows leave holes, which are closed when they outnumber the rows.\n */\nclass RowStore {\n private items: Row[] = [];\n\n private readonly byId = new Map<string, Row>();\n\n /** `tops[i]` is the offset of row `i` from the top of the first row. */\n private tops: number[] = [];\n\n private end = 0;\n\n /** Slots handed out so far, including holes left by removed rows. */\n private nextSlot = 0;\n\n get length() {\n return this.items.length;\n }\n\n /** Sum of all row heights. */\n get totalHeight() {\n return this.end;\n }\n\n /** Number of slots in use or left as holes; the length the column stores need. */\n get slotCount() {\n return this.nextSlot;\n }\n\n get keys(): RowId[] {\n return this.items.map(row => row.id);\n }\n\n get(id: Key): Row | undefined {\n return this.byId.get(String(id));\n }\n\n at(index: number): Row | undefined {\n return this.items[index];\n }\n\n topOf(index: number) {\n return this.tops[index] ?? this.end;\n }\n\n /** Index of the first row that ends below `offset`; `length` when the offset is past the last row. */\n indexAt(offset: number) {\n if (offset <= 0) return 0;\n if (offset >= this.end) return this.length;\n\n let low = 0;\n let high = this.items.length - 1;\n while (low < high) {\n const middle = Math.ceil((low + high) / 2);\n if (this.tops[middle] <= offset) low = middle;\n else high = middle - 1;\n }\n return low;\n }\n\n /** Appends the row, or replaces the row with the same id in place; returns the stored row. */\n set(row: Omit<Row, 'index' | 'slot'>): Row {\n const key = String(row.id);\n const previous = this.byId.get(key);\n if (previous) {\n const replacement = { id: row.id, height: row.height, index: previous.index, slot: previous.slot };\n this.items[previous.index] = replacement;\n this.byId.set(key, replacement);\n this.reindexFrom(previous.index);\n return replacement;\n }\n\n const index = this.items.length;\n const added = { id: row.id, height: row.height, index, slot: this.nextSlot++ };\n this.items.push(added);\n this.byId.set(key, added);\n this.tops.push(this.end);\n this.end += Math.round(row.height);\n return added;\n }\n\n /** Sets one row's height and moves the rows below it; returns whether anything changed. Costs the rows after it. */\n setHeight(id: Key, height: number) {\n const row = this.get(id);\n if (!row || row.height === height) return false;\n\n row.height = height;\n this.reindexFrom(row.index);\n return true;\n }\n\n /** Sets every row's height in one pass. */\n setHeights(heightOf: (id: RowId) => number) {\n this.items.forEach(row => { row.height = heightOf(row.id); });\n this.reindexFrom(0);\n }\n\n /**\n * Index of the row whose bottom border is within `tolerance` of `offset` (measured like `topOf`), or -1.\n * The border above a row belongs to the row before it; where two are in reach the nearer wins.\n */\n borderAt(offset: number, tolerance: number) {\n if (this.items.length === 0) return -1;\n\n const index = this.indexAt(offset);\n const below = index < this.items.length ? Math.abs(this.topOf(index + 1) - offset) : Infinity;\n const above = index > 0 ? Math.abs(this.topOf(index) - offset) : Infinity;\n if (Math.min(above, below) > tolerance) return -1;\n return above < below ? index - 1 : index;\n }\n\n /**\n * Removes the rows with the given ids, ignoring unknown ones.\n * Returns the slots of the removed rows in ascending order, which the column stores must clear.\n * Other rows keep their slots, so removing costs nothing per column; see `compactSlots`.\n */\n removeMany(ids: Key[]): number[] {\n const removed = new Set<Row>();\n ids.forEach(id => {\n const row = this.get(id);\n if (row) removed.add(row);\n });\n if (removed.size === 0) return [];\n\n removed.forEach(row => this.byId.delete(String(row.id)));\n const indexes = Array.from(removed, row => row.index).sort((a, b) => a - b);\n\n this.closeGaps(indexes);\n this.reindexFrom(indexes[0]);\n return Array.from(removed, row => row.slot).sort((a, b) => a - b);\n }\n\n /**\n * Renumbers the slots densely once more than half of them are holes left by removed rows.\n * Returns the previous slots of the remaining rows in ascending order (the column stores keep exactly those),\n * or undefined when nothing was renumbered. Doing this rarely keeps removal cheap for streams that drop old rows.\n */\n compactSlots(): Int32Array | undefined {\n const holes = this.nextSlot - this.items.length;\n if (holes < MIN_HOLES_TO_COMPACT || holes <= this.items.length) return undefined;\n\n const live = Int32Array.from(this.items, row => row.slot).sort();\n const renumbered = new Int32Array(this.nextSlot);\n live.forEach((slot, rank) => { renumbered[slot] = rank; });\n this.items.forEach(row => { row.slot = renumbered[row.slot]; });\n this.nextSlot = this.items.length;\n return live;\n }\n\n /** Reorders the rows; the sort is stable, so equal rows keep their relative order. */\n sort(compare: (a: Row, b: Row) => number) {\n this.items.sort(compare);\n this.reindexFrom(0);\n }\n\n /**\n * Puts the given rows back in order, assuming every other row is already ordered.\n * `compare` must be a total order (no ties), which a slot tiebreak provides. Costs one comparison pass per\n * moved row (a binary search) plus a copy, instead of sorting every row.\n */\n resort(ids: Iterable<Key>, compare: (a: Row, b: Row) => number) {\n const moving = new Set<Row>();\n for (const id of ids) {\n const row = this.get(id);\n if (row) moving.add(row);\n }\n if (moving.size === 0) return;\n\n const oldIndexes = Array.from(moving, row => row.index).sort((a, b) => a - b);\n this.closeGaps(oldIndexes);\n\n // only the moving rows are compared; the rest is moved around with memmoves, never visited one by one\n const inserts = Array.from(moving).sort(compare);\n const positions = inserts.map(row => this.lowerBound(this.items, row, compare));\n const settledLength = this.items.length;\n inserts.forEach(row => this.items.push(row));\n\n // from the back, so every settled row moves once, past the inserts that end up before it\n const { items } = this;\n let end = settledLength;\n for (let at = inserts.length - 1; at >= 0; at--) {\n for (let from = end - 1; from >= positions[at]; from--) items[from + at + 1] = items[from];\n items[positions[at] + at] = inserts[at];\n end = positions[at];\n }\n\n this.reindexFrom(Math.min(oldIndexes[0], positions[0]));\n }\n\n clear() {\n this.items = [];\n this.byId.clear();\n this.tops = [];\n this.end = 0;\n this.nextSlot = 0;\n }\n\n /** Removes the items at the given ascending indexes in place, moving the others down in runs. */\n private closeGaps(indexes: readonly number[]) {\n const { items } = this;\n let write = indexes[0];\n indexes.forEach((removedIndex, at) => {\n const end = indexes[at + 1] ?? items.length;\n // a plain loop: Array.prototype.copyWithin is much slower than this on arrays of objects\n for (let read = removedIndex + 1; read < end; read++) items[write++] = items[read];\n });\n items.length = write;\n }\n\n /** Index of the first row in `rows` that is not ordered before `row`. */\n private lowerBound(rows: Row[], row: Row, compare: (a: Row, b: Row) => number) {\n let low = 0;\n let high = rows.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (compare(rows[middle], row) < 0) low = middle + 1;\n else high = middle;\n }\n return low;\n }\n\n /** Recomputes positions and offsets from `from` onwards. */\n private reindexFrom(from: number) {\n this.tops.length = this.items.length;\n let top = from === 0 ? 0 : this.tops[from - 1] + Math.round(this.items[from - 1].height);\n for (let index = from; index < this.items.length; index++) {\n const row = this.items[index];\n row.index = index;\n this.tops[index] = top;\n top += Math.round(row.height);\n }\n this.end = top;\n }\n}\n\nexport default RowStore;\n","import type { RowId, RowInput } from '../types';\n\nexport const getNow = () => new Date().valueOf();\n\nexport const getRowId = (row: RowInput, _index?: number): RowId => row.id;\n","import ColumnStore from './column-store';\nimport RowStore from './row-store';\nimport { getNow } from './selectors';\nimport type { Row } from './row-store';\nimport type { Key, RowId, RowInput, SortKey } from '../types';\n\nexport type RowIdGetter = (row: RowInput, index?: number) => RowId;\n\nexport interface DataStoreEnvironment {\n getRowId: RowIdGetter;\n getCellHeight: () => number;\n /** The height a row should have when it differs from `getCellHeight()`, asked once its values are stored. */\n getRowHeight?: (id: RowId) => number | undefined;\n}\n\ninterface PendingChange {\n type: 'update' | 'remove';\n row: RowInput;\n}\n\nconst collator = new Intl.Collator();\n\n/** Fewer changed rows than this fraction of all rows are moved one by one; more are cheaper to sort together. */\nconst INCREMENTAL_SORT_RATIO = 8;\n\nconst typeRank = (value: unknown) => {\n if (value === undefined || value === null) return 3;\n if (typeof value === 'number' || typeof value === 'bigint') return 0;\n return typeof value === 'string' ? 1 : 2;\n};\n\n/** Numbers numerically, then text, then anything else as text; empty values sort last. */\nexport const compareValues = (a: unknown, b: unknown) => {\n const rank = typeRank(a) - typeRank(b);\n if (rank !== 0) return rank;\n if (typeRank(a) === 3) return 0;\n if (typeRank(a) === 0) return Number(a) - Number(b);\n return collator.compare(String(a), String(b));\n};\n\n/**\n * Sort keys for the default ordering of a column, computed once so comparing two rows is two array reads:\n * a type rank, and within it a number (the value, or the position of its text among all the column's texts).\n */\nconst createDefaultKey = (values: readonly unknown[]) => {\n const ranks = new Uint8Array(values.length);\n const keys = new Float64Array(values.length);\n // every distinct text gets an id on the way, so ranks can be looked up by index instead of by text again\n const textIds = new Int32Array(values.length);\n const ids = new Map<string, number>();\n for (let slot = 0; slot < values.length; slot++) {\n const value = values[slot];\n const rank = typeRank(value);\n ranks[slot] = rank;\n if (rank === 0) {\n keys[slot] = Number(value);\n continue;\n }\n if (rank !== 1 && rank !== 2) continue;\n\n const text = String(value);\n let id = ids.get(text);\n if (id === undefined) {\n id = ids.size;\n ids.set(text, id);\n }\n textIds[slot] = id;\n }\n\n // equal texts (as the collator sees them) share a position, so they tie and fall through to the next key\n const positions = new Float64Array(ids.size);\n const sorted = Array.from(ids.keys()).sort(collator.compare);\n let position = 0;\n sorted.forEach((text, index) => {\n if (index > 0 && collator.compare(sorted[index - 1], text) !== 0) position++;\n positions[ids.get(text) ?? 0] = position;\n });\n for (let slot = 0; slot < values.length; slot++) {\n if (ranks[slot] === 1 || ranks[slot] === 2) keys[slot] = positions[textIds[slot]];\n }\n return { ranks, keys };\n};\n\ntype DefaultKey = ReturnType<typeof createDefaultKey>;\n\n/**\n * Cell values stored by column (one array per column, addressed by the row's slot) plus the row order,\n * with the queued add/update/remove handling and the sort model. Independent of the DOM.\n */\nclass DataStore {\n rows = new RowStore();\n columns = new Map<string, ColumnStore>();\n\n /** Queued changes, applied in the order they were made. */\n private pending: PendingChange[] = [];\n private sortModel: readonly SortKey[] = [];\n private sortDirty = false;\n /** Ids of the rows changed since the last sort; only those have to move when few changed. */\n private sortChanged = new Set<string>();\n /** Sort keys per column, reused until the column's values change (e.g. when only the direction flips). */\n private defaultKeys = new WeakMap<ColumnStore, { version: number; key: DefaultKey }>();\n\n private environment: DataStoreEnvironment;\n\n constructor(environment: DataStoreEnvironment) {\n this.environment = environment;\n }\n\n get hasPending() {\n return this.pending.length > 0;\n }\n\n getSortModel() {\n return this.sortModel;\n }\n\n /** Orders the rows by the given columns, in priority order; an empty model restores the insertion order. */\n setSortModel(model: readonly SortKey[]) {\n this.sortModel = [...model];\n this.sort();\n }\n\n /** Value of a cell, `undefined` when the row has none. */\n getValue(rowId: RowId, columnKey: Key) {\n const row = this.rows.get(rowId);\n return row ? this.columns.get(String(columnKey))?.get(row.slot) : undefined;\n }\n\n getUpdatedAt(rowId: RowId, columnKey: Key) {\n const row = this.rows.get(rowId);\n return row ? this.columns.get(String(columnKey))?.getUpdatedAt(row.slot) : undefined;\n }\n\n queueUpdate(row: RowInput) {\n this.pending.push({ type: 'update', row });\n }\n\n queueRemove(row: RowInput) {\n this.pending.push({ type: 'remove', row });\n }\n\n clear() {\n this.rows.clear();\n this.columns.clear();\n }\n\n /** Replaces everything, dropping any queued changes. */\n setRows(data: RowInput[]) {\n this.pending = [];\n this.clear();\n this.sortChanged.clear();\n // size the columns of the first row up front instead of growing them one value at a time\n Object.keys(data[0] ?? {}).forEach(key => this.columns.set(key, new ColumnStore(data.length)));\n data.forEach((row, index) => this.addRow(this.environment.getRowId(row, index), row, undefined));\n // rows were added in insertion order, which is the order without a sort model\n if (this.sortModel.length > 0) this.sort();\n }\n\n /**\n * Applies the queued changes in the order they were queued; consecutive removals are applied together.\n * Returns whether rows changed position (removed or re-sorted), which needs the whole grid to be redrawn.\n */\n flush(now = getNow()) {\n const changes = this.pending;\n this.pending = [];\n const removals: Key[] = [];\n let moved = false;\n const applyRemovals = () => {\n moved = this.removeRows(removals) || moved;\n removals.length = 0;\n };\n\n changes.forEach(({ type, row }) => {\n if (type === 'remove') {\n removals.push(this.environment.getRowId(row));\n return;\n }\n applyRemovals();\n this.applyUpdate(row, now);\n });\n applyRemovals();\n\n if (!this.sortDirty) return moved;\n this.sortChanges();\n return true;\n }\n\n private column(key: string) {\n let column = this.columns.get(key);\n if (!column) {\n column = new ColumnStore(this.rows.slotCount);\n this.columns.set(key, column);\n }\n return column;\n }\n\n private addRow(id: RowId, row: RowInput, updatedAt: number | undefined) {\n const { slot } = this.rows.set({ id, height: this.environment.getCellHeight() });\n const keys = Object.keys(row);\n for (const key of keys) this.column(key).set(slot, row[key], updatedAt);\n this.markSortDirty(id, keys);\n const height = this.environment.getRowHeight?.(id);\n if (height !== undefined) this.rows.setHeight(id, height);\n }\n\n private removeRows(ids: Key[]) {\n if (ids.length === 0) return false;\n\n const slots = this.rows.removeMany(ids);\n this.columns.forEach(column => column.clearSlots(slots));\n const kept = this.rows.compactSlots();\n if (kept) this.columns.forEach(column => column.compact(kept));\n return slots.length > 0;\n }\n\n private applyUpdate(row: RowInput, now: number) {\n const rowId = this.environment.getRowId(row);\n const rowData = this.rows.get(rowId);\n if (!rowData) {\n this.addRow(rowId, row, now);\n return;\n }\n Object.keys(row).forEach(key => this.applyValue(rowData.id, rowData.slot, key, row[key], now));\n }\n\n private applyValue(rowId: RowId, slot: number, key: string, value: unknown, now: number) {\n const column = this.column(key);\n const previous = column.get(slot);\n if (previous === value) return;\n // a value appearing in a column the row did not have yet is not an update worth flashing\n column.set(slot, value, previous === undefined ? undefined : now);\n this.markSortDirty(rowId, [key]);\n }\n\n private markSortDirty(rowId: RowId, keys: string[]) {\n if (!this.sortModel.some(({ columnId }) => keys.includes(String(columnId)))) return;\n this.sortDirty = true;\n this.sortChanged.add(String(rowId));\n }\n\n private defaultKeyOf(column: ColumnStore) {\n const cached = this.defaultKeys.get(column);\n if (cached && cached.version === column.version) return cached.key;\n\n const key = createDefaultKey(column.values);\n this.defaultKeys.set(column, { version: column.version, key });\n return key;\n }\n\n /** Orders two rows by the sort model, ties by slot so the order is total. */\n private createComparator(precompute: boolean) {\n const [only, ...rest] = this.sortModel;\n const onlyColumn = only && !only.compare && precompute && rest.length === 0 ? this.columns.get(String(only.columnId)) : undefined;\n if (onlyColumn) {\n // the common case, a single default-ordered column, without the per-key loop and calls\n const { ranks, keys } = this.defaultKeyOf(onlyColumn);\n const sign = only.direction === 'desc' ? -1 : 1;\n return (a: Row, b: Row) => {\n const order = ranks[a.slot] - ranks[b.slot] || keys[a.slot] - keys[b.slot] || 0;\n return order === 0 ? a.slot - b.slot : order * sign;\n };\n }\n\n const keys = this.sortModel.map(({ columnId, direction = 'asc', compare }) => {\n const column = this.columns.get(String(columnId));\n const values = column?.values;\n const sign = direction === 'desc' ? -1 : 1;\n if (!column || !values) return { order: () => 0, sign };\n if (compare) return { order: (a: Row, b: Row) => compare(values[a.slot], values[b.slot]), sign };\n if (!precompute) return { order: (a: Row, b: Row) => compareValues(values[a.slot], values[b.slot]), sign };\n\n const { ranks, keys: sortKeys } = this.defaultKeyOf(column);\n return {\n order: (a: Row, b: Row) => ranks[a.slot] - ranks[b.slot] || sortKeys[a.slot] - sortKeys[b.slot] || 0,\n sign,\n };\n });\n\n return (a: Row, b: Row) => {\n for (const { order, sign } of keys) {\n const result = order(a, b);\n if (result !== 0) return result * sign;\n }\n return a.slot - b.slot;\n };\n }\n\n private sort() {\n this.sortDirty = false;\n this.sortChanged.clear();\n this.rows.sort(this.createComparator(true));\n }\n\n /** Re-sorts after a flush: moves only the changed rows when they are few, otherwise sorts everything. */\n private sortChanges() {\n const changed = this.sortChanged;\n if (changed.size * INCREMENTAL_SORT_RATIO >= this.rows.length) {\n this.sort();\n return;\n }\n\n this.sortDirty = false;\n this.sortChanged = new Set();\n this.rows.resort(changed, this.createComparator(false));\n }\n}\n\nexport default DataStore;\n","/** Size-bounded map that evicts the least recently used entry first. */\nclass LruCache<T> {\n private readonly entries = new Map<string, T>();\n\n private readonly limit: number;\n\n constructor(limit: number) {\n this.limit = limit;\n }\n\n get(key: string): T | undefined {\n const value = this.entries.get(key);\n if (value === undefined) return undefined;\n // re-insert so iteration order tracks recency\n this.entries.delete(key);\n this.entries.set(key, value);\n return value;\n }\n\n set(key: string, value: T) {\n this.entries.delete(key);\n this.entries.set(key, value);\n const [oldest] = this.entries.keys();\n if (this.entries.size > this.limit && oldest !== undefined) this.entries.delete(oldest);\n }\n\n clear() {\n this.entries.clear();\n }\n\n get size() {\n return this.entries.size;\n }\n}\n\nexport default LruCache;\n","/**\n * Minimal declarative layer over the canvas 2D API.\n *\n * `<Group>` and friends do not draw when evaluated. They build a light tree of nodes, and calling\n * `node.draw(ctx, x, y)` paints it, with `(x, y)` as the origin that child positions are relative to.\n * Nothing is rasterized to an intermediate canvas unless a component opts into bitmap caching.\n */\nexport interface VNode {\n draw(ctx: CanvasRenderingContext2D, x: number, y: number): void;\n}\n\n/** `false`, `null` and `undefined` are skipped, so `{condition && <Rect />}` works. */\nexport type Child = VNode | false | null | undefined;\n\nexport type Children = Child | readonly Child[];\n\nexport interface ChildrenProps {\n /** A single child, an array of them, or the mix of both that JSX produces for several children. */\n children?: Children | readonly Children[];\n}\n\nexport type Component<Props extends object> = (props: Props) => VNode;\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n type Element = VNode;\n interface ElementChildrenAttribute {\n children: unknown;\n }\n interface IntrinsicElements {}\n }\n}\n\nconst isNode = (child: Child): child is VNode => !!child;\n\n/** Wraps a paint function into a leaf component; positions in `props` are relative to the draw origin. */\nexport const primitive = <Props extends object>(\n paint: (ctx: CanvasRenderingContext2D, props: Props, x: number, y: number) => void,\n): Component<Props> => props => ({\n draw: (ctx, x, y) => paint(ctx, props, x, y),\n});\n\nexport interface GroupProps extends ChildrenProps {\n x?: number;\n y?: number;\n}\n\n/** Draws its children relative to its own offset. */\nexport const Group: Component<GroupProps> = ({ x = 0, y = 0, children }) => ({\n draw: (ctx, originX, originY) => [children]\n .flat(2)\n .filter(isNode)\n .forEach(child => child.draw(ctx, originX + x, originY + y)),\n});\n\nconst React = {\n createElement<Props extends object>(\n component: Component<Props & ChildrenProps>,\n props: Props | null,\n ...children: Children[]\n ): VNode {\n return component(Object.assign({}, props, { children }));\n },\n};\n\nexport default React;\n","import LruCache from './lru-cache';\nimport { primitive } from './jsx';\nimport type { RenderProps } from '../types';\n\nabstract class Renderer<Options extends object> {\n readonly options: Options;\n\n protected constructor(options: Options) {\n this.options = { ...options };\n }\n\n /** Applies the given options and notifies `optionsUpdated` with the previous ones. */\n update(options: Partial<Options>) {\n const previous = { ...this.options };\n Object.assign(this.options, options);\n this.optionsUpdated(previous);\n }\n\n optionsUpdated(_previous: Options) {}\n\n clearCache() {}\n}\n\n/**\n * Renderer producing a bitmap from props; usable as a JSX tag through `element`.\n * Bitmaps are reused through a bounded LRU cache whenever `cacheKey` returns a key.\n */\nexport abstract class CanvasRenderer<Options extends object> extends Renderer<Options> {\n private readonly bitmaps = new LruCache<HTMLCanvasElement>(4096);\n\n abstract render(props: RenderProps): HTMLCanvasElement;\n\n /** Props with the same key must render the same pixels. Undefined disables caching. */\n protected cacheKey(_props: RenderProps): string | undefined {\n return undefined;\n }\n\n /** Device pixels per CSS pixel of the layer being drawn to; bitmaps are rendered at this scale to stay sharp. */\n pixelRatio = 1;\n\n clearCache() {\n this.bitmaps.clear();\n }\n\n paint(ctx: CanvasRenderingContext2D, props: RenderProps, x: number, y: number) {\n const key = this.cacheKey(props);\n const bitmap = (key === undefined ? undefined : this.bitmaps.get(key)) ?? this.renderBitmap(props, key);\n if (bitmap.width <= 0 || bitmap.height <= 0) return;\n ctx.drawImage(bitmap, x + (props.x ?? 0), y + (props.y ?? 0), bitmap.width / this.pixelRatio, bitmap.height / this.pixelRatio);\n }\n\n readonly element = primitive<RenderProps>((ctx, props, x, y) => this.paint(ctx, props, x, y));\n\n private renderBitmap(props: RenderProps, key: string | undefined) {\n const canvas = this.render(props);\n if (key === undefined || canvas.width <= 0 || canvas.height <= 0) return canvas;\n\n const bitmap = document.createElement('canvas');\n bitmap.width = canvas.width;\n bitmap.height = canvas.height;\n bitmap.getContext('2d')?.drawImage(canvas, 0, 0);\n this.bitmaps.set(key, bitmap);\n return bitmap;\n }\n}\n\nexport default Renderer;\n","export const getContext2d = (canvas: HTMLCanvasElement, options?: CanvasRenderingContext2DSettings) => {\n const ctx = canvas.getContext('2d', options);\n if (!ctx) throw new Error('2D canvas context is not available');\n return ctx;\n};\n","import Renderer from './renderer';\nimport { getContext2d } from './canvas';\n\ninterface LoadingOptions {\n ctx: CanvasRenderingContext2D;\n}\n\nclass Loading extends Renderer<LoadingOptions> {\n private readonly ctx: CanvasRenderingContext2D;\n\n private readonly offCanvas = document.createElement('canvas');\n\n private readonly offCtx: CanvasRenderingContext2D;\n\n private rotation = 270 * (Math.PI / 180);\n\n private readonly speed = 6;\n\n private readonly count = 75;\n\n constructor(options: LoadingOptions) {\n super(options);\n\n this.ctx = this.options.ctx;\n\n this.offCanvas.width = 250;\n this.offCanvas.height = 250;\n this.offCtx = getContext2d(this.offCanvas);\n this.offCtx.lineWidth = 0.5;\n this.setColor('rgba(255, 255, 255, 0.75)');\n }\n\n /** The colour the loader is drawn in; it takes a moment to fully replace the old one. */\n setColor(color: string) {\n this.offCtx.strokeStyle = color;\n }\n\n updateLoader() {\n this.rotation += this.speed / 100;\n }\n\n renderLoader() {\n this.offCtx.save();\n this.offCtx.globalCompositeOperation = 'source-over';\n this.offCtx.translate(125, 125);\n this.offCtx.rotate(this.rotation);\n let i = this.count;\n while (i--) {\n this.offCtx.beginPath();\n this.offCtx.arc(0, 0, i + (Math.random() * 35), Math.random(), Math.PI / 3 + (Math.random() / 12), false);\n this.offCtx.stroke();\n }\n this.offCtx.restore();\n }\n\n render() {\n this.offCtx.globalCompositeOperation = 'destination-out';\n this.offCtx.fillStyle = 'rgba(255, 255, 255, 0.03)';\n this.offCtx.fillRect(0, 0, 250, 250);\n this.updateLoader();\n this.renderLoader();\n\n const x = Math.round((this.ctx.canvas.width - this.offCanvas.width) / 2);\n const y = Math.round((this.ctx.canvas.height - this.offCanvas.height) / 2);\n this.ctx.clearRect(x, y, 250, 250);\n this.ctx.drawImage(this.offCanvas, x, y);\n\n return this.offCanvas;\n }\n}\n\nexport default Loading;\n","import { getContext2d } from './canvas';\n\nexport interface LayerOptions {\n /** Transparent canvas. Opaque layers (`false`) draw faster; keep the bottom layer opaque. */\n alpha?: boolean;\n /** Lets the browser present frames without syncing to the compositor: lower latency, but may tear. Off by default. */\n desynchronized?: boolean;\n /** Name of an existing layer to stack this one below; defaults to the top. */\n before?: string;\n}\n\n/** A named canvas stacked in the grid; renderers draw into its context. */\nclass Layer {\n readonly name: string;\n\n readonly canvas = document.createElement('canvas');\n\n readonly ctx: CanvasRenderingContext2D;\n\n constructor(name: string, { alpha = true, desynchronized = false }: Pick<LayerOptions, 'alpha' | 'desynchronized'> = {}) {\n this.name = name;\n this.canvas.className = `drawingLayer ${name}`;\n this.ctx = getContext2d(this.canvas, { alpha, desynchronized });\n }\n\n /** Size in CSS pixels; the backing store is `pixelRatio` times larger. */\n width = 0;\n\n height = 0;\n\n pixelRatio = 1;\n\n /**\n * Resizes the canvas, scaling the context so renderers keep drawing in CSS pixels.\n * Returns false, leaving the canvas untouched, when nothing changed (assigning a size clears the canvas).\n */\n resize(width: number, height: number, pixelRatio = 1) {\n if (width === this.width && height === this.height && pixelRatio === this.pixelRatio) return false;\n\n this.width = width;\n this.height = height;\n this.pixelRatio = pixelRatio;\n this.canvas.width = Math.round(width * pixelRatio);\n this.canvas.height = Math.round(height * pixelRatio);\n this.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);\n return true;\n }\n\n clear() {\n this.ctx.clearRect(0, 0, this.width, this.height);\n }\n}\n\nexport default Layer;\n","import type { CellRenderer, RendererRef } from '../types';\n\n/** Named renderers; columns refer to them by name or hand over a renderer directly. */\nclass RendererRegistry {\n private readonly renderers = new Map<string, CellRenderer>();\n\n private readonly warned = new Set<string>();\n\n register(name: string, renderer: CellRenderer) {\n this.renderers.set(name, renderer);\n this.warned.delete(name);\n }\n\n unregister(name: string) {\n this.renderers.delete(name);\n }\n\n get(name: string) {\n return this.renderers.get(name);\n }\n\n /** Resolves a reference without allocating; unknown names are reported once and yield undefined. */\n resolve(ref: RendererRef): CellRenderer | undefined {\n if (typeof ref !== 'string') return ref;\n\n const renderer = this.renderers.get(ref);\n if (!renderer && !this.warned.has(ref)) {\n this.warned.add(ref);\n console.warn(`canvas-grid: no renderer registered as \"${ref}\"`);\n }\n return renderer;\n }\n\n clearCaches() {\n this.renderers.forEach(renderer => renderer.clearCache?.());\n }\n}\n\nexport default RendererRegistry;\n","import { primitive } from '../utils/jsx';\n\nexport interface RectProps {\n x?: number;\n y?: number;\n width: number;\n height: number;\n color: string;\n /** Opacity from 0 to 1, applied on top of the color. */\n alpha?: number;\n}\n\n/** Solid rectangle, filled straight onto the target context. */\nconst Rect = primitive<RectProps>((ctx, { x = 0, y = 0, width, height, color, alpha = 1 }, originX, originY) => {\n const w = Math.trunc(width);\n const h = Math.trunc(height);\n if (!color || w <= 0 || h <= 0 || alpha <= 0) return;\n\n ctx.fillStyle = color;\n if (alpha >= 1) {\n ctx.fillRect(originX + x, originY + y, w, h);\n return;\n }\n ctx.globalAlpha = alpha;\n ctx.fillRect(originX + x, originY + y, w, h);\n ctx.globalAlpha = 1;\n});\n\nexport default Rect;\n","import React, { Group } from '../utils/jsx';\nimport Renderer from '../utils/renderer';\nimport Rect from '../rectangle';\nimport type { CellContext, CellRenderer } from '../types';\n\nexport interface CellBackgroundOptions {\n layer: string;\n enableFlashing: boolean;\n background: string;\n flashInDuration: number;\n flashOutDuration: number;\n flashColor: string;\n /** Laid over odd rows. */\n zebraColor: string;\n /** Laid over the hovered row, faded in and out. */\n hoverColor: string;\n borderRightWidth: number;\n borderRightColor: string;\n borderBottomWidth: number;\n borderBottomColor: string;\n}\n\n/** How long the hover highlight takes to fade in or out, in ms. */\nconst HOVER_DURATION = 120;\n\ninterface HoverFade {\n from: number;\n to: number;\n start: number;\n}\n/** Opacity of the flash that replaces the fade for people who prefer reduced motion. */\nconst REDUCED_MOTION_ALPHA = 0.5;\n\nconst reducedMotionQuery = typeof window !== 'undefined' && typeof window.matchMedia === 'function'\n ? window.matchMedia('(prefers-reduced-motion: reduce)')\n : undefined;\n\nconst smoothstep = (t: number) => t * t * (3 - 2 * t);\n\nclass CellBackground extends Renderer<CellBackgroundOptions> implements CellRenderer {\n static readonly defaultOptions: CellBackgroundOptions = {\n layer: 'background',\n enableFlashing: true,\n background: '#333',\n flashInDuration: 200,\n flashOutDuration: 400,\n flashColor: 'rgb(214, 144, 13)',\n zebraColor: 'rgba(255, 255, 255, 0.025)',\n hoverColor: 'rgba(255, 255, 255, 0.06)',\n borderRightWidth: 0,\n borderRightColor: '#fff',\n borderBottomWidth: 0,\n borderBottomColor: '#fff',\n };\n\n constructor(options: Partial<CellBackgroundOptions> = {}) {\n super({ ...CellBackground.defaultOptions, ...options });\n }\n\n /** Index of the row under the pointer, set by the grid through `hover`. */\n hoveredRowIndex: number | undefined = undefined;\n\n /** Rows whose highlight is fading in or out, or fully on. */\n private readonly hoverFades = new Map<number, HoverFade>();\n\n private get hoverDuration() {\n return reducedMotionQuery?.matches ? 0 : HOVER_DURATION;\n }\n\n /** Moves the highlight to the given row (or none); the rows involved fade from where they are. */\n hover(index: number | undefined, now = Date.now()) {\n if (index === this.hoveredRowIndex) return;\n\n if (this.hoveredRowIndex !== undefined) this.startFade(this.hoveredRowIndex, 0, now);\n if (index !== undefined) this.startFade(index, 1, now);\n this.hoveredRowIndex = index;\n }\n\n private startFade(row: number, to: number, now: number) {\n this.hoverFades.set(row, { from: this.getHoverFraction(row, now), to, start: now });\n }\n\n /** How much of the highlight a row shows, from 0 to 1; finished fade-outs are forgotten. */\n private getHoverFraction(row: number, now: number) {\n const fade = this.hoverFades.get(row);\n if (!fade) return 0;\n\n const duration = this.hoverDuration;\n const progress = duration <= 0 ? 1 : Math.min(1, Math.max(0, (now - fade.start) / duration));\n if (progress >= 1 && fade.to === 0) this.hoverFades.delete(row);\n const eased = 1 - (1 - progress) * (1 - progress);\n return fade.from + (fade.to - fade.from) * eased;\n }\n\n get layer() {\n return this.options.layer;\n }\n\n /** Cells flash after their value changed, until the flash has faded out. */\n isAnimating({ age, row, now }: Readonly<CellContext>) {\n const fade = row === undefined ? undefined : this.hoverFades.get(row.index);\n if (fade && now - fade.start < this.hoverDuration) return true;\n return this.options.enableFlashing && age <= this.options.flashInDuration + this.options.flashOutDuration;\n }\n\n /** Flash opacity for a cell updated `age` ms ago: eases in, eases out, then 0. A steady highlight with reduced motion. */\n private getFlashAlpha(age: number) {\n if (!this.options.enableFlashing) return 0;\n\n const { flashInDuration, flashOutDuration } = this.options;\n if (age > flashInDuration + flashOutDuration) return 0;\n if (reducedMotionQuery?.matches) return REDUCED_MOTION_ALPHA;\n\n const remaining = Math.max(0, (flashInDuration + flashOutDuration - age) / flashOutDuration);\n const alpha = age < flashInDuration ? smoothstep(age / flashInDuration) : remaining * remaining;\n return Math.round(alpha * 1000) / 1000;\n }\n\n draw({ ctx, x, y, width, height, age, row, now }: Readonly<CellContext>) {\n const { background, flashColor, zebraColor, hoverColor, borderRightWidth, borderRightColor, borderBottomWidth, borderBottomColor } = this.options;\n const flash = this.getFlashAlpha(age);\n const hover = row === undefined ? 0 : this.getHoverFraction(row.index, now);\n\n (\n <Group>\n <Rect width={width} height={height} color={background} />\n {row !== undefined && row.index % 2 === 1 && <Rect width={width} height={height} color={zebraColor} />}\n {hover > 0 && <Rect width={width} height={height} color={hoverColor} alpha={hover} />}\n {flash > 0 && <Rect width={width} height={height} color={flashColor} alpha={flash} />}\n {borderRightWidth > 0 && <Rect x={width - borderRightWidth} width={borderRightWidth} height={height} color={borderRightColor} />}\n {borderBottomWidth > 0 && <Rect y={height - borderBottomWidth} width={width} height={borderBottomWidth} color={borderBottomColor} />}\n </Group>\n ).draw(ctx, x, y);\n }\n}\n\nexport default CellBackground;\n","/**\n * Characters that join with their neighbours into one visible glyph: any combining mark (accents, Indic vowel signs and\n * viramas, Thai marks), the conjoining Hangul jamo, the zero width (non-)joiner and everything outside the BMP, which\n * is a surrogate pair in UTF-16 (most emoji). Text with any is measured per grapheme, not per UTF-16 unit.\n */\nconst joiningCharacters = /[\\p{M}ᄀ-ᇿꥠ-ힰ-\\u{10000}-\\u{10ffff}]/u;\n\n/** From here on come combining marks, Hebrew, Arabic, the other scripts that shape or join, CJK and emoji. */\nconst FIRST_COMPLEX_CODE = 0x300;\n\nconst segmenter = new Intl.Segmenter();\n\nconst toGraphemes = (text: string) => Array.from(segmenter.segment(text), ({ segment }) => segment);\n\nconst toUnits = (text: string) => (joiningCharacters.test(text) ? toGraphemes(text) : text);\n\nconst hasComplexCharacters = (text: string) => {\n for (let i = 0; i < text.length; i++) {\n if (text.charCodeAt(i) >= FIRST_COMPLEX_CODE) return true;\n }\n return false;\n};\n\n/** How many leading units fit with room left for the ellipsis: all of them when everything fits, -1 when nothing does. */\nconst countFitting = (units: ArrayLike<string>, available: number, ellipsis: string, widthOf: (unit: string) => number) => {\n let used = 0;\n let end = 0;\n while (end < units.length) {\n const width = widthOf(units[end]);\n if (used + width > available) break;\n used += width;\n end++;\n }\n if (end === units.length) return end;\n\n // the ellipsis needs room too: give up units until it fits\n const ellipsisWidth = widthOf(ellipsis);\n while (end > 0 && used + ellipsisWidth > available) {\n end--;\n used -= widthOf(units[end]);\n }\n return used + ellipsisWidth > available ? -1 : end;\n};\n\nconst sumWidths = (units: ArrayLike<string>, widthOf: (unit: string) => number) => {\n let total = 0;\n for (let i = 0; i < units.length; i++) total += widthOf(units[i]);\n return total;\n};\n\n/** The text that was cut to `available` pixels, remembered per text so a cell that is drawn again costs one lookup. */\nexport interface FittedText {\n available: number;\n text: string;\n}\n\nexport type FitCache = Map<string, FittedText>;\n\nconst MAX_CACHED_TEXTS = 4096;\n\nconst remember = (cache: FitCache | undefined, text: string, available: number, fitted: string) => {\n if (!cache) return fitted;\n\n const entry = cache.get(text);\n if (entry) {\n entry.available = available;\n entry.text = fitted;\n return fitted;\n }\n if (cache.size >= MAX_CACHED_TEXTS) cache.clear();\n cache.set(text, { available, text: fitted });\n return fitted;\n};\n\nexport interface ExactFit {\n /** Width of a string as the browser lays it out, with kerning, ligatures and joined scripts. */\n measure: (text: string) => number;\n /** Cuts already made, so a text that is drawn again is not measured again. */\n cache?: FitCache;\n /** The character widths add up to the real width, as for a monospace font: Latin text then needs no measuring. */\n sumIsExact: boolean;\n /**\n * How much wider (negative: narrower) two neighbouring characters are laid out than their own widths add up to:\n * kerning and ligatures. With it, simple Latin text is cut by arithmetic instead of by measuring.\n */\n kerning?: (left: string, right: string) => number;\n}\n\n/** Cuts the units to fit using real measurements: the character sum is only an estimate where to cut. */\nconst fitExactly = (text: string, available: number, ellipsis: string, widthOf: (unit: string) => number, exact: ExactFit) => {\n const { measure, cache } = exact;\n const cached = cache?.get(text);\n if (cached?.available === available) return cached.text;\n\n const units = toUnits(text);\n if (countFitting(units, available, ellipsis, widthOf) === units.length) return text;\n\n const whole = measure(text);\n if (whole <= available) return remember(cache, text, available, text);\n\n // estimate where to cut by scaling the widths to the measured total, then correct it against real measurements\n const scale = whole / sumWidths(units, widthOf);\n let keep = countFitting(units, available, ellipsis, unit => widthOf(unit) * scale);\n const prefix = (count: number) => (typeof units === 'string' ? units.slice(0, count) : units.slice(0, count).join(''));\n while (keep > 0 && measure(prefix(keep) + ellipsis) > available) keep--;\n return remember(cache, text, available, keep < 0 || (keep === 0 && measure(ellipsis) > available) ? '' : prefix(keep) + ellipsis);\n};\n\n/**\n * Cuts text of simple characters with the character widths corrected by the kerning of each pair, which is how the\n * browser lays out Latin text apart from rare effects over three or more letters. Measures nothing once the pairs are known.\n */\nconst fitKerned = (\n text: string,\n available: number,\n ellipsis: string,\n widthOf: (character: string) => number,\n kerning: (left: string, right: string) => number,\n) => {\n const ellipsisWidth = widthOf(ellipsis);\n const ellipsisHead = ellipsis.charAt(0);\n let used = 0;\n let keep = 0;\n while (keep < text.length) {\n const next = used + widthOf(text.charAt(keep)) + (keep === 0 ? 0 : kerning(text.charAt(keep - 1), text.charAt(keep)));\n if (next > available) break;\n used = next;\n keep++;\n }\n if (keep === text.length) return text;\n\n // `used` is the width of the first `keep` characters; the ellipsis needs room too\n while (keep > 0 && used + kerning(text.charAt(keep - 1), ellipsisHead) + ellipsisWidth > available) {\n keep--;\n used -= widthOf(text.charAt(keep)) + (keep === 0 ? 0 : kerning(text.charAt(keep - 1), text.charAt(keep)));\n }\n return keep > 0 || ellipsisWidth <= available ? text.slice(0, keep) + ellipsis : '';\n};\n\n/**\n * Cuts `text` to fit `available` pixels, ending in `ellipsis` when something was cut.\n * `widthOf` gives the width of one character, and the text width is the sum of those: cheap, and exact for a\n * monospace font. That is all that runs for text that fits, which is nearly every cell. A cell that does not fit\n * is measured again with `exact.measure` when the sum cannot be trusted, which is for proportional fonts (kerning\n * makes the sum overshoot) and for text with joined scripts such as Arabic (it overshoots by 40%).\n * Characters that form one glyph (emoji, letters with combining accents) are kept or cut together.\n */\nconst fitText = (\n text: string,\n available: number,\n ellipsis: string,\n widthOf: (character: string) => number,\n exact: ExactFit = { measure: value => sumWidths(toUnits(value), widthOf), sumIsExact: true },\n) => {\n const keep = countFitting(text, available, ellipsis, widthOf);\n if (keep === text.length) return text;\n if (exact.sumIsExact && !hasComplexCharacters(text)) return keep < 0 ? '' : text.slice(0, keep) + ellipsis;\n\n if (exact.kerning && !hasComplexCharacters(text)) return fitKerned(text, available, ellipsis, widthOf, exact.kerning);\n return fitExactly(text, available, ellipsis, widthOf, exact);\n};\n\nexport default fitText;\n","import Renderer from '../utils/renderer';\nimport { primitive } from '../utils/jsx';\nimport fitText from '../utils/fit-text';\nimport type { ExactFit, FitCache } from '../utils/fit-text';\nimport { getContext2d } from '../utils/canvas';\nimport type { RenderProps } from '../types';\n\nexport interface TextStyle {\n /** Canvas `textRendering`: trade speed for legibility or exact geometry. Browser default is `'auto'`. */\n textRendering: CanvasTextRendering;\n /** Canvas `fontKerning`. Browser default is `'auto'`. */\n fontKerning: CanvasFontKerning;\n /** Extra space after each character, a CSS length such as `'0.5px'`. */\n letterSpacing: string;\n /**\n * `'ltr'` and `'rtl'` set the direction of every cell; `'auto'` picks it per cell from the first letter,\n * so mixed data works. Right-to-left text is aligned to the right of the cell.\n */\n direction: 'ltr' | 'rtl' | 'auto';\n /**\n * What happens to text wider than its cell. `'clip'` cuts it off at the cell edge, which needs no measuring.\n * `'ellipsis'` shortens it and ends it with the ellipsis, which means measuring the text.\n */\n textOverflow: 'clip' | 'ellipsis';\n}\n\nexport interface TextOptions extends TextStyle {\n ellipsis: string;\n cellPadding: {\n top: number;\n right: number;\n bottom: number;\n left: number;\n };\n font: string;\n color: string;\n isEllipsisRight: boolean;\n}\n\nexport const defaultTextStyle: Readonly<TextStyle> = {\n textRendering: 'auto',\n fontKerning: 'auto',\n letterSpacing: '0px',\n direction: 'ltr',\n textOverflow: 'clip',\n};\n\n/** What is measured for one font: character widths, the cuts already made and whether widths add up exactly. */\ninterface FontMeasures {\n font: string;\n widths: Map<string, number>;\n /** Kerning of the character pairs seen, by the two character codes. */\n pairs: Map<number, number>;\n fitted: FitCache;\n probed: boolean;\n widthOf: (character: string) => number;\n exactFit: ExactFit;\n}\n\n/** From here on come combining marks, Hebrew, Arabic, the other scripts that shape or join, CJK and emoji. */\nconst FIRST_COMPLEX_CHARACTER = 0x300;\n\n/** First letter of a right-to-left script (Hebrew, Arabic, Syriac, Thaana, N'Ko and their presentation forms). */\nconst rightToLeftLetter = /^[^\\p{L}]*(?=[-ࣿיִ-﷿ﹰ-ﻼ])\\p{L}/u;\n\nclass TextRenderer extends Renderer<TextOptions> {\n static readonly defaultOptions: TextOptions = {\n ...defaultTextStyle,\n ellipsis: '…',\n cellPadding: {\n top: 3,\n right: 3,\n bottom: 3,\n left: 3,\n },\n font: '12px sans-serif',\n color: '#fff',\n isEllipsisRight: true,\n };\n\n /** Measurements per font, so columns with their own font do not mix up widths. Cleared when anything affecting widths changes. */\n private readonly fonts = new Map<string, FontMeasures>();\n\n private readonly measureContext = getContext2d(document.createElement('canvas'));\n\n private measuredState = '';\n\n /** Set once a style option differs from the default, so grids that never touch them set nothing extra per cell. */\n private styled = false;\n\n constructor(options: Partial<TextOptions> = {}) {\n super({ ...TextRenderer.defaultOptions, ...options });\n this.styled = this.differsFromDefault();\n }\n\n private differsFromDefault() {\n // the overflow mode is not a canvas state, so it does not make the renderer set any per cell\n return (Object.keys(defaultTextStyle) as Array<keyof TextStyle>).some(key => key !== 'textOverflow' && this.options[key] !== defaultTextStyle[key]);\n }\n\n set font(font: string) {\n if (this.options.font !== font) {\n this.options.font = font;\n this.clearCache();\n }\n }\n\n get font() {\n return this.options.font;\n }\n\n set color(color: string) {\n this.options.color = color;\n }\n\n get color() {\n return this.options.color;\n }\n\n /** Changes the text style; widths are measured again when something changed. */\n setStyle(style: Partial<TextStyle>) {\n if (!(Object.keys(style) as Array<keyof TextStyle>).some(key => style[key] !== this.options[key])) return;\n\n this.update(style);\n this.styled = this.styled || this.differsFromDefault();\n this.clearCache();\n }\n\n /** Text is drawn straight into the layer, whose transform already scales it to the device pixel ratio. */\n pixelRatio = 1;\n\n clearCache() {\n this.fonts.clear();\n this.lastMeasures = undefined;\n this.measuredState = '';\n }\n\n /** The measurements of a font, created on first use. */\n private measuresOf(font: string) {\n const known = this.fonts.get(font);\n if (known) return known;\n\n const fitted: FitCache = new Map();\n const measures: FontMeasures = {\n font,\n widths: new Map(),\n pairs: new Map(),\n fitted,\n probed: false,\n // passed to `fitText` as they are, so drawing a cell allocates no closures\n widthOf: character => this.measureCharacter(measures, character),\n exactFit: {\n measure: text => this.measureString(measures, text),\n cache: fitted,\n sumIsExact: true,\n kerning: (left, right) => this.measureKerning(measures, left, right),\n },\n };\n this.fonts.set(font, measures);\n return measures;\n }\n\n /** Gives the measuring context the font and style the text is drawn with. */\n private prepareMeasuring(measures: FontMeasures) {\n const { textRendering, fontKerning, letterSpacing } = this.options;\n const state = `${measures.font}|${textRendering}|${fontKerning}|${letterSpacing}`;\n if (this.measuredState !== state) {\n this.measureContext.font = measures.font;\n this.measureContext.textRendering = textRendering;\n this.measureContext.fontKerning = fontKerning;\n this.measureContext.letterSpacing = letterSpacing;\n this.measuredState = state;\n }\n if (measures.probed) return;\n\n measures.probed = true;\n // in a monospace font the character widths add up to the width of any Latin text, so that text needs no measuring\n measures.exactFit.sumIsExact = Math.abs(this.measureContext.measureText('i').width - this.measureContext.measureText('W').width) < 0.01;\n }\n\n /** Width of one character in a font, measured once. */\n private measureCharacter(measures: FontMeasures, character: string) {\n const cached = measures.widths.get(character);\n if (cached !== undefined) return cached;\n\n this.prepareMeasuring(measures);\n const width = this.measureContext.measureText(character).width;\n measures.widths.set(character, width);\n return width;\n }\n\n /** What a pair of characters is wider than the two alone, measured once per pair: negative for kerned pairs such as \"AV\". */\n private measureKerning(measures: FontMeasures, left: string, right: string) {\n const key = left.charCodeAt(0) * 0x10000 + right.charCodeAt(0);\n const known = measures.pairs.get(key);\n if (known !== undefined) return known;\n\n const kerning = this.measureString(measures, left + right) - this.measureCharacter(measures, left) - this.measureCharacter(measures, right);\n measures.pairs.set(key, kerning);\n return kerning;\n }\n\n /** Width of a string as the browser lays it out: includes kerning, ligatures and joined scripts. */\n private measureString(measures: FontMeasures, text: string) {\n this.prepareMeasuring(measures);\n return this.measureContext.measureText(text).width;\n }\n\n /** Sum of the character widths in the renderer's font: exact for monospace fonts, a close upper bound for most others. */\n getTextWidth(text: string) {\n const { widthOf } = this.measuresOf(this.options.font);\n let totalWidth = 0;\n for (let i = 0; i < text.length; i++) totalWidth += widthOf(text.charAt(i));\n return totalWidth;\n }\n\n /**\n * Whether simple text surely fits: the cached character widths add up to at most `available`. Kerning only narrows\n * text, so a fit by the sum is a fit. Anything past Latin (joined scripts, emoji) is not trusted and gets clipped.\n */\n private fitsBySum(text: string, available: number, widthOf: (character: string) => number) {\n let used = 0;\n for (let i = 0; i < text.length; i++) {\n if (text.charCodeAt(i) >= FIRST_COMPLEX_CHARACTER) return false;\n used += widthOf(text.charAt(i));\n if (used > available) return false;\n }\n return true;\n }\n\n /** The font of the cell drawn last: columns mostly share one, so the lookup by font name is skipped. */\n private lastMeasures: FontMeasures | undefined = undefined;\n\n private isRightToLeft(text: string) {\n const { direction } = this.options;\n return direction === 'auto' ? rightToLeftLetter.test(text) : direction === 'rtl';\n }\n\n /**\n * Draws the text clipped with an ellipsis; `(x, y)` is the offset of the text box from `(originX, originY)`.\n * The whole string is drawn with one `fillText`: recording one command per cell is much cheaper than\n * one `drawImage` per character, and the browser keeps its own glyph cache.\n */\n paint(ctx: CanvasRenderingContext2D, { value = '', x = 0, y = 0, width = 0, height = 0, font = this.options.font }: RenderProps, originX: number, originY: number) {\n const { cellPadding } = this.options;\n const available = width - cellPadding.left - cellPadding.right;\n const measures = this.lastMeasures?.font === font ? this.lastMeasures : this.measuresOf(font);\n this.lastMeasures = measures;\n const clip = this.options.textOverflow === 'clip' && !this.fitsBySum(value, available, measures.widthOf);\n const text = this.options.textOverflow === 'clip' ? value : fitText(value, available, this.options.ellipsis, measures.widthOf, measures.exactFit);\n if (text === '' || height - cellPadding.top - cellPadding.bottom <= 0) return;\n\n if (clip) {\n // only text that may be wider than the cell needs the (comparatively costly) clip\n ctx.save();\n ctx.beginPath();\n ctx.rect(originX + x + cellPadding.left, originY + y, Math.max(0, available), height);\n ctx.clip();\n }\n\n const rightToLeft = this.styled && this.isRightToLeft(text);\n if (this.styled) {\n ctx.textRendering = this.options.textRendering;\n ctx.fontKerning = this.options.fontKerning;\n ctx.letterSpacing = this.options.letterSpacing;\n ctx.direction = rightToLeft ? 'rtl' : 'ltr';\n }\n ctx.font = font;\n ctx.fillStyle = this.options.color;\n ctx.textAlign = rightToLeft ? 'right' : 'left';\n // centred in the padded box, so fonts of different sizes line up in a row\n ctx.textBaseline = 'middle';\n // at a fractional pixel ratio (125%, 150% zoom) integer CSS pixels fall between device pixels and blur the glyphs\n const { pixelRatio } = this;\n const textX = rightToLeft ? originX + x + width - cellPadding.right : originX + x + cellPadding.left;\n ctx.fillText(\n text,\n Math.round(textX * pixelRatio) / pixelRatio,\n Math.round((originY + y + cellPadding.top + (height - cellPadding.top - cellPadding.bottom) / 2) * pixelRatio) / pixelRatio,\n );\n if (clip) ctx.restore();\n }\n\n readonly element = primitive<RenderProps>((ctx, props, x, y) => this.paint(ctx, props, x, y));\n}\n\nexport default TextRenderer;\n","import { primitive } from '../utils/jsx';\nimport type { SortDirection } from '../types';\n\nexport interface SortIndicatorProps {\n /** Width and height of the area the arrow is centred in, relative to the draw origin. */\n width: number;\n height: number;\n direction: SortDirection;\n color: string;\n}\n\n/** Width of the arrow's area, for the header to keep its text clear of it. */\nexport const SORT_INDICATOR_AREA = 18;\n\nconst ARROW_WIDTH = 8;\nconst ARROW_HEIGHT = 5;\nconst ARROW_ALPHA = 0.75;\n\n/** Small filled triangle at the right end of a header: pointing up for ascending, down for descending. */\nconst SortIndicator = primitive<SortIndicatorProps>((ctx, { width, height, direction, color }, originX, originY) => {\n // whole pixels, so the edges stay crisp\n const left = Math.round(originX + width - (SORT_INDICATOR_AREA + ARROW_WIDTH) / 2);\n const top = Math.round(originY + (height - ARROW_HEIGHT) / 2);\n const ascending = direction === 'asc';\n\n ctx.beginPath();\n ctx.moveTo(left, ascending ? top + ARROW_HEIGHT : top);\n ctx.lineTo(left + ARROW_WIDTH, ascending ? top + ARROW_HEIGHT : top);\n ctx.lineTo(left + ARROW_WIDTH / 2, ascending ? top : top + ARROW_HEIGHT);\n ctx.closePath();\n ctx.fillStyle = color;\n ctx.globalAlpha = ARROW_ALPHA;\n ctx.fill();\n ctx.globalAlpha = 1;\n});\n\nexport default SortIndicator;\n","import React, { Group } from '../utils/jsx';\nimport Renderer from '../utils/renderer';\nimport Rect from '../rectangle';\nimport TextRenderer from '../text';\nimport type { TextStyle } from '../text';\nimport SortIndicator, { SORT_INDICATOR_AREA } from '../sort-indicator';\nimport type { CellContext, CellRenderer, SortDirection } from '../types';\n\nexport interface HeaderOptions {\n layer: string;\n background: string;\n /** Background of a header or row number with some of its cells selected. */\n selectedBackground: string;\n /** Background of a header or row number whose whole column or row is selected. */\n fullySelectedBackground: string;\n font: string;\n color: string;\n borderRightWidth: number;\n borderRightColor: string;\n borderBottomWidth: number;\n borderBottomColor: string;\n}\n\nclass HeaderRenderer extends Renderer<HeaderOptions> implements CellRenderer {\n static readonly defaultOptions: HeaderOptions = {\n layer: 'header',\n background: '#333',\n selectedBackground: '#2f3d4a',\n fullySelectedBackground: '#3a5a7c',\n font: '13px sans-serif',\n color: '#fff',\n borderRightWidth: 1,\n borderRightColor: '#fff',\n borderBottomWidth: 1,\n borderBottomColor: '#fff',\n };\n\n private readonly textRenderer: TextRenderer;\n\n /** Sort direction by column id, set by the grid; sorted headers show an arrow. */\n private readonly sortDirections = new Map<string, SortDirection>();\n\n /** Shows the arrows of the columns in the sort model; the grid redraws the headers afterwards. */\n setSortModel(model: readonly { columnId: string | number; direction?: SortDirection }[]) {\n this.sortDirections.clear();\n model.forEach(({ columnId, direction = 'asc' }) => this.sortDirections.set(String(columnId), direction));\n }\n\n constructor(options: Partial<HeaderOptions> = {}) {\n super({ ...HeaderRenderer.defaultOptions, ...options });\n\n this.textRenderer = new TextRenderer({\n font: this.options.font,\n color: this.options.color,\n });\n }\n\n get layer() {\n return this.options.layer;\n }\n\n set font(font: string) {\n this.options.font = font;\n this.textRenderer.font = font;\n }\n\n get font() {\n return this.textRenderer.font;\n }\n\n set pixelRatio(pixelRatio: number) {\n this.textRenderer.pixelRatio = pixelRatio;\n }\n\n get pixelRatio() {\n return this.textRenderer.pixelRatio;\n }\n\n setTextStyle(style: Partial<TextStyle>) {\n this.textRenderer.setStyle(style);\n }\n\n optionsUpdated() {\n this.textRenderer.color = this.options.color;\n }\n\n clearCache() {\n this.textRenderer.clearCache();\n }\n\n private backgroundFor(selected: CellContext['selected']) {\n if (selected === 'full') return this.options.fullySelectedBackground;\n if (selected === 'partial') return this.options.selectedBackground;\n return this.options.background;\n }\n\n draw({ ctx, x, y, width, height, column, formatted, selected }: Readonly<CellContext>) {\n if (width === 0 || height === 0) return;\n\n const direction = column === undefined ? undefined : this.sortDirections.get(String(column.id));\n const { borderRightWidth, borderRightColor, borderBottomWidth, borderBottomColor } = this.options;\n\n const background = this.backgroundFor(selected);\n\n (\n <Group>\n <Rect width={width} height={height} color={background} />\n {borderRightWidth > 0 && <Rect x={width - borderRightWidth} width={borderRightWidth} height={height} color={borderRightColor} />}\n {borderBottomWidth > 0 && <Rect y={height - borderBottomWidth} width={width} height={borderBottomWidth} color={borderBottomColor} />}\n <this.textRenderer.element value={formatted} font={column?.headerFont} width={direction ? width - SORT_INDICATOR_AREA : width} height={height} />\n {direction && <SortIndicator width={width} height={height} direction={direction} color={this.options.color} />}\n </Group>\n ).draw(ctx, x, y);\n }\n}\n\nexport default HeaderRenderer;\n","import React from '../utils/jsx';\nimport Renderer from '../utils/renderer';\nimport TextRenderer from '../text';\nimport type { TextStyle } from '../text';\nimport type { CellContext, CellRenderer } from '../types';\n\nexport interface CellValueOptions {\n layer: string;\n font: string;\n color: string;\n}\n\nexport default class CellValueRenderer extends Renderer<CellValueOptions> implements CellRenderer {\n static readonly defaultOptions: CellValueOptions = {\n layer: 'content',\n font: '12px sans-serif',\n color: '#fff',\n };\n\n private readonly renderer: TextRenderer;\n\n constructor(options: Partial<CellValueOptions> = {}) {\n super({ ...CellValueRenderer.defaultOptions, ...options });\n\n this.renderer = new TextRenderer({\n font: this.options.font,\n color: this.options.color,\n });\n }\n\n get layer() {\n return this.options.layer;\n }\n\n set font(font: string) {\n this.options.font = font;\n this.renderer.font = font;\n }\n\n get font() {\n return this.options.font;\n }\n\n set color(color: string) {\n this.options.color = color;\n this.renderer.color = color;\n }\n\n get color() {\n return this.options.color;\n }\n\n set pixelRatio(pixelRatio: number) {\n this.renderer.pixelRatio = pixelRatio;\n }\n\n get pixelRatio() {\n return this.renderer.pixelRatio;\n }\n\n setTextStyle(style: Partial<TextStyle>) {\n this.renderer.setStyle(style);\n }\n\n clearCache() {\n this.renderer.clearCache();\n }\n\n draw({ ctx, x, y, width, height, column, formatted, valueChanged, forced }: Readonly<CellContext>) {\n if (!valueChanged && !forced) return;\n\n ctx.clearRect(x, y, width, height);\n (<this.renderer.element value={formatted} font={column?.font} width={width} height={height} />).draw(ctx, x, y);\n }\n}\n","export const INHERIT_FONT = 'inherit';\n\ntype FontStyle = Pick<CSSStyleDeclaration, 'fontStyle' | 'fontWeight' | 'fontSize' | 'fontFamily'>;\n\n/**\n * The element's computed font as a canvas font string, or `fallback` when it has none (not attached yet).\n * Built from the longhands, because `getComputedStyle(...).font` is empty in some browsers.\n */\nexport const resolveFont = (font: string, style: FontStyle, fallback: string) => {\n if (font !== INHERIT_FONT) return font;\n if (!style.fontSize || !style.fontFamily) return fallback;\n return [style.fontStyle, style.fontWeight, style.fontSize, style.fontFamily].filter(Boolean).join(' ');\n};\n","export type ThemeName = 'light' | 'dark';\n\n/** Everything the grid takes from CSS; colours and fonts are CSS values, sizes are px. */\nexport interface Theme {\n background: string;\n text: string;\n font: string;\n rowHeight: number;\n /** Right and bottom edge of body cells. */\n border: string;\n headerBackground: string;\n headerText: string;\n headerFont: string;\n headerHeight: number;\n headerBorder: string;\n headerBottomBorder: string;\n /** Header of a column or row number with some of its cells selected. */\n headerSelected: string;\n /** Header of a column or row number with all its cells selected. */\n headerFullySelected: string;\n /** Laid over odd rows; usually translucent. */\n zebra: string;\n /** Laid over the row under the pointer; usually translucent. */\n hover: string;\n /** Laid over a cell that just changed, at the strength of the flash. */\n flash: string;\n selection: string;\n selectionBorder: string;\n}\n\ntype ThemeKey = keyof Theme;\n\n/** The CSS custom property of each themed value. */\nexport const THEME_TOKENS: Readonly<Record<ThemeKey, string>> = {\n background: '--cg-background',\n text: '--cg-text-color',\n font: '--cg-font',\n rowHeight: '--cg-row-height',\n border: '--cg-border-color',\n headerBackground: '--cg-header-background',\n headerText: '--cg-header-text-color',\n headerFont: '--cg-header-font',\n headerHeight: '--cg-header-height',\n headerBorder: '--cg-header-border-color',\n headerBottomBorder: '--cg-header-bottom-border-color',\n headerSelected: '--cg-header-selected-background',\n headerFullySelected: '--cg-header-fully-selected-background',\n zebra: '--cg-zebra-color',\n hover: '--cg-hover-color',\n flash: '--cg-flash-color',\n selection: '--cg-selection-color',\n selectionBorder: '--cg-selection-border-color',\n};\n\nconst shared = {\n font: '12px sans-serif',\n rowHeight: 20,\n headerFont: '13px sans-serif',\n headerHeight: 30,\n flash: 'rgb(214, 144, 13)',\n};\n\nexport const THEME_DEFAULTS: Readonly<Record<ThemeName, Readonly<Theme>>> = {\n dark: {\n ...shared,\n background: '#333',\n text: '#efefef',\n border: '#3b3b3b',\n headerBackground: '#262626',\n headerText: '#efefef',\n headerBorder: '#333',\n headerBottomBorder: '#4a4a4a',\n headerSelected: '#2f3d4a',\n headerFullySelected: '#3a5a7c',\n zebra: 'rgba(255, 255, 255, 0.025)',\n hover: 'rgba(255, 255, 255, 0.06)',\n selection: 'rgba(74, 144, 217, 0.25)',\n selectionBorder: '#4a90d9',\n },\n light: {\n ...shared,\n background: '#fff',\n text: '#1f2328',\n border: '#e4e7eb',\n headerBackground: '#f3f4f6',\n headerText: '#1f2328',\n headerBorder: '#e4e7eb',\n headerBottomBorder: '#c9ced6',\n headerSelected: '#dbe8f6',\n headerFullySelected: '#b9d3ee',\n zebra: 'rgba(0, 0, 0, 0.025)',\n hover: 'rgba(0, 0, 0, 0.05)',\n selection: 'rgba(74, 144, 217, 0.2)',\n selectionBorder: '#2f6fb5',\n },\n};\n\n/** What the CSS side of a theme is read through; the browser provides it, tests fake it. */\nexport interface ThemeSource {\n /** The value of a custom property, or an empty string when it is not set. */\n read: (token: string) => string;\n isColor: (value: string) => boolean;\n isFont: (value: string) => boolean;\n}\n\nconst PIXEL_KEYS: readonly ThemeKey[] = ['rowHeight', 'headerHeight'];\nconst FONT_KEYS: readonly ThemeKey[] = ['font', 'headerFont'];\n\nconst toPixels = (value: string) => {\n const pixels = /^\\d+(\\.\\d+)?(px)?$/.test(value) ? parseFloat(value) : NaN;\n return pixels > 0 ? pixels : undefined;\n};\n\n/** Each value from its custom property, or from the defaults of `name` when it is missing or invalid. */\nexport const readTheme = (name: ThemeName, { read, isColor, isFont }: ThemeSource): Theme => {\n const defaults = THEME_DEFAULTS[name];\n const parse = (key: ThemeKey, value: string): string | number | undefined => {\n if (!value) return undefined;\n if (PIXEL_KEYS.includes(key)) return toPixels(value);\n if (FONT_KEYS.includes(key)) return isFont(value) ? value : undefined;\n return isColor(value) ? value : undefined;\n };\n\n return Object.fromEntries(\n (Object.keys(THEME_TOKENS) as ThemeKey[]).map(key => [key, parse(key, read(THEME_TOKENS[key]).trim()) ?? defaults[key]]),\n ) as unknown as Theme;\n};\n\nexport const isSameTheme = (a: Theme, b: Theme) => (Object.keys(THEME_TOKENS) as ThemeKey[]).every(key => a[key] === b[key]);\n\n/** `fillStyle` ignores colours it cannot parse, so a colour is valid when it sticks whichever value it replaces. */\nexport const createColorCheck = (ctx: Pick<CanvasRenderingContext2D, 'fillStyle'>) => (value: string) => {\n ctx.fillStyle = '#000000';\n ctx.fillStyle = value;\n const onBlack = ctx.fillStyle;\n ctx.fillStyle = '#ffffff';\n ctx.fillStyle = value;\n return onBlack === ctx.fillStyle;\n};\n\nexport const isCssFont = (value: string) => typeof CSS === 'undefined' || CSS.supports('font', value);\n","/** Narrowest a column can get when it sets no `minWidth`. */\nexport const DEFAULT_MIN_COLUMN_WIDTH = 20;\n\n/** Keeps a width within its limits; a `maxWidth` below the minimum loses. */\nexport const clampWidth = (width: number, minWidth = DEFAULT_MIN_COLUMN_WIDTH, maxWidth = Infinity) =>\n Math.round(Math.max(minWidth, Math.min(maxWidth, width)));\n\n/**\n * Left edge of every column, followed by the total width: `offsets[i]` is where column `i` starts and\n * `offsets[widths.length]` is where the last one ends. Widths are rounded, as they are when drawn.\n */\nexport const buildOffsets = (widths: readonly number[]) => {\n const offsets = new Array<number>(widths.length + 1);\n offsets[0] = 0;\n widths.forEach((width, index) => {\n offsets[index + 1] = offsets[index] + Math.round(width);\n });\n return offsets;\n};\n\n/** Index of the column containing `x`, found by binary search; clamped to the first and last column. */\nexport const columnAt = (offsets: readonly number[], x: number) => {\n const last = offsets.length - 2;\n if (last < 0) return -1;\n\n let low = 0;\n let high = last;\n while (low < high) {\n const middle = (low + high + 1) >> 1;\n if (offsets[middle] <= x) low = middle;\n else high = middle - 1;\n }\n return low;\n};\n\n/**\n * The column whose right edge is within `tolerance` of `x`, i.e. the one a drag from there would resize,\n * or -1. Where two edges are equally close (zero-width columns do not exist, but touch targets overlap) the left one wins.\n */\nexport const borderAt = (offsets: readonly number[], x: number, tolerance: number) => {\n const index = columnAt(offsets, x + tolerance);\n if (index < 0) return -1;\n\n // the border on the right of the column containing the point, or of the previous column when the point is near its left edge\n const rightOfPrevious = index > 0 && Math.abs(offsets[index] - x) <= tolerance ? index - 1 : -1;\n const rightOfCurrent = Math.abs(offsets[index + 1] - x) <= tolerance ? index : -1;\n return rightOfPrevious >= 0 ? rightOfPrevious : rightOfCurrent;\n};\n","import type { CellPosition, CellRange, GridSelection, SelectionLevel, SelectionMode, Span } from '../types';\n\n/** Furthest the grid scrolls per frame while a selection is dragged past its edge, in px. */\nexport const DRAG_SCROLL_MAX = 30;\n\n/** The two indexes as a span, smaller first. */\nexport const span = (a: number, b: number): Span => (a <= b ? [a, b] : [b, a]);\n\nconst makeRange = (rows: Span | undefined, columns: Span | undefined): CellRange => ({\n ...(rows && { rows }),\n ...(columns && { columns }),\n});\n\nexport const rangeBetween = (from: CellPosition, to: CellPosition): CellRange =>\n makeRange(span(from.row, to.row), span(from.column, to.column));\n\n/** The range a drag from `from` to `to` selects: what it covers depends on the mode, whole rows in `row` mode and so on. */\nexport const rangeFor = (mode: SelectionMode, from: CellPosition, to: CellPosition): CellRange => {\n if (mode === 'range') return rangeBetween(from, to);\n if (mode === 'row') return makeRange(span(from.row, to.row), undefined);\n if (mode === 'column') return makeRange(undefined, span(from.column, to.column));\n return rangeBetween(to, to);\n};\n\nconst normalizeSpan = (value: Span): Span => span(Math.max(0, Math.floor(value[0])), Math.max(0, Math.floor(value[1])));\n\n/** A copy with whole-number, ordered, non-negative spans; what `setSelection` stores. */\nexport const normalizeRange = (range: CellRange): CellRange =>\n makeRange(range.rows && normalizeSpan(range.rows), range.columns && normalizeSpan(range.columns));\n\nconst copySpan = (value: Span | undefined): Span | undefined => value && [value[0], value[1]];\n\nconst copyRange = (range: CellRange): CellRange => makeRange(copySpan(range.rows), copySpan(range.columns));\n\n/** Rows and columns a range really covers, both inclusive. */\nexport interface Bounds {\n top: number;\n bottom: number;\n left: number;\n right: number;\n}\n\n/** The part of the range inside a grid of the given size, or undefined when none of it is. */\nexport const resolve = (range: CellRange, rowCount: number, columnCount: number): Bounds | undefined => {\n const top = Math.max(0, range.rows?.[0] ?? 0);\n const bottom = Math.min(rowCount - 1, range.rows?.[1] ?? rowCount - 1);\n const left = Math.max(0, range.columns?.[0] ?? 0);\n const right = Math.min(columnCount - 1, range.columns?.[1] ?? columnCount - 1);\n return top > bottom || left > right ? undefined : { top, bottom, left, right };\n};\n\nconst within = (index: number, value: Span | undefined) => value === undefined || (index >= value[0] && index <= value[1]);\n\nconst coversAll = (value: Span | undefined, count: number) => value === undefined || (value[0] <= 0 && value[1] >= count - 1);\n\nexport const contains = (range: CellRange, row: number, column: number) => within(row, range.rows) && within(column, range.columns);\n\n/** How much of a column is selected. Row numbers are drawn on every scroll, so this allocates nothing. */\nexport const columnLevel = (ranges: readonly CellRange[], column: number, rowCount: number): SelectionLevel => {\n let level: SelectionLevel = 'none';\n for (const range of ranges) {\n if (!within(column, range.columns)) continue;\n if (coversAll(range.rows, rowCount)) return 'full';\n level = 'partial';\n }\n return level;\n};\n\n/** How much of a row is selected. */\nexport const rowLevel = (ranges: readonly CellRange[], row: number, columnCount: number): SelectionLevel => {\n let level: SelectionLevel = 'none';\n for (const range of ranges) {\n if (!within(row, range.rows)) continue;\n if (coversAll(range.columns, columnCount)) return 'full';\n level = 'partial';\n }\n return level;\n};\n\n/** What a range covers: everything, whole columns, whole rows, or a block of cells. */\nexport const shapeOf = (range: CellRange): 'all' | 'column' | 'row' | 'block' => {\n if (range.rows === undefined && range.columns === undefined) return 'all';\n if (range.rows === undefined) return 'column';\n if (range.columns === undefined) return 'row';\n return 'block';\n};\n\n/** Rows run down the grid and columns across it; a header selects a line of cells along one of them. */\nexport type Axis = 'row' | 'column';\n\n/** A whole row or column, or a run of them from `from` to `to`. */\nexport const lineRange = (axis: Axis, from: number, to: number): CellRange =>\n axis === 'column' ? makeRange(undefined, span(from, to)) : makeRange(span(from, to), undefined);\n\n/** The cell at `index` along the axis and `cross` along the other. */\nexport const linePosition = (axis: Axis, index: number, cross: number): CellPosition =>\n axis === 'column' ? { row: cross, column: index } : { row: index, column: cross };\n\n/** The index of a position along the axis. */\nexport const lineIndex = (axis: Axis, position: CellPosition) => (axis === 'column' ? position.column : position.row);\n\n/** The index of a position along the other axis. */\nexport const crossIndex = (axis: Axis, position: CellPosition) => (axis === 'column' ? position.row : position.column);\n\nconst sameSpan = (a: Span | undefined, b: Span | undefined) => a?.[0] === b?.[0] && a?.[1] === b?.[1];\n\nconst sameRange = (a: CellRange, b: CellRange) => sameSpan(a.rows, b.rows) && sameSpan(a.columns, b.columns);\n\nconst samePosition = (a: CellPosition | undefined, b: CellPosition | undefined) => a?.row === b?.row && a?.column === b?.column;\n\nconst clampSpan = (value: Span | undefined, count: number): Span | undefined => value && [value[0], Math.min(value[1], count - 1)];\n\nconst clampPosition = (position: CellPosition | undefined, rowCount: number, columnCount: number): CellPosition | undefined =>\n position && { row: Math.min(position.row, rowCount - 1), column: Math.min(position.column, columnCount - 1) };\n\n/**\n * The selected ranges, the active cell (where typing and keyboard moves start; it sits inside the last range)\n * and the focus corner (the end of the last range that moves when the selection is extended).\n * Every change returns whether the ranges or the active cell differ afterwards.\n */\nclass SelectionModel {\n ranges: CellRange[] = [];\n\n active: CellPosition | undefined = undefined;\n\n focus: CellPosition | undefined = undefined;\n\n private assign(ranges: CellRange[], active: CellPosition | undefined, focus: CellPosition | undefined) {\n const changed = ranges.length !== this.ranges.length\n || ranges.some((range, index) => !sameRange(range, this.ranges[index]))\n || !samePosition(active, this.active);\n this.ranges = ranges;\n this.active = active && { row: active.row, column: active.column };\n this.focus = focus && { row: focus.row, column: focus.column };\n return changed;\n }\n\n /** Makes this the only range, with `active` in focus. */\n set(range: CellRange, active: CellPosition, focus: CellPosition = active) {\n return this.assign([normalizeRange(range)], active, focus);\n }\n\n /** Adds a range to the selection, as ctrl+click does. */\n add(range: CellRange, active: CellPosition) {\n return this.assign([...this.ranges, normalizeRange(range)], active, active);\n }\n\n /** Replaces the last range, as shift+click or dragging does; the active cell stays and `focus` becomes the moving corner. */\n extend(range: CellRange, focus: CellPosition) {\n if (this.ranges.length === 0 || this.active === undefined) return this.set(range, focus);\n return this.assign([...this.ranges.slice(0, -1), normalizeRange(range)], this.active, focus);\n }\n\n clear() {\n return this.assign([], undefined, undefined);\n }\n\n /** Moves the active cell without touching the ranges, as Enter and Tab do inside a selection. */\n activate(position: CellPosition) {\n return this.assign(this.ranges, position, position);\n }\n\n /** Replaces everything, with the first cell of the last range active unless `active` says otherwise. */\n replace(ranges: readonly CellRange[], active?: CellPosition) {\n const normalized = ranges.map(normalizeRange);\n const last = normalized[normalized.length - 1];\n if (last === undefined) return this.clear();\n\n const start = active ?? { row: last.rows?.[0] ?? 0, column: last.columns?.[0] ?? 0 };\n return this.assign(normalized, start, start);\n }\n\n /** Fits the selection to a grid of the given size, dropping what lies outside it; an empty grid selects nothing. */\n clamp(rowCount: number, columnCount: number) {\n if (rowCount === 0 || columnCount === 0) return this.clear();\n\n const ranges = this.ranges\n .filter(range => resolve(range, rowCount, columnCount) !== undefined)\n .map(range => makeRange(clampSpan(range.rows, rowCount), clampSpan(range.columns, columnCount)));\n if (ranges.length === 0) return this.clear();\n\n return this.assign(ranges, clampPosition(this.active, rowCount, columnCount), clampPosition(this.focus, rowCount, columnCount));\n }\n\n /** A copy that is safe to hand out. */\n snapshot(): GridSelection {\n return { ranges: this.ranges.map(copyRange), active: this.active && { ...this.active } };\n }\n}\n\n/** How fast to scroll while dragging with the pointer at `value` and the visible area between `min` and `max`: negative is back, 0 inside. */\nexport const dragScrollSpeed = (value: number, min: number, max: number) => {\n if (value < min) return -Math.min(DRAG_SCROLL_MAX, Math.max(2, (min - value) / 4));\n if (value > max) return Math.min(DRAG_SCROLL_MAX, Math.max(2, (value - max) / 4));\n return 0;\n};\n\nexport default SelectionModel;\n","import { crossIndex, lineIndex, linePosition } from './selection';\nimport type { Axis, Bounds } from './selection';\nimport type { CellPosition } from '../types';\n\n/** The size of the grid the keyboard moves in; `pageRows` is how many rows PageUp and PageDown skip. */\nexport interface GridSize {\n rowCount: number;\n columnCount: number;\n pageRows: number;\n}\n\nconst clamp = (value: number, last: number) => Math.max(0, Math.min(last, value));\n\n/**\n * Where a navigation key takes the cursor from `from`, or undefined for any other key. Arrows move one cell and, with ctrl, to the edge;\n * Home and End go to the first and last column (with ctrl also the first and last row); PageUp and PageDown move a page of rows.\n * The result is always inside the grid.\n */\nexport const moveTarget = (from: CellPosition, key: string, ctrl: boolean, { rowCount, columnCount, pageRows }: GridSize): CellPosition | undefined => {\n const lastRow = rowCount - 1;\n const lastColumn = columnCount - 1;\n const at = (row: number, column: number): CellPosition => ({ row: clamp(row, lastRow), column: clamp(column, lastColumn) });\n switch (key) {\n case 'ArrowUp': return at(ctrl ? 0 : from.row - 1, from.column);\n case 'ArrowDown': return at(ctrl ? lastRow : from.row + 1, from.column);\n case 'ArrowLeft': return at(from.row, ctrl ? 0 : from.column - 1);\n case 'ArrowRight': return at(from.row, ctrl ? lastColumn : from.column + 1);\n case 'Home': return at(ctrl ? 0 : from.row, 0);\n case 'End': return at(ctrl ? lastRow : from.row, lastColumn);\n case 'PageUp': return at(from.row - pageRows, from.column);\n case 'PageDown': return at(from.row + pageRows, from.column);\n default: return undefined;\n }\n};\n\n/**\n * The next cell inside `bounds` for Enter (`axis` `'row'`, going down) or Tab (`'column'`, going right), one back with `backwards`.\n * Past the end of a line it continues on the next one, and past the last cell it starts over.\n */\nexport const stepWithin = (bounds: Bounds, from: CellPosition, axis: Axis, backwards: boolean): CellPosition => {\n const direction = backwards ? -1 : 1;\n const [alongFirst, alongLast, crossFirst, crossLast] = axis === 'row'\n ? [bounds.top, bounds.bottom, bounds.left, bounds.right]\n : [bounds.left, bounds.right, bounds.top, bounds.bottom];\n const along = lineIndex(axis, from) + direction;\n if (along >= alongFirst && along <= alongLast) return linePosition(axis, along, crossIndex(axis, from));\n\n const crossCount = crossLast - crossFirst + 1;\n const wrapped = crossFirst + ((crossIndex(axis, from) + direction - crossFirst) % crossCount + crossCount) % crossCount;\n return linePosition(axis, direction > 0 ? alongFirst : alongLast, wrapped);\n};\n\n/**\n * The scroll offset that brings the span `start` to `end` into view in a viewport of `size`, starting from `scroll`:\n * unchanged when it is already visible, and the span's start wins when it is larger than the viewport.\n */\nexport const revealOffset = (start: number, end: number, scroll: number, size: number) => Math.min(start, Math.max(scroll, end - size));\n","import type { Bounds } from './selection';\n\n/** Most cells one copy puts on the clipboard, so selecting everything in a huge grid cannot freeze the page. */\nexport const MAX_COPY_CELLS = 1_000_000;\n\n/** Text as one field of tab-separated values: wrapped in quotes, with quotes doubled, when it holds a tab, a line break or a quote, as spreadsheets do. */\nexport const escapeField = (text: string) => (/[\\t\\r\\n\"]/.test(text) ? `\"${text.replaceAll('\"', '\"\"')}\"` : text);\n\nexport interface CopiedText {\n text: string;\n /** Rows were left off to stay within `MAX_COPY_CELLS`. */\n truncated: boolean;\n}\n\n/**\n * The cells of `bounds` as tab-separated values, a row per line, from the text `textAt` gives for each cell.\n * Stops after as many whole rows as fit in `maxCells`, but always includes one.\n */\nexport const toTsv = (bounds: Bounds, textAt: (row: number, column: number) => string, maxCells = MAX_COPY_CELLS): CopiedText => {\n const width = bounds.right - bounds.left + 1;\n const height = bounds.bottom - bounds.top + 1;\n const rows = Math.min(height, Math.max(1, Math.floor(maxCells / width)));\n const lines = Array.from({ length: rows }, (_, offset) =>\n Array.from({ length: width }, (__, column) => escapeField(textAt(bounds.top + offset, bounds.left + column))).join('\\t'));\n return { text: lines.join('\\r\\n'), truncated: rows < height };\n};\n","export interface MenuEntry {\n id: string;\n label: string;\n disabled: boolean;\n}\n\n/**\n * A small popup menu, made of plain elements so it is accessible and can reach past the grid's box.\n * It sits in the top layer (`popover`), which closes it on an outside click or Escape. It is built when first opened.\n */\nexport class ContextMenu {\n private element: HTMLElement | undefined;\n\n private readonly host: HTMLElement;\n\n private readonly onPick: (id: string) => void;\n\n /** `onPick` is called with the id of the entry the user picked, after the menu closed. */\n constructor(host: HTMLElement, onPick: (id: string) => void) {\n this.host = host;\n this.onPick = onPick;\n }\n\n get isOpen() {\n return this.element?.matches(':popover-open') ?? false;\n }\n\n /** Shows the entries with their top left corner at the viewport position, moved in if it would overflow. */\n open(clientX: number, clientY: number, entries: readonly MenuEntry[]) {\n this.close();\n const menu = this.element ?? this.create();\n menu.replaceChildren(...entries.map(entry => this.createItem(entry)));\n menu.style.left = `${clientX}px`;\n menu.style.top = `${clientY}px`;\n menu.showPopover();\n\n const { width, height } = menu.getBoundingClientRect();\n menu.style.left = `${Math.max(0, Math.min(clientX, document.documentElement.clientWidth - width))}px`;\n menu.style.top = `${Math.max(0, Math.min(clientY, document.documentElement.clientHeight - height))}px`;\n this.items().find(item => !item.disabled)?.focus({ preventScroll: true });\n }\n\n close() {\n if (this.isOpen) this.element?.hidePopover();\n }\n\n private items() {\n return Array.from(this.element?.querySelectorAll<HTMLButtonElement>('[role=\"menuitem\"]') ?? []);\n }\n\n private create() {\n const menu = document.createElement('div');\n menu.className = 'contextMenu';\n menu.role = 'menu';\n menu.popover = 'auto';\n menu.addEventListener('keydown', this.onKeyDown);\n // light dismiss and Escape both end up here; focus goes back to the grid so the keyboard keeps working\n menu.addEventListener('toggle', event => {\n if ((event as ToggleEvent).newState === 'closed' && menu.contains(document.activeElement)) this.host.focus({ preventScroll: true });\n });\n this.host.append(menu);\n this.element = menu;\n return menu;\n }\n\n private createItem({ id, label, disabled }: MenuEntry) {\n const item = document.createElement('button');\n item.type = 'button';\n item.role = 'menuitem';\n item.textContent = label;\n item.disabled = disabled;\n item.addEventListener('click', () => {\n this.close();\n this.onPick(id);\n });\n return item;\n }\n\n private readonly onKeyDown = (event: KeyboardEvent) => {\n // the menu sits inside the grid, which would also act on Enter, Escape and the rest, and cancel the click Enter makes\n event.stopPropagation();\n const items = this.items().filter(item => !item.disabled);\n const index = items.indexOf(document.activeElement as HTMLButtonElement);\n const step = (to: number) => items[(to + items.length) % items.length]?.focus();\n if (event.key === 'ArrowDown') step(index + 1);\n else if (event.key === 'ArrowUp') step(index < 0 ? -1 : index - 1);\n else if (event.key === 'Home') step(0);\n else if (event.key === 'End') step(-1);\n else if (event.key === 'Tab') this.close();\n else return;\n\n event.preventDefault();\n };\n}\n\nexport default ContextMenu;\n","import throttle from 'lodash.throttle';\nimport debounce from 'lodash.debounce';\nimport Collection from './utils/collection';\nimport ColumnStore from './utils/column-store';\nimport DataStore from './utils/data-store';\nimport LruCache from './utils/lru-cache';\nimport { getRowId } from './utils/selectors';\nimport styles from './component.css?inline';\nimport Loading from './utils/loading';\nimport Layer from './utils/layer';\nimport RendererRegistry from './utils/renderer-registry';\nimport CellBackground from './cell-background';\nimport HeaderRenderer from './header';\nimport CellValueRenderer from './cell-value';\nimport { defaultTextStyle } from './text';\nimport type { TextStyle } from './text';\nimport { resolveFont } from './utils/inherited-font';\nimport { createColorCheck, isCssFont, isSameTheme, readTheme, THEME_DEFAULTS } from './utils/theme';\nimport type { Theme, ThemeName } from './utils/theme';\nimport { borderAt, buildOffsets, clampWidth, columnAt } from './utils/column-layout';\nimport { SORT_INDICATOR_AREA } from './sort-indicator';\nimport SelectionModel, {\n columnLevel,\n contains,\n crossIndex,\n dragScrollSpeed,\n lineIndex,\n linePosition,\n lineRange,\n rangeFor,\n resolve,\n rowLevel,\n shapeOf,\n} from './utils/selection';\nimport type { Axis } from './utils/selection';\nimport { moveTarget, revealOffset, stepWithin } from './utils/selection-navigation';\nimport { toTsv } from './utils/clipboard';\nimport ContextMenu from './utils/context-menu';\nimport type { LayerOptions } from './utils/layer';\nimport type {\n CellContext,\n CellFocusDetail,\n CellPosition,\n CellRange,\n CellRenderer,\n CellState,\n ContextMenuDetail,\n ContextMenuItem,\n GridSelection,\n Key,\n RendererRef,\n RowId,\n RowInput,\n SelectionChangeDetail,\n SelectionCopyDetail,\n SelectionLevel,\n SelectionMode,\n SortDirection,\n SortKey,\n} from './types';\nimport type { RowIdGetter } from './utils/data-store';\nimport type { Row } from './utils/row-store';\n\nconst classes = {\n scrollArea: 'scrollArea',\n resizeGuide: 'resizeGuide',\n horizontalGuide: 'horizontal',\n};\n\n/** How far from a column border the pointer still grabs it, in CSS px. Fingers are less precise than mice. */\nconst RESIZE_GRAB = { mouse: 4, touch: 12 };\n/** Longest a live `columnresizing` event is held back while dragging, in ms. */\nconst RESIZE_EVENT_INTERVAL_MS = 50;\n/** Most rows measured by auto-fit; the rows in view are what counts, and 100k rows must not make it slow. */\nconst AUTO_SIZE_SAMPLE_ROWS = 500;\n/** How far a touch may move and still count as a tap, in CSS px. */\nconst TAP_SLOP = 8;\n\n/** Layers and renderers every grid starts with. */\nconst builtIn = {\n background: 'background',\n content: 'content',\n selection: 'selection',\n header: 'header',\n backgroundRenderer: 'background',\n valueRenderer: 'value',\n headerRenderer: 'header',\n};\n\nconst BUILT_IN_LAYERS = [builtIn.background, builtIn.content, builtIn.selection, builtIn.header];\n\n/** What the grid remembers about a cell between frames. */\ninterface CellEntry {\n /** The raw value last drawn, and its formatted text; formatting only runs when the value differs. */\n value: unknown;\n formatted: string | undefined;\n animating: boolean;\n state: CellState;\n}\n\nconst STYLE_ELEMENT_ID = 'canvas-grid-styles';\n\nconst injectStyles = () => {\n if (document.getElementById(STYLE_ELEMENT_ID)) return;\n const style = document.createElement('style');\n style.id = STYLE_ELEMENT_ID;\n style.textContent = styles;\n document.head.appendChild(style);\n};\n\nconst parentOf = (element: Element) => {\n const root = element.getRootNode();\n return element.parentElement ?? (root instanceof ShadowRoot ? root.host : null);\n};\n\n/** The element and everything above it, out of shadow roots too. */\nconst ancestorsOf = (element: Element) => {\n const chain: Element[] = [];\n for (let current: Element | null = element; current; current = parentOf(current)) chain.push(current);\n return chain;\n};\n\nexport interface ColumnHeader {\n index: number;\n id: Key;\n displayName?: string;\n width: number;\n /** Narrowest the column can get when resized, in px. Defaults to 20. */\n minWidth?: number;\n /** Widest the column can get when resized, in px. Defaults to unlimited. */\n maxWidth?: number;\n /** Whether the user can drag this column's right border. Defaults to `true`; `setColumnWidth` ignores it. */\n resizable?: boolean;\n /** Renderers drawing a cell of this column, in order. Defaults to the grid's `cellRenderers`. */\n renderers?: RendererRef[];\n valueFormatter: (value: unknown) => string;\n /** CSS font of this column's cells, instead of the grid's `font`. Not `'inherit'`: that is the grid's. */\n font?: string;\n /** CSS font of this column's header, instead of the grid's `headerFont`. */\n headerFont?: string;\n /** Renderer drawing the header of this column. */\n headerRenderer: RendererRef;\n}\n\n/** What `getColumnState` returns and `setColumnState` takes: enough to restore the column widths later. */\nexport interface ColumnState {\n id: Key;\n width: number;\n}\n\n/** What triggered a resize: the user dragging or double-clicking a border, `autoSizeColumns`, or code calling `setColumnWidth` / `setColumnState`. */\nexport type ColumnResizeSource = 'drag' | 'auto' | 'api';\n\nexport interface ColumnResizeDetail {\n columnId: Key;\n width: number;\n source: ColumnResizeSource;\n}\n\nexport type ColumnDefinition = Key | (Partial<ColumnHeader> & { id: Key });\n\nexport interface Transaction {\n add?: RowInput[];\n remove?: RowInput[];\n update?: RowInput[];\n}\n\ninterface AgApi {\n setRowData: (data: RowInput[]) => void;\n updateRowData: (transaction: Transaction) => void;\n setColumnDefs: (columns: ColumnDefinition[]) => void;\n getRowNodeId: RowIdGetter;\n}\n\nexport type {\n CellContext,\n CellFocusDetail,\n CellPosition,\n CellRange,\n CellRenderer,\n CellState,\n ContextMenuDetail,\n ContextMenuItem,\n GridSelection,\n LayerOptions,\n RendererRef,\n SelectionChangeDetail,\n SelectionCopyDetail,\n SelectionMode,\n SortDirection,\n SortKey,\n};\n\nexport interface RowResizeDetail {\n rowId: RowId;\n height: number;\n source: RowResizeSource;\n}\n\n/** What triggered a row resize: the user dragging a row-number border, or code calling `setRowHeightById`. */\nexport type RowResizeSource = 'drag' | 'api';\n\ntype ResizeTarget = { axis: 'column'; column: ColumnHeader } | { axis: 'row'; row: Row };\n\n/** A border being dragged: where the pointer started, the size at that point, and when the last live event went out. */\ninterface DragProgress {\n start: number;\n startSize: number;\n lastEvent: number;\n}\n\ntype ColumnDrag = DragProgress & { axis: 'column'; column: ColumnHeader };\n\ntype RowDrag = DragProgress & { axis: 'row'; row: Row };\n\ntype ResizeDrag = ColumnDrag | RowDrag;\n\n/** Which keys change what a click does: shift extends the selection, ctrl or cmd adds a range to it. */\ninterface PointerModifiers {\n extend: boolean;\n additive: boolean;\n}\n\n/** What a press can select: a cell, a whole column (header), a whole row (row number), or everything (the corner). */\ntype SelectionHit =\n | { zone: 'cell'; row: number; column: number }\n | { zone: 'column'; column: number }\n | { zone: 'row'; row: number }\n | { zone: 'all' };\n\n/** A selection being dragged out with the pointer, from `anchor` to wherever the pointer is. */\ninterface SelectionDrag {\n pointerId: number;\n anchor: CellPosition;\n /** Set when the drag started on column headers (`'column'`) or row numbers (`'row'`) and selects whole columns or rows. */\n axis: Axis | undefined;\n /** Pointer position in client coordinates. */\n x: number;\n y: number;\n /** Pending animation frame of the scrolling that continues while the pointer rests outside the grid. */\n frame: number | undefined;\n}\n\n/** A touch that may turn out to be a tap; a touch that moves is a scroll instead. */\ninterface TouchTap {\n pointerId: number;\n x: number;\n y: number;\n hit: SelectionHit;\n modifiers: PointerModifiers;\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'canvas-grid': CanvasGridComponent;\n }\n\n interface HTMLElementEventMap {\n columnresizing: CustomEvent<ColumnResizeDetail>;\n columnresized: CustomEvent<ColumnResizeDetail>;\n rowresizing: CustomEvent<RowResizeDetail>;\n rowresized: CustomEvent<RowResizeDetail>;\n selectionchange: CustomEvent<SelectionChangeDetail>;\n cellfocus: CustomEvent<CellFocusDetail>;\n selectioncopy: CustomEvent<SelectionCopyDetail>;\n gridcontextmenu: CustomEvent<ContextMenuDetail>;\n }\n}\n\n/** Slack for the frame cap, in ms. */\nconst FRAME_JITTER_MS = 2;\nconst DEFAULT_FONT = '12px sans-serif';\nconst DEFAULT_HEADER_FONT = '13px sans-serif';\n\nclass CanvasGridComponent extends HTMLElement {\n /** Maximum redraw rate. */\n fps = 60;\n /** Theme read from the CSS custom properties, `refreshTheme` keeps it current. Explicit options win over it. */\n private theme: Theme = THEME_DEFAULTS.dark;\n _font: string | undefined = undefined;\n _headerFont: string | undefined = undefined;\n _headerHeight: number | undefined = undefined;\n _cellHeight: number | undefined = undefined;\n cellPadding = {\n top: 3,\n right: 3,\n bottom: 3,\n left: 3,\n };\n showRowNumbers = true;\n showHeaders = true;\n rowNumbersWidth = 30;\n ellipsis = '…';\n private _backgroundColor: string | undefined = undefined;\n private _headerBackgroundColor: string | undefined = undefined;\n private _textColor: string | undefined = undefined;\n /** Tint of selected cells; set it, then call `forceDraw`. */\n selectionColor: string | undefined = undefined;\n /** Colour of the outline of a selection and of the border around the active cell. */\n selectionBorderColor: string | undefined = undefined;\n\n /** Cell background; set it to override `--cg-background`, `undefined` hands it back to the theme. */\n get backgroundColor(): string {\n return this._backgroundColor ?? this.theme.background;\n }\n\n set backgroundColor(color: string | undefined) {\n this._backgroundColor = color;\n this.applyTheme();\n }\n\n /** Header background; overrides `--cg-header-background`. An empty string hides the corner above the row numbers. */\n get headerBackgroundColor(): string {\n return this._headerBackgroundColor ?? this.theme.headerBackground;\n }\n\n set headerBackgroundColor(color: string | undefined) {\n this._headerBackgroundColor = color;\n this.applyTheme();\n }\n\n /** Text colour of cells and headers; overrides `--cg-text-color` and `--cg-header-text-color`. */\n get textColor(): string {\n return this._textColor ?? this.theme.text;\n }\n\n set textColor(color: string | undefined) {\n this._textColor = color;\n this.applyTheme();\n }\n\n get headerHeight() {\n return this._headerHeight ?? this.theme.headerHeight;\n }\n\n set headerHeight(height: number) {\n this._headerHeight = height;\n }\n\n get cellHeight() {\n return this._cellHeight ?? this.theme.rowHeight;\n }\n\n set cellHeight(height: number) {\n this._cellHeight = height;\n }\n dataStore = new DataStore({\n getRowId: (row, index) => this.getRowId(row, index),\n getCellHeight: () => this.cellHeight,\n getRowHeight: id => this.newRowHeight(id),\n });\n _dataCollection = this.dataStore.rows;\n /** Per-cell memory of the rows drawn recently; bounded, since only the rows in view need it. */\n cellEntries = new LruCache<Record<string, CellEntry>>(2048);\n getRowId: RowIdGetter = getRowId;\n headers = new Collection<ColumnHeader>();\n animationFrame: number | undefined = undefined;\n scrollYOffset = 0;\n prevScrollYOffset = 0;\n scrollXOffset = 0;\n prevScrollXOffset = 0;\n lastRender = new Date().valueOf();\n lastDraw = this.lastRender;\n isScrolling = false;\n scrollHelper = document.createElement('div');\n scrollArea = this.createScrollArea();\n\n /** Canvases from bottom to top. */\n layers: Layer[] = [];\n private readonly layersByName = new Map<string, Layer>();\n private readonly warnedLayers = new Set<string>();\n renderers = new RendererRegistry();\n /** Renderers drawing a cell when its column does not name its own. */\n cellRenderers: RendererRef[] = [builtIn.backgroundRenderer, builtIn.valueRenderer];\n\n cellBackgroundRenderer = new CellBackground({\n layer: builtIn.background,\n background: this.theme.background,\n enableFlashing: true,\n flashInDuration: 200,\n flashOutDuration: 400,\n flashColor: this.theme.flash,\n zebraColor: this.theme.zebra,\n hoverColor: this.theme.hover,\n borderRightWidth: 1,\n borderRightColor: this.theme.border,\n borderBottomWidth: 1,\n borderBottomColor: this.theme.border,\n });\n\n cellValueRenderer = new CellValueRenderer({\n layer: builtIn.content,\n font: this.theme.font,\n color: this.theme.text,\n });\n\n headerCellRenderer = new HeaderRenderer({\n layer: builtIn.header,\n font: this.theme.headerFont,\n color: this.theme.headerText,\n background: this.theme.headerBackground,\n selectedBackground: this.theme.headerSelected,\n fullySelectedBackground: this.theme.headerFullySelected,\n borderRightWidth: 1,\n borderRightColor: this.theme.headerBorder,\n borderBottomWidth: 1,\n borderBottomColor: this.theme.headerBottomBorder,\n });\n\n loadingIndicator: Loading;\n /** Reused for every cell drawn; see CellContext. */\n private readonly cell: CellContext;\n private readonly placeholderState: CellState = {};\n throttleTransation = throttle(() => {\n const prevSize = this.totalHeight;\n const moved = this.dataStore.flush();\n if (prevSize !== this.totalHeight) {\n this.refreshScrollbar();\n }\n this.refitSelection();\n // rows that were removed or re-sorted changed position, and a normal draw only repaints cells whose value changed\n if (moved) this.forceDraw();\n this.requestRender();\n }, 50);\n\n agApi: AgApi;\n\n constructor() {\n super();\n\n this.resize = this.resize.bind(this);\n this.setValues = this.setValues.bind(this);\n this.setColumns = this.setColumns.bind(this);\n this.clearValues = this.clearValues.bind(this);\n this.updateLastRender = this.updateLastRender.bind(this);\n this.transaction = this.transaction.bind(this);\n this.queueUpdate = this.queueUpdate.bind(this);\n\n this.addLayer(builtIn.background, { alpha: false });\n this.addLayer(builtIn.content);\n this.addLayer(builtIn.header);\n this.registerRenderer(builtIn.backgroundRenderer, this.cellBackgroundRenderer);\n this.registerRenderer(builtIn.valueRenderer, this.cellValueRenderer);\n this.registerRenderer(builtIn.headerRenderer, this.headerCellRenderer);\n this.loadingIndicator = new Loading({ ctx: this.requireLayer(builtIn.header).ctx });\n this.cell = {\n ctx: this.requireLayer(builtIn.content).ctx,\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n row: undefined,\n column: undefined,\n value: undefined,\n formatted: '',\n updatedAt: undefined,\n age: Infinity,\n now: 0,\n dt: 0,\n valueChanged: false,\n forced: false,\n isScrolling: false,\n selected: 'none',\n state: {},\n };\n\n const component = this;\n this.agApi = {\n setRowData: this.setValues,\n updateRowData: this.transaction,\n setColumnDefs: this.setColumns,\n get getRowNodeId() {\n return component.getRowId;\n },\n set getRowNodeId(getId) {\n if (typeof getId === 'function') component.getRowId = getId;\n },\n };\n }\n\n /** Canvas of the content layer, which also defines the viewport size. */\n get canvas() {\n return this.requireLayer(builtIn.content).canvas;\n }\n\n get flashInDuration() {\n return this.cellBackgroundRenderer.options.flashInDuration;\n }\n\n set flashInDuration(flashInDuration: number) {\n this.cellBackgroundRenderer.update({ flashInDuration });\n }\n\n get flashOutDuration() {\n return this.cellBackgroundRenderer.options.flashOutDuration;\n }\n\n set flashOutDuration(flashOutDuration: number) {\n this.cellBackgroundRenderer.update({ flashOutDuration });\n }\n\n getLayer(name: string) {\n return this.layersByName.get(name);\n }\n\n private requireLayer(name: string) {\n const layer = this.getLayer(name);\n if (!layer) throw new Error(`canvas-grid: no layer named \"${name}\"`);\n return layer;\n }\n\n /** Adds a canvas on top of the existing layers, or below the layer named in `before`. */\n addLayer(name: string, { alpha = true, desynchronized = false, before }: LayerOptions = {}) {\n if (this.getLayer(name)) throw new Error(`canvas-grid: layer \"${name}\" already exists`);\n\n const layer = new Layer(name, { alpha, desynchronized });\n const next = before === undefined ? undefined : this.requireLayer(before);\n this.layers.splice(next ? this.layers.indexOf(next) : this.layers.length, 0, layer);\n this.layersByName.set(name, layer);\n // the constructor already runs on elements that are in the document, before connectedCallback mounted anything\n if (this.scrollArea.parentElement === this) {\n this.insertBefore(layer.canvas, next?.canvas ?? this.scrollArea);\n layer.resize(this.clientWidth, this.clientHeight, this.pixelRatio);\n this.forceDraw();\n }\n return layer;\n }\n\n removeLayer(name: string) {\n const layer = this.requireLayer(name);\n this.layers = this.layers.filter(candidate => candidate !== layer);\n this.layersByName.delete(name);\n layer.canvas.remove();\n }\n\n /** Makes a renderer available to columns under `name`; registering an existing name replaces it. */\n registerRenderer(name: string, renderer: CellRenderer) {\n this.renderers.register(name, renderer);\n }\n\n unregisterRenderer(name: string) {\n this.renderers.unregister(name);\n }\n\n createScrollArea() {\n const scrollArea = document.createElement('div');\n scrollArea.className = classes.scrollArea;\n scrollArea.appendChild(this.scrollHelper);\n return scrollArea;\n }\n\n set font(font: string) {\n if (this._font !== font) {\n this._font = font;\n this.cellValueRenderer.font = resolveFont(font, getComputedStyle(this), DEFAULT_FONT);\n }\n }\n\n get font() {\n return this._font ?? this.theme.font;\n }\n\n set headerFont(font: string) {\n if (this._headerFont !== font) {\n this._headerFont = font;\n this.headerCellRenderer.font = resolveFont(font, getComputedStyle(this), DEFAULT_HEADER_FONT);\n }\n }\n\n get headerFont() {\n return this._headerFont ?? this.theme.headerFont;\n }\n\n private textStyle: TextStyle = { ...defaultTextStyle };\n\n private setTextStyle(style: Partial<TextStyle>) {\n this.textStyle = { ...this.textStyle, ...style };\n this.cellValueRenderer.setTextStyle(this.textStyle);\n this.headerCellRenderer.setTextStyle(this.textStyle);\n this.forceDraw();\n }\n\n /** Canvas `textRendering` for cells and headers: `'auto'` (default), `'optimizeSpeed'`, `'optimizeLegibility'` or `'geometricPrecision'`. */\n set textRendering(textRendering: TextStyle['textRendering']) {\n this.setTextStyle({ textRendering });\n }\n\n get textRendering() {\n return this.textStyle.textRendering;\n }\n\n /** Canvas `fontKerning` for cells and headers: `'auto'` (default), `'normal'` or `'none'`. */\n set fontKerning(fontKerning: TextStyle['fontKerning']) {\n this.setTextStyle({ fontKerning });\n }\n\n get fontKerning() {\n return this.textStyle.fontKerning;\n }\n\n /** Extra space after each character as a CSS length, `'0px'` by default. */\n set letterSpacing(letterSpacing: string) {\n this.setTextStyle({ letterSpacing });\n }\n\n get letterSpacing() {\n return this.textStyle.letterSpacing;\n }\n\n /**\n * What happens to text wider than its cell: `'clip'` (default) cuts it off at the cell edge and measures nothing,\n * `'ellipsis'` shortens it and ends it with an ellipsis, which means measuring the text.\n */\n set textOverflow(textOverflow: TextStyle['textOverflow']) {\n this.setTextStyle({ textOverflow });\n }\n\n get textOverflow() {\n return this.textStyle.textOverflow;\n }\n\n /** `'ltr'` (default), `'rtl'`, or `'auto'` to pick the direction per cell from its first letter. */\n set direction(direction: TextStyle['direction']) {\n this.setTextStyle({ direction });\n }\n\n get direction() {\n return this.textStyle.direction;\n }\n\n connectedCallback() {\n this.layers.forEach(layer => this.appendChild(layer.canvas));\n this.appendChild(this.scrollArea);\n this.appendChild(this.resizeGuide);\n\n this.updateLastRender();\n this.refreshTheme();\n this.refreshFonts();\n this.watchTheme();\n if (this.headers.length === 0) this.setColumns(Array(50).fill(1).map((_, index) => index));\n\n document.addEventListener('visibilitychange', this.onVisibilityChange);\n this.observeSize();\n this.pixelRatioQuery = window.matchMedia(`(resolution: ${this.pixelRatio}dppx)`);\n this.pixelRatioQuery.addEventListener('change', this.watchPixelRatio, { once: true });\n\n if (document.fonts) {\n document.fonts.addEventListener('loadingdone', this.onFontsLoaded);\n } else {\n this.fontsTimeout = setTimeout(this.onFontsLoaded, 2000);\n }\n\n const debounceAfterScroll = debounce(() => {\n this.isScrolling = false;\n }, 200);\n this.scrollArea.addEventListener('pointermove', this.onPointerMove);\n this.scrollArea.addEventListener('pointerleave', this.onPointerLeave);\n this.scrollArea.addEventListener('pointerdown', this.onResizePointerDown);\n this.scrollArea.addEventListener('pointermove', this.onResizePointerMove);\n this.scrollArea.addEventListener('pointerup', this.onResizePointerEnd);\n this.scrollArea.addEventListener('pointercancel', this.onResizePointerEnd);\n this.scrollArea.addEventListener('dblclick', this.onResizeDoubleClick);\n this.scrollArea.addEventListener('touchstart', this.onResizeTouchStart, { passive: false });\n // after the resize listeners, which claim a press on a border first\n this.scrollArea.addEventListener('pointerdown', this.onSelectPointerDown);\n this.scrollArea.addEventListener('pointermove', this.onSelectPointerMove);\n this.scrollArea.addEventListener('pointerup', this.onSelectPointerEnd);\n this.scrollArea.addEventListener('pointercancel', this.onSelectPointerEnd);\n this.addEventListener('keydown', this.onKeyDown);\n this.addEventListener('copy', this.onCopy);\n this.addEventListener('contextmenu', this.onContextMenu);\n // the offsets are read once per frame in `render`, so a scroll event costs nothing and no frame shows a stale position\n this.scrollArea.addEventListener('scroll', () => {\n this.contextMenu?.close();\n this.isScrolling = true;\n this.updateHoveredRow();\n debounceAfterScroll();\n this.requestRender();\n });\n }\n\n /** Rows whose cells must be redrawn because the hover highlight moved off or onto them. */\n private hoverDirty: (number | undefined)[] = [];\n\n private setHoveredRow(index: number | undefined) {\n const previous = this.cellBackgroundRenderer.hoveredRowIndex;\n if (previous === index) return;\n\n this.cellBackgroundRenderer.hover(index);\n // added to, not replaced: the pointer can cross several rows before the next frame, and each needs its redraw\n this.hoverDirty.push(previous, index);\n this.requestRender();\n }\n\n /** Pointer position relative to the grid, kept to find the hovered row again after scrolling. */\n private pointerY: number | undefined = undefined;\n\n private updateHoveredRow() {\n if (this.pointerY === undefined) return;\n\n const y = this.pointerY - (this.showHeaders ? this.headerHeight : 0);\n const index = this._dataCollection.indexAt(y + this.scrollArea.scrollTop);\n this.setHoveredRow(y < 0 || index >= this._dataCollection.length ? undefined : index);\n }\n\n private readonly onPointerMove = (event: PointerEvent) => {\n this.pointerY = event.clientY - this.getBoundingClientRect().top;\n this.updateHoveredRow();\n };\n\n private readonly onPointerLeave = () => {\n this.pointerY = undefined;\n this.setHoveredRow(undefined);\n };\n\n private fontsTimeout: ReturnType<typeof setTimeout> | undefined = undefined;\n\n private readonly onVisibilityChange = () => {\n if (document.visibilityState === 'hidden') {\n this.cancelRender();\n return;\n }\n this.resize();\n };\n\n /**\n * Re-reads the fonts and redraws. Call it after changing the CSS font of the grid or its ancestors\n * while `font` / `headerFont` are `'inherit'`. Web fonts finishing to load trigger it too.\n */\n refreshFonts() {\n this.cellValueRenderer.font = resolveFont(this.font, getComputedStyle(this), DEFAULT_FONT);\n this.headerCellRenderer.font = resolveFont(this.headerFont, getComputedStyle(this), DEFAULT_HEADER_FONT);\n this.renderers.clearCaches();\n this.resize();\n }\n\n private readonly onFontsLoaded = () => this.refreshFonts();\n\n private themeQuery: MediaQueryList | undefined = undefined;\n private themeObserver: MutationObserver | undefined = undefined;\n private colorCheck: ((value: string) => boolean) | undefined = undefined;\n\n /** The `theme` attribute when it names a theme, else the colour scheme the page prefers. */\n private get themeName(): ThemeName {\n const attribute = this.getAttribute('theme');\n if (attribute === 'light' || attribute === 'dark') return attribute;\n return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';\n }\n\n /**\n * Re-reads the `--cg-*` custom properties and redraws when a value changed. Runs by itself when the colour scheme,\n * the `theme` attribute or the `class`, `style` or `data-theme` attribute of the grid or an ancestor change;\n * call it after changing the tokens any other way, such as a stylesheet rule that is toggled.\n */\n refreshTheme() {\n const style = getComputedStyle(this);\n this.colorCheck ??= createColorCheck(document.createElement('canvas').getContext('2d') ?? { fillStyle: '' });\n const next = readTheme(this.themeName, {\n read: token => style.getPropertyValue(token),\n isColor: this.colorCheck,\n isFont: isCssFont,\n });\n if (isSameTheme(next, this.theme)) return;\n\n const sizeChanged = next.rowHeight !== this.theme.rowHeight || next.headerHeight !== this.theme.headerHeight;\n this.theme = next;\n if (sizeChanged) this.syncThemeHeights();\n this.applyTheme();\n }\n\n /** Hands the theme, with the explicit options on top, to the renderers and redraws. */\n private applyTheme() {\n const { theme } = this;\n this.cellBackgroundRenderer.update({\n background: this.backgroundColor,\n borderRightColor: theme.border,\n borderBottomColor: theme.border,\n zebraColor: theme.zebra,\n hoverColor: theme.hover,\n flashColor: theme.flash,\n });\n this.headerCellRenderer.update({\n background: this.headerBackgroundColor,\n color: this._textColor ?? theme.headerText,\n selectedBackground: theme.headerSelected,\n fullySelectedBackground: theme.headerFullySelected,\n borderRightColor: theme.headerBorder,\n borderBottomColor: theme.headerBottomBorder,\n });\n this.cellValueRenderer.color = this.textColor;\n this.loadingIndicator.setColor(this.textColor);\n this.refreshFonts();\n }\n\n /** Row heights follow `--cg-row-height` until `cellHeight`, `setRowHeight` or a drag sets them. */\n private syncThemeHeights() {\n if (this._cellHeight === undefined && this.rowHeightOf === undefined) this._dataCollection.setHeights(id => this.heightOfRow(id));\n this.refreshRowHeights();\n this.refreshScrollbar();\n }\n\n private readonly onThemeChange = () => this.refreshTheme();\n\n private watchTheme() {\n this.themeQuery = window.matchMedia('(prefers-color-scheme: light)');\n this.themeQuery.addEventListener('change', this.onThemeChange);\n this.themeObserver = new MutationObserver(this.onThemeChange);\n ancestorsOf(this).forEach(element => this.themeObserver?.observe(element, { attributes: true, attributeFilter: ['class', 'style', 'theme', 'data-theme'] }));\n }\n\n private unwatchTheme() {\n this.themeQuery?.removeEventListener('change', this.onThemeChange);\n this.themeObserver?.disconnect();\n }\n\n cancelRender() {\n if (this.animationFrame !== undefined) cancelAnimationFrame(this.animationFrame);\n this.animationFrame = undefined;\n }\n\n /**\n * Schedules a draw for the next animation frame. Nothing is drawn while the grid is idle:\n * scrolling, data changes and resizes request a draw, and `draw` requests the next one itself while a cell animates.\n */\n requestRender() {\n this.animationFrame ??= requestAnimationFrame(() => this.render());\n }\n\n updateLastRender() {\n this.lastRender = new Date().valueOf();\n }\n\n render() {\n this.animationFrame = undefined;\n this.readScrollOffsets();\n if (this.relayoutPending) {\n this.relayoutPending = false;\n this.forceDraw();\n this.updateLastRender();\n return;\n }\n const delta = new Date().valueOf() - this.lastRender;\n // the frame cap is for animations; scrolling draws on every frame, or it would visibly lag behind the scrollbar\n // a little under the frame time: frames arrive a fraction early or late, and would otherwise be skipped by turns\n if (!this.isScrolling && delta < (1000 / this.fps) - FRAME_JITTER_MS) {\n this.requestRender();\n return;\n }\n this.draw();\n this.updateLastRender();\n }\n\n private readScrollOffsets() {\n this.scrollXOffset = Math.round(this.scrollArea.scrollLeft);\n this.scrollYOffset = Math.round(this.scrollArea.scrollTop);\n }\n\n hasScrolled() {\n return this.hasXScrolled() || this.hasYScrolled();\n }\n\n hasYScrolled() {\n return this.prevScrollYOffset !== this.scrollYOffset;\n }\n\n hasXScrolled() {\n return this.prevScrollXOffset !== this.scrollXOffset;\n }\n\n isInViewport(x = 0, y = 0, width = 0, height = 0) {\n if (x > this.viewportWidth) return false;\n if (y > this.viewportHeight) return false;\n if (x + width < 0) return false;\n if (y + height < 0) return false;\n\n return true;\n }\n\n /** Fills the shared context for something that is not a data cell: a header, row number or placeholder. */\n private describe(x: number, y: number, width: number, height: number, overrides: Partial<CellContext>) {\n return Object.assign(this.cell, {\n x,\n y,\n width,\n height,\n row: undefined,\n column: undefined,\n value: undefined,\n formatted: '',\n updatedAt: undefined,\n age: Infinity,\n valueChanged: true,\n forced: true,\n selected: 'none',\n state: this.placeholderState,\n }, overrides);\n }\n\n private paint(ref: RendererRef) {\n const renderer = this.renderers.resolve(ref);\n const layer = renderer && this.layersByName.get(renderer.layer);\n if (renderer && !layer && !this.warnedLayers.has(renderer.layer)) {\n this.warnedLayers.add(renderer.layer);\n console.warn(`canvas-grid: renderer draws on missing layer \"${renderer.layer}\"`);\n }\n if (!renderer || !layer) return;\n\n this.cell.ctx = layer.ctx;\n renderer.draw(this.cell);\n }\n\n private paintAll(refs: readonly RendererRef[]) {\n refs.forEach(ref => this.paint(ref));\n }\n\n private isAnimating(refs: readonly RendererRef[]) {\n return refs.some(ref => this.renderers.resolve(ref)?.isAnimating?.(this.cell) === true);\n }\n\n draw(forced = false) {\n const now = new Date().valueOf();\n const redrawAll = forced || this.hasScrolled();\n this.cell.now = now;\n this.cell.dt = now - this.lastDraw;\n this.cell.isScrolling = this.isScrolling;\n this.lastDraw = now;\n // everything visible is painted again after a scroll, so custom layers start clean: a renderer that only clears its own cell\n // would leave what it drew at the old position in the gaps between cells\n if (!forced && this.hasScrolled()) this.clearCustomLayers();\n // the loading indicator animates until there is data\n let keepDrawing = this._dataCollection.length === 0;\n\n if ((forced || this.hasXScrolled() || this.headersDirty) && this.showHeaders) {\n this.renderHeaders();\n }\n\n const fakeRows = 200;\n if (forced && this.showRowNumbers && this._dataCollection.length === 0) {\n for (let fakeRowIndex= 0; fakeRowIndex <= fakeRows; fakeRowIndex++) {\n this.renderRowNumber({ index: fakeRowIndex }, (fakeRowIndex * this.cellHeight) + (this.showHeaders ? this.headerHeight : 0) - this.scrollYOffset);\n }\n }\n\n if (this._dataCollection.length === 0) {\n this.loadingIndicator.render();\n for (let fakeRowIndex= 0; fakeRowIndex <= fakeRows; fakeRowIndex++) {\n this.headers.forEach(header => {\n this.describe(\n Math.round(this.columnOffsets[header.index] + (this.showRowNumbers ? this.rowNumbersWidth : 0) - this.scrollXOffset),\n Math.round((fakeRowIndex * this.cellHeight) + (this.showHeaders ? this.headerHeight : 0) - this.scrollYOffset),\n header.width,\n this.cellHeight,\n { column: header, valueChanged: false },\n );\n this.paintAll(header.renderers ?? this.cellRenderers);\n });\n }\n }\n\n const originY = Math.round((this.showHeaders ? this.headerHeight : 0) - this.scrollYOffset);\n const xOffset = Math.round((this.showRowNumbers ? this.rowNumbersWidth : 0) - this.scrollXOffset);\n // only the rows overlapping the viewport: found by offset instead of walking from the first row\n const firstRow = this._dataCollection.indexAt(-originY);\n const visibleColumns = this.getVisibleColumns(xOffset);\n for (let rowIndex = firstRow; rowIndex < this._dataCollection.length; rowIndex++) {\n const row = this._dataCollection.at(rowIndex);\n const currentY = originY + this._dataCollection.topOf(rowIndex);\n if (!row || currentY >= this.viewportHeight) break;\n\n const { id: key, slot } = row;\n\n if ((forced || this.hasYScrolled() || this.headersDirty) && this.showRowNumbers) {\n this.renderRowNumber(row, currentY);\n }\n\n if (row.height + currentY > 0) {\n let entries = this.cellEntries.get(String(key));\n if (!entries) {\n entries = {};\n this.cellEntries.set(String(key), entries);\n }\n const cellRow = { id: key, index: row.index };\n\n for (const { header, id: columnKey, x, store } of visibleColumns) {\n const value = store?.get(slot);\n if (value === undefined) continue;\n\n const entry = entries[columnKey] ??= { value: undefined, formatted: undefined, animating: false, state: {} };\n // values are only formatted for the cells being drawn, and again only once they change\n const formatted = entry.formatted !== undefined && entry.value === value ? entry.formatted : header.valueFormatter(value);\n const valueChanged = entry.formatted !== formatted;\n const updatedAt = store?.getUpdatedAt(slot);\n\n const { cell } = this;\n cell.x = x;\n cell.y = currentY;\n cell.width = Math.round(header.width);\n cell.height = row.height;\n cell.row = cellRow;\n cell.column = header;\n cell.value = value;\n cell.formatted = formatted;\n cell.updatedAt = updatedAt;\n cell.age = updatedAt === undefined ? Infinity : now - updatedAt;\n cell.valueChanged = valueChanged;\n cell.forced = redrawAll;\n cell.selected = 'none';\n cell.state = entry.state;\n const refs = header.renderers ?? this.cellRenderers;\n const animating = this.isAnimating(refs);\n // an animation gets one last frame after it stops, so its final state is what stays on screen\n if (redrawAll || valueChanged || animating || entry.animating || this.hoverDirty.includes(rowIndex)) this.paintAll(refs);\n entry.animating = animating;\n entry.value = value;\n entry.formatted = formatted;\n keepDrawing ||= animating;\n }\n }\n }\n if (redrawAll || this.selectionDirty) this.renderSelection();\n if (this.scrollYOffset > 0 || this.scrollXOffset > 0) {\n this.renderBrick();\n }\n this.hoverDirty = [];\n this.selectionDirty = false;\n this.headersDirty = false;\n this.prevScrollYOffset = this.scrollYOffset;\n this.prevScrollXOffset = this.scrollXOffset;\n if (keepDrawing) this.requestRender();\n }\n\n /** The columns overlapping the viewport horizontally, with their x position and values; found once per draw, not per row. */\n private getVisibleColumns(xOffset: number) {\n const visible: { header: ColumnHeader; id: string; x: number; store: ColumnStore | undefined }[] = [];\n const { columnList, columnOffsets } = this;\n for (let index = Math.max(0, columnAt(columnOffsets, -xOffset)); index < columnList.length; index++) {\n const x = xOffset + columnOffsets[index];\n if (x > this.viewportWidth) break;\n\n const header = columnList[index];\n visible.push({ header, id: String(header.id), x, store: this.dataStore.columns.get(String(header.id)) });\n }\n return visible;\n }\n\n /** Columns in display order, and where each starts; rebuilt when columns or widths change. */\n private columnList: ColumnHeader[] = [];\n\n private columnOffsets: number[] = [0];\n\n private updateColumnLayout() {\n this.columnList = [];\n this.headers.forEach(header => this.columnList.push(header));\n this.columnOffsets = buildOffsets(this.columnList.map(header => header.width));\n }\n\n /** The selection must be drawn again on the next frame. */\n private selectionDirty = false;\n\n /** The headers and row numbers must be drawn again, because the selection they show changed. */\n private headersDirty = false;\n\n /** How much of a column is selected, for its header. */\n private columnSelection(index: number): SelectionLevel {\n const { ranges } = this.selectionModel;\n return ranges.length === 0 ? 'none' : columnLevel(ranges, index, this._dataCollection.length);\n }\n\n /** How much of a row is selected, for its row number. */\n private rowSelection(index: number): SelectionLevel {\n const { ranges } = this.selectionModel;\n return ranges.length === 0 ? 'none' : rowLevel(ranges, index, this.columnList.length);\n }\n\n /** Whether the selection layer holds anything, so a grid that never selects never clears it. */\n private selectionDrawn = false;\n\n /** Tints each selected range and outlines the active cell: one rectangle per range, however many cells it covers. */\n private renderSelection() {\n const { ranges, active } = this.selectionModel;\n if (ranges.length === 0 && !this.selectionDrawn) return;\n\n const layer = this.getLayer(builtIn.selection);\n if (!layer) return;\n\n const { ctx } = layer;\n layer.clear();\n this.selectionDrawn = ranges.length > 0;\n if (!this.selectionDrawn) return;\n\n const left = this.showRowNumbers ? this.rowNumbersWidth : 0;\n const top = this.showHeaders ? this.headerHeight : 0;\n const originX = left - this.scrollXOffset;\n const originY = top - this.scrollYOffset;\n const { _dataCollection: rows, columnOffsets } = this;\n const rectOf = (range: CellRange) => {\n const bounds = resolve(range, rows.length, this.columnList.length);\n if (!bounds) return undefined;\n\n const x = originX + columnOffsets[bounds.left];\n const y = originY + rows.topOf(bounds.top);\n return { x, y, width: originX + columnOffsets[bounds.right + 1] - x, height: originY + rows.topOf(bounds.bottom + 1) - y };\n };\n\n ctx.save();\n ctx.beginPath();\n ctx.rect(left, top, this.viewportWidth - left, this.viewportHeight - top);\n ctx.clip();\n ctx.fillStyle = this.selectionColor ?? this.theme.selection;\n ctx.strokeStyle = this.selectionBorderColor ?? this.theme.selectionBorder;\n ctx.lineWidth = 1;\n ranges.map(rectOf).forEach(rect => {\n if (!rect) return;\n ctx.fillRect(rect.x, rect.y, rect.width, rect.height);\n ctx.strokeRect(rect.x + 0.5, rect.y + 0.5, rect.width - 1, rect.height - 1);\n });\n const cell = active && rectOf({ rows: [active.row, active.row], columns: [active.column, active.column] });\n if (cell) {\n // the active cell is left untinted, like in a spreadsheet\n ctx.clearRect(cell.x, cell.y, cell.width, cell.height);\n ctx.lineWidth = 2;\n ctx.strokeRect(cell.x + 1, cell.y + 1, cell.width - 2, cell.height - 2);\n }\n ctx.restore();\n }\n\n renderRowNumber(row: { index: number; height?: number }, y: number) {\n if (!this.isInViewport(0, y, this.rowNumbersWidth, row.height)) return;\n this.describe(0, Math.ceil(y), this.rowNumbersWidth, row.height ?? 0, {\n row: { id: row.index, index: row.index },\n formatted: `${row.index + 1}`,\n selected: this.rowSelection(row.index),\n });\n this.paint(builtIn.headerRenderer);\n }\n\n private clearCustomLayers() {\n this.layers.filter(layer => !BUILT_IN_LAYERS.includes(layer.name)).forEach(layer => layer.clear());\n }\n\n forceDraw() {\n this.layers.forEach(layer => layer.clear());\n this.draw(true);\n }\n\n /** Viewport size in CSS pixels as of the last resize; cached because reading `clientWidth` per cell is slow. */\n viewportWidth = 0;\n\n viewportHeight = 0;\n\n /** Device pixels per CSS pixel; canvases are scaled by it to stay sharp on HiDPI screens. */\n get pixelRatio() {\n return window.devicePixelRatio || 1;\n }\n\n /** Resizes the layers when the size or pixel ratio changed, then redraws everything. */\n resize() {\n this.cancelRender();\n const { pixelRatio } = this;\n this.viewportWidth = this.clientWidth;\n this.viewportHeight = this.clientHeight;\n this.layers.forEach(layer => layer.resize(this.clientWidth, this.clientHeight, pixelRatio));\n if (this.cellValueRenderer.pixelRatio !== pixelRatio) {\n this.renderers.clearCaches();\n }\n this.cellValueRenderer.pixelRatio = pixelRatio;\n this.headerCellRenderer.pixelRatio = pixelRatio;\n this.forceDraw();\n }\n\n /** Redraws when the element changes size, instead of checking on every frame. */\n private observeSize() {\n this.resizeObserver ??= new ResizeObserver(() => this.resize());\n this.resizeObserver.observe(this);\n }\n\n /** The pixel ratio changes with browser zoom or when the window moves to another screen. */\n private watchPixelRatio = () => {\n this.pixelRatioQuery?.removeEventListener('change', this.watchPixelRatio);\n this.pixelRatioQuery = window.matchMedia(`(resolution: ${this.pixelRatio}dppx)`);\n this.pixelRatioQuery.addEventListener('change', this.watchPixelRatio, { once: true });\n this.resize();\n };\n\n private resizeObserver: ResizeObserver | undefined = undefined;\n\n private pixelRatioQuery: MediaQueryList | undefined = undefined;\n\n /** A row's position and height along with its values by column id, or undefined for an unknown row. */\n getRowData(rowId: RowId) {\n const row = this._dataCollection.get(rowId);\n if (!row) return undefined;\n\n const values: Record<string, unknown> = {};\n this.dataStore.columns.forEach((column, key) => {\n const value = column.get(row.slot);\n if (value !== undefined) values[key] = value;\n });\n return { id: row.id, index: row.index, height: row.height, values };\n }\n\n /** Orders the rows by the given columns, in priority order; an empty list restores the original order. */\n setSortModel(model: readonly SortKey[]) {\n this.dataStore.setSortModel(model);\n this.headerCellRenderer.setSortModel(model);\n this.forceDraw();\n }\n\n getSortModel() {\n return this.dataStore.getSortModel();\n }\n\n renderBrick() {\n if (this.showHeaders && this.showRowNumbers && this.headerBackgroundColor) {\n this.describe(0, 0, this.rowNumbersWidth, this.headerHeight, {});\n this.paint(builtIn.headerRenderer);\n }\n }\n\n renderHeaders() {\n const xOffset = (this.showRowNumbers ? this.rowNumbersWidth : 0) - this.scrollXOffset;\n\n this.getVisibleColumns(xOffset).forEach(({ header, x }) => {\n this.describe(x, 0, Math.round(header.width), this.headerHeight, {\n column: header,\n formatted: header.displayName ?? '',\n selected: this.columnSelection(header.index),\n });\n this.paint(header.headerRenderer);\n });\n\n if (this.scrollXOffset + this.rowNumbersWidth > 0) {\n this.renderBrick();\n }\n }\n\n getColumnHeader(key: Key) {\n return this.headers.get(key);\n }\n\n /** Redraws everything on the next frame, without waiting for the frame cap; for changes that move cells, like resizing. */\n private requestRelayout() {\n this.relayoutPending = true;\n this.requestRender();\n }\n\n private relayoutPending = false;\n\n private emitResized(type: 'columnresized' | 'columnresizing', column: ColumnHeader, source: ColumnResizeSource) {\n this.dispatchEvent(new CustomEvent<ColumnResizeDetail>(type, { detail: { columnId: column.id, width: column.width, source } }));\n }\n\n /** Sets the widths within each column's limits and refreshes the layout once; returns the columns that actually changed. */\n private applyColumnWidths(widths: Iterable<[Key, number]>) {\n const changed = Array.from(widths)\n .map(([id, width]) => ({ column: this.headers.get(id), width }))\n .filter(({ column, width }) => column !== undefined && clampWidth(width, column.minWidth, column.maxWidth) !== Math.round(column.width))\n .flatMap(({ column, width }) => (column === undefined ? [] : [{ column, width: clampWidth(width, column.minWidth, column.maxWidth) }]))\n .map(({ column, width }) => Object.assign(column, { width }));\n if (changed.length === 0) return changed;\n\n this.updateColumnLayout();\n this.refreshScrollbar();\n this.requestRelayout();\n return changed;\n }\n\n /** Sets a column's width in px, within its `minWidth` / `maxWidth`, and fires `columnresized` when it changed. Works for columns that are not `resizable`. */\n setColumnWidth(id: Key, width: number) {\n this.applyColumnWidths([[id, width]]).forEach(column => this.emitResized('columnresized', column, 'api'));\n }\n\n /** The widths of all columns, in display order; pass it to `setColumnState` to restore them. */\n getColumnState(): ColumnState[] {\n return this.columnList.map(({ id, width }) => ({ id, width: Math.round(width) }));\n }\n\n /** Restores widths from `getColumnState`; unknown columns are skipped. Fires `columnresized` for each column that changed. */\n setColumnState(state: readonly ColumnState[]) {\n this.applyColumnWidths(state.map(({ id, width }): [Key, number] => [id, width]))\n .forEach(column => this.emitResized('columnresized', column, 'api'));\n }\n\n private measureContext: CanvasRenderingContext2D | null | undefined = undefined;\n\n /**\n * Fits columns (all of them by default) to their content: the header and the rows in view, at most\n * `AUTO_SIZE_SAMPLE_ROWS` of them, so it stays fast with any number of rows. Fires `columnresized` for each that changed.\n */\n autoSizeColumns(ids?: readonly Key[]) {\n this.measureContext ??= document.createElement('canvas').getContext('2d');\n const ctx = this.measureContext;\n if (!ctx) return;\n\n const { scrollTop } = this.scrollArea;\n const rows: Row[] = [];\n for (let index = this._dataCollection.indexAt(scrollTop); index < this._dataCollection.length && rows.length < AUTO_SIZE_SAMPLE_ROWS; index++) {\n const row = this._dataCollection.at(index);\n if (!row || this._dataCollection.topOf(index) > scrollTop + this.viewportHeight) break;\n rows.push(row);\n }\n\n const padding = this.cellPadding.left + this.cellPadding.right + 1;\n const widest = (font: string, texts: Iterable<string>) => {\n ctx.font = font;\n return Math.max(0, ...Array.from(texts, text => ctx.measureText(text).width));\n };\n const widths = (ids ?? this.columnList.map(({ id }) => id))\n .flatMap(id => this.headers.get(id) ?? [])\n .map((column): [Key, number] => {\n const store = this.dataStore.columns.get(String(column.id));\n const texts = rows.flatMap(({ slot }) => store?.get(slot) ?? []).map(value => column.valueFormatter(value));\n const header = widest(column.headerFont ?? this.headerCellRenderer.font, [column.displayName ?? '']) + padding + SORT_INDICATOR_AREA;\n const content = widest(column.font ?? this.cellValueRenderer.font, texts) + padding;\n return [column.id, Math.ceil(Math.max(header, content))];\n });\n this.applyColumnWidths(widths).forEach(column => this.emitResized('columnresized', column, 'auto'));\n }\n\n /** Smallest row height the user can drag to, or a row-height function can return. */\n private static readonly MIN_ROW_HEIGHT = 8;\n\n /** Heights set for single rows by dragging or `setRowHeightById`, by row id; they win over `setRowHeight`'s function. */\n private readonly rowHeightOverrides = new Map<string, number>();\n\n private rowHeightOf: ((id: RowId) => number) | undefined = undefined;\n\n private heightOfRow(id: RowId) {\n const height = this.rowHeightOverrides.get(String(id)) ?? this.rowHeightOf?.(id) ?? this.cellHeight;\n return Math.max(CanvasGridComponent.MIN_ROW_HEIGHT, Math.round(height));\n }\n\n /** Only asked for rows being added, and only when it can differ from `cellHeight`. */\n private readonly newRowHeight = (id: RowId) =>\n this.rowHeightOverrides.size === 0 && this.rowHeightOf === undefined ? undefined : this.heightOfRow(id);\n\n private refreshRowHeights() {\n this.refreshScrollbar();\n this.requestRelayout();\n }\n\n private emitRowResized(type: 'rowresized' | 'rowresizing', rowId: RowId, source: RowResizeSource) {\n const height = this._dataCollection.get(rowId)?.height;\n if (height !== undefined) this.dispatchEvent(new CustomEvent<RowResizeDetail>(type, { detail: { rowId, height, source } }));\n }\n\n /**\n * Sets the height of every row: a number in px (also the height of rows added later), or a function of the row id\n * returning one, called for existing rows now and for rows as they are added once their values are stored.\n * Replaces the heights of rows resized one by one. Fires no events.\n */\n setRowHeight(height: number | ((id: RowId) => number)) {\n this.rowHeightOverrides.clear();\n if (typeof height === 'function') this.rowHeightOf = height;\n else {\n this.rowHeightOf = undefined;\n this._cellHeight = height;\n }\n this._dataCollection.setHeights(id => this.heightOfRow(id));\n this.refreshRowHeights();\n }\n\n /** Sets one row's height in px (at least 8) and fires `rowresized`; the height sticks to the row through sorting and updates. */\n setRowHeightById(id: RowId, height: number) {\n this.rowHeightOverrides.set(String(id), Math.max(CanvasGridComponent.MIN_ROW_HEIGHT, Math.round(height)));\n if (!this._dataCollection.setHeight(id, this.heightOfRow(id))) return;\n\n this.refreshRowHeights();\n this.emitRowResized('rowresized', id, 'api');\n }\n\n private resizeDrag: ResizeDrag | undefined = undefined;\n\n /** The column border or row border under the pointer, when it can be dragged. */\n private findResizeTarget(clientX: number, clientY: number, pointerType: string): ResizeTarget | undefined {\n const rect = this.getBoundingClientRect();\n const x = clientX - rect.left;\n const y = clientY - rect.top;\n const grab = pointerType === 'touch' ? RESIZE_GRAB.touch : RESIZE_GRAB.mouse;\n // not over the vertical scrollbar\n if (x < 0 || y < 0 || x > this.scrollArea.clientWidth) return undefined;\n\n const rowNumbers = this.showRowNumbers ? this.rowNumbersWidth : 0;\n const headers = this.showHeaders ? this.headerHeight : 0;\n if (this.showHeaders && y <= headers) return this.findColumnBorder(x - rowNumbers, grab);\n if (this.showRowNumbers && x < rowNumbers) return this.findRowBorder(y - headers, grab);\n return undefined;\n }\n\n private findColumnBorder(x: number, grab: number): ResizeTarget | undefined {\n if (x < 0) return undefined;\n\n const column = this.columnList[borderAt(this.columnOffsets, x + this.scrollArea.scrollLeft, grab)];\n return column === undefined || column.resizable === false ? undefined : { axis: 'column', column };\n }\n\n private findRowBorder(y: number, grab: number): ResizeTarget | undefined {\n const row = this._dataCollection.at(this._dataCollection.borderAt(y + this.scrollArea.scrollTop, grab));\n return row === undefined ? undefined : { axis: 'row', row };\n }\n\n private moveResizeGuide() {\n const { resizeDrag, resizeGuide } = this;\n resizeGuide.style.display = resizeDrag ? 'block' : 'none';\n if (!resizeDrag) return;\n\n const horizontal = resizeDrag.axis === 'row';\n resizeGuide.classList.toggle(classes.horizontalGuide, horizontal);\n const column = this.showRowNumbers ? this.rowNumbersWidth : 0;\n const header = this.showHeaders ? this.headerHeight : 0;\n resizeGuide.style.transform = resizeDrag.axis === 'row'\n ? `translateY(${header + this._dataCollection.topOf(resizeDrag.row.index) + resizeDrag.row.height - this.scrollArea.scrollTop}px)`\n : `translateX(${column + (this.columnOffsets[resizeDrag.column.index + 1] ?? 0) - this.scrollArea.scrollLeft}px)`;\n }\n\n private readonly resizeGuide = Object.assign(document.createElement('div'), { className: classes.resizeGuide });\n\n private readonly onResizePointerDown = (event: PointerEvent) => {\n const target = event.button === 0 ? this.findResizeTarget(event.clientX, event.clientY, event.pointerType) : undefined;\n if (!target) return;\n\n event.preventDefault();\n this.scrollArea.setPointerCapture(event.pointerId);\n this.resizeDrag = target.axis === 'row'\n ? { ...target, start: event.clientY, startSize: target.row.height, lastEvent: 0 }\n : { ...target, start: event.clientX, startSize: target.column.width, lastEvent: 0 };\n this.moveResizeGuide();\n };\n\n private readonly onResizePointerMove = (event: PointerEvent) => {\n const { resizeDrag } = this;\n if (!resizeDrag) {\n // the cursor follows the border; touch has no hover\n const target = this.findResizeTarget(event.clientX, event.clientY, event.pointerType);\n this.scrollArea.style.cursor = target === undefined ? '' : `${target.axis === 'row' ? 'row' : 'col'}-resize`;\n return;\n }\n\n if (resizeDrag.axis === 'row') this.dragRow(resizeDrag, event.clientY - resizeDrag.start);\n else this.dragColumn(resizeDrag, event.clientX - resizeDrag.start);\n this.moveResizeGuide();\n };\n\n private dragColumn(drag: ColumnDrag, delta: number) {\n const { column } = drag;\n this.applyColumnWidths([[column.id, drag.startSize + delta]]);\n if (!this.dueForLiveEvent(drag)) return;\n\n this.emitResized('columnresizing', column, 'drag');\n }\n\n private dragRow(drag: RowDrag, delta: number) {\n const { id } = drag.row;\n this.rowHeightOverrides.set(String(id), Math.max(CanvasGridComponent.MIN_ROW_HEIGHT, Math.round(drag.startSize + delta)));\n if (this._dataCollection.setHeight(id, this.heightOfRow(id))) this.refreshRowHeights();\n if (!this.dueForLiveEvent(drag)) return;\n\n this.emitRowResized('rowresizing', id, 'drag');\n }\n\n /** Whether enough time has passed since the last live event; counts this one as sent when it has. */\n private dueForLiveEvent(drag: ResizeDrag) {\n const now = performance.now();\n if (now - drag.lastEvent < RESIZE_EVENT_INTERVAL_MS) return false;\n\n drag.lastEvent = now;\n return true;\n }\n\n private readonly onResizePointerEnd = (event: PointerEvent) => {\n const { resizeDrag } = this;\n if (!resizeDrag) return;\n\n this.resizeDrag = undefined;\n this.scrollArea.releasePointerCapture(event.pointerId);\n this.moveResizeGuide();\n if (resizeDrag.axis === 'row' && resizeDrag.row.height !== resizeDrag.startSize) this.emitRowResized('rowresized', resizeDrag.row.id, 'drag');\n if (resizeDrag.axis === 'column' && resizeDrag.column.width !== resizeDrag.startSize) this.emitResized('columnresized', resizeDrag.column, 'drag');\n };\n\n private readonly onResizeDoubleClick = (event: MouseEvent) => {\n const target = this.findResizeTarget(event.clientX, event.clientY, 'mouse');\n if (target?.axis !== 'column') return;\n\n const { column } = target;\n if (column === this.columnList[this.columnList.length - 1] && this.fillRemainingSpace(column)) return;\n this.autoSizeColumns([column.id]);\n };\n\n /** Widens the last column to the right edge of the viewport when the columns leave it empty; returns whether there was room. */\n private fillRemainingSpace(column: ColumnHeader) {\n const free = this.scrollArea.clientWidth - (this.showRowNumbers ? this.rowNumbersWidth : 0) - this.columnOffsets[this.columnOffsets.length - 1];\n if (free <= 0) return false;\n\n this.applyColumnWidths([[column.id, column.width + free]]).forEach(changed => this.emitResized('columnresized', changed, 'auto'));\n return true;\n }\n\n /** Keeps a touch that starts on a border from scrolling the grid, so the pointer events can drag it instead. */\n private readonly onResizeTouchStart = (event: TouchEvent) => {\n const [touch] = Array.from(event.touches);\n if (event.touches.length === 1 && this.findResizeTarget(touch.clientX, touch.clientY, 'touch')) event.preventDefault();\n };\n\n private readonly selectionModel = new SelectionModel();\n\n private mode: SelectionMode = 'none';\n\n /**\n * What the user can select with the pointer: `'none'` (default), one `'cell'`, `'range'`s of cells with whole rows and columns\n * (like a spreadsheet), or whole `'row'`s or `'column'`s. `getSelection` and `setSelection` work in every mode; switching to `'none'` clears it.\n */\n set selectionMode(mode: SelectionMode) {\n if (mode === this.mode) return;\n\n this.mode = mode;\n this.updateTabIndex();\n if (mode === 'none') this.clearSelection();\n }\n\n /** Whether the grid put `tabindex` on itself, so it is only taken away again when it was not the page's. */\n private ownsTabIndex = false;\n\n /** A grid with selection takes keyboard focus; one without it stays out of the tab order, as before. */\n private updateTabIndex() {\n if (this.mode !== 'none' && !this.hasAttribute('tabindex')) {\n this.tabIndex = 0;\n this.ownsTabIndex = true;\n }\n if (this.mode === 'none' && this.ownsTabIndex) {\n this.removeAttribute('tabindex');\n this.ownsTabIndex = false;\n }\n }\n\n get selectionMode() {\n return this.mode;\n }\n\n /** The selected ranges and the active cell, by displayed position; the ranges are copies. */\n getSelection(): GridSelection {\n return this.selectionModel.snapshot();\n }\n\n /**\n * Selects the given ranges, with `active` in focus (the first cell of the last range by default). A range that leaves out `rows` or `columns`\n * covers all of them. Positions beyond the data are cut off when it changes. Fires `selectionchange`, and `cellfocus` when the active cell moved.\n */\n setSelection(ranges: readonly CellRange[], active?: CellPosition) {\n this.changeSelection(() => this.selectionModel.replace(ranges, active), false);\n }\n\n clearSelection() {\n this.changeSelection(() => this.selectionModel.clear(), false);\n }\n\n private emitSelectionChange(selecting: boolean) {\n this.dispatchEvent(new CustomEvent<SelectionChangeDetail>('selectionchange', { detail: { ...this.selectionModel.snapshot(), selecting } }));\n }\n\n private emitCellFocus() {\n const { active } = this.selectionModel;\n const row = active && this._dataCollection.at(active.row);\n const column = active && this.columnList[active.column];\n if (!active || !row || !column) return;\n\n this.dispatchEvent(new CustomEvent<CellFocusDetail>('cellfocus', {\n detail: { rowId: row.id, rowIndex: active.row, columnId: column.id, columnIndex: active.column },\n }));\n }\n\n /** Applies a change to the selection, then redraws it and fires the events if something differs. */\n private changeSelection(change: () => boolean, selecting: boolean) {\n const previous = this.selectionModel.active && { ...this.selectionModel.active };\n if (!change()) return false;\n\n // a canvas is only worth its memory and compositing once something is selected\n if (this.selectionModel.ranges.length > 0 && !this.getLayer(builtIn.selection)) this.addLayer(builtIn.selection, { before: builtIn.header });\n this.selectionDirty = true;\n this.headersDirty = true;\n this.requestRender();\n this.emitSelectionChange(selecting);\n const { active } = this.selectionModel;\n if (active && (active.row !== previous?.row || active.column !== previous.column)) this.emitCellFocus();\n return true;\n }\n\n /** Cuts the selection to the data after rows or columns changed, and redraws it: ranges that reach the end follow the data. */\n private refitSelection() {\n if (this.selectionModel.ranges.length === 0) return;\n\n this.changeSelection(() => this.selectionModel.clamp(this._dataCollection.length, this.columnList.length), false);\n this.selectionDirty = true;\n }\n\n private selectDrag: SelectionDrag | undefined = undefined;\n\n private touchTap: TouchTap | undefined = undefined;\n\n /** Where in the grid, in px from its top left, a point of the viewport is. */\n private offsetsOf(clientX: number, clientY: number) {\n const rect = this.getBoundingClientRect();\n const left = this.showRowNumbers ? this.rowNumbersWidth : 0;\n const top = this.showHeaders ? this.headerHeight : 0;\n return { x: clientX - rect.left, y: clientY - rect.top, left, top };\n }\n\n /** Index of the column at `contentX` px from the left of the first column, or undefined past the last one. */\n private columnIndexAt(contentX: number) {\n const column = columnAt(this.columnOffsets, contentX);\n return column < 0 || contentX >= this.columnOffsets[this.columnOffsets.length - 1] ? undefined : column;\n }\n\n /** Index of the row at `contentY` px from the top of the first row, or undefined past the last one. */\n private rowIndexAt(contentY: number) {\n const row = this._dataCollection.indexAt(contentY);\n return row >= this._dataCollection.length ? undefined : row;\n }\n\n /** What is under the pointer that a press can select: a cell, a column header, a row number or the corner. Scrollbars and empty space are nothing. */\n private hitAt(clientX: number, clientY: number): SelectionHit | undefined {\n const { x, y, left, top } = this.offsetsOf(clientX, clientY);\n if (x < 0 || y < 0 || x > this.scrollArea.clientWidth || y > this.scrollArea.clientHeight) return undefined;\n\n const inHeader = y < top;\n const inRowNumbers = x < left;\n const column = this.columnIndexAt(x - left + this.scrollArea.scrollLeft);\n const row = this.rowIndexAt(y - top + this.scrollArea.scrollTop);\n if (inHeader && inRowNumbers) return { zone: 'all' };\n if (inHeader) return column === undefined ? undefined : { zone: 'column', column };\n if (inRowNumbers) return row === undefined ? undefined : { zone: 'row', row };\n return column === undefined || row === undefined ? undefined : { zone: 'cell', row, column };\n }\n\n /** The cell nearest to the pointer, wherever it is: dragging past an edge selects up to that edge. */\n private nearestCell(clientX: number, clientY: number): CellPosition | undefined {\n const rows = this._dataCollection.length;\n if (rows === 0 || this.columnList.length === 0) return undefined;\n\n const { x, y, left, top } = this.offsetsOf(clientX, clientY);\n return {\n row: Math.min(rows - 1, this._dataCollection.indexAt(Math.max(0, y - top) + this.scrollArea.scrollTop)),\n column: columnAt(this.columnOffsets, Math.max(0, x - left) + this.scrollArea.scrollLeft),\n };\n }\n\n /** The row and column a header selection that was just made starts from: those at the top left of the viewport. */\n private firstVisible(axis: Axis) {\n return axis === 'column'\n ? this._dataCollection.indexAt(this.scrollArea.scrollTop)\n : Math.max(0, columnAt(this.columnOffsets, this.scrollArea.scrollLeft));\n }\n\n /**\n * Applies a press on a cell: plain selects it, shift extends from the active cell, ctrl or cmd adds a range.\n * Returns the cell a drag from here starts at.\n */\n private pressCell(cell: CellPosition, { extend, additive }: PointerModifiers, selecting: boolean) {\n const { selectionModel, mode } = this;\n const { active } = selectionModel;\n if (extend && active && mode !== 'cell') {\n const range = rangeFor(mode, active, cell);\n this.changeSelection(() => (additive ? selectionModel.extend(range, cell) : selectionModel.set(range, active, cell)), selecting);\n return { ...active };\n }\n\n const range = rangeFor(mode, cell, cell);\n this.changeSelection(() => (additive && mode !== 'cell' ? selectionModel.add(range, cell) : selectionModel.set(range, cell)), selecting);\n return cell;\n }\n\n /**\n * Applies a press on a column header or row number: it selects the whole column or row, shift extends from the active cell's,\n * ctrl or cmd adds one. Returns the cell a drag from here starts at.\n */\n private pressLine(axis: Axis, index: number, { extend, additive }: PointerModifiers, selecting: boolean) {\n const { selectionModel } = this;\n const { active } = selectionModel;\n if (extend && active) {\n const range = lineRange(axis, lineIndex(axis, active), index);\n const focus = linePosition(axis, index, crossIndex(axis, active));\n this.changeSelection(() => (additive ? selectionModel.extend(range, focus) : selectionModel.set(range, active, focus)), selecting);\n return { ...active };\n }\n\n const cell = linePosition(axis, index, this.firstVisible(axis));\n const range = lineRange(axis, index, index);\n this.changeSelection(() => (additive ? selectionModel.add(range, cell) : selectionModel.set(range, cell)), selecting);\n return cell;\n }\n\n /** Selects everything, keeping the active cell. */\n private selectEverything(selecting: boolean) {\n const active = this.selectionModel.active ?? { row: this.firstVisible('column'), column: this.firstVisible('row') };\n this.changeSelection(() => this.selectionModel.set({}, active), selecting);\n }\n\n /** Which modes a press in each part of the grid selects in; a column header does nothing when only rows can be selected, and so on. */\n private static readonly ZONE_MODES: Record<SelectionHit['zone'], readonly SelectionMode[]> = {\n cell: ['cell', 'range', 'row', 'column'],\n column: ['range', 'column'],\n row: ['range', 'row'],\n all: ['range', 'row', 'column'],\n };\n\n /** Applies a press wherever it landed. Returns the drag it starts, or undefined when there is nothing to drag. */\n private press(hit: SelectionHit, modifiers: PointerModifiers, selecting: boolean): Pick<SelectionDrag, 'anchor' | 'axis'> | undefined {\n if (!CanvasGridComponent.ZONE_MODES[hit.zone].includes(this.mode)) return undefined;\n if (hit.zone === 'all') {\n this.selectEverything(selecting);\n return undefined;\n }\n if (hit.zone === 'column') return { anchor: this.pressLine('column', hit.column, modifiers, selecting), axis: 'column' };\n if (hit.zone === 'row') return { anchor: this.pressLine('row', hit.row, modifiers, selecting), axis: 'row' };\n return { anchor: this.pressCell({ row: hit.row, column: hit.column }, modifiers, selecting), axis: undefined };\n }\n\n private dragSelectTo({ x, y, anchor, axis }: SelectionDrag) {\n const cell = this.nearestCell(x, y);\n if (!cell) return;\n\n if (axis) {\n const focus = linePosition(axis, lineIndex(axis, cell), crossIndex(axis, anchor));\n this.changeSelection(() => this.selectionModel.extend(lineRange(axis, lineIndex(axis, anchor), lineIndex(axis, cell)), focus), true);\n return;\n }\n if (this.mode === 'cell') return;\n\n const range = rangeFor(this.mode, anchor, cell);\n this.changeSelection(() => this.selectionModel.extend(range, cell), true);\n }\n\n private readonly onSelectPointerDown = (event: PointerEvent) => {\n if (this.mode === 'none' || event.button !== 0 || this.resizeDrag) return;\n\n const hit = this.hitAt(event.clientX, event.clientY);\n if (!hit) return;\n\n const modifiers = { extend: event.shiftKey, additive: event.ctrlKey || event.metaKey };\n if (event.pointerType === 'touch') {\n // a touch that moves scrolls, so it only selects when it ends where it started\n this.touchTap = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, hit, modifiers };\n return;\n }\n\n // cancelling the press also cancels the browser's own focusing, so the grid takes focus for the keyboard here\n event.preventDefault();\n this.focus({ preventScroll: true });\n const drag = this.press(hit, modifiers, true);\n if (!drag) return;\n\n this.scrollArea.setPointerCapture(event.pointerId);\n this.selectDrag = { ...drag, pointerId: event.pointerId, x: event.clientX, y: event.clientY, frame: undefined };\n };\n\n private readonly onSelectPointerMove = (event: PointerEvent) => {\n const { touchTap, selectDrag } = this;\n if (touchTap && Math.hypot(event.clientX - touchTap.x, event.clientY - touchTap.y) > TAP_SLOP) this.touchTap = undefined;\n if (!selectDrag || selectDrag.pointerId !== event.pointerId) return;\n\n selectDrag.x = event.clientX;\n selectDrag.y = event.clientY;\n this.dragSelectTo(selectDrag);\n selectDrag.frame ??= requestAnimationFrame(this.scrollWhileDragging);\n };\n\n /** Keeps scrolling, and extending the selection with it, for as long as the pointer is held outside the cells. */\n private readonly scrollWhileDragging = () => {\n const drag = this.selectDrag;\n if (!drag) return;\n\n drag.frame = undefined;\n const { x, y, left, top } = this.offsetsOf(drag.x, drag.y);\n // a drag along the headers only follows the pointer across, and one along the row numbers only down\n const dx = drag.axis === 'row' ? 0 : dragScrollSpeed(x, left, this.scrollArea.clientWidth);\n const dy = drag.axis === 'column' ? 0 : dragScrollSpeed(y, top, this.scrollArea.clientHeight);\n if (dx === 0 && dy === 0) return;\n\n this.scrollArea.scrollBy(dx, dy);\n this.dragSelectTo(drag);\n drag.frame = requestAnimationFrame(this.scrollWhileDragging);\n };\n\n private readonly onSelectPointerEnd = (event: PointerEvent) => {\n const { touchTap, selectDrag } = this;\n if (touchTap?.pointerId === event.pointerId) {\n this.touchTap = undefined;\n if (event.type === 'pointerup') {\n this.focus({ preventScroll: true });\n this.press(touchTap.hit, touchTap.modifiers, false);\n }\n return;\n }\n if (!selectDrag || selectDrag.pointerId !== event.pointerId) return;\n\n this.endSelectDrag();\n if (this.scrollArea.hasPointerCapture(event.pointerId)) this.scrollArea.releasePointerCapture(event.pointerId);\n this.emitSelectionChange(false);\n };\n\n private endSelectDrag() {\n if (this.selectDrag?.frame !== undefined) cancelAnimationFrame(this.selectDrag.frame);\n this.selectDrag = undefined;\n }\n\n /** Scrolls the least that brings a cell fully into view. */\n private revealCell({ row, column }: CellPosition) {\n const { scrollArea, _dataCollection: rows, columnOffsets } = this;\n const { left, top } = this.offsetsOf(0, 0);\n const scrollTop = revealOffset(rows.topOf(row), rows.topOf(row + 1), scrollArea.scrollTop, scrollArea.clientHeight - top);\n const scrollLeft = revealOffset(columnOffsets[column], columnOffsets[column + 1], scrollArea.scrollLeft, scrollArea.clientWidth - left);\n if (scrollTop !== scrollArea.scrollTop) scrollArea.scrollTop = scrollTop;\n if (scrollLeft !== scrollArea.scrollLeft) scrollArea.scrollLeft = scrollLeft;\n }\n\n private get gridSize() {\n const { top } = this.offsetsOf(0, 0);\n return {\n rowCount: this._dataCollection.length,\n columnCount: this.columnList.length,\n pageRows: Math.max(1, Math.floor((this.scrollArea.clientHeight - top) / this.cellHeight)),\n };\n }\n\n /** Selects one cell, or its whole row or column in those modes, and brings it into view. */\n private moveTo(cell: CellPosition) {\n const range = rangeFor(this.mode, cell, cell);\n this.changeSelection(() => this.selectionModel.set(range, cell), false);\n this.revealCell(cell);\n }\n\n /** Stretches the newest range to `cell`; it keeps being whole columns or whole rows when it was, and the active cell stays. */\n private extendTo(cell: CellPosition) {\n const { selectionModel, mode } = this;\n const { active, focus } = selectionModel;\n const last = selectionModel.ranges[selectionModel.ranges.length - 1];\n if (!active || !focus || !last) return;\n\n const shape = shapeOf(last);\n if (shape === 'all') return;\n if (shape === 'block') {\n const range = rangeFor(mode, active, cell);\n this.changeSelection(() => selectionModel.extend(range, cell), false);\n this.revealCell(cell);\n return;\n }\n\n const axis = shape;\n const range = lineRange(axis, lineIndex(axis, active), lineIndex(axis, cell));\n const moved = linePosition(axis, lineIndex(axis, cell), crossIndex(axis, focus));\n this.changeSelection(() => selectionModel.extend(range, moved), false);\n this.revealCell(moved);\n }\n\n /** Moves the active cell inside a selection of several cells; with one cell selected Enter moves the selection, and Tab is left to the page. */\n private stepActive(axis: Axis, backwards: boolean) {\n const { selectionModel } = this;\n const { active } = selectionModel;\n const last = selectionModel.ranges[selectionModel.ranges.length - 1];\n const bounds = last && resolve(last, this._dataCollection.length, this.columnList.length);\n if (!active) return false;\n if (bounds && (bounds.top !== bounds.bottom || bounds.left !== bounds.right)) {\n const next = stepWithin(bounds, active, axis, backwards);\n this.changeSelection(() => selectionModel.activate(next), false);\n this.revealCell(next);\n return true;\n }\n if (axis === 'column') return false;\n\n const target = moveTarget(active, backwards ? 'ArrowUp' : 'ArrowDown', false, this.gridSize);\n if (target) this.moveTo(target);\n return true;\n }\n\n /** Selects the whole column (ctrl+space) or row (shift+space) of the active cell. */\n private selectLineOfActive(axis: Axis) {\n const { active } = this.selectionModel;\n if (!active || !CanvasGridComponent.ZONE_MODES[axis].includes(this.mode)) return false;\n\n const range = lineRange(axis, lineIndex(axis, active), lineIndex(axis, active));\n this.changeSelection(() => this.selectionModel.set(range, active), false);\n return true;\n }\n\n /** Collapses the selection to its active cell. */\n private collapseSelection() {\n const { active } = this.selectionModel;\n if (!active) return false;\n\n const range = rangeFor(this.mode, active, active);\n return this.changeSelection(() => this.selectionModel.set(range, active), false);\n }\n\n /** Moves or extends the selection for a navigation key; the first press just selects the cell at the top left of the view. */\n private navigate(event: KeyboardEvent, ctrl: boolean) {\n const { active, focus } = this.selectionModel;\n const size = this.gridSize;\n if (size.rowCount === 0 || size.columnCount === 0) return false;\n\n const start = { row: this.firstVisible('column'), column: this.firstVisible('row') };\n const extend = event.shiftKey && this.mode !== 'cell';\n const target = moveTarget(active ? (extend && focus) || active : start, event.key, ctrl, size);\n if (!target) return false;\n\n if (!active) this.moveTo(start);\n else if (extend) this.extendTo(target);\n else this.moveTo(target);\n return true;\n }\n\n /** Returns whether the key was a selection key, which is then kept from also scrolling the page. */\n private handleSelectionKey(event: KeyboardEvent) {\n const ctrl = event.ctrlKey || event.metaKey;\n const { key, shiftKey } = event;\n if (ctrl && key.toLowerCase() === 'a') {\n if (!CanvasGridComponent.ZONE_MODES.all.includes(this.mode)) return false;\n this.selectEverything(false);\n return true;\n }\n if (key === ' ' && ctrl) return this.selectLineOfActive('column');\n if (key === ' ' && shiftKey) return this.selectLineOfActive('row');\n if (key === 'Enter') return this.stepActive('row', shiftKey);\n if (key === 'Tab') return this.stepActive('column', shiftKey);\n if (key === 'Escape') return this.collapseSelection();\n return this.navigate(event, ctrl);\n }\n\n private readonly onKeyDown = (event: KeyboardEvent) => {\n if (this.mode === 'none' || event.defaultPrevented || event.altKey || !this.handleSelectionKey(event)) return;\n\n event.preventDefault();\n };\n\n /** The newest range as tab-separated text of the formatted values, as shown; undefined when nothing is selected. */\n private copiedSelection(): SelectionCopyDetail | undefined {\n const { ranges } = this.selectionModel;\n const range = ranges[ranges.length - 1];\n const bounds = range && resolve(range, this._dataCollection.length, this.columnList.length);\n if (!range || !bounds) return undefined;\n\n const columns = this.columnList.slice(bounds.left, bounds.right + 1)\n .map(header => ({ header, store: this.dataStore.columns.get(String(header.id)) }));\n const { text, truncated } = toTsv(bounds, (row, column) => {\n const { header, store } = columns[column - bounds.left];\n const value = store?.get(this._dataCollection.at(row)?.slot ?? -1);\n return value === undefined ? '' : header.valueFormatter(value);\n });\n return { text, range: { ...range }, truncated };\n }\n\n /** The selection as it is about to be copied, once `selectioncopy` let it through; undefined when there is nothing to copy or a listener cancelled. */\n private requestCopy() {\n const copied = this.mode === 'none' ? undefined : this.copiedSelection();\n if (!copied) return undefined;\n\n return this.dispatchEvent(new CustomEvent<SelectionCopyDetail>('selectioncopy', { detail: copied, cancelable: true })) ? copied : undefined;\n }\n\n /** Puts the selection on the clipboard when the user copies. `selectioncopy` can change the text or cancel the copy. */\n private readonly onCopy = (event: ClipboardEvent) => {\n const copied = event.clipboardData && this.requestCopy();\n if (!copied || !event.clipboardData) return;\n\n event.clipboardData.setData('text/plain', copied.text);\n event.preventDefault();\n };\n\n /**\n * Copies the newest selected range to the clipboard, as the copy shortcut does, `selectioncopy` included.\n * Resolves to whether anything was copied. Browsers allow it from a user action only, such as a click.\n */\n async copySelection() {\n const copied = this.requestCopy();\n if (!copied) return false;\n\n await navigator.clipboard.writeText(copied.text);\n return true;\n }\n\n /** The entries of the context menu. Replace them to change the menu; an empty list keeps the browser's own menu. */\n contextMenuItems: ContextMenuItem[] = [\n { id: 'copy', label: 'Copy', disabled: () => this.selectionModel.ranges.length === 0, run: () => void this.copySelection() },\n ];\n\n private contextMenu: ContextMenu | undefined;\n\n private menuDetail: ContextMenuDetail | undefined;\n\n /** Whether a right click on this hit already has what it selects selected; those that do keep their selection. */\n private isSelected(hit: SelectionHit) {\n const { ranges } = this.selectionModel;\n if (hit.zone === 'cell') return ranges.some(range => contains(range, hit.row, hit.column));\n if (hit.zone === 'column') return columnLevel(ranges, hit.column, this._dataCollection.length) === 'full';\n if (hit.zone === 'row') return rowLevel(ranges, hit.row, this.columnList.length) === 'full';\n return ranges.some(range => shapeOf(range) === 'all');\n }\n\n /** Where the menu opens for a key press: the corner of the active cell, or of the grid's cells. */\n private menuAnchor(): { x: number; y: number } {\n const { x, y, left, top } = this.offsetsOf(0, 0);\n const { active } = this.selectionModel;\n if (!active) return { x: left - x, y: top - y };\n\n return {\n x: left - x + this.columnOffsets[active.column] - this.scrollArea.scrollLeft,\n y: top - y + this._dataCollection.topOf(active.row + 1) - this.scrollArea.scrollTop,\n };\n }\n\n /** Opens the context menu on a right click, a long press or the menu key, once `gridcontextmenu` let it. */\n private readonly onContextMenu = (event: MouseEvent) => {\n if (this.mode === 'none' || this.contextMenuItems.length === 0 || event.defaultPrevented) return;\n\n // the menu key and Shift+F10 report no button 2, and a position that is not where the user is looking\n const byPointer = event.button === 2;\n const hit = byPointer ? this.hitAt(event.clientX, event.clientY) : undefined;\n if (byPointer && !hit) return;\n\n event.preventDefault();\n this.focus({ preventScroll: true });\n if (hit && !this.isSelected(hit)) this.press(hit, { extend: false, additive: false }, false);\n\n const anchor = byPointer ? { x: event.clientX, y: event.clientY } : this.menuAnchor();\n const active = this.selectionModel.active;\n const detail: ContextMenuDetail = {\n ...this.selectionModel.snapshot(),\n ...anchor,\n row: hit ? (hit.zone === 'cell' || hit.zone === 'row' ? hit.row : undefined) : active?.row,\n column: hit ? (hit.zone === 'cell' || hit.zone === 'column' ? hit.column : undefined) : active?.column,\n items: [...this.contextMenuItems],\n };\n if (!this.dispatchEvent(new CustomEvent<ContextMenuDetail>('gridcontextmenu', { detail, cancelable: true }))) return;\n if (detail.items.length === 0) return;\n\n this.menuDetail = detail;\n this.contextMenu ??= new ContextMenu(this, id => this.menuDetail?.items.find(item => item.id === id)?.run(this.menuDetail));\n this.contextMenu.open(detail.x, detail.y, detail.items.map(({ id, label, disabled }) => ({\n id,\n label,\n disabled: typeof disabled === 'function' ? disabled(detail) : disabled ?? false,\n })));\n };\n\n get totalHeight() {\n return this._dataCollection.totalHeight;\n }\n\n refreshScrollbar() {\n const height = this.totalHeight + this.headerHeight;\n this.scrollHelper.style.height = `${height}px`;\n const width = this.columnOffsets[this.columnOffsets.length - 1];\n this.scrollHelper.style.width = `${width}px`;\n }\n\n queueUpdate(row: RowInput) {\n this.dataStore.queueUpdate(row);\n this.throttleTransation();\n }\n\n queueRemove(row: RowInput) {\n this.dataStore.queueRemove(row);\n this.throttleTransation();\n }\n\n transaction({ add = [], remove = [], update = [] }: Transaction) {\n if (Array.isArray(add)) {\n add.forEach(row => this.queueUpdate(row));\n }\n\n if (Array.isArray(update)) {\n update.forEach(row => this.queueUpdate(row));\n }\n\n if (Array.isArray(remove)) {\n remove.forEach(row => this.queueRemove(row));\n }\n }\n\n clearValues() {\n this.dataStore.clear();\n this.cellEntries.clear();\n }\n\n formatValue(key: Key, value: unknown) {\n return this.headers.get(key)?.valueFormatter(value) ?? String(value);\n }\n\n setValues(data: RowInput[]) {\n this.throttleTransation.cancel();\n this.clearValues();\n if (!Array.isArray(data)) return;\n this.dataStore.setRows(data);\n this.refreshScrollbar();\n this.refitSelection();\n this.forceDraw();\n }\n\n setColumns(columns: ColumnDefinition[]) {\n if (Array.isArray(columns)) {\n this.headers.clear();\n // cached formatted values belong to the previous formatters\n this.cellEntries.clear();\n const defaults = {\n width: 100,\n valueFormatter: (v: unknown) => String(v),\n headerRenderer: builtIn.headerRenderer,\n };\n columns.forEach((column, index) => {\n if (typeof column === 'string' || typeof column === 'number') {\n const columnId = column + '';\n this.headers.set(columnId, {\n ...defaults,\n index: index,\n id: column,\n displayName: columnId,\n });\n }\n if (typeof column === 'object') {\n this.headers.set(column.id + '', {\n ...defaults,\n index: index,\n ...column,\n });\n }\n });\n this.updateColumnLayout();\n this.refreshScrollbar();\n this.refitSelection();\n this.forceDraw();\n }\n }\n\n disconnectedCallback() {\n this.cancelRender();\n this.endSelectDrag();\n document.removeEventListener('visibilitychange', this.onVisibilityChange);\n this.resizeObserver?.disconnect();\n this.pixelRatioQuery?.removeEventListener('change', this.watchPixelRatio);\n this.unwatchTheme();\n document.fonts?.removeEventListener('loadingdone', this.onFontsLoaded);\n clearTimeout(this.fontsTimeout);\n }\n}\n\nif (window && window.customElements) {\n injectStyles();\n customElements.define('canvas-grid', CanvasGridComponent);\n}\n\nexport default CanvasGridComponent;\n"],"ignoreList":[0,1],"mappings":"C,8xBAUA,IAAI4B,EAAkB,sBAGlBC,EAAM,IAMNC,EAAS,aAGTC,EAAa,qBAGbC,EAAa,aAGbC,EAAY,cAGZC,EAAe,SAGfC,EAAa,OAAO,QAAU,UAAY,QAAU,OAAO,SAAW,QAAU,OAGhFC,EAAW,OAAO,MAAQ,UAAY,MAAQ,KAAK,SAAW,QAAU,KAGxEC,EAAOF,GAAcC,GAAY,SAAS,aAAa,CAAC,CAAC,EAUzDE,EAPc,OAAO,UAOQ,SAG7BC,EAAY,KAAK,IACjBC,EAAY,KAAK,IAkBjBC,EAAM,UAAW,CACnB,O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F,EAAQ,cAC1B,EACAjF,EAAQ,SAAS,EAAQ,IAAU,CACjC,GAAI,OAAOxK,GAAW,UAAY,OAAOA,GAAW,SAAU,CAC5D,IAAMG,EAAWH,EAAS,GAC1B,KAAK,QAAQ,IAAIG,EAAU,CACzB,GAAGgJ,EACI,QACP,GAAInJ,EACJ,YAAaG,CACf,CAAC,CACH,CACI,OAAOH,GAAW,UACpB,KAAK,QAAQ,IAAIA,EAAO,GAAK,GAAI,CAC/B,GAAGmJ,EACI,QACP,GAAGnJ,CACL,CAAC,CAEL,CAAC,EACD,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,KAAK,eAAe,EACpB,KAAK,UAAU,CACjB,CACF,CAEA,sBAAuB,CACrB,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,SAAS,oBAAoB,mBAAoB,KAAK,kBAAkB,EACxE,KAAK,gBAAgB,WAAW,EAChC,KAAK,iBAAiB,oBAAoB,SAAU,KAAK,eAAe,EACxE,KAAK,aAAa,EAClB,SAAS,OAAO,oBAAoB,cAAe,KAAK,aAAa,EACrE,aAAa,KAAK,YAAY,CAChC,CACF,E,OAEI,QAAU,OAAO,iBACnB4P,GAAa,EACb,eAAe,OAAO,cAAeS,EAAmB,G"}
|
|
1
|
+
{"version":3,"file":"web-component.js","names":["styles","throttle","debounce","factory","global","__create","__defProp","__getOwnPropDesc","__getOwnPropNames","__getProtoOf","__hasOwnProp","__commonJSMin","mod","cb","__copyProps","from","keys","i","n","key","to","except","k","desc","__toESM","isNodeMode","target","require_lodash_throttle","FUNC_ERROR_TEXT","NAN","reTrim","reIsBadHex","reIsBinary","reIsOctal","freeParseInt","freeGlobal","freeSelf","root","objectToString","nativeMax","nativeMin","now","debounce","lastArgs","lastThis","maxWait","result","timerId","lastCallTime","lastInvokeTime","leading","maxing","trailing","func","toNumber","wait","isObject","options","invokeFunc","args","thisArg","time","leadingEdge","timerExpired","remainingWait","timeSinceLastCall","timeSinceLastInvoke","shouldInvoke","trailingEdge","cancel","flush","debounced","isInvoking","throttle","\"leading\"","\"maxWait\"","\"trailing\"","type","value","isObjectLike","isSymbol","other","isBinary","require_lodash_debounce","import_lodash_throttle","import_lodash_debounce","Collection","entry","existing","matcher","id","fn","ColumnStore","length","slot","updatedAt","slots","MIN_HOLES_TO_COMPACT","RowStore","row","index","offset","low","high","middle","previous","replacement","added","height","heightOf","below","above","tolerance","removed","ids","indexes","a","b","holes","live","renumbered","rank","compare","moving","oldIndexes","inserts","positions","settledLength","end","at","items","write","read","removedIndex","rows","top","getNow","getRowId","collator","INCREMENTAL_SORT_RATIO","typeRank","compareValues","createDefaultKey","ranks","values","textIds","text","sorted","position","DataStore","environment","model","rowId","columnKey","data","changes","removals","moved","applyRemovals","column","kept","rowData","columnId","cached","only","rest","onlyColumn","precompute","sign","order","direction","sortKeys","changed","LruCache","limit","oldest","component_default","isNode","child","primitive","paint","ctx","props","x","y","Group","children","originX","originY","React","component","Renderer","getContext2d","canvas","Loading","color","Layer","name","width","pixelRatio","RendererRegistry","renderer","ref","Rect","w","h","alpha","HOVER_DURATION","REDUCED_MOTION_ALPHA","reducedMotionQuery","smoothstep","t","CellBackground","fade","duration","progress","eased","age","flashInDuration","flashOutDuration","remaining","flash","hover","background","zebraColor","hoverColor","flashColor","borderRightWidth","borderRightColor","borderBottomWidth","borderBottomColor","joiningCharacters","FIRST_COMPLEX_CODE","segmenter","toGraphemes","segment","toUnits","hasComplexCharacters","countFitting","used","units","widthOf","available","ellipsisWidth","ellipsis","sumWidths","total","MAX_CACHED_TEXTS","remember","cache","fitted","fitExactly","exact","whole","measure","scale","keep","unit","prefix","count","fitKerned","ellipsisHead","next","kerning","fitText","defaultTextStyle","FIRST_COMPLEX_CHARACTER","rightToLeftLetter","TextRenderer","font","style","known","measures","character","left","right","state","textRendering","fontKerning","letterSpacing","totalWidth","cellPadding","clip","rightToLeft","textX","ARROW_WIDTH","ARROW_HEIGHT","ARROW_ALPHA","SortIndicator","ascending","HeaderRenderer","selected","formatted","CellValueRenderer","valueChanged","forced","resolveFont","fallback","THEME_TOKENS","shared","THEME_DEFAULTS","PIXEL_KEYS","FONT_KEYS","toPixels","pixels","readTheme","defaults","parse","isFont","isColor","isSameTheme","createColorCheck","onBlack","isCssFont","clampWidth","minWidth","maxWidth","buildOffsets","offsets","widths","columnAt","last","borderAt","rightOfPrevious","rightOfCurrent","span","makeRange","columns","rangeBetween","rangeFor","mode","normalizeSpan","normalizeRange","range","copySpan","copyRange","resolve","bottom","rowCount","columnCount","within","coversAll","contains","columnLevel","level","ranges","rowLevel","shapeOf","lineRange","axis","linePosition","cross","lineIndex","crossIndex","sameSpan","sameRange","samePosition","clampSpan","clampPosition","SelectionModel","active","focus","normalized","start","dragScrollSpeed","min","max","clamp","moveTarget","lastRow","lastColumn","ctrl","pageRows","stepWithin","backwards","alongFirst","alongLast","crossFirst","crossLast","bounds","along","crossCount","wrapped","revealOffset","scroll","size","stepAfterEdit","inside","MAX_COPY_CELLS","escapeField","toTsv","maxCells","textAt","ContextMenu","host","onPick","menu","entries","clientX","clientY","item","event","label","disabled","step","asText","createInput","input","focusText","typed","createTextEditor","initialText","createNumberEditor","createCheckboxEditor","toOption","option","LIST_MAX_HEIGHT","LIST_MARGIN","createSelectEditor","listed","labelOf","open","box","list","choose","commit","place","show","visible","rect","upwards","typeAhead","wanted","found","createBuiltIn","editor","context","createEditor","startsByTyping","INVALID","parseNumber","editorKind","resolveEdit","kind","isText","rules","full","change","raw","verdict","error","classes","RESIZE_GRAB","RESIZE_EVENT_INTERVAL_MS","AUTO_SIZE_SAMPLE_ROWS","TAP_SLOP","builtIn","BUILT_IN_LAYERS","STYLE_ELEMENT_ID","injectStyles","parentOf","element","ancestorsOf","chain","current","FRAME_JITTER_MS","DEFAULT_FONT","DEFAULT_HEADER_FONT","CanvasGridComponent","prevSize","getId","layer","before","candidate","scrollArea","debounceAfterScroll","attribute","token","sizeChanged","theme","delta","overrides","refs","redrawAll","keepDrawing","fakeRowIndex","header","xOffset","firstRow","visibleColumns","rowIndex","currentY","cellRow","store","animating","columnOffsets","columnList","rectOf","cell","scrollTop","padding","widest","texts","content","grab","pointerType","rowNumbers","headers","resizeDrag","horizontal","resizeGuide","drag","free","touch","selecting","contentX","contentY","inHeader","inRowNumbers","selectionModel","extend","additive","hit","modifiers","anchor","touchTap","selectDrag","dx","dy","scrollLeft","shape","shiftKey","copied","byPointer","detail","editable","instance","wrapper","edit","oldValue","ok","message","newValue","setter","hadFocus","cut","hidden","single","add","update","remove","v"],"sources":["../node_modules/lodash.throttle/index.js","../node_modules/lodash.debounce/index.js","../components/utils/collection.ts","../components/utils/column-store.ts","../components/utils/row-store.ts","../components/utils/selectors.ts","../components/utils/data-store.ts","../components/utils/lru-cache.ts","../components/utils/jsx.ts","../components/utils/renderer.ts","../components/utils/canvas.ts","../components/utils/loading.ts","../components/utils/layer.ts","../components/utils/renderer-registry.ts","../components/rectangle/index.ts","../components/cell-background/index.tsx","../components/utils/fit-text.ts","../components/text/index.ts","../components/sort-indicator/index.ts","../components/header/index.tsx","../components/cell-value/index.tsx","../components/utils/inherited-font.ts","../components/utils/theme.ts","../components/utils/column-layout.ts","../components/utils/selection.ts","../components/utils/selection-navigation.ts","../components/utils/clipboard.ts","../components/utils/context-menu.ts","../components/utils/cell-editors.ts","../components/utils/edit-value.ts","../components/web-component.ts"],"sourcesContent":["/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the `TypeError` message for \"Functions\" methods. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n return root.Date.now();\n};\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n result = wait - timeSinceLastCall;\n\n return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\n/**\n * Creates a throttled function that only invokes `func` at most once per\n * every `wait` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `func` invocations and a `flush` method to\n * immediately invoke them. Provide `options` to indicate whether `func`\n * should be invoked on the leading and/or trailing edge of the `wait`\n * timeout. The `func` is invoked with the last arguments provided to the\n * throttled function. Subsequent calls to the throttled function return the\n * result of the last `func` invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the throttled function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.throttle` and `_.debounce`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=true]\n * Specify invoking on the leading edge of the timeout.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // Avoid excessively updating the position while scrolling.\n * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n *\n * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });\n * jQuery(element).on('click', throttled);\n *\n * // Cancel the trailing throttled invocation.\n * jQuery(window).on('popstate', throttled.cancel);\n */\nfunction throttle(func, wait, options) {\n var leading = true,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (isObject(options)) {\n leading = 'leading' in options ? !!options.leading : leading;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n return debounce(func, wait, {\n 'leading': leading,\n 'maxWait': wait,\n 'trailing': trailing\n });\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && objectToString.call(value) == symbolTag);\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = throttle;\n","/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the `TypeError` message for \"Functions\" methods. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n return root.Date.now();\n};\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n result = wait - timeSinceLastCall;\n\n return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && objectToString.call(value) == symbolTag);\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = debounce;\n","import type { Key } from '../types';\n\ninterface Entry<T> {\n key: Key;\n value: T;\n}\n\n/**\n * Insertion-ordered map. Keys are compared as strings (1 and '1' are the same entry),\n * and every operation is O(1) apart from iteration.\n */\nclass Collection<T> {\n private entries = new Map<string, Entry<T>>();\n\n constructor() {\n this.get = this.get.bind(this);\n this.set = this.set.bind(this);\n this.clear = this.clear.bind(this);\n this.forEach = this.forEach.bind(this);\n }\n\n get keys(): Key[] {\n return Array.from(this.entries.values(), entry => entry.key);\n }\n\n get(key: Key): T | undefined {\n return this.entries.get(String(key))?.value;\n }\n\n set(key: Key, value: T) {\n const existing = this.entries.get(String(key));\n if (existing) {\n existing.value = value;\n return;\n }\n this.entries.set(String(key), { key, value });\n }\n\n add(value: T) {\n this.set(this.entries.size, value);\n }\n\n delete(key: Key) {\n this.entries.delete(String(key));\n }\n\n clear(matcher?: (item: T, key: Key) => boolean) {\n if (typeof matcher !== 'function') {\n this.entries.clear();\n return;\n }\n this.entries.forEach(({ key, value }, id) => {\n if (matcher(value, key)) this.entries.delete(id);\n });\n }\n\n forEach(fn: (item: T, key: Key) => void) {\n this.entries.forEach(({ key, value }) => fn(value, key));\n }\n\n get length() {\n return this.entries.size;\n }\n}\n\nexport default Collection;\n","/**\n * Values of one column for all rows, indexed by row slot. Two flat arrays instead of an object per cell.\n * `undefined` means the row has no value in this column.\n */\nclass ColumnStore {\n values: unknown[];\n\n /** Changes whenever a value is set, cleared or moved, so results computed from the values can be reused while it stays the same. */\n version = 0;\n\n /** When each value last changed, 0 when unknown; only allocated once a value changes after loading. */\n private updatedAt: number[] | undefined = undefined;\n\n constructor(length = 0) {\n this.values = new Array(length).fill(undefined);\n }\n\n get(slot: number) {\n return this.values[slot];\n }\n\n getUpdatedAt(slot: number): number | undefined {\n return this.updatedAt?.[slot] || undefined;\n }\n\n set(slot: number, value: unknown, updatedAt?: number) {\n this.version++;\n while (this.values.length < slot) this.values.push(undefined);\n this.values[slot] = value;\n if (updatedAt === undefined && this.updatedAt === undefined) return;\n\n this.updatedAt ??= new Array(this.values.length).fill(0);\n while (this.updatedAt.length < this.values.length) this.updatedAt.push(0);\n this.updatedAt[slot] = updatedAt ?? 0;\n }\n\n /** Empties the given slots, leaving holes; the other slots keep their place. */\n clearSlots(slots: readonly number[]) {\n this.version++;\n slots.forEach(slot => {\n if (slot < this.values.length) this.values[slot] = undefined;\n if (this.updatedAt && slot < this.updatedAt.length) this.updatedAt[slot] = 0;\n });\n }\n\n /** Keeps only the given slots (ascending), renumbering them 0, 1, 2... in that order. */\n compact(slots: ArrayLike<number>) {\n this.version++;\n this.values = Array.from(slots, slot => this.values[slot]);\n const { updatedAt } = this;\n if (updatedAt) this.updatedAt = Array.from(slots, slot => updatedAt[slot] ?? 0);\n }\n}\n\nexport default ColumnStore;\n","import type { Key, RowData, RowId } from '../types';\n\nexport type Row = RowData;\n\n/** Holes below this are not worth a pass over every column. */\nconst MIN_HOLES_TO_COMPACT = 1024;\n\n/**\n * Rows in display order: a dense array with an id lookup and each row's top offset,\n * so appends, lookups and finding the row at a scroll offset never scan every row.\n * Removing rows renumbers the positions after the first removed one (once per call).\n * Rows keep a `slot` into the column stores that does not change when the rows are sorted or others removed;\n * removed rows leave holes, which are closed when they outnumber the rows.\n */\nclass RowStore {\n private items: Row[] = [];\n\n private readonly byId = new Map<string, Row>();\n\n /** `tops[i]` is the offset of row `i` from the top of the first row. */\n private tops: number[] = [];\n\n private end = 0;\n\n /** Slots handed out so far, including holes left by removed rows. */\n private nextSlot = 0;\n\n get length() {\n return this.items.length;\n }\n\n /** Sum of all row heights. */\n get totalHeight() {\n return this.end;\n }\n\n /** Number of slots in use or left as holes; the length the column stores need. */\n get slotCount() {\n return this.nextSlot;\n }\n\n get keys(): RowId[] {\n return this.items.map(row => row.id);\n }\n\n get(id: Key): Row | undefined {\n return this.byId.get(String(id));\n }\n\n at(index: number): Row | undefined {\n return this.items[index];\n }\n\n topOf(index: number) {\n return this.tops[index] ?? this.end;\n }\n\n /** Index of the first row that ends below `offset`; `length` when the offset is past the last row. */\n indexAt(offset: number) {\n if (offset <= 0) return 0;\n if (offset >= this.end) return this.length;\n\n let low = 0;\n let high = this.items.length - 1;\n while (low < high) {\n const middle = Math.ceil((low + high) / 2);\n if (this.tops[middle] <= offset) low = middle;\n else high = middle - 1;\n }\n return low;\n }\n\n /** Appends the row, or replaces the row with the same id in place; returns the stored row. */\n set(row: Omit<Row, 'index' | 'slot'>): Row {\n const key = String(row.id);\n const previous = this.byId.get(key);\n if (previous) {\n const replacement = { id: row.id, height: row.height, index: previous.index, slot: previous.slot };\n this.items[previous.index] = replacement;\n this.byId.set(key, replacement);\n this.reindexFrom(previous.index);\n return replacement;\n }\n\n const index = this.items.length;\n const added = { id: row.id, height: row.height, index, slot: this.nextSlot++ };\n this.items.push(added);\n this.byId.set(key, added);\n this.tops.push(this.end);\n this.end += Math.round(row.height);\n return added;\n }\n\n /** Sets one row's height and moves the rows below it; returns whether anything changed. Costs the rows after it. */\n setHeight(id: Key, height: number) {\n const row = this.get(id);\n if (!row || row.height === height) return false;\n\n row.height = height;\n this.reindexFrom(row.index);\n return true;\n }\n\n /** Sets every row's height in one pass. */\n setHeights(heightOf: (id: RowId) => number) {\n this.items.forEach(row => { row.height = heightOf(row.id); });\n this.reindexFrom(0);\n }\n\n /**\n * Index of the row whose bottom border is within `tolerance` of `offset` (measured like `topOf`), or -1.\n * The border above a row belongs to the row before it; where two are in reach the nearer wins.\n */\n borderAt(offset: number, tolerance: number) {\n if (this.items.length === 0) return -1;\n\n const index = this.indexAt(offset);\n const below = index < this.items.length ? Math.abs(this.topOf(index + 1) - offset) : Infinity;\n const above = index > 0 ? Math.abs(this.topOf(index) - offset) : Infinity;\n if (Math.min(above, below) > tolerance) return -1;\n return above < below ? index - 1 : index;\n }\n\n /**\n * Removes the rows with the given ids, ignoring unknown ones.\n * Returns the slots of the removed rows in ascending order, which the column stores must clear.\n * Other rows keep their slots, so removing costs nothing per column; see `compactSlots`.\n */\n removeMany(ids: Key[]): number[] {\n const removed = new Set<Row>();\n ids.forEach(id => {\n const row = this.get(id);\n if (row) removed.add(row);\n });\n if (removed.size === 0) return [];\n\n removed.forEach(row => this.byId.delete(String(row.id)));\n const indexes = Array.from(removed, row => row.index).sort((a, b) => a - b);\n\n this.closeGaps(indexes);\n this.reindexFrom(indexes[0]);\n return Array.from(removed, row => row.slot).sort((a, b) => a - b);\n }\n\n /**\n * Renumbers the slots densely once more than half of them are holes left by removed rows.\n * Returns the previous slots of the remaining rows in ascending order (the column stores keep exactly those),\n * or undefined when nothing was renumbered. Doing this rarely keeps removal cheap for streams that drop old rows.\n */\n compactSlots(): Int32Array | undefined {\n const holes = this.nextSlot - this.items.length;\n if (holes < MIN_HOLES_TO_COMPACT || holes <= this.items.length) return undefined;\n\n const live = Int32Array.from(this.items, row => row.slot).sort();\n const renumbered = new Int32Array(this.nextSlot);\n live.forEach((slot, rank) => { renumbered[slot] = rank; });\n this.items.forEach(row => { row.slot = renumbered[row.slot]; });\n this.nextSlot = this.items.length;\n return live;\n }\n\n /** Reorders the rows; the sort is stable, so equal rows keep their relative order. */\n sort(compare: (a: Row, b: Row) => number) {\n this.items.sort(compare);\n this.reindexFrom(0);\n }\n\n /**\n * Puts the given rows back in order, assuming every other row is already ordered.\n * `compare` must be a total order (no ties), which a slot tiebreak provides. Costs one comparison pass per\n * moved row (a binary search) plus a copy, instead of sorting every row.\n */\n resort(ids: Iterable<Key>, compare: (a: Row, b: Row) => number) {\n const moving = new Set<Row>();\n for (const id of ids) {\n const row = this.get(id);\n if (row) moving.add(row);\n }\n if (moving.size === 0) return;\n\n const oldIndexes = Array.from(moving, row => row.index).sort((a, b) => a - b);\n this.closeGaps(oldIndexes);\n\n // only the moving rows are compared; the rest is moved around with memmoves, never visited one by one\n const inserts = Array.from(moving).sort(compare);\n const positions = inserts.map(row => this.lowerBound(this.items, row, compare));\n const settledLength = this.items.length;\n inserts.forEach(row => this.items.push(row));\n\n // from the back, so every settled row moves once, past the inserts that end up before it\n const { items } = this;\n let end = settledLength;\n for (let at = inserts.length - 1; at >= 0; at--) {\n for (let from = end - 1; from >= positions[at]; from--) items[from + at + 1] = items[from];\n items[positions[at] + at] = inserts[at];\n end = positions[at];\n }\n\n this.reindexFrom(Math.min(oldIndexes[0], positions[0]));\n }\n\n clear() {\n this.items = [];\n this.byId.clear();\n this.tops = [];\n this.end = 0;\n this.nextSlot = 0;\n }\n\n /** Removes the items at the given ascending indexes in place, moving the others down in runs. */\n private closeGaps(indexes: readonly number[]) {\n const { items } = this;\n let write = indexes[0];\n indexes.forEach((removedIndex, at) => {\n const end = indexes[at + 1] ?? items.length;\n // a plain loop: Array.prototype.copyWithin is much slower than this on arrays of objects\n for (let read = removedIndex + 1; read < end; read++) items[write++] = items[read];\n });\n items.length = write;\n }\n\n /** Index of the first row in `rows` that is not ordered before `row`. */\n private lowerBound(rows: Row[], row: Row, compare: (a: Row, b: Row) => number) {\n let low = 0;\n let high = rows.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (compare(rows[middle], row) < 0) low = middle + 1;\n else high = middle;\n }\n return low;\n }\n\n /** Recomputes positions and offsets from `from` onwards. */\n private reindexFrom(from: number) {\n this.tops.length = this.items.length;\n let top = from === 0 ? 0 : this.tops[from - 1] + Math.round(this.items[from - 1].height);\n for (let index = from; index < this.items.length; index++) {\n const row = this.items[index];\n row.index = index;\n this.tops[index] = top;\n top += Math.round(row.height);\n }\n this.end = top;\n }\n}\n\nexport default RowStore;\n","import type { RowId, RowInput } from '../types';\n\nexport const getNow = () => new Date().valueOf();\n\nexport const getRowId = (row: RowInput, _index?: number): RowId => row.id;\n","import ColumnStore from './column-store';\nimport RowStore from './row-store';\nimport { getNow } from './selectors';\nimport type { Row } from './row-store';\nimport type { Key, RowId, RowInput, SortKey } from '../types';\n\nexport type RowIdGetter = (row: RowInput, index?: number) => RowId;\n\nexport interface DataStoreEnvironment {\n getRowId: RowIdGetter;\n getCellHeight: () => number;\n /** The height a row should have when it differs from `getCellHeight()`, asked once its values are stored. */\n getRowHeight?: (id: RowId) => number | undefined;\n}\n\ninterface PendingChange {\n type: 'update' | 'remove';\n row: RowInput;\n}\n\nconst collator = new Intl.Collator();\n\n/** Fewer changed rows than this fraction of all rows are moved one by one; more are cheaper to sort together. */\nconst INCREMENTAL_SORT_RATIO = 8;\n\nconst typeRank = (value: unknown) => {\n if (value === undefined || value === null) return 3;\n if (typeof value === 'number' || typeof value === 'bigint') return 0;\n return typeof value === 'string' ? 1 : 2;\n};\n\n/** Numbers numerically, then text, then anything else as text; empty values sort last. */\nexport const compareValues = (a: unknown, b: unknown) => {\n const rank = typeRank(a) - typeRank(b);\n if (rank !== 0) return rank;\n if (typeRank(a) === 3) return 0;\n if (typeRank(a) === 0) return Number(a) - Number(b);\n return collator.compare(String(a), String(b));\n};\n\n/**\n * Sort keys for the default ordering of a column, computed once so comparing two rows is two array reads:\n * a type rank, and within it a number (the value, or the position of its text among all the column's texts).\n */\nconst createDefaultKey = (values: readonly unknown[]) => {\n const ranks = new Uint8Array(values.length);\n const keys = new Float64Array(values.length);\n // every distinct text gets an id on the way, so ranks can be looked up by index instead of by text again\n const textIds = new Int32Array(values.length);\n const ids = new Map<string, number>();\n for (let slot = 0; slot < values.length; slot++) {\n const value = values[slot];\n const rank = typeRank(value);\n ranks[slot] = rank;\n if (rank === 0) {\n keys[slot] = Number(value);\n continue;\n }\n if (rank !== 1 && rank !== 2) continue;\n\n const text = String(value);\n let id = ids.get(text);\n if (id === undefined) {\n id = ids.size;\n ids.set(text, id);\n }\n textIds[slot] = id;\n }\n\n // equal texts (as the collator sees them) share a position, so they tie and fall through to the next key\n const positions = new Float64Array(ids.size);\n const sorted = Array.from(ids.keys()).sort(collator.compare);\n let position = 0;\n sorted.forEach((text, index) => {\n if (index > 0 && collator.compare(sorted[index - 1], text) !== 0) position++;\n positions[ids.get(text) ?? 0] = position;\n });\n for (let slot = 0; slot < values.length; slot++) {\n if (ranks[slot] === 1 || ranks[slot] === 2) keys[slot] = positions[textIds[slot]];\n }\n return { ranks, keys };\n};\n\ntype DefaultKey = ReturnType<typeof createDefaultKey>;\n\n/**\n * Cell values stored by column (one array per column, addressed by the row's slot) plus the row order,\n * with the queued add/update/remove handling and the sort model. Independent of the DOM.\n */\nclass DataStore {\n rows = new RowStore();\n columns = new Map<string, ColumnStore>();\n\n /** Queued changes, applied in the order they were made. */\n private pending: PendingChange[] = [];\n private sortModel: readonly SortKey[] = [];\n private sortDirty = false;\n /** Ids of the rows changed since the last sort; only those have to move when few changed. */\n private sortChanged = new Set<string>();\n /** Sort keys per column, reused until the column's values change (e.g. when only the direction flips). */\n private defaultKeys = new WeakMap<ColumnStore, { version: number; key: DefaultKey }>();\n\n private environment: DataStoreEnvironment;\n\n constructor(environment: DataStoreEnvironment) {\n this.environment = environment;\n }\n\n get hasPending() {\n return this.pending.length > 0;\n }\n\n getSortModel() {\n return this.sortModel;\n }\n\n /** Orders the rows by the given columns, in priority order; an empty model restores the insertion order. */\n setSortModel(model: readonly SortKey[]) {\n this.sortModel = [...model];\n this.sort();\n }\n\n /** Value of a cell, `undefined` when the row has none. */\n getValue(rowId: RowId, columnKey: Key) {\n const row = this.rows.get(rowId);\n return row ? this.columns.get(String(columnKey))?.get(row.slot) : undefined;\n }\n\n getUpdatedAt(rowId: RowId, columnKey: Key) {\n const row = this.rows.get(rowId);\n return row ? this.columns.get(String(columnKey))?.getUpdatedAt(row.slot) : undefined;\n }\n\n /**\n * Writes one cell right away, skipping the queue, and re-sorts when it is the sort key.\n * Returns whether rows changed position; false too when the row does not exist.\n */\n setValue(rowId: RowId, columnKey: Key, value: unknown, now = getNow()) {\n const row = this.rows.get(rowId);\n if (!row) return false;\n\n this.applyValue(rowId, row.slot, String(columnKey), value, now);\n if (!this.sortDirty) return false;\n\n this.sortChanges();\n return true;\n }\n\n queueUpdate(row: RowInput) {\n this.pending.push({ type: 'update', row });\n }\n\n queueRemove(row: RowInput) {\n this.pending.push({ type: 'remove', row });\n }\n\n clear() {\n this.rows.clear();\n this.columns.clear();\n }\n\n /** Replaces everything, dropping any queued changes. */\n setRows(data: RowInput[]) {\n this.pending = [];\n this.clear();\n this.sortChanged.clear();\n // size the columns of the first row up front instead of growing them one value at a time\n Object.keys(data[0] ?? {}).forEach(key => this.columns.set(key, new ColumnStore(data.length)));\n data.forEach((row, index) => this.addRow(this.environment.getRowId(row, index), row, undefined));\n // rows were added in insertion order, which is the order without a sort model\n if (this.sortModel.length > 0) this.sort();\n }\n\n /**\n * Applies the queued changes in the order they were queued; consecutive removals are applied together.\n * Returns whether rows changed position (removed or re-sorted), which needs the whole grid to be redrawn.\n */\n flush(now = getNow()) {\n const changes = this.pending;\n this.pending = [];\n const removals: Key[] = [];\n let moved = false;\n const applyRemovals = () => {\n moved = this.removeRows(removals) || moved;\n removals.length = 0;\n };\n\n changes.forEach(({ type, row }) => {\n if (type === 'remove') {\n removals.push(this.environment.getRowId(row));\n return;\n }\n applyRemovals();\n this.applyUpdate(row, now);\n });\n applyRemovals();\n\n if (!this.sortDirty) return moved;\n this.sortChanges();\n return true;\n }\n\n private column(key: string) {\n let column = this.columns.get(key);\n if (!column) {\n column = new ColumnStore(this.rows.slotCount);\n this.columns.set(key, column);\n }\n return column;\n }\n\n private addRow(id: RowId, row: RowInput, updatedAt: number | undefined) {\n const { slot } = this.rows.set({ id, height: this.environment.getCellHeight() });\n const keys = Object.keys(row);\n for (const key of keys) this.column(key).set(slot, row[key], updatedAt);\n this.markSortDirty(id, keys);\n const height = this.environment.getRowHeight?.(id);\n if (height !== undefined) this.rows.setHeight(id, height);\n }\n\n private removeRows(ids: Key[]) {\n if (ids.length === 0) return false;\n\n const slots = this.rows.removeMany(ids);\n this.columns.forEach(column => column.clearSlots(slots));\n const kept = this.rows.compactSlots();\n if (kept) this.columns.forEach(column => column.compact(kept));\n return slots.length > 0;\n }\n\n private applyUpdate(row: RowInput, now: number) {\n const rowId = this.environment.getRowId(row);\n const rowData = this.rows.get(rowId);\n if (!rowData) {\n this.addRow(rowId, row, now);\n return;\n }\n Object.keys(row).forEach(key => this.applyValue(rowData.id, rowData.slot, key, row[key], now));\n }\n\n private applyValue(rowId: RowId, slot: number, key: string, value: unknown, now: number) {\n const column = this.column(key);\n const previous = column.get(slot);\n if (previous === value) return;\n // a value appearing in a column the row did not have yet is not an update worth flashing\n column.set(slot, value, previous === undefined ? undefined : now);\n this.markSortDirty(rowId, [key]);\n }\n\n private markSortDirty(rowId: RowId, keys: string[]) {\n if (!this.sortModel.some(({ columnId }) => keys.includes(String(columnId)))) return;\n this.sortDirty = true;\n this.sortChanged.add(String(rowId));\n }\n\n private defaultKeyOf(column: ColumnStore) {\n const cached = this.defaultKeys.get(column);\n if (cached && cached.version === column.version) return cached.key;\n\n const key = createDefaultKey(column.values);\n this.defaultKeys.set(column, { version: column.version, key });\n return key;\n }\n\n /** Orders two rows by the sort model, ties by slot so the order is total. */\n private createComparator(precompute: boolean) {\n const [only, ...rest] = this.sortModel;\n const onlyColumn = only && !only.compare && precompute && rest.length === 0 ? this.columns.get(String(only.columnId)) : undefined;\n if (onlyColumn) {\n // the common case, a single default-ordered column, without the per-key loop and calls\n const { ranks, keys } = this.defaultKeyOf(onlyColumn);\n const sign = only.direction === 'desc' ? -1 : 1;\n return (a: Row, b: Row) => {\n const order = ranks[a.slot] - ranks[b.slot] || keys[a.slot] - keys[b.slot] || 0;\n return order === 0 ? a.slot - b.slot : order * sign;\n };\n }\n\n const keys = this.sortModel.map(({ columnId, direction = 'asc', compare }) => {\n const column = this.columns.get(String(columnId));\n const values = column?.values;\n const sign = direction === 'desc' ? -1 : 1;\n if (!column || !values) return { order: () => 0, sign };\n if (compare) return { order: (a: Row, b: Row) => compare(values[a.slot], values[b.slot]), sign };\n if (!precompute) return { order: (a: Row, b: Row) => compareValues(values[a.slot], values[b.slot]), sign };\n\n const { ranks, keys: sortKeys } = this.defaultKeyOf(column);\n return {\n order: (a: Row, b: Row) => ranks[a.slot] - ranks[b.slot] || sortKeys[a.slot] - sortKeys[b.slot] || 0,\n sign,\n };\n });\n\n return (a: Row, b: Row) => {\n for (const { order, sign } of keys) {\n const result = order(a, b);\n if (result !== 0) return result * sign;\n }\n return a.slot - b.slot;\n };\n }\n\n private sort() {\n this.sortDirty = false;\n this.sortChanged.clear();\n this.rows.sort(this.createComparator(true));\n }\n\n /** Re-sorts after a flush: moves only the changed rows when they are few, otherwise sorts everything. */\n private sortChanges() {\n const changed = this.sortChanged;\n if (changed.size * INCREMENTAL_SORT_RATIO >= this.rows.length) {\n this.sort();\n return;\n }\n\n this.sortDirty = false;\n this.sortChanged = new Set();\n this.rows.resort(changed, this.createComparator(false));\n }\n}\n\nexport default DataStore;\n","/** Size-bounded map that evicts the least recently used entry first. */\nclass LruCache<T> {\n private readonly entries = new Map<string, T>();\n\n private readonly limit: number;\n\n constructor(limit: number) {\n this.limit = limit;\n }\n\n get(key: string): T | undefined {\n const value = this.entries.get(key);\n if (value === undefined) return undefined;\n // re-insert so iteration order tracks recency\n this.entries.delete(key);\n this.entries.set(key, value);\n return value;\n }\n\n set(key: string, value: T) {\n this.entries.delete(key);\n this.entries.set(key, value);\n const [oldest] = this.entries.keys();\n if (this.entries.size > this.limit && oldest !== undefined) this.entries.delete(oldest);\n }\n\n clear() {\n this.entries.clear();\n }\n\n get size() {\n return this.entries.size;\n }\n}\n\nexport default LruCache;\n","/**\n * Minimal declarative layer over the canvas 2D API.\n *\n * `<Group>` and friends do not draw when evaluated. They build a light tree of nodes, and calling\n * `node.draw(ctx, x, y)` paints it, with `(x, y)` as the origin that child positions are relative to.\n * Nothing is rasterized to an intermediate canvas unless a component opts into bitmap caching.\n */\nexport interface VNode {\n draw(ctx: CanvasRenderingContext2D, x: number, y: number): void;\n}\n\n/** `false`, `null` and `undefined` are skipped, so `{condition && <Rect />}` works. */\nexport type Child = VNode | false | null | undefined;\n\nexport type Children = Child | readonly Child[];\n\nexport interface ChildrenProps {\n /** A single child, an array of them, or the mix of both that JSX produces for several children. */\n children?: Children | readonly Children[];\n}\n\nexport type Component<Props extends object> = (props: Props) => VNode;\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n type Element = VNode;\n interface ElementChildrenAttribute {\n children: unknown;\n }\n interface IntrinsicElements {}\n }\n}\n\nconst isNode = (child: Child): child is VNode => !!child;\n\n/** Wraps a paint function into a leaf component; positions in `props` are relative to the draw origin. */\nexport const primitive = <Props extends object>(\n paint: (ctx: CanvasRenderingContext2D, props: Props, x: number, y: number) => void,\n): Component<Props> => props => ({\n draw: (ctx, x, y) => paint(ctx, props, x, y),\n});\n\nexport interface GroupProps extends ChildrenProps {\n x?: number;\n y?: number;\n}\n\n/** Draws its children relative to its own offset. */\nexport const Group: Component<GroupProps> = ({ x = 0, y = 0, children }) => ({\n draw: (ctx, originX, originY) => [children]\n .flat(2)\n .filter(isNode)\n .forEach(child => child.draw(ctx, originX + x, originY + y)),\n});\n\nconst React = {\n createElement<Props extends object>(\n component: Component<Props & ChildrenProps>,\n props: Props | null,\n ...children: Children[]\n ): VNode {\n return component(Object.assign({}, props, { children }));\n },\n};\n\nexport default React;\n","import LruCache from './lru-cache';\nimport { primitive } from './jsx';\nimport type { RenderProps } from '../types';\n\nabstract class Renderer<Options extends object> {\n readonly options: Options;\n\n protected constructor(options: Options) {\n this.options = { ...options };\n }\n\n /** Applies the given options and notifies `optionsUpdated` with the previous ones. */\n update(options: Partial<Options>) {\n const previous = { ...this.options };\n Object.assign(this.options, options);\n this.optionsUpdated(previous);\n }\n\n optionsUpdated(_previous: Options) {}\n\n clearCache() {}\n}\n\n/**\n * Renderer producing a bitmap from props; usable as a JSX tag through `element`.\n * Bitmaps are reused through a bounded LRU cache whenever `cacheKey` returns a key.\n */\nexport abstract class CanvasRenderer<Options extends object> extends Renderer<Options> {\n private readonly bitmaps = new LruCache<HTMLCanvasElement>(4096);\n\n abstract render(props: RenderProps): HTMLCanvasElement;\n\n /** Props with the same key must render the same pixels. Undefined disables caching. */\n protected cacheKey(_props: RenderProps): string | undefined {\n return undefined;\n }\n\n /** Device pixels per CSS pixel of the layer being drawn to; bitmaps are rendered at this scale to stay sharp. */\n pixelRatio = 1;\n\n clearCache() {\n this.bitmaps.clear();\n }\n\n paint(ctx: CanvasRenderingContext2D, props: RenderProps, x: number, y: number) {\n const key = this.cacheKey(props);\n const bitmap = (key === undefined ? undefined : this.bitmaps.get(key)) ?? this.renderBitmap(props, key);\n if (bitmap.width <= 0 || bitmap.height <= 0) return;\n ctx.drawImage(bitmap, x + (props.x ?? 0), y + (props.y ?? 0), bitmap.width / this.pixelRatio, bitmap.height / this.pixelRatio);\n }\n\n readonly element = primitive<RenderProps>((ctx, props, x, y) => this.paint(ctx, props, x, y));\n\n private renderBitmap(props: RenderProps, key: string | undefined) {\n const canvas = this.render(props);\n if (key === undefined || canvas.width <= 0 || canvas.height <= 0) return canvas;\n\n const bitmap = document.createElement('canvas');\n bitmap.width = canvas.width;\n bitmap.height = canvas.height;\n bitmap.getContext('2d')?.drawImage(canvas, 0, 0);\n this.bitmaps.set(key, bitmap);\n return bitmap;\n }\n}\n\nexport default Renderer;\n","export const getContext2d = (canvas: HTMLCanvasElement, options?: CanvasRenderingContext2DSettings) => {\n const ctx = canvas.getContext('2d', options);\n if (!ctx) throw new Error('2D canvas context is not available');\n return ctx;\n};\n","import Renderer from './renderer';\nimport { getContext2d } from './canvas';\n\ninterface LoadingOptions {\n ctx: CanvasRenderingContext2D;\n}\n\nclass Loading extends Renderer<LoadingOptions> {\n private readonly ctx: CanvasRenderingContext2D;\n\n private readonly offCanvas = document.createElement('canvas');\n\n private readonly offCtx: CanvasRenderingContext2D;\n\n private rotation = 270 * (Math.PI / 180);\n\n private readonly speed = 6;\n\n private readonly count = 75;\n\n constructor(options: LoadingOptions) {\n super(options);\n\n this.ctx = this.options.ctx;\n\n this.offCanvas.width = 250;\n this.offCanvas.height = 250;\n this.offCtx = getContext2d(this.offCanvas);\n this.offCtx.lineWidth = 0.5;\n this.setColor('rgba(255, 255, 255, 0.75)');\n }\n\n /** The colour the loader is drawn in; it takes a moment to fully replace the old one. */\n setColor(color: string) {\n this.offCtx.strokeStyle = color;\n }\n\n updateLoader() {\n this.rotation += this.speed / 100;\n }\n\n renderLoader() {\n this.offCtx.save();\n this.offCtx.globalCompositeOperation = 'source-over';\n this.offCtx.translate(125, 125);\n this.offCtx.rotate(this.rotation);\n let i = this.count;\n while (i--) {\n this.offCtx.beginPath();\n this.offCtx.arc(0, 0, i + (Math.random() * 35), Math.random(), Math.PI / 3 + (Math.random() / 12), false);\n this.offCtx.stroke();\n }\n this.offCtx.restore();\n }\n\n render() {\n this.offCtx.globalCompositeOperation = 'destination-out';\n this.offCtx.fillStyle = 'rgba(255, 255, 255, 0.03)';\n this.offCtx.fillRect(0, 0, 250, 250);\n this.updateLoader();\n this.renderLoader();\n\n const x = Math.round((this.ctx.canvas.width - this.offCanvas.width) / 2);\n const y = Math.round((this.ctx.canvas.height - this.offCanvas.height) / 2);\n this.ctx.clearRect(x, y, 250, 250);\n this.ctx.drawImage(this.offCanvas, x, y);\n\n return this.offCanvas;\n }\n}\n\nexport default Loading;\n","import { getContext2d } from './canvas';\n\nexport interface LayerOptions {\n /** Transparent canvas. Opaque layers (`false`) draw faster; keep the bottom layer opaque. */\n alpha?: boolean;\n /** Lets the browser present frames without syncing to the compositor: lower latency, but may tear. Off by default. */\n desynchronized?: boolean;\n /** Name of an existing layer to stack this one below; defaults to the top. */\n before?: string;\n}\n\n/** A named canvas stacked in the grid; renderers draw into its context. */\nclass Layer {\n readonly name: string;\n\n readonly canvas = document.createElement('canvas');\n\n readonly ctx: CanvasRenderingContext2D;\n\n constructor(name: string, { alpha = true, desynchronized = false }: Pick<LayerOptions, 'alpha' | 'desynchronized'> = {}) {\n this.name = name;\n this.canvas.className = `drawingLayer ${name}`;\n this.ctx = getContext2d(this.canvas, { alpha, desynchronized });\n }\n\n /** Size in CSS pixels; the backing store is `pixelRatio` times larger. */\n width = 0;\n\n height = 0;\n\n pixelRatio = 1;\n\n /**\n * Resizes the canvas, scaling the context so renderers keep drawing in CSS pixels.\n * Returns false, leaving the canvas untouched, when nothing changed (assigning a size clears the canvas).\n */\n resize(width: number, height: number, pixelRatio = 1) {\n if (width === this.width && height === this.height && pixelRatio === this.pixelRatio) return false;\n\n this.width = width;\n this.height = height;\n this.pixelRatio = pixelRatio;\n this.canvas.width = Math.round(width * pixelRatio);\n this.canvas.height = Math.round(height * pixelRatio);\n this.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);\n return true;\n }\n\n clear() {\n this.ctx.clearRect(0, 0, this.width, this.height);\n }\n}\n\nexport default Layer;\n","import type { CellRenderer, RendererRef } from '../types';\n\n/** Named renderers; columns refer to them by name or hand over a renderer directly. */\nclass RendererRegistry {\n private readonly renderers = new Map<string, CellRenderer>();\n\n private readonly warned = new Set<string>();\n\n register(name: string, renderer: CellRenderer) {\n this.renderers.set(name, renderer);\n this.warned.delete(name);\n }\n\n unregister(name: string) {\n this.renderers.delete(name);\n }\n\n get(name: string) {\n return this.renderers.get(name);\n }\n\n /** Resolves a reference without allocating; unknown names are reported once and yield undefined. */\n resolve(ref: RendererRef): CellRenderer | undefined {\n if (typeof ref !== 'string') return ref;\n\n const renderer = this.renderers.get(ref);\n if (!renderer && !this.warned.has(ref)) {\n this.warned.add(ref);\n console.warn(`canvas-grid: no renderer registered as \"${ref}\"`);\n }\n return renderer;\n }\n\n clearCaches() {\n this.renderers.forEach(renderer => renderer.clearCache?.());\n }\n}\n\nexport default RendererRegistry;\n","import { primitive } from '../utils/jsx';\n\nexport interface RectProps {\n x?: number;\n y?: number;\n width: number;\n height: number;\n color: string;\n /** Opacity from 0 to 1, applied on top of the color. */\n alpha?: number;\n}\n\n/** Solid rectangle, filled straight onto the target context. */\nconst Rect = primitive<RectProps>((ctx, { x = 0, y = 0, width, height, color, alpha = 1 }, originX, originY) => {\n const w = Math.trunc(width);\n const h = Math.trunc(height);\n if (!color || w <= 0 || h <= 0 || alpha <= 0) return;\n\n ctx.fillStyle = color;\n if (alpha >= 1) {\n ctx.fillRect(originX + x, originY + y, w, h);\n return;\n }\n ctx.globalAlpha = alpha;\n ctx.fillRect(originX + x, originY + y, w, h);\n ctx.globalAlpha = 1;\n});\n\nexport default Rect;\n","import React, { Group } from '../utils/jsx';\nimport Renderer from '../utils/renderer';\nimport Rect from '../rectangle';\nimport type { CellContext, CellRenderer } from '../types';\n\nexport interface CellBackgroundOptions {\n layer: string;\n enableFlashing: boolean;\n background: string;\n flashInDuration: number;\n flashOutDuration: number;\n flashColor: string;\n /** Laid over odd rows. */\n zebraColor: string;\n /** Laid over the hovered row, faded in and out. */\n hoverColor: string;\n borderRightWidth: number;\n borderRightColor: string;\n borderBottomWidth: number;\n borderBottomColor: string;\n}\n\n/** How long the hover highlight takes to fade in or out, in ms. */\nconst HOVER_DURATION = 120;\n\ninterface HoverFade {\n from: number;\n to: number;\n start: number;\n}\n/** Opacity of the flash that replaces the fade for people who prefer reduced motion. */\nconst REDUCED_MOTION_ALPHA = 0.5;\n\nconst reducedMotionQuery = typeof window !== 'undefined' && typeof window.matchMedia === 'function'\n ? window.matchMedia('(prefers-reduced-motion: reduce)')\n : undefined;\n\nconst smoothstep = (t: number) => t * t * (3 - 2 * t);\n\nclass CellBackground extends Renderer<CellBackgroundOptions> implements CellRenderer {\n static readonly defaultOptions: CellBackgroundOptions = {\n layer: 'background',\n enableFlashing: true,\n background: '#333',\n flashInDuration: 200,\n flashOutDuration: 400,\n flashColor: 'rgb(214, 144, 13)',\n zebraColor: 'rgba(255, 255, 255, 0.025)',\n hoverColor: 'rgba(255, 255, 255, 0.06)',\n borderRightWidth: 0,\n borderRightColor: '#fff',\n borderBottomWidth: 0,\n borderBottomColor: '#fff',\n };\n\n constructor(options: Partial<CellBackgroundOptions> = {}) {\n super({ ...CellBackground.defaultOptions, ...options });\n }\n\n /** Index of the row under the pointer, set by the grid through `hover`. */\n hoveredRowIndex: number | undefined = undefined;\n\n /** Rows whose highlight is fading in or out, or fully on. */\n private readonly hoverFades = new Map<number, HoverFade>();\n\n private get hoverDuration() {\n return reducedMotionQuery?.matches ? 0 : HOVER_DURATION;\n }\n\n /** Moves the highlight to the given row (or none); the rows involved fade from where they are. */\n hover(index: number | undefined, now = Date.now()) {\n if (index === this.hoveredRowIndex) return;\n\n if (this.hoveredRowIndex !== undefined) this.startFade(this.hoveredRowIndex, 0, now);\n if (index !== undefined) this.startFade(index, 1, now);\n this.hoveredRowIndex = index;\n }\n\n private startFade(row: number, to: number, now: number) {\n this.hoverFades.set(row, { from: this.getHoverFraction(row, now), to, start: now });\n }\n\n /** How much of the highlight a row shows, from 0 to 1; finished fade-outs are forgotten. */\n private getHoverFraction(row: number, now: number) {\n const fade = this.hoverFades.get(row);\n if (!fade) return 0;\n\n const duration = this.hoverDuration;\n const progress = duration <= 0 ? 1 : Math.min(1, Math.max(0, (now - fade.start) / duration));\n if (progress >= 1 && fade.to === 0) this.hoverFades.delete(row);\n const eased = 1 - (1 - progress) * (1 - progress);\n return fade.from + (fade.to - fade.from) * eased;\n }\n\n get layer() {\n return this.options.layer;\n }\n\n /** Cells flash after their value changed, until the flash has faded out. */\n isAnimating({ age, row, now }: Readonly<CellContext>) {\n const fade = row === undefined ? undefined : this.hoverFades.get(row.index);\n if (fade && now - fade.start < this.hoverDuration) return true;\n return this.options.enableFlashing && age <= this.options.flashInDuration + this.options.flashOutDuration;\n }\n\n /** Flash opacity for a cell updated `age` ms ago: eases in, eases out, then 0. A steady highlight with reduced motion. */\n private getFlashAlpha(age: number) {\n if (!this.options.enableFlashing) return 0;\n\n const { flashInDuration, flashOutDuration } = this.options;\n if (age > flashInDuration + flashOutDuration) return 0;\n if (reducedMotionQuery?.matches) return REDUCED_MOTION_ALPHA;\n\n const remaining = Math.max(0, (flashInDuration + flashOutDuration - age) / flashOutDuration);\n const alpha = age < flashInDuration ? smoothstep(age / flashInDuration) : remaining * remaining;\n return Math.round(alpha * 1000) / 1000;\n }\n\n draw({ ctx, x, y, width, height, age, row, now }: Readonly<CellContext>) {\n const { background, flashColor, zebraColor, hoverColor, borderRightWidth, borderRightColor, borderBottomWidth, borderBottomColor } = this.options;\n const flash = this.getFlashAlpha(age);\n const hover = row === undefined ? 0 : this.getHoverFraction(row.index, now);\n\n (\n <Group>\n <Rect width={width} height={height} color={background} />\n {row !== undefined && row.index % 2 === 1 && <Rect width={width} height={height} color={zebraColor} />}\n {hover > 0 && <Rect width={width} height={height} color={hoverColor} alpha={hover} />}\n {flash > 0 && <Rect width={width} height={height} color={flashColor} alpha={flash} />}\n {borderRightWidth > 0 && <Rect x={width - borderRightWidth} width={borderRightWidth} height={height} color={borderRightColor} />}\n {borderBottomWidth > 0 && <Rect y={height - borderBottomWidth} width={width} height={borderBottomWidth} color={borderBottomColor} />}\n </Group>\n ).draw(ctx, x, y);\n }\n}\n\nexport default CellBackground;\n","/**\n * Characters that join with their neighbours into one visible glyph: any combining mark (accents, Indic vowel signs and\n * viramas, Thai marks), the conjoining Hangul jamo, the zero width (non-)joiner and everything outside the BMP, which\n * is a surrogate pair in UTF-16 (most emoji). Text with any is measured per grapheme, not per UTF-16 unit.\n */\nconst joiningCharacters = /[\\p{M}ᄀ-ᇿꥠ-ힰ-\\u{10000}-\\u{10ffff}]/u;\n\n/** From here on come combining marks, Hebrew, Arabic, the other scripts that shape or join, CJK and emoji. */\nconst FIRST_COMPLEX_CODE = 0x300;\n\nconst segmenter = new Intl.Segmenter();\n\nconst toGraphemes = (text: string) => Array.from(segmenter.segment(text), ({ segment }) => segment);\n\nconst toUnits = (text: string) => (joiningCharacters.test(text) ? toGraphemes(text) : text);\n\nconst hasComplexCharacters = (text: string) => {\n for (let i = 0; i < text.length; i++) {\n if (text.charCodeAt(i) >= FIRST_COMPLEX_CODE) return true;\n }\n return false;\n};\n\n/** How many leading units fit with room left for the ellipsis: all of them when everything fits, -1 when nothing does. */\nconst countFitting = (units: ArrayLike<string>, available: number, ellipsis: string, widthOf: (unit: string) => number) => {\n let used = 0;\n let end = 0;\n while (end < units.length) {\n const width = widthOf(units[end]);\n if (used + width > available) break;\n used += width;\n end++;\n }\n if (end === units.length) return end;\n\n // the ellipsis needs room too: give up units until it fits\n const ellipsisWidth = widthOf(ellipsis);\n while (end > 0 && used + ellipsisWidth > available) {\n end--;\n used -= widthOf(units[end]);\n }\n return used + ellipsisWidth > available ? -1 : end;\n};\n\nconst sumWidths = (units: ArrayLike<string>, widthOf: (unit: string) => number) => {\n let total = 0;\n for (let i = 0; i < units.length; i++) total += widthOf(units[i]);\n return total;\n};\n\n/** The text that was cut to `available` pixels, remembered per text so a cell that is drawn again costs one lookup. */\nexport interface FittedText {\n available: number;\n text: string;\n}\n\nexport type FitCache = Map<string, FittedText>;\n\nconst MAX_CACHED_TEXTS = 4096;\n\nconst remember = (cache: FitCache | undefined, text: string, available: number, fitted: string) => {\n if (!cache) return fitted;\n\n const entry = cache.get(text);\n if (entry) {\n entry.available = available;\n entry.text = fitted;\n return fitted;\n }\n if (cache.size >= MAX_CACHED_TEXTS) cache.clear();\n cache.set(text, { available, text: fitted });\n return fitted;\n};\n\nexport interface ExactFit {\n /** Width of a string as the browser lays it out, with kerning, ligatures and joined scripts. */\n measure: (text: string) => number;\n /** Cuts already made, so a text that is drawn again is not measured again. */\n cache?: FitCache;\n /** The character widths add up to the real width, as for a monospace font: Latin text then needs no measuring. */\n sumIsExact: boolean;\n /**\n * How much wider (negative: narrower) two neighbouring characters are laid out than their own widths add up to:\n * kerning and ligatures. With it, simple Latin text is cut by arithmetic instead of by measuring.\n */\n kerning?: (left: string, right: string) => number;\n}\n\n/** Cuts the units to fit using real measurements: the character sum is only an estimate where to cut. */\nconst fitExactly = (text: string, available: number, ellipsis: string, widthOf: (unit: string) => number, exact: ExactFit) => {\n const { measure, cache } = exact;\n const cached = cache?.get(text);\n if (cached?.available === available) return cached.text;\n\n const units = toUnits(text);\n if (countFitting(units, available, ellipsis, widthOf) === units.length) return text;\n\n const whole = measure(text);\n if (whole <= available) return remember(cache, text, available, text);\n\n // estimate where to cut by scaling the widths to the measured total, then correct it against real measurements\n const scale = whole / sumWidths(units, widthOf);\n let keep = countFitting(units, available, ellipsis, unit => widthOf(unit) * scale);\n const prefix = (count: number) => (typeof units === 'string' ? units.slice(0, count) : units.slice(0, count).join(''));\n while (keep > 0 && measure(prefix(keep) + ellipsis) > available) keep--;\n return remember(cache, text, available, keep < 0 || (keep === 0 && measure(ellipsis) > available) ? '' : prefix(keep) + ellipsis);\n};\n\n/**\n * Cuts text of simple characters with the character widths corrected by the kerning of each pair, which is how the\n * browser lays out Latin text apart from rare effects over three or more letters. Measures nothing once the pairs are known.\n */\nconst fitKerned = (\n text: string,\n available: number,\n ellipsis: string,\n widthOf: (character: string) => number,\n kerning: (left: string, right: string) => number,\n) => {\n const ellipsisWidth = widthOf(ellipsis);\n const ellipsisHead = ellipsis.charAt(0);\n let used = 0;\n let keep = 0;\n while (keep < text.length) {\n const next = used + widthOf(text.charAt(keep)) + (keep === 0 ? 0 : kerning(text.charAt(keep - 1), text.charAt(keep)));\n if (next > available) break;\n used = next;\n keep++;\n }\n if (keep === text.length) return text;\n\n // `used` is the width of the first `keep` characters; the ellipsis needs room too\n while (keep > 0 && used + kerning(text.charAt(keep - 1), ellipsisHead) + ellipsisWidth > available) {\n keep--;\n used -= widthOf(text.charAt(keep)) + (keep === 0 ? 0 : kerning(text.charAt(keep - 1), text.charAt(keep)));\n }\n return keep > 0 || ellipsisWidth <= available ? text.slice(0, keep) + ellipsis : '';\n};\n\n/**\n * Cuts `text` to fit `available` pixels, ending in `ellipsis` when something was cut.\n * `widthOf` gives the width of one character, and the text width is the sum of those: cheap, and exact for a\n * monospace font. That is all that runs for text that fits, which is nearly every cell. A cell that does not fit\n * is measured again with `exact.measure` when the sum cannot be trusted, which is for proportional fonts (kerning\n * makes the sum overshoot) and for text with joined scripts such as Arabic (it overshoots by 40%).\n * Characters that form one glyph (emoji, letters with combining accents) are kept or cut together.\n */\nconst fitText = (\n text: string,\n available: number,\n ellipsis: string,\n widthOf: (character: string) => number,\n exact: ExactFit = { measure: value => sumWidths(toUnits(value), widthOf), sumIsExact: true },\n) => {\n const keep = countFitting(text, available, ellipsis, widthOf);\n if (keep === text.length) return text;\n if (exact.sumIsExact && !hasComplexCharacters(text)) return keep < 0 ? '' : text.slice(0, keep) + ellipsis;\n\n if (exact.kerning && !hasComplexCharacters(text)) return fitKerned(text, available, ellipsis, widthOf, exact.kerning);\n return fitExactly(text, available, ellipsis, widthOf, exact);\n};\n\nexport default fitText;\n","import Renderer from '../utils/renderer';\nimport { primitive } from '../utils/jsx';\nimport fitText from '../utils/fit-text';\nimport type { ExactFit, FitCache } from '../utils/fit-text';\nimport { getContext2d } from '../utils/canvas';\nimport type { RenderProps } from '../types';\n\nexport interface TextStyle {\n /** Canvas `textRendering`: trade speed for legibility or exact geometry. Browser default is `'auto'`. */\n textRendering: CanvasTextRendering;\n /** Canvas `fontKerning`. Browser default is `'auto'`. */\n fontKerning: CanvasFontKerning;\n /** Extra space after each character, a CSS length such as `'0.5px'`. */\n letterSpacing: string;\n /**\n * `'ltr'` and `'rtl'` set the direction of every cell; `'auto'` picks it per cell from the first letter,\n * so mixed data works. Right-to-left text is aligned to the right of the cell.\n */\n direction: 'ltr' | 'rtl' | 'auto';\n /**\n * What happens to text wider than its cell. `'clip'` cuts it off at the cell edge, which needs no measuring.\n * `'ellipsis'` shortens it and ends it with the ellipsis, which means measuring the text.\n */\n textOverflow: 'clip' | 'ellipsis';\n}\n\nexport interface TextOptions extends TextStyle {\n ellipsis: string;\n cellPadding: {\n top: number;\n right: number;\n bottom: number;\n left: number;\n };\n font: string;\n color: string;\n isEllipsisRight: boolean;\n}\n\nexport const defaultTextStyle: Readonly<TextStyle> = {\n textRendering: 'auto',\n fontKerning: 'auto',\n letterSpacing: '0px',\n direction: 'ltr',\n textOverflow: 'clip',\n};\n\n/** What is measured for one font: character widths, the cuts already made and whether widths add up exactly. */\ninterface FontMeasures {\n font: string;\n widths: Map<string, number>;\n /** Kerning of the character pairs seen, by the two character codes. */\n pairs: Map<number, number>;\n fitted: FitCache;\n probed: boolean;\n widthOf: (character: string) => number;\n exactFit: ExactFit;\n}\n\n/** From here on come combining marks, Hebrew, Arabic, the other scripts that shape or join, CJK and emoji. */\nconst FIRST_COMPLEX_CHARACTER = 0x300;\n\n/** First letter of a right-to-left script (Hebrew, Arabic, Syriac, Thaana, N'Ko and their presentation forms). */\nconst rightToLeftLetter = /^[^\\p{L}]*(?=[-ࣿיִ-﷿ﹰ-ﻼ])\\p{L}/u;\n\nclass TextRenderer extends Renderer<TextOptions> {\n static readonly defaultOptions: TextOptions = {\n ...defaultTextStyle,\n ellipsis: '…',\n cellPadding: {\n top: 3,\n right: 3,\n bottom: 3,\n left: 3,\n },\n font: '12px sans-serif',\n color: '#fff',\n isEllipsisRight: true,\n };\n\n /** Measurements per font, so columns with their own font do not mix up widths. Cleared when anything affecting widths changes. */\n private readonly fonts = new Map<string, FontMeasures>();\n\n private readonly measureContext = getContext2d(document.createElement('canvas'));\n\n private measuredState = '';\n\n /** Set once a style option differs from the default, so grids that never touch them set nothing extra per cell. */\n private styled = false;\n\n constructor(options: Partial<TextOptions> = {}) {\n super({ ...TextRenderer.defaultOptions, ...options });\n this.styled = this.differsFromDefault();\n }\n\n private differsFromDefault() {\n // the overflow mode is not a canvas state, so it does not make the renderer set any per cell\n return (Object.keys(defaultTextStyle) as Array<keyof TextStyle>).some(key => key !== 'textOverflow' && this.options[key] !== defaultTextStyle[key]);\n }\n\n set font(font: string) {\n if (this.options.font !== font) {\n this.options.font = font;\n this.clearCache();\n }\n }\n\n get font() {\n return this.options.font;\n }\n\n set color(color: string) {\n this.options.color = color;\n }\n\n get color() {\n return this.options.color;\n }\n\n /** Changes the text style; widths are measured again when something changed. */\n setStyle(style: Partial<TextStyle>) {\n if (!(Object.keys(style) as Array<keyof TextStyle>).some(key => style[key] !== this.options[key])) return;\n\n this.update(style);\n this.styled = this.styled || this.differsFromDefault();\n this.clearCache();\n }\n\n /** Text is drawn straight into the layer, whose transform already scales it to the device pixel ratio. */\n pixelRatio = 1;\n\n clearCache() {\n this.fonts.clear();\n this.lastMeasures = undefined;\n this.measuredState = '';\n }\n\n /** The measurements of a font, created on first use. */\n private measuresOf(font: string) {\n const known = this.fonts.get(font);\n if (known) return known;\n\n const fitted: FitCache = new Map();\n const measures: FontMeasures = {\n font,\n widths: new Map(),\n pairs: new Map(),\n fitted,\n probed: false,\n // passed to `fitText` as they are, so drawing a cell allocates no closures\n widthOf: character => this.measureCharacter(measures, character),\n exactFit: {\n measure: text => this.measureString(measures, text),\n cache: fitted,\n sumIsExact: true,\n kerning: (left, right) => this.measureKerning(measures, left, right),\n },\n };\n this.fonts.set(font, measures);\n return measures;\n }\n\n /** Gives the measuring context the font and style the text is drawn with. */\n private prepareMeasuring(measures: FontMeasures) {\n const { textRendering, fontKerning, letterSpacing } = this.options;\n const state = `${measures.font}|${textRendering}|${fontKerning}|${letterSpacing}`;\n if (this.measuredState !== state) {\n this.measureContext.font = measures.font;\n this.measureContext.textRendering = textRendering;\n this.measureContext.fontKerning = fontKerning;\n this.measureContext.letterSpacing = letterSpacing;\n this.measuredState = state;\n }\n if (measures.probed) return;\n\n measures.probed = true;\n // in a monospace font the character widths add up to the width of any Latin text, so that text needs no measuring\n measures.exactFit.sumIsExact = Math.abs(this.measureContext.measureText('i').width - this.measureContext.measureText('W').width) < 0.01;\n }\n\n /** Width of one character in a font, measured once. */\n private measureCharacter(measures: FontMeasures, character: string) {\n const cached = measures.widths.get(character);\n if (cached !== undefined) return cached;\n\n this.prepareMeasuring(measures);\n const width = this.measureContext.measureText(character).width;\n measures.widths.set(character, width);\n return width;\n }\n\n /** What a pair of characters is wider than the two alone, measured once per pair: negative for kerned pairs such as \"AV\". */\n private measureKerning(measures: FontMeasures, left: string, right: string) {\n const key = left.charCodeAt(0) * 0x10000 + right.charCodeAt(0);\n const known = measures.pairs.get(key);\n if (known !== undefined) return known;\n\n const kerning = this.measureString(measures, left + right) - this.measureCharacter(measures, left) - this.measureCharacter(measures, right);\n measures.pairs.set(key, kerning);\n return kerning;\n }\n\n /** Width of a string as the browser lays it out: includes kerning, ligatures and joined scripts. */\n private measureString(measures: FontMeasures, text: string) {\n this.prepareMeasuring(measures);\n return this.measureContext.measureText(text).width;\n }\n\n /** Sum of the character widths in the renderer's font: exact for monospace fonts, a close upper bound for most others. */\n getTextWidth(text: string) {\n const { widthOf } = this.measuresOf(this.options.font);\n let totalWidth = 0;\n for (let i = 0; i < text.length; i++) totalWidth += widthOf(text.charAt(i));\n return totalWidth;\n }\n\n /**\n * Whether simple text surely fits: the cached character widths add up to at most `available`. Kerning only narrows\n * text, so a fit by the sum is a fit. Anything past Latin (joined scripts, emoji) is not trusted and gets clipped.\n */\n private fitsBySum(text: string, available: number, widthOf: (character: string) => number) {\n let used = 0;\n for (let i = 0; i < text.length; i++) {\n if (text.charCodeAt(i) >= FIRST_COMPLEX_CHARACTER) return false;\n used += widthOf(text.charAt(i));\n if (used > available) return false;\n }\n return true;\n }\n\n /** The font of the cell drawn last: columns mostly share one, so the lookup by font name is skipped. */\n private lastMeasures: FontMeasures | undefined = undefined;\n\n private isRightToLeft(text: string) {\n const { direction } = this.options;\n return direction === 'auto' ? rightToLeftLetter.test(text) : direction === 'rtl';\n }\n\n /**\n * Draws the text clipped with an ellipsis; `(x, y)` is the offset of the text box from `(originX, originY)`.\n * The whole string is drawn with one `fillText`: recording one command per cell is much cheaper than\n * one `drawImage` per character, and the browser keeps its own glyph cache.\n */\n paint(ctx: CanvasRenderingContext2D, { value = '', x = 0, y = 0, width = 0, height = 0, font = this.options.font }: RenderProps, originX: number, originY: number) {\n const { cellPadding } = this.options;\n const available = width - cellPadding.left - cellPadding.right;\n const measures = this.lastMeasures?.font === font ? this.lastMeasures : this.measuresOf(font);\n this.lastMeasures = measures;\n const clip = this.options.textOverflow === 'clip' && !this.fitsBySum(value, available, measures.widthOf);\n const text = this.options.textOverflow === 'clip' ? value : fitText(value, available, this.options.ellipsis, measures.widthOf, measures.exactFit);\n if (text === '' || height - cellPadding.top - cellPadding.bottom <= 0) return;\n\n if (clip) {\n // only text that may be wider than the cell needs the (comparatively costly) clip\n ctx.save();\n ctx.beginPath();\n ctx.rect(originX + x + cellPadding.left, originY + y, Math.max(0, available), height);\n ctx.clip();\n }\n\n const rightToLeft = this.styled && this.isRightToLeft(text);\n if (this.styled) {\n ctx.textRendering = this.options.textRendering;\n ctx.fontKerning = this.options.fontKerning;\n ctx.letterSpacing = this.options.letterSpacing;\n ctx.direction = rightToLeft ? 'rtl' : 'ltr';\n }\n ctx.font = font;\n ctx.fillStyle = this.options.color;\n ctx.textAlign = rightToLeft ? 'right' : 'left';\n // centred in the padded box, so fonts of different sizes line up in a row\n ctx.textBaseline = 'middle';\n // at a fractional pixel ratio (125%, 150% zoom) integer CSS pixels fall between device pixels and blur the glyphs\n const { pixelRatio } = this;\n const textX = rightToLeft ? originX + x + width - cellPadding.right : originX + x + cellPadding.left;\n ctx.fillText(\n text,\n Math.round(textX * pixelRatio) / pixelRatio,\n Math.round((originY + y + cellPadding.top + (height - cellPadding.top - cellPadding.bottom) / 2) * pixelRatio) / pixelRatio,\n );\n if (clip) ctx.restore();\n }\n\n readonly element = primitive<RenderProps>((ctx, props, x, y) => this.paint(ctx, props, x, y));\n}\n\nexport default TextRenderer;\n","import { primitive } from '../utils/jsx';\nimport type { SortDirection } from '../types';\n\nexport interface SortIndicatorProps {\n /** Width and height of the area the arrow is centred in, relative to the draw origin. */\n width: number;\n height: number;\n direction: SortDirection;\n color: string;\n}\n\n/** Width of the arrow's area, for the header to keep its text clear of it. */\nexport const SORT_INDICATOR_AREA = 18;\n\nconst ARROW_WIDTH = 8;\nconst ARROW_HEIGHT = 5;\nconst ARROW_ALPHA = 0.75;\n\n/** Small filled triangle at the right end of a header: pointing up for ascending, down for descending. */\nconst SortIndicator = primitive<SortIndicatorProps>((ctx, { width, height, direction, color }, originX, originY) => {\n // whole pixels, so the edges stay crisp\n const left = Math.round(originX + width - (SORT_INDICATOR_AREA + ARROW_WIDTH) / 2);\n const top = Math.round(originY + (height - ARROW_HEIGHT) / 2);\n const ascending = direction === 'asc';\n\n ctx.beginPath();\n ctx.moveTo(left, ascending ? top + ARROW_HEIGHT : top);\n ctx.lineTo(left + ARROW_WIDTH, ascending ? top + ARROW_HEIGHT : top);\n ctx.lineTo(left + ARROW_WIDTH / 2, ascending ? top : top + ARROW_HEIGHT);\n ctx.closePath();\n ctx.fillStyle = color;\n ctx.globalAlpha = ARROW_ALPHA;\n ctx.fill();\n ctx.globalAlpha = 1;\n});\n\nexport default SortIndicator;\n","import React, { Group } from '../utils/jsx';\nimport Renderer from '../utils/renderer';\nimport Rect from '../rectangle';\nimport TextRenderer from '../text';\nimport type { TextStyle } from '../text';\nimport SortIndicator, { SORT_INDICATOR_AREA } from '../sort-indicator';\nimport type { CellContext, CellRenderer, SortDirection } from '../types';\n\nexport interface HeaderOptions {\n layer: string;\n background: string;\n /** Background of a header or row number with some of its cells selected. */\n selectedBackground: string;\n /** Background of a header or row number whose whole column or row is selected. */\n fullySelectedBackground: string;\n font: string;\n color: string;\n borderRightWidth: number;\n borderRightColor: string;\n borderBottomWidth: number;\n borderBottomColor: string;\n}\n\nclass HeaderRenderer extends Renderer<HeaderOptions> implements CellRenderer {\n static readonly defaultOptions: HeaderOptions = {\n layer: 'header',\n background: '#333',\n selectedBackground: '#2f3d4a',\n fullySelectedBackground: '#3a5a7c',\n font: '13px sans-serif',\n color: '#fff',\n borderRightWidth: 1,\n borderRightColor: '#fff',\n borderBottomWidth: 1,\n borderBottomColor: '#fff',\n };\n\n private readonly textRenderer: TextRenderer;\n\n /** Sort direction by column id, set by the grid; sorted headers show an arrow. */\n private readonly sortDirections = new Map<string, SortDirection>();\n\n /** Shows the arrows of the columns in the sort model; the grid redraws the headers afterwards. */\n setSortModel(model: readonly { columnId: string | number; direction?: SortDirection }[]) {\n this.sortDirections.clear();\n model.forEach(({ columnId, direction = 'asc' }) => this.sortDirections.set(String(columnId), direction));\n }\n\n constructor(options: Partial<HeaderOptions> = {}) {\n super({ ...HeaderRenderer.defaultOptions, ...options });\n\n this.textRenderer = new TextRenderer({\n font: this.options.font,\n color: this.options.color,\n });\n }\n\n get layer() {\n return this.options.layer;\n }\n\n set font(font: string) {\n this.options.font = font;\n this.textRenderer.font = font;\n }\n\n get font() {\n return this.textRenderer.font;\n }\n\n set pixelRatio(pixelRatio: number) {\n this.textRenderer.pixelRatio = pixelRatio;\n }\n\n get pixelRatio() {\n return this.textRenderer.pixelRatio;\n }\n\n setTextStyle(style: Partial<TextStyle>) {\n this.textRenderer.setStyle(style);\n }\n\n optionsUpdated() {\n this.textRenderer.color = this.options.color;\n }\n\n clearCache() {\n this.textRenderer.clearCache();\n }\n\n private backgroundFor(selected: CellContext['selected']) {\n if (selected === 'full') return this.options.fullySelectedBackground;\n if (selected === 'partial') return this.options.selectedBackground;\n return this.options.background;\n }\n\n draw({ ctx, x, y, width, height, column, formatted, selected }: Readonly<CellContext>) {\n if (width === 0 || height === 0) return;\n\n const direction = column === undefined ? undefined : this.sortDirections.get(String(column.id));\n const { borderRightWidth, borderRightColor, borderBottomWidth, borderBottomColor } = this.options;\n\n const background = this.backgroundFor(selected);\n\n (\n <Group>\n <Rect width={width} height={height} color={background} />\n {borderRightWidth > 0 && <Rect x={width - borderRightWidth} width={borderRightWidth} height={height} color={borderRightColor} />}\n {borderBottomWidth > 0 && <Rect y={height - borderBottomWidth} width={width} height={borderBottomWidth} color={borderBottomColor} />}\n <this.textRenderer.element value={formatted} font={column?.headerFont} width={direction ? width - SORT_INDICATOR_AREA : width} height={height} />\n {direction && <SortIndicator width={width} height={height} direction={direction} color={this.options.color} />}\n </Group>\n ).draw(ctx, x, y);\n }\n}\n\nexport default HeaderRenderer;\n","import React from '../utils/jsx';\nimport Renderer from '../utils/renderer';\nimport TextRenderer from '../text';\nimport type { TextStyle } from '../text';\nimport type { CellContext, CellRenderer } from '../types';\n\nexport interface CellValueOptions {\n layer: string;\n font: string;\n color: string;\n}\n\nexport default class CellValueRenderer extends Renderer<CellValueOptions> implements CellRenderer {\n static readonly defaultOptions: CellValueOptions = {\n layer: 'content',\n font: '12px sans-serif',\n color: '#fff',\n };\n\n private readonly renderer: TextRenderer;\n\n constructor(options: Partial<CellValueOptions> = {}) {\n super({ ...CellValueRenderer.defaultOptions, ...options });\n\n this.renderer = new TextRenderer({\n font: this.options.font,\n color: this.options.color,\n });\n }\n\n get layer() {\n return this.options.layer;\n }\n\n set font(font: string) {\n this.options.font = font;\n this.renderer.font = font;\n }\n\n get font() {\n return this.options.font;\n }\n\n set color(color: string) {\n this.options.color = color;\n this.renderer.color = color;\n }\n\n get color() {\n return this.options.color;\n }\n\n set pixelRatio(pixelRatio: number) {\n this.renderer.pixelRatio = pixelRatio;\n }\n\n get pixelRatio() {\n return this.renderer.pixelRatio;\n }\n\n setTextStyle(style: Partial<TextStyle>) {\n this.renderer.setStyle(style);\n }\n\n clearCache() {\n this.renderer.clearCache();\n }\n\n draw({ ctx, x, y, width, height, column, formatted, valueChanged, forced }: Readonly<CellContext>) {\n if (!valueChanged && !forced) return;\n\n ctx.clearRect(x, y, width, height);\n (<this.renderer.element value={formatted} font={column?.font} width={width} height={height} />).draw(ctx, x, y);\n }\n}\n","export const INHERIT_FONT = 'inherit';\n\ntype FontStyle = Pick<CSSStyleDeclaration, 'fontStyle' | 'fontWeight' | 'fontSize' | 'fontFamily'>;\n\n/**\n * The element's computed font as a canvas font string, or `fallback` when it has none (not attached yet).\n * Built from the longhands, because `getComputedStyle(...).font` is empty in some browsers.\n */\nexport const resolveFont = (font: string, style: FontStyle, fallback: string) => {\n if (font !== INHERIT_FONT) return font;\n if (!style.fontSize || !style.fontFamily) return fallback;\n return [style.fontStyle, style.fontWeight, style.fontSize, style.fontFamily].filter(Boolean).join(' ');\n};\n","export type ThemeName = 'light' | 'dark';\n\n/** Everything the grid takes from CSS; colours and fonts are CSS values, sizes are px. */\nexport interface Theme {\n background: string;\n text: string;\n font: string;\n rowHeight: number;\n /** Right and bottom edge of body cells. */\n border: string;\n headerBackground: string;\n headerText: string;\n headerFont: string;\n headerHeight: number;\n headerBorder: string;\n headerBottomBorder: string;\n /** Header of a column or row number with some of its cells selected. */\n headerSelected: string;\n /** Header of a column or row number with all its cells selected. */\n headerFullySelected: string;\n /** Laid over odd rows; usually translucent. */\n zebra: string;\n /** Laid over the row under the pointer; usually translucent. */\n hover: string;\n /** Laid over a cell that just changed, at the strength of the flash. */\n flash: string;\n selection: string;\n selectionBorder: string;\n}\n\ntype ThemeKey = keyof Theme;\n\n/** The CSS custom property of each themed value. */\nexport const THEME_TOKENS: Readonly<Record<ThemeKey, string>> = {\n background: '--cg-background',\n text: '--cg-text-color',\n font: '--cg-font',\n rowHeight: '--cg-row-height',\n border: '--cg-border-color',\n headerBackground: '--cg-header-background',\n headerText: '--cg-header-text-color',\n headerFont: '--cg-header-font',\n headerHeight: '--cg-header-height',\n headerBorder: '--cg-header-border-color',\n headerBottomBorder: '--cg-header-bottom-border-color',\n headerSelected: '--cg-header-selected-background',\n headerFullySelected: '--cg-header-fully-selected-background',\n zebra: '--cg-zebra-color',\n hover: '--cg-hover-color',\n flash: '--cg-flash-color',\n selection: '--cg-selection-color',\n selectionBorder: '--cg-selection-border-color',\n};\n\nconst shared = {\n font: '12px sans-serif',\n rowHeight: 20,\n headerFont: '13px sans-serif',\n headerHeight: 30,\n flash: 'rgb(214, 144, 13)',\n};\n\nexport const THEME_DEFAULTS: Readonly<Record<ThemeName, Readonly<Theme>>> = {\n dark: {\n ...shared,\n background: '#333',\n text: '#efefef',\n border: '#3b3b3b',\n headerBackground: '#262626',\n headerText: '#efefef',\n headerBorder: '#333',\n headerBottomBorder: '#4a4a4a',\n headerSelected: '#2f3d4a',\n headerFullySelected: '#3a5a7c',\n zebra: 'rgba(255, 255, 255, 0.025)',\n hover: 'rgba(255, 255, 255, 0.06)',\n selection: 'rgba(74, 144, 217, 0.25)',\n selectionBorder: '#4a90d9',\n },\n light: {\n ...shared,\n background: '#fff',\n text: '#1f2328',\n border: '#e4e7eb',\n headerBackground: '#f3f4f6',\n headerText: '#1f2328',\n headerBorder: '#e4e7eb',\n headerBottomBorder: '#c9ced6',\n headerSelected: '#dbe8f6',\n headerFullySelected: '#b9d3ee',\n zebra: 'rgba(0, 0, 0, 0.025)',\n hover: 'rgba(0, 0, 0, 0.05)',\n selection: 'rgba(74, 144, 217, 0.2)',\n selectionBorder: '#2f6fb5',\n },\n};\n\n/** What the CSS side of a theme is read through; the browser provides it, tests fake it. */\nexport interface ThemeSource {\n /** The value of a custom property, or an empty string when it is not set. */\n read: (token: string) => string;\n isColor: (value: string) => boolean;\n isFont: (value: string) => boolean;\n}\n\nconst PIXEL_KEYS: readonly ThemeKey[] = ['rowHeight', 'headerHeight'];\nconst FONT_KEYS: readonly ThemeKey[] = ['font', 'headerFont'];\n\nconst toPixels = (value: string) => {\n const pixels = /^\\d+(\\.\\d+)?(px)?$/.test(value) ? parseFloat(value) : NaN;\n return pixels > 0 ? pixels : undefined;\n};\n\n/** Each value from its custom property, or from the defaults of `name` when it is missing or invalid. */\nexport const readTheme = (name: ThemeName, { read, isColor, isFont }: ThemeSource): Theme => {\n const defaults = THEME_DEFAULTS[name];\n const parse = (key: ThemeKey, value: string): string | number | undefined => {\n if (!value) return undefined;\n if (PIXEL_KEYS.includes(key)) return toPixels(value);\n if (FONT_KEYS.includes(key)) return isFont(value) ? value : undefined;\n return isColor(value) ? value : undefined;\n };\n\n return Object.fromEntries(\n (Object.keys(THEME_TOKENS) as ThemeKey[]).map(key => [key, parse(key, read(THEME_TOKENS[key]).trim()) ?? defaults[key]]),\n ) as unknown as Theme;\n};\n\nexport const isSameTheme = (a: Theme, b: Theme) => (Object.keys(THEME_TOKENS) as ThemeKey[]).every(key => a[key] === b[key]);\n\n/** `fillStyle` ignores colours it cannot parse, so a colour is valid when it sticks whichever value it replaces. */\nexport const createColorCheck = (ctx: Pick<CanvasRenderingContext2D, 'fillStyle'>) => (value: string) => {\n ctx.fillStyle = '#000000';\n ctx.fillStyle = value;\n const onBlack = ctx.fillStyle;\n ctx.fillStyle = '#ffffff';\n ctx.fillStyle = value;\n return onBlack === ctx.fillStyle;\n};\n\nexport const isCssFont = (value: string) => typeof CSS === 'undefined' || CSS.supports('font', value);\n","/** Narrowest a column can get when it sets no `minWidth`. */\nexport const DEFAULT_MIN_COLUMN_WIDTH = 20;\n\n/** Keeps a width within its limits; a `maxWidth` below the minimum loses. */\nexport const clampWidth = (width: number, minWidth = DEFAULT_MIN_COLUMN_WIDTH, maxWidth = Infinity) =>\n Math.round(Math.max(minWidth, Math.min(maxWidth, width)));\n\n/**\n * Left edge of every column, followed by the total width: `offsets[i]` is where column `i` starts and\n * `offsets[widths.length]` is where the last one ends. Widths are rounded, as they are when drawn.\n */\nexport const buildOffsets = (widths: readonly number[]) => {\n const offsets = new Array<number>(widths.length + 1);\n offsets[0] = 0;\n widths.forEach((width, index) => {\n offsets[index + 1] = offsets[index] + Math.round(width);\n });\n return offsets;\n};\n\n/** Index of the column containing `x`, found by binary search; clamped to the first and last column. */\nexport const columnAt = (offsets: readonly number[], x: number) => {\n const last = offsets.length - 2;\n if (last < 0) return -1;\n\n let low = 0;\n let high = last;\n while (low < high) {\n const middle = (low + high + 1) >> 1;\n if (offsets[middle] <= x) low = middle;\n else high = middle - 1;\n }\n return low;\n};\n\n/**\n * The column whose right edge is within `tolerance` of `x`, i.e. the one a drag from there would resize,\n * or -1. Where two edges are equally close (zero-width columns do not exist, but touch targets overlap) the left one wins.\n */\nexport const borderAt = (offsets: readonly number[], x: number, tolerance: number) => {\n const index = columnAt(offsets, x + tolerance);\n if (index < 0) return -1;\n\n // the border on the right of the column containing the point, or of the previous column when the point is near its left edge\n const rightOfPrevious = index > 0 && Math.abs(offsets[index] - x) <= tolerance ? index - 1 : -1;\n const rightOfCurrent = Math.abs(offsets[index + 1] - x) <= tolerance ? index : -1;\n return rightOfPrevious >= 0 ? rightOfPrevious : rightOfCurrent;\n};\n","import type { CellPosition, CellRange, GridSelection, SelectionLevel, SelectionMode, Span } from '../types';\n\n/** Furthest the grid scrolls per frame while a selection is dragged past its edge, in px. */\nexport const DRAG_SCROLL_MAX = 30;\n\n/** The two indexes as a span, smaller first. */\nexport const span = (a: number, b: number): Span => (a <= b ? [a, b] : [b, a]);\n\nconst makeRange = (rows: Span | undefined, columns: Span | undefined): CellRange => ({\n ...(rows && { rows }),\n ...(columns && { columns }),\n});\n\nexport const rangeBetween = (from: CellPosition, to: CellPosition): CellRange =>\n makeRange(span(from.row, to.row), span(from.column, to.column));\n\n/** The range a drag from `from` to `to` selects: what it covers depends on the mode, whole rows in `row` mode and so on. */\nexport const rangeFor = (mode: SelectionMode, from: CellPosition, to: CellPosition): CellRange => {\n if (mode === 'range') return rangeBetween(from, to);\n if (mode === 'row') return makeRange(span(from.row, to.row), undefined);\n if (mode === 'column') return makeRange(undefined, span(from.column, to.column));\n return rangeBetween(to, to);\n};\n\nconst normalizeSpan = (value: Span): Span => span(Math.max(0, Math.floor(value[0])), Math.max(0, Math.floor(value[1])));\n\n/** A copy with whole-number, ordered, non-negative spans; what `setSelection` stores. */\nexport const normalizeRange = (range: CellRange): CellRange =>\n makeRange(range.rows && normalizeSpan(range.rows), range.columns && normalizeSpan(range.columns));\n\nconst copySpan = (value: Span | undefined): Span | undefined => value && [value[0], value[1]];\n\nconst copyRange = (range: CellRange): CellRange => makeRange(copySpan(range.rows), copySpan(range.columns));\n\n/** Rows and columns a range really covers, both inclusive. */\nexport interface Bounds {\n top: number;\n bottom: number;\n left: number;\n right: number;\n}\n\n/** The part of the range inside a grid of the given size, or undefined when none of it is. */\nexport const resolve = (range: CellRange, rowCount: number, columnCount: number): Bounds | undefined => {\n const top = Math.max(0, range.rows?.[0] ?? 0);\n const bottom = Math.min(rowCount - 1, range.rows?.[1] ?? rowCount - 1);\n const left = Math.max(0, range.columns?.[0] ?? 0);\n const right = Math.min(columnCount - 1, range.columns?.[1] ?? columnCount - 1);\n return top > bottom || left > right ? undefined : { top, bottom, left, right };\n};\n\nconst within = (index: number, value: Span | undefined) => value === undefined || (index >= value[0] && index <= value[1]);\n\nconst coversAll = (value: Span | undefined, count: number) => value === undefined || (value[0] <= 0 && value[1] >= count - 1);\n\nexport const contains = (range: CellRange, row: number, column: number) => within(row, range.rows) && within(column, range.columns);\n\n/** How much of a column is selected. Row numbers are drawn on every scroll, so this allocates nothing. */\nexport const columnLevel = (ranges: readonly CellRange[], column: number, rowCount: number): SelectionLevel => {\n let level: SelectionLevel = 'none';\n for (const range of ranges) {\n if (!within(column, range.columns)) continue;\n if (coversAll(range.rows, rowCount)) return 'full';\n level = 'partial';\n }\n return level;\n};\n\n/** How much of a row is selected. */\nexport const rowLevel = (ranges: readonly CellRange[], row: number, columnCount: number): SelectionLevel => {\n let level: SelectionLevel = 'none';\n for (const range of ranges) {\n if (!within(row, range.rows)) continue;\n if (coversAll(range.columns, columnCount)) return 'full';\n level = 'partial';\n }\n return level;\n};\n\n/** What a range covers: everything, whole columns, whole rows, or a block of cells. */\nexport const shapeOf = (range: CellRange): 'all' | 'column' | 'row' | 'block' => {\n if (range.rows === undefined && range.columns === undefined) return 'all';\n if (range.rows === undefined) return 'column';\n if (range.columns === undefined) return 'row';\n return 'block';\n};\n\n/** Rows run down the grid and columns across it; a header selects a line of cells along one of them. */\nexport type Axis = 'row' | 'column';\n\n/** A whole row or column, or a run of them from `from` to `to`. */\nexport const lineRange = (axis: Axis, from: number, to: number): CellRange =>\n axis === 'column' ? makeRange(undefined, span(from, to)) : makeRange(span(from, to), undefined);\n\n/** The cell at `index` along the axis and `cross` along the other. */\nexport const linePosition = (axis: Axis, index: number, cross: number): CellPosition =>\n axis === 'column' ? { row: cross, column: index } : { row: index, column: cross };\n\n/** The index of a position along the axis. */\nexport const lineIndex = (axis: Axis, position: CellPosition) => (axis === 'column' ? position.column : position.row);\n\n/** The index of a position along the other axis. */\nexport const crossIndex = (axis: Axis, position: CellPosition) => (axis === 'column' ? position.row : position.column);\n\nconst sameSpan = (a: Span | undefined, b: Span | undefined) => a?.[0] === b?.[0] && a?.[1] === b?.[1];\n\nconst sameRange = (a: CellRange, b: CellRange) => sameSpan(a.rows, b.rows) && sameSpan(a.columns, b.columns);\n\nconst samePosition = (a: CellPosition | undefined, b: CellPosition | undefined) => a?.row === b?.row && a?.column === b?.column;\n\nconst clampSpan = (value: Span | undefined, count: number): Span | undefined => value && [value[0], Math.min(value[1], count - 1)];\n\nconst clampPosition = (position: CellPosition | undefined, rowCount: number, columnCount: number): CellPosition | undefined =>\n position && { row: Math.min(position.row, rowCount - 1), column: Math.min(position.column, columnCount - 1) };\n\n/**\n * The selected ranges, the active cell (where typing and keyboard moves start; it sits inside the last range)\n * and the focus corner (the end of the last range that moves when the selection is extended).\n * Every change returns whether the ranges or the active cell differ afterwards.\n */\nclass SelectionModel {\n ranges: CellRange[] = [];\n\n active: CellPosition | undefined = undefined;\n\n focus: CellPosition | undefined = undefined;\n\n private assign(ranges: CellRange[], active: CellPosition | undefined, focus: CellPosition | undefined) {\n const changed = ranges.length !== this.ranges.length\n || ranges.some((range, index) => !sameRange(range, this.ranges[index]))\n || !samePosition(active, this.active);\n this.ranges = ranges;\n this.active = active && { row: active.row, column: active.column };\n this.focus = focus && { row: focus.row, column: focus.column };\n return changed;\n }\n\n /** Makes this the only range, with `active` in focus. */\n set(range: CellRange, active: CellPosition, focus: CellPosition = active) {\n return this.assign([normalizeRange(range)], active, focus);\n }\n\n /** Adds a range to the selection, as ctrl+click does. */\n add(range: CellRange, active: CellPosition) {\n return this.assign([...this.ranges, normalizeRange(range)], active, active);\n }\n\n /** Replaces the last range, as shift+click or dragging does; the active cell stays and `focus` becomes the moving corner. */\n extend(range: CellRange, focus: CellPosition) {\n if (this.ranges.length === 0 || this.active === undefined) return this.set(range, focus);\n return this.assign([...this.ranges.slice(0, -1), normalizeRange(range)], this.active, focus);\n }\n\n clear() {\n return this.assign([], undefined, undefined);\n }\n\n /** Moves the active cell without touching the ranges, as Enter and Tab do inside a selection. */\n activate(position: CellPosition) {\n return this.assign(this.ranges, position, position);\n }\n\n /** Replaces everything, with the first cell of the last range active unless `active` says otherwise. */\n replace(ranges: readonly CellRange[], active?: CellPosition) {\n const normalized = ranges.map(normalizeRange);\n const last = normalized[normalized.length - 1];\n if (last === undefined) return this.clear();\n\n const start = active ?? { row: last.rows?.[0] ?? 0, column: last.columns?.[0] ?? 0 };\n return this.assign(normalized, start, start);\n }\n\n /** Fits the selection to a grid of the given size, dropping what lies outside it; an empty grid selects nothing. */\n clamp(rowCount: number, columnCount: number) {\n if (rowCount === 0 || columnCount === 0) return this.clear();\n\n const ranges = this.ranges\n .filter(range => resolve(range, rowCount, columnCount) !== undefined)\n .map(range => makeRange(clampSpan(range.rows, rowCount), clampSpan(range.columns, columnCount)));\n if (ranges.length === 0) return this.clear();\n\n return this.assign(ranges, clampPosition(this.active, rowCount, columnCount), clampPosition(this.focus, rowCount, columnCount));\n }\n\n /** A copy that is safe to hand out. */\n snapshot(): GridSelection {\n return { ranges: this.ranges.map(copyRange), active: this.active && { ...this.active } };\n }\n}\n\n/** How fast to scroll while dragging with the pointer at `value` and the visible area between `min` and `max`: negative is back, 0 inside. */\nexport const dragScrollSpeed = (value: number, min: number, max: number) => {\n if (value < min) return -Math.min(DRAG_SCROLL_MAX, Math.max(2, (min - value) / 4));\n if (value > max) return Math.min(DRAG_SCROLL_MAX, Math.max(2, (value - max) / 4));\n return 0;\n};\n\nexport default SelectionModel;\n","import { crossIndex, lineIndex, linePosition } from './selection';\nimport type { Axis, Bounds } from './selection';\nimport type { CellPosition } from '../types';\n\n/** The size of the grid the keyboard moves in; `pageRows` is how many rows PageUp and PageDown skip. */\nexport interface GridSize {\n rowCount: number;\n columnCount: number;\n pageRows: number;\n}\n\nconst clamp = (value: number, last: number) => Math.max(0, Math.min(last, value));\n\n/**\n * Where a navigation key takes the cursor from `from`, or undefined for any other key. Arrows move one cell and, with ctrl, to the edge;\n * Home and End go to the first and last column (with ctrl also the first and last row); PageUp and PageDown move a page of rows.\n * The result is always inside the grid.\n */\nexport const moveTarget = (from: CellPosition, key: string, ctrl: boolean, { rowCount, columnCount, pageRows }: GridSize): CellPosition | undefined => {\n const lastRow = rowCount - 1;\n const lastColumn = columnCount - 1;\n const at = (row: number, column: number): CellPosition => ({ row: clamp(row, lastRow), column: clamp(column, lastColumn) });\n switch (key) {\n case 'ArrowUp': return at(ctrl ? 0 : from.row - 1, from.column);\n case 'ArrowDown': return at(ctrl ? lastRow : from.row + 1, from.column);\n case 'ArrowLeft': return at(from.row, ctrl ? 0 : from.column - 1);\n case 'ArrowRight': return at(from.row, ctrl ? lastColumn : from.column + 1);\n case 'Home': return at(ctrl ? 0 : from.row, 0);\n case 'End': return at(ctrl ? lastRow : from.row, lastColumn);\n case 'PageUp': return at(from.row - pageRows, from.column);\n case 'PageDown': return at(from.row + pageRows, from.column);\n default: return undefined;\n }\n};\n\n/**\n * The next cell inside `bounds` for Enter (`axis` `'row'`, going down) or Tab (`'column'`, going right), one back with `backwards`.\n * Past the end of a line it continues on the next one, and past the last cell it starts over.\n */\nexport const stepWithin = (bounds: Bounds, from: CellPosition, axis: Axis, backwards: boolean): CellPosition => {\n const direction = backwards ? -1 : 1;\n const [alongFirst, alongLast, crossFirst, crossLast] = axis === 'row'\n ? [bounds.top, bounds.bottom, bounds.left, bounds.right]\n : [bounds.left, bounds.right, bounds.top, bounds.bottom];\n const along = lineIndex(axis, from) + direction;\n if (along >= alongFirst && along <= alongLast) return linePosition(axis, along, crossIndex(axis, from));\n\n const crossCount = crossLast - crossFirst + 1;\n const wrapped = crossFirst + ((crossIndex(axis, from) + direction - crossFirst) % crossCount + crossCount) % crossCount;\n return linePosition(axis, direction > 0 ? alongFirst : alongLast, wrapped);\n};\n\n/**\n * The scroll offset that brings the span `start` to `end` into view in a viewport of `size`, starting from `scroll`:\n * unchanged when it is already visible, and the span's start wins when it is larger than the viewport.\n */\nexport const revealOffset = (start: number, end: number, scroll: number, size: number) => Math.min(start, Math.max(scroll, end - size));\n\n/**\n * Where the selection goes after an edit ends on `from`: Enter (`axis` `'row'`) moves down, Tab (`'column'`) right, one back with `backwards`.\n * Tab continues on the next row past the last column; at the edge of the grid the cell stays.\n */\nexport const stepAfterEdit = (from: CellPosition, axis: Axis, backwards: boolean, { rowCount, columnCount }: GridSize): CellPosition => {\n const direction = backwards ? -1 : 1;\n const inside = (row: number, column: number) => row >= 0 && row < rowCount && column >= 0 && column < columnCount;\n if (axis === 'row') return inside(from.row + direction, from.column) ? { row: from.row + direction, column: from.column } : from;\n if (inside(from.row, from.column + direction)) return { row: from.row, column: from.column + direction };\n\n const row = from.row + direction;\n return inside(row, 0) ? { row, column: backwards ? columnCount - 1 : 0 } : from;\n};\n","import type { Bounds } from './selection';\n\n/** Most cells one copy puts on the clipboard, so selecting everything in a huge grid cannot freeze the page. */\nexport const MAX_COPY_CELLS = 1_000_000;\n\n/** Text as one field of tab-separated values: wrapped in quotes, with quotes doubled, when it holds a tab, a line break or a quote, as spreadsheets do. */\nexport const escapeField = (text: string) => (/[\\t\\r\\n\"]/.test(text) ? `\"${text.replaceAll('\"', '\"\"')}\"` : text);\n\nexport interface CopiedText {\n text: string;\n /** Rows were left off to stay within `MAX_COPY_CELLS`. */\n truncated: boolean;\n}\n\n/**\n * The cells of `bounds` as tab-separated values, a row per line, from the text `textAt` gives for each cell.\n * Stops after as many whole rows as fit in `maxCells`, but always includes one.\n */\nexport const toTsv = (bounds: Bounds, textAt: (row: number, column: number) => string, maxCells = MAX_COPY_CELLS): CopiedText => {\n const width = bounds.right - bounds.left + 1;\n const height = bounds.bottom - bounds.top + 1;\n const rows = Math.min(height, Math.max(1, Math.floor(maxCells / width)));\n const lines = Array.from({ length: rows }, (_, offset) =>\n Array.from({ length: width }, (__, column) => escapeField(textAt(bounds.top + offset, bounds.left + column))).join('\\t'));\n return { text: lines.join('\\r\\n'), truncated: rows < height };\n};\n","export interface MenuEntry {\n id: string;\n label: string;\n disabled: boolean;\n}\n\n/**\n * A small popup menu, made of plain elements so it is accessible and can reach past the grid's box.\n * It sits in the top layer (`popover`), which closes it on an outside click or Escape. It is built when first opened.\n */\nexport class ContextMenu {\n private element: HTMLElement | undefined;\n\n private readonly host: HTMLElement;\n\n private readonly onPick: (id: string) => void;\n\n /** `onPick` is called with the id of the entry the user picked, after the menu closed. */\n constructor(host: HTMLElement, onPick: (id: string) => void) {\n this.host = host;\n this.onPick = onPick;\n }\n\n get isOpen() {\n return this.element?.matches(':popover-open') ?? false;\n }\n\n /** Shows the entries with their top left corner at the viewport position, moved in if it would overflow. */\n open(clientX: number, clientY: number, entries: readonly MenuEntry[]) {\n this.close();\n const menu = this.element ?? this.create();\n menu.replaceChildren(...entries.map(entry => this.createItem(entry)));\n menu.style.left = `${clientX}px`;\n menu.style.top = `${clientY}px`;\n menu.showPopover();\n\n const { width, height } = menu.getBoundingClientRect();\n menu.style.left = `${Math.max(0, Math.min(clientX, document.documentElement.clientWidth - width))}px`;\n menu.style.top = `${Math.max(0, Math.min(clientY, document.documentElement.clientHeight - height))}px`;\n this.items().find(item => !item.disabled)?.focus({ preventScroll: true });\n }\n\n close() {\n if (this.isOpen) this.element?.hidePopover();\n }\n\n private items() {\n return Array.from(this.element?.querySelectorAll<HTMLButtonElement>('[role=\"menuitem\"]') ?? []);\n }\n\n private create() {\n const menu = document.createElement('div');\n menu.className = 'contextMenu';\n menu.role = 'menu';\n menu.popover = 'auto';\n menu.addEventListener('keydown', this.onKeyDown);\n // light dismiss and Escape both end up here; focus goes back to the grid so the keyboard keeps working\n menu.addEventListener('toggle', event => {\n if ((event as ToggleEvent).newState === 'closed' && menu.contains(document.activeElement)) this.host.focus({ preventScroll: true });\n });\n this.host.append(menu);\n this.element = menu;\n return menu;\n }\n\n private createItem({ id, label, disabled }: MenuEntry) {\n const item = document.createElement('button');\n item.type = 'button';\n item.role = 'menuitem';\n item.textContent = label;\n item.disabled = disabled;\n item.addEventListener('click', () => {\n this.close();\n this.onPick(id);\n });\n return item;\n }\n\n private readonly onKeyDown = (event: KeyboardEvent) => {\n // the menu sits inside the grid, which would also act on Enter, Escape and the rest, and cancel the click Enter makes\n event.stopPropagation();\n const items = this.items().filter(item => !item.disabled);\n const index = items.indexOf(document.activeElement as HTMLButtonElement);\n const step = (to: number) => items[(to + items.length) % items.length]?.focus();\n if (event.key === 'ArrowDown') step(index + 1);\n else if (event.key === 'ArrowUp') step(index < 0 ? -1 : index - 1);\n else if (event.key === 'Home') step(0);\n else if (event.key === 'End') step(-1);\n else if (event.key === 'Tab') this.close();\n else return;\n\n event.preventDefault();\n };\n}\n\nexport default ContextMenu;\n","import type { BuiltInCellEditor, CellEditor, CellEditorContext, CellEditorInstance, SelectOption } from '../types';\n\nconst asText = (value: unknown) => (value === undefined || value === null ? '' : String(value));\n\nconst createInput = (type: string) => {\n const input = document.createElement('input');\n input.type = type;\n return input;\n};\n\n/** Selects the whole text, or puts the caret after the key that opened the editor. */\nconst focusText = (input: HTMLInputElement, typed: boolean) => {\n input.focus({ preventScroll: true });\n if (typed) input.setSelectionRange(input.value.length, input.value.length);\n else input.select();\n};\n\nconst createTextEditor = ({ value, initialText }: CellEditorContext): CellEditorInstance => {\n const input = createInput('text');\n input.value = initialText ?? asText(value);\n return { element: input, getValue: () => input.value, focus: () => focusText(input, initialText !== undefined) };\n};\n\n/**\n * A text box with the numeric keypad on touch screens, aligned like the cell it covers. It is not `type=\"number\"`, which hides what was typed when it\n * is not a number (so a typo would clear the cell), steps on arrow keys and wheel, and shows spin buttons; the parser reports a bad number instead.\n */\nconst createNumberEditor = ({ value, initialText }: CellEditorContext): CellEditorInstance => {\n const input = createInput('text');\n input.inputMode = 'decimal';\n input.autocomplete = 'off';\n input.classList.add('number');\n input.value = initialText ?? asText(value);\n return { element: input, getValue: () => input.value, focus: () => focusText(input, initialText !== undefined) };\n};\n\nconst createCheckboxEditor = ({ value }: CellEditorContext): CellEditorInstance => {\n const input = createInput('checkbox');\n input.checked = value === true;\n return { element: input, getValue: () => input.checked, focus: () => input.focus({ preventScroll: true }) };\n};\n\nconst toOption = (option: string | number | SelectOption): SelectOption => (typeof option === 'object' ? option : { value: option });\n\n/** Most rows the list shows before it scrolls, and the room it keeps from the window's edge, in px. */\nconst LIST_MAX_HEIGHT = 240;\nconst LIST_MARGIN = 8;\n\n/**\n * A dropdown drawn by the grid, since the browser's own list cannot follow the theme and clips its text in short rows. It opens at once,\n * arrows and typing move through the options, a click picks one and commits. The list sits in the top layer, so no cell or scroll area clips it.\n * A value outside the options is listed first, so leaving it alone keeps it.\n */\nconst createSelectEditor = (options: readonly (string | number | SelectOption)[], { value, commit }: CellEditorContext): CellEditorInstance => {\n const listed = options.map(toOption);\n const entries = listed.some(entry => entry.value === value) ? listed : [{ value, label: asText(value) }, ...listed];\n const labelOf = (entry: SelectOption) => entry.label ?? asText(entry.value);\n let index = Math.max(0, entries.findIndex(entry => entry.value === value));\n let open = false;\n\n const box = document.createElement('div');\n box.className = 'cellSelect';\n box.tabIndex = 0;\n box.role = 'combobox';\n box.ariaHasPopup = 'listbox';\n const label = document.createElement('span');\n label.className = 'cellSelectLabel';\n const list = document.createElement('div');\n list.className = 'cellSelectList';\n list.role = 'listbox';\n list.popover = 'manual';\n box.append(label, list);\n\n const items = entries.map((entry, position) => {\n const item = document.createElement('div');\n item.role = 'option';\n item.textContent = labelOf(entry);\n // the editor keeps the focus, or leaving it would commit\n item.addEventListener('pointerdown', event => event.preventDefault());\n item.addEventListener('click', () => {\n choose(position);\n commit();\n });\n return item;\n });\n list.append(...items);\n\n function choose(position: number) {\n index = position;\n label.textContent = labelOf(entries[position]);\n items.forEach((item, at) => {\n item.classList.toggle('active', at === position);\n item.ariaSelected = String(at === position);\n });\n items[position]?.scrollIntoView({ block: 'nearest' });\n }\n\n const place = (visible: boolean) => {\n const show = open && visible;\n box.ariaExpanded = String(open);\n if (show !== list.matches(':popover-open')) {\n if (show) list.showPopover();\n else list.hidePopover();\n }\n if (!show) return;\n\n const rect = box.getBoundingClientRect();\n const height = Math.min(list.scrollHeight, LIST_MAX_HEIGHT);\n const below = window.innerHeight - rect.bottom - LIST_MARGIN;\n const above = rect.top - LIST_MARGIN;\n const upwards = height > below && above > below;\n list.style.maxHeight = `${Math.min(LIST_MAX_HEIGHT, upwards ? above : below)}px`;\n list.style.minWidth = `${rect.width}px`;\n list.style.left = `${rect.left}px`;\n list.style.top = `${upwards ? rect.top - Math.min(height, above) : rect.bottom}px`;\n items[index]?.scrollIntoView({ block: 'nearest' });\n };\n\n const typeAhead = (key: string) => {\n const wanted = key.toLowerCase();\n const order = [...entries.keys()].map((_, step) => (index + 1 + step) % entries.length);\n const found = order.find(position => labelOf(entries[position]).toLowerCase().startsWith(wanted));\n if (found !== undefined) choose(found);\n };\n\n box.addEventListener('pointerdown', event => {\n // a press on an option is the option's, and closing the list now would swallow its click\n if (event.target instanceof Node && list.contains(event.target)) return;\n\n event.preventDefault();\n box.focus({ preventScroll: true });\n open = !open;\n place(true);\n });\n box.addEventListener('keydown', event => {\n const step = { ArrowDown: 1, ArrowUp: -1 }[event.key];\n const typed = event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;\n if (step === undefined && !typed) return;\n\n event.preventDefault();\n open = true;\n if (step === undefined) typeAhead(event.key);\n else choose(Math.max(0, Math.min(entries.length - 1, index + step)));\n place(true);\n });\n\n choose(index);\n return {\n element: box,\n getValue: () => entries[index]?.value,\n focus() {\n box.focus({ preventScroll: true });\n open = true;\n place(true);\n },\n place,\n destroy() {\n open = false;\n place(false);\n },\n };\n};\n\nconst createBuiltIn = (editor: BuiltInCellEditor, context: CellEditorContext) => {\n if (editor === 'checkbox') return createCheckboxEditor(context);\n if (typeof editor === 'object') return createSelectEditor(editor.options, context);\n return editor === 'number' ? createNumberEditor(context) : createTextEditor(context);\n};\n\n/** Builds the editor a column asks for; a column without one edits text. */\nexport const createEditor = (editor: CellEditor | undefined, context: CellEditorContext): CellEditorInstance =>\n typeof editor === 'function' ? editor(context) : createBuiltIn(editor ?? 'text', context);\n\n/** Whether typing a character on the cell can start this editor. */\nexport const startsByTyping = (editor: CellEditor | undefined) => editor === undefined || typeof editor === 'function' || editor === 'text' || editor === 'number';\n","import type { BuiltInCellEditor, CellEditor, CellValueChange } from '../types';\n\nexport type EditResult = { ok: true; value: unknown } | { ok: false; message: string };\n\nexport interface ValueRules {\n parse?: (text: string, change: CellValueChange) => unknown;\n validate?: (value: unknown, change: CellValueChange) => boolean | string;\n}\n\nconst INVALID = 'Invalid value';\n\n/** The text of a number editor as a number; empty text is no value. */\nexport const parseNumber = (text: string) => {\n if (text.trim() === '') return undefined;\n\n const value = Number(text);\n if (Number.isNaN(value)) throw new Error('Not a number');\n return value;\n};\n\n/** The editor type a column uses when it names none. */\nexport const editorKind = (editor: CellEditor | undefined): BuiltInCellEditor | 'custom' => {\n if (editor === undefined) return 'text';\n return typeof editor === 'function' ? 'custom' : editor;\n};\n\n/** Turns what an editor holds into the value to store: strings of text editors are parsed, then everything is validated. */\nexport const resolveEdit = (raw: unknown, editor: CellEditor | undefined, rules: ValueRules, change: Omit<CellValueChange, 'newValue'>): EditResult => {\n const kind = editorKind(editor);\n const isText = kind === 'text' || kind === 'number';\n const parse = rules.parse ?? (kind === 'number' ? parseNumber : undefined);\n const full = { ...change, newValue: raw };\n try {\n const value = isText && typeof raw === 'string' && parse ? parse(raw, full) : raw;\n const verdict = rules.validate?.(value, { ...full, newValue: value }) ?? true;\n if (verdict === true) return { ok: true, value };\n return { ok: false, message: typeof verdict === 'string' ? verdict : INVALID };\n } catch (error) {\n return { ok: false, message: error instanceof Error && error.message ? error.message : INVALID };\n }\n};\n","import throttle from 'lodash.throttle';\nimport debounce from 'lodash.debounce';\nimport Collection from './utils/collection';\nimport ColumnStore from './utils/column-store';\nimport DataStore from './utils/data-store';\nimport LruCache from './utils/lru-cache';\nimport { getRowId } from './utils/selectors';\nimport styles from './component.css?inline';\nimport Loading from './utils/loading';\nimport Layer from './utils/layer';\nimport RendererRegistry from './utils/renderer-registry';\nimport CellBackground from './cell-background';\nimport HeaderRenderer from './header';\nimport CellValueRenderer from './cell-value';\nimport { defaultTextStyle } from './text';\nimport type { TextStyle } from './text';\nimport { resolveFont } from './utils/inherited-font';\nimport { createColorCheck, isCssFont, isSameTheme, readTheme, THEME_DEFAULTS } from './utils/theme';\nimport type { Theme, ThemeName } from './utils/theme';\nimport { borderAt, buildOffsets, clampWidth, columnAt } from './utils/column-layout';\nimport { SORT_INDICATOR_AREA } from './sort-indicator';\nimport SelectionModel, {\n columnLevel,\n contains,\n crossIndex,\n dragScrollSpeed,\n lineIndex,\n linePosition,\n lineRange,\n rangeFor,\n resolve,\n rowLevel,\n shapeOf,\n} from './utils/selection';\nimport type { Axis } from './utils/selection';\nimport { moveTarget, revealOffset, stepAfterEdit, stepWithin } from './utils/selection-navigation';\nimport { toTsv } from './utils/clipboard';\nimport ContextMenu from './utils/context-menu';\nimport { createEditor, startsByTyping } from './utils/cell-editors';\nimport { resolveEdit } from './utils/edit-value';\nimport type { EditResult } from './utils/edit-value';\nimport type { LayerOptions } from './utils/layer';\nimport type {\n BuiltInCellEditor,\n CellContext,\n CellEditable,\n CellEditContext,\n CellEditEndDetail,\n CellEditor,\n CellEditorContext,\n CellEditorInstance,\n CellEditStartDetail,\n CellFocusDetail,\n CellPosition,\n CellRange,\n CellRenderer,\n CellState,\n CellValueChange,\n CellValueChangedDetail,\n ContextMenuDetail,\n ContextMenuItem,\n CustomCellEditor,\n EditOutOfView,\n GridSelection,\n Key,\n RendererRef,\n RowId,\n RowInput,\n SelectionChangeDetail,\n SelectionCopyDetail,\n SelectionLevel,\n SelectionMode,\n SelectOption,\n SortDirection,\n SortKey,\n} from './types';\nimport type { RowIdGetter } from './utils/data-store';\nimport type { Row } from './utils/row-store';\n\nconst classes = {\n scrollArea: 'scrollArea',\n resizeGuide: 'resizeGuide',\n horizontalGuide: 'horizontal',\n};\n\n/** How far from a column border the pointer still grabs it, in CSS px. Fingers are less precise than mice. */\nconst RESIZE_GRAB = { mouse: 4, touch: 12 };\n/** Longest a live `columnresizing` event is held back while dragging, in ms. */\nconst RESIZE_EVENT_INTERVAL_MS = 50;\n/** Most rows measured by auto-fit; the rows in view are what counts, and 100k rows must not make it slow. */\nconst AUTO_SIZE_SAMPLE_ROWS = 500;\n/** How far a touch may move and still count as a tap, in CSS px. */\nconst TAP_SLOP = 8;\n\n/** Layers and renderers every grid starts with. */\nconst builtIn = {\n background: 'background',\n content: 'content',\n selection: 'selection',\n header: 'header',\n backgroundRenderer: 'background',\n valueRenderer: 'value',\n headerRenderer: 'header',\n};\n\nconst BUILT_IN_LAYERS = [builtIn.background, builtIn.content, builtIn.selection, builtIn.header];\n\n/** What the grid remembers about a cell between frames. */\ninterface CellEntry {\n /** The raw value last drawn, and its formatted text; formatting only runs when the value differs. */\n value: unknown;\n formatted: string | undefined;\n animating: boolean;\n state: CellState;\n}\n\nconst STYLE_ELEMENT_ID = 'canvas-grid-styles';\n\nconst injectStyles = () => {\n if (document.getElementById(STYLE_ELEMENT_ID)) return;\n const style = document.createElement('style');\n style.id = STYLE_ELEMENT_ID;\n style.textContent = styles;\n document.head.appendChild(style);\n};\n\nconst parentOf = (element: Element) => {\n const root = element.getRootNode();\n return element.parentElement ?? (root instanceof ShadowRoot ? root.host : null);\n};\n\n/** The element and everything above it, out of shadow roots too. */\nconst ancestorsOf = (element: Element) => {\n const chain: Element[] = [];\n for (let current: Element | null = element; current; current = parentOf(current)) chain.push(current);\n return chain;\n};\n\nexport interface ColumnHeader {\n index: number;\n id: Key;\n displayName?: string;\n width: number;\n /** Narrowest the column can get when resized, in px. Defaults to 20. */\n minWidth?: number;\n /** Widest the column can get when resized, in px. Defaults to unlimited. */\n maxWidth?: number;\n /** Whether the user can drag this column's right border. Defaults to `true`; `setColumnWidth` ignores it. */\n resizable?: boolean;\n /** Renderers drawing a cell of this column, in order. Defaults to the grid's `cellRenderers`. */\n renderers?: RendererRef[];\n valueFormatter: (value: unknown) => string;\n /** CSS font of this column's cells, instead of the grid's `font`. Not `'inherit'`: that is the grid's. */\n font?: string;\n /** CSS font of this column's header, instead of the grid's `headerFont`. */\n headerFont?: string;\n /** Renderer drawing the header of this column. */\n headerRenderer: RendererRef;\n /** Whether the user can edit this column's cells: `true`, or a function asked per cell. Defaults to `false`. `startEditing` follows it too. */\n editable?: CellEditable;\n /** Editor over the cell: `'text'` (default), `'number'`, `'checkbox'`, `{ type: 'select', options }`, or a function building a custom one. */\n cellEditor?: CellEditor;\n /** Turns the text of the text and number editors into the value to store; throw to mark the text invalid. Defaults to the text, or a number for `'number'`. */\n valueParser?: (text: string, change: CellValueChange) => unknown;\n /** Says whether a parsed value may be stored: `true`, or `false` / a message for an invalid-state editor that cannot be committed. */\n validator?: (value: unknown, change: CellValueChange) => boolean | string;\n /** Applies a committed edit instead of the grid storing it. Return `false` to reject the edit and keep the editor open. */\n valueSetter?: (change: CellValueChange) => boolean | void;\n}\n\n/** What `getColumnState` returns and `setColumnState` takes: enough to restore the column widths later. */\nexport interface ColumnState {\n id: Key;\n width: number;\n}\n\n/** What triggered a resize: the user dragging or double-clicking a border, `autoSizeColumns`, or code calling `setColumnWidth` / `setColumnState`. */\nexport type ColumnResizeSource = 'drag' | 'auto' | 'api';\n\nexport interface ColumnResizeDetail {\n columnId: Key;\n width: number;\n source: ColumnResizeSource;\n}\n\nexport type ColumnDefinition = Key | (Partial<ColumnHeader> & { id: Key });\n\nexport interface Transaction {\n add?: RowInput[];\n remove?: RowInput[];\n update?: RowInput[];\n}\n\ninterface AgApi {\n setRowData: (data: RowInput[]) => void;\n updateRowData: (transaction: Transaction) => void;\n setColumnDefs: (columns: ColumnDefinition[]) => void;\n getRowNodeId: RowIdGetter;\n}\n\nexport type {\n BuiltInCellEditor,\n CellContext,\n CellEditable,\n CellEditContext,\n CellEditEndDetail,\n CellEditor,\n CellEditorContext,\n CellEditorInstance,\n CellEditStartDetail,\n CellFocusDetail,\n CellPosition,\n CellRange,\n CellRenderer,\n CellState,\n CellValueChange,\n CellValueChangedDetail,\n ContextMenuDetail,\n ContextMenuItem,\n CustomCellEditor,\n EditOutOfView,\n GridSelection,\n LayerOptions,\n RendererRef,\n SelectionChangeDetail,\n SelectionCopyDetail,\n SelectionMode,\n SelectOption,\n SortDirection,\n SortKey,\n};\n\nexport interface RowResizeDetail {\n rowId: RowId;\n height: number;\n source: RowResizeSource;\n}\n\n/** What triggered a row resize: the user dragging a row-number border, or code calling `setRowHeightById`. */\nexport type RowResizeSource = 'drag' | 'api';\n\ntype ResizeTarget = { axis: 'column'; column: ColumnHeader } | { axis: 'row'; row: Row };\n\n/** A border being dragged: where the pointer started, the size at that point, and when the last live event went out. */\ninterface DragProgress {\n start: number;\n startSize: number;\n lastEvent: number;\n}\n\ntype ColumnDrag = DragProgress & { axis: 'column'; column: ColumnHeader };\n\ntype RowDrag = DragProgress & { axis: 'row'; row: Row };\n\ntype ResizeDrag = ColumnDrag | RowDrag;\n\n/** Which keys change what a click does: shift extends the selection, ctrl or cmd adds a range to it. */\ninterface PointerModifiers {\n extend: boolean;\n additive: boolean;\n}\n\n/** What a press can select: a cell, a whole column (header), a whole row (row number), or everything (the corner). */\ntype SelectionHit =\n | { zone: 'cell'; row: number; column: number }\n | { zone: 'column'; column: number }\n | { zone: 'row'; row: number }\n | { zone: 'all' };\n\n/** A selection being dragged out with the pointer, from `anchor` to wherever the pointer is. */\ninterface SelectionDrag {\n pointerId: number;\n anchor: CellPosition;\n /** Set when the drag started on column headers (`'column'`) or row numbers (`'row'`) and selects whole columns or rows. */\n axis: Axis | undefined;\n /** Pointer position in client coordinates. */\n x: number;\n y: number;\n /** Pending animation frame of the scrolling that continues while the pointer rests outside the grid. */\n frame: number | undefined;\n}\n\n/** The cell being edited, the editor over it and the value the cell had when editing began. */\ninterface EditSession {\n cell: CellEditContext;\n instance: CellEditorInstance;\n wrapper: HTMLElement;\n}\n\n/** A touch that may turn out to be a tap; a touch that moves is a scroll instead. */\ninterface TouchTap {\n pointerId: number;\n x: number;\n y: number;\n hit: SelectionHit;\n modifiers: PointerModifiers;\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'canvas-grid': CanvasGridComponent;\n }\n\n interface HTMLElementEventMap {\n columnresizing: CustomEvent<ColumnResizeDetail>;\n columnresized: CustomEvent<ColumnResizeDetail>;\n rowresizing: CustomEvent<RowResizeDetail>;\n rowresized: CustomEvent<RowResizeDetail>;\n selectionchange: CustomEvent<SelectionChangeDetail>;\n cellfocus: CustomEvent<CellFocusDetail>;\n selectioncopy: CustomEvent<SelectionCopyDetail>;\n gridcontextmenu: CustomEvent<ContextMenuDetail>;\n celleditstart: CustomEvent<CellEditStartDetail>;\n celleditend: CustomEvent<CellEditEndDetail>;\n cellvaluechanged: CustomEvent<CellValueChangedDetail>;\n }\n}\n\n/** Slack for the frame cap, in ms. */\nconst FRAME_JITTER_MS = 2;\nconst DEFAULT_FONT = '12px sans-serif';\nconst DEFAULT_HEADER_FONT = '13px sans-serif';\n\nclass CanvasGridComponent extends HTMLElement {\n /** Maximum redraw rate. */\n fps = 60;\n /** Theme read from the CSS custom properties, `refreshTheme` keeps it current. Explicit options win over it. */\n private theme: Theme = THEME_DEFAULTS.dark;\n _font: string | undefined = undefined;\n _headerFont: string | undefined = undefined;\n _headerHeight: number | undefined = undefined;\n _cellHeight: number | undefined = undefined;\n cellPadding = {\n top: 3,\n right: 3,\n bottom: 3,\n left: 3,\n };\n showRowNumbers = true;\n showHeaders = true;\n rowNumbersWidth = 30;\n ellipsis = '…';\n private _backgroundColor: string | undefined = undefined;\n private _headerBackgroundColor: string | undefined = undefined;\n private _textColor: string | undefined = undefined;\n /** Tint of selected cells; set it, then call `forceDraw`. */\n selectionColor: string | undefined = undefined;\n /** Colour of the outline of a selection and of the border around the active cell. */\n selectionBorderColor: string | undefined = undefined;\n\n /** Cell background; set it to override `--cg-background`, `undefined` hands it back to the theme. */\n get backgroundColor(): string {\n return this._backgroundColor ?? this.theme.background;\n }\n\n set backgroundColor(color: string | undefined) {\n this._backgroundColor = color;\n this.applyTheme();\n }\n\n /** Header background; overrides `--cg-header-background`. An empty string hides the corner above the row numbers. */\n get headerBackgroundColor(): string {\n return this._headerBackgroundColor ?? this.theme.headerBackground;\n }\n\n set headerBackgroundColor(color: string | undefined) {\n this._headerBackgroundColor = color;\n this.applyTheme();\n }\n\n /** Text colour of cells and headers; overrides `--cg-text-color` and `--cg-header-text-color`. */\n get textColor(): string {\n return this._textColor ?? this.theme.text;\n }\n\n set textColor(color: string | undefined) {\n this._textColor = color;\n this.applyTheme();\n }\n\n get headerHeight() {\n return this._headerHeight ?? this.theme.headerHeight;\n }\n\n set headerHeight(height: number) {\n this._headerHeight = height;\n }\n\n get cellHeight() {\n return this._cellHeight ?? this.theme.rowHeight;\n }\n\n set cellHeight(height: number) {\n this._cellHeight = height;\n }\n dataStore = new DataStore({\n getRowId: (row, index) => this.getRowId(row, index),\n getCellHeight: () => this.cellHeight,\n getRowHeight: id => this.newRowHeight(id),\n });\n _dataCollection = this.dataStore.rows;\n /** Per-cell memory of the rows drawn recently; bounded, since only the rows in view need it. */\n cellEntries = new LruCache<Record<string, CellEntry>>(2048);\n getRowId: RowIdGetter = getRowId;\n headers = new Collection<ColumnHeader>();\n animationFrame: number | undefined = undefined;\n scrollYOffset = 0;\n prevScrollYOffset = 0;\n scrollXOffset = 0;\n prevScrollXOffset = 0;\n lastRender = new Date().valueOf();\n lastDraw = this.lastRender;\n isScrolling = false;\n scrollHelper = document.createElement('div');\n scrollArea = this.createScrollArea();\n\n /** Canvases from bottom to top. */\n layers: Layer[] = [];\n private readonly layersByName = new Map<string, Layer>();\n private readonly warnedLayers = new Set<string>();\n renderers = new RendererRegistry();\n /** Renderers drawing a cell when its column does not name its own. */\n cellRenderers: RendererRef[] = [builtIn.backgroundRenderer, builtIn.valueRenderer];\n\n cellBackgroundRenderer = new CellBackground({\n layer: builtIn.background,\n background: this.theme.background,\n enableFlashing: true,\n flashInDuration: 200,\n flashOutDuration: 400,\n flashColor: this.theme.flash,\n zebraColor: this.theme.zebra,\n hoverColor: this.theme.hover,\n borderRightWidth: 1,\n borderRightColor: this.theme.border,\n borderBottomWidth: 1,\n borderBottomColor: this.theme.border,\n });\n\n cellValueRenderer = new CellValueRenderer({\n layer: builtIn.content,\n font: this.theme.font,\n color: this.theme.text,\n });\n\n headerCellRenderer = new HeaderRenderer({\n layer: builtIn.header,\n font: this.theme.headerFont,\n color: this.theme.headerText,\n background: this.theme.headerBackground,\n selectedBackground: this.theme.headerSelected,\n fullySelectedBackground: this.theme.headerFullySelected,\n borderRightWidth: 1,\n borderRightColor: this.theme.headerBorder,\n borderBottomWidth: 1,\n borderBottomColor: this.theme.headerBottomBorder,\n });\n\n loadingIndicator: Loading;\n /** Reused for every cell drawn; see CellContext. */\n private readonly cell: CellContext;\n private readonly placeholderState: CellState = {};\n throttleTransation = throttle(() => {\n const prevSize = this.totalHeight;\n const moved = this.dataStore.flush();\n if (prevSize !== this.totalHeight) {\n this.refreshScrollbar();\n }\n this.refitSelection();\n // rows that were removed or re-sorted changed position, and a normal draw only repaints cells whose value changed\n if (moved) this.forceDraw();\n this.requestRender();\n }, 50);\n\n agApi: AgApi;\n\n constructor() {\n super();\n\n this.resize = this.resize.bind(this);\n this.setValues = this.setValues.bind(this);\n this.setColumns = this.setColumns.bind(this);\n this.clearValues = this.clearValues.bind(this);\n this.updateLastRender = this.updateLastRender.bind(this);\n this.transaction = this.transaction.bind(this);\n this.queueUpdate = this.queueUpdate.bind(this);\n\n this.addLayer(builtIn.background, { alpha: false });\n this.addLayer(builtIn.content);\n this.addLayer(builtIn.header);\n this.registerRenderer(builtIn.backgroundRenderer, this.cellBackgroundRenderer);\n this.registerRenderer(builtIn.valueRenderer, this.cellValueRenderer);\n this.registerRenderer(builtIn.headerRenderer, this.headerCellRenderer);\n this.loadingIndicator = new Loading({ ctx: this.requireLayer(builtIn.header).ctx });\n this.cell = {\n ctx: this.requireLayer(builtIn.content).ctx,\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n row: undefined,\n column: undefined,\n value: undefined,\n formatted: '',\n updatedAt: undefined,\n age: Infinity,\n now: 0,\n dt: 0,\n valueChanged: false,\n forced: false,\n isScrolling: false,\n selected: 'none',\n state: {},\n };\n\n const component = this;\n this.agApi = {\n setRowData: this.setValues,\n updateRowData: this.transaction,\n setColumnDefs: this.setColumns,\n get getRowNodeId() {\n return component.getRowId;\n },\n set getRowNodeId(getId) {\n if (typeof getId === 'function') component.getRowId = getId;\n },\n };\n }\n\n /** Canvas of the content layer, which also defines the viewport size. */\n get canvas() {\n return this.requireLayer(builtIn.content).canvas;\n }\n\n get flashInDuration() {\n return this.cellBackgroundRenderer.options.flashInDuration;\n }\n\n set flashInDuration(flashInDuration: number) {\n this.cellBackgroundRenderer.update({ flashInDuration });\n }\n\n get flashOutDuration() {\n return this.cellBackgroundRenderer.options.flashOutDuration;\n }\n\n set flashOutDuration(flashOutDuration: number) {\n this.cellBackgroundRenderer.update({ flashOutDuration });\n }\n\n getLayer(name: string) {\n return this.layersByName.get(name);\n }\n\n private requireLayer(name: string) {\n const layer = this.getLayer(name);\n if (!layer) throw new Error(`canvas-grid: no layer named \"${name}\"`);\n return layer;\n }\n\n /** Adds a canvas on top of the existing layers, or below the layer named in `before`. */\n addLayer(name: string, { alpha = true, desynchronized = false, before }: LayerOptions = {}) {\n if (this.getLayer(name)) throw new Error(`canvas-grid: layer \"${name}\" already exists`);\n\n const layer = new Layer(name, { alpha, desynchronized });\n const next = before === undefined ? undefined : this.requireLayer(before);\n this.layers.splice(next ? this.layers.indexOf(next) : this.layers.length, 0, layer);\n this.layersByName.set(name, layer);\n // the constructor already runs on elements that are in the document, before connectedCallback mounted anything\n if (this.scrollArea.parentElement === this) {\n this.insertBefore(layer.canvas, next?.canvas ?? this.scrollArea);\n layer.resize(this.clientWidth, this.clientHeight, this.pixelRatio);\n this.forceDraw();\n }\n return layer;\n }\n\n removeLayer(name: string) {\n const layer = this.requireLayer(name);\n this.layers = this.layers.filter(candidate => candidate !== layer);\n this.layersByName.delete(name);\n layer.canvas.remove();\n }\n\n /** Makes a renderer available to columns under `name`; registering an existing name replaces it. */\n registerRenderer(name: string, renderer: CellRenderer) {\n this.renderers.register(name, renderer);\n }\n\n unregisterRenderer(name: string) {\n this.renderers.unregister(name);\n }\n\n createScrollArea() {\n const scrollArea = document.createElement('div');\n scrollArea.className = classes.scrollArea;\n scrollArea.appendChild(this.scrollHelper);\n return scrollArea;\n }\n\n set font(font: string) {\n if (this._font !== font) {\n this._font = font;\n this.cellValueRenderer.font = resolveFont(font, getComputedStyle(this), DEFAULT_FONT);\n }\n }\n\n get font() {\n return this._font ?? this.theme.font;\n }\n\n set headerFont(font: string) {\n if (this._headerFont !== font) {\n this._headerFont = font;\n this.headerCellRenderer.font = resolveFont(font, getComputedStyle(this), DEFAULT_HEADER_FONT);\n }\n }\n\n get headerFont() {\n return this._headerFont ?? this.theme.headerFont;\n }\n\n private textStyle: TextStyle = { ...defaultTextStyle };\n\n private setTextStyle(style: Partial<TextStyle>) {\n this.textStyle = { ...this.textStyle, ...style };\n this.cellValueRenderer.setTextStyle(this.textStyle);\n this.headerCellRenderer.setTextStyle(this.textStyle);\n this.forceDraw();\n }\n\n /** Canvas `textRendering` for cells and headers: `'auto'` (default), `'optimizeSpeed'`, `'optimizeLegibility'` or `'geometricPrecision'`. */\n set textRendering(textRendering: TextStyle['textRendering']) {\n this.setTextStyle({ textRendering });\n }\n\n get textRendering() {\n return this.textStyle.textRendering;\n }\n\n /** Canvas `fontKerning` for cells and headers: `'auto'` (default), `'normal'` or `'none'`. */\n set fontKerning(fontKerning: TextStyle['fontKerning']) {\n this.setTextStyle({ fontKerning });\n }\n\n get fontKerning() {\n return this.textStyle.fontKerning;\n }\n\n /** Extra space after each character as a CSS length, `'0px'` by default. */\n set letterSpacing(letterSpacing: string) {\n this.setTextStyle({ letterSpacing });\n }\n\n get letterSpacing() {\n return this.textStyle.letterSpacing;\n }\n\n /**\n * What happens to text wider than its cell: `'clip'` (default) cuts it off at the cell edge and measures nothing,\n * `'ellipsis'` shortens it and ends it with an ellipsis, which means measuring the text.\n */\n set textOverflow(textOverflow: TextStyle['textOverflow']) {\n this.setTextStyle({ textOverflow });\n }\n\n get textOverflow() {\n return this.textStyle.textOverflow;\n }\n\n /** `'ltr'` (default), `'rtl'`, or `'auto'` to pick the direction per cell from its first letter. */\n set direction(direction: TextStyle['direction']) {\n this.setTextStyle({ direction });\n }\n\n get direction() {\n return this.textStyle.direction;\n }\n\n connectedCallback() {\n this.layers.forEach(layer => this.appendChild(layer.canvas));\n this.appendChild(this.scrollArea);\n this.appendChild(this.resizeGuide);\n\n this.updateLastRender();\n this.refreshTheme();\n this.refreshFonts();\n this.watchTheme();\n if (this.headers.length === 0) this.setColumns(Array(50).fill(1).map((_, index) => index));\n\n document.addEventListener('visibilitychange', this.onVisibilityChange);\n this.observeSize();\n this.pixelRatioQuery = window.matchMedia(`(resolution: ${this.pixelRatio}dppx)`);\n this.pixelRatioQuery.addEventListener('change', this.watchPixelRatio, { once: true });\n\n if (document.fonts) {\n document.fonts.addEventListener('loadingdone', this.onFontsLoaded);\n } else {\n this.fontsTimeout = setTimeout(this.onFontsLoaded, 2000);\n }\n\n const debounceAfterScroll = debounce(() => {\n this.isScrolling = false;\n }, 200);\n this.scrollArea.addEventListener('pointermove', this.onPointerMove);\n this.scrollArea.addEventListener('pointerleave', this.onPointerLeave);\n this.scrollArea.addEventListener('pointerdown', this.onResizePointerDown);\n this.scrollArea.addEventListener('pointermove', this.onResizePointerMove);\n this.scrollArea.addEventListener('pointerup', this.onResizePointerEnd);\n this.scrollArea.addEventListener('pointercancel', this.onResizePointerEnd);\n this.scrollArea.addEventListener('dblclick', this.onResizeDoubleClick);\n this.scrollArea.addEventListener('touchstart', this.onResizeTouchStart, { passive: false });\n // after the resize listeners, which claim a press on a border first\n this.scrollArea.addEventListener('pointerdown', this.onSelectPointerDown);\n this.scrollArea.addEventListener('pointermove', this.onSelectPointerMove);\n this.scrollArea.addEventListener('pointerup', this.onSelectPointerEnd);\n this.scrollArea.addEventListener('pointercancel', this.onSelectPointerEnd);\n this.scrollArea.addEventListener('dblclick', this.onEditDoubleClick);\n this.addEventListener('keydown', this.onKeyDown);\n this.addEventListener('copy', this.onCopy);\n this.addEventListener('contextmenu', this.onContextMenu);\n // the offsets are read once per frame in `render`, so a scroll event costs nothing and no frame shows a stale position\n this.scrollArea.addEventListener('scroll', () => {\n this.contextMenu?.close();\n this.isScrolling = true;\n this.updateHoveredRow();\n debounceAfterScroll();\n this.requestRender();\n });\n }\n\n /** Rows whose cells must be redrawn because the hover highlight moved off or onto them. */\n private hoverDirty: (number | undefined)[] = [];\n\n private setHoveredRow(index: number | undefined) {\n const previous = this.cellBackgroundRenderer.hoveredRowIndex;\n if (previous === index) return;\n\n this.cellBackgroundRenderer.hover(index);\n // added to, not replaced: the pointer can cross several rows before the next frame, and each needs its redraw\n this.hoverDirty.push(previous, index);\n this.requestRender();\n }\n\n /** Pointer position relative to the grid, kept to find the hovered row again after scrolling. */\n private pointerY: number | undefined = undefined;\n\n private updateHoveredRow() {\n if (this.pointerY === undefined) return;\n\n const y = this.pointerY - (this.showHeaders ? this.headerHeight : 0);\n const index = this._dataCollection.indexAt(y + this.scrollArea.scrollTop);\n this.setHoveredRow(y < 0 || index >= this._dataCollection.length ? undefined : index);\n }\n\n private readonly onPointerMove = (event: PointerEvent) => {\n this.pointerY = event.clientY - this.getBoundingClientRect().top;\n this.updateHoveredRow();\n };\n\n private readonly onPointerLeave = () => {\n this.pointerY = undefined;\n this.setHoveredRow(undefined);\n };\n\n private fontsTimeout: ReturnType<typeof setTimeout> | undefined = undefined;\n\n private readonly onVisibilityChange = () => {\n if (document.visibilityState === 'hidden') {\n this.cancelRender();\n return;\n }\n this.resize();\n };\n\n /**\n * Re-reads the fonts and redraws. Call it after changing the CSS font of the grid or its ancestors\n * while `font` / `headerFont` are `'inherit'`. Web fonts finishing to load trigger it too.\n */\n refreshFonts() {\n this.cellValueRenderer.font = resolveFont(this.font, getComputedStyle(this), DEFAULT_FONT);\n this.headerCellRenderer.font = resolveFont(this.headerFont, getComputedStyle(this), DEFAULT_HEADER_FONT);\n this.renderers.clearCaches();\n this.resize();\n }\n\n private readonly onFontsLoaded = () => this.refreshFonts();\n\n private themeQuery: MediaQueryList | undefined = undefined;\n private themeObserver: MutationObserver | undefined = undefined;\n private colorCheck: ((value: string) => boolean) | undefined = undefined;\n\n /** The `theme` attribute when it names a theme, else the colour scheme the page prefers. */\n private get themeName(): ThemeName {\n const attribute = this.getAttribute('theme');\n if (attribute === 'light' || attribute === 'dark') return attribute;\n return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';\n }\n\n /**\n * Re-reads the `--cg-*` custom properties and redraws when a value changed. Runs by itself when the colour scheme,\n * the `theme` attribute or the `class`, `style` or `data-theme` attribute of the grid or an ancestor change;\n * call it after changing the tokens any other way, such as a stylesheet rule that is toggled.\n */\n refreshTheme() {\n const style = getComputedStyle(this);\n this.colorCheck ??= createColorCheck(document.createElement('canvas').getContext('2d') ?? { fillStyle: '' });\n const next = readTheme(this.themeName, {\n read: token => style.getPropertyValue(token),\n isColor: this.colorCheck,\n isFont: isCssFont,\n });\n if (isSameTheme(next, this.theme)) return;\n\n const sizeChanged = next.rowHeight !== this.theme.rowHeight || next.headerHeight !== this.theme.headerHeight;\n this.theme = next;\n if (sizeChanged) this.syncThemeHeights();\n this.applyTheme();\n }\n\n /** Hands the theme, with the explicit options on top, to the renderers and redraws. */\n private applyTheme() {\n const { theme } = this;\n this.cellBackgroundRenderer.update({\n background: this.backgroundColor,\n borderRightColor: theme.border,\n borderBottomColor: theme.border,\n zebraColor: theme.zebra,\n hoverColor: theme.hover,\n flashColor: theme.flash,\n });\n this.headerCellRenderer.update({\n background: this.headerBackgroundColor,\n color: this._textColor ?? theme.headerText,\n selectedBackground: theme.headerSelected,\n fullySelectedBackground: theme.headerFullySelected,\n borderRightColor: theme.headerBorder,\n borderBottomColor: theme.headerBottomBorder,\n });\n this.cellValueRenderer.color = this.textColor;\n this.loadingIndicator.setColor(this.textColor);\n this.refreshFonts();\n }\n\n /** Row heights follow `--cg-row-height` until `cellHeight`, `setRowHeight` or a drag sets them. */\n private syncThemeHeights() {\n if (this._cellHeight === undefined && this.rowHeightOf === undefined) this._dataCollection.setHeights(id => this.heightOfRow(id));\n this.refreshRowHeights();\n this.refreshScrollbar();\n }\n\n private readonly onThemeChange = () => this.refreshTheme();\n\n private watchTheme() {\n this.themeQuery = window.matchMedia('(prefers-color-scheme: light)');\n this.themeQuery.addEventListener('change', this.onThemeChange);\n this.themeObserver = new MutationObserver(this.onThemeChange);\n ancestorsOf(this).forEach(element => this.themeObserver?.observe(element, { attributes: true, attributeFilter: ['class', 'style', 'theme', 'data-theme'] }));\n }\n\n private unwatchTheme() {\n this.themeQuery?.removeEventListener('change', this.onThemeChange);\n this.themeObserver?.disconnect();\n }\n\n cancelRender() {\n if (this.animationFrame !== undefined) cancelAnimationFrame(this.animationFrame);\n this.animationFrame = undefined;\n }\n\n /**\n * Schedules a draw for the next animation frame. Nothing is drawn while the grid is idle:\n * scrolling, data changes and resizes request a draw, and `draw` requests the next one itself while a cell animates.\n */\n requestRender() {\n this.animationFrame ??= requestAnimationFrame(() => this.render());\n }\n\n updateLastRender() {\n this.lastRender = new Date().valueOf();\n }\n\n render() {\n this.animationFrame = undefined;\n this.readScrollOffsets();\n if (this.relayoutPending) {\n this.relayoutPending = false;\n this.forceDraw();\n this.updateLastRender();\n return;\n }\n const delta = new Date().valueOf() - this.lastRender;\n // the frame cap is for animations; scrolling draws on every frame, or it would visibly lag behind the scrollbar\n // a little under the frame time: frames arrive a fraction early or late, and would otherwise be skipped by turns\n if (!this.isScrolling && delta < (1000 / this.fps) - FRAME_JITTER_MS) {\n this.requestRender();\n return;\n }\n this.draw();\n this.updateLastRender();\n }\n\n private readScrollOffsets() {\n this.scrollXOffset = Math.round(this.scrollArea.scrollLeft);\n this.scrollYOffset = Math.round(this.scrollArea.scrollTop);\n }\n\n hasScrolled() {\n return this.hasXScrolled() || this.hasYScrolled();\n }\n\n hasYScrolled() {\n return this.prevScrollYOffset !== this.scrollYOffset;\n }\n\n hasXScrolled() {\n return this.prevScrollXOffset !== this.scrollXOffset;\n }\n\n isInViewport(x = 0, y = 0, width = 0, height = 0) {\n if (x > this.viewportWidth) return false;\n if (y > this.viewportHeight) return false;\n if (x + width < 0) return false;\n if (y + height < 0) return false;\n\n return true;\n }\n\n /** Fills the shared context for something that is not a data cell: a header, row number or placeholder. */\n private describe(x: number, y: number, width: number, height: number, overrides: Partial<CellContext>) {\n return Object.assign(this.cell, {\n x,\n y,\n width,\n height,\n row: undefined,\n column: undefined,\n value: undefined,\n formatted: '',\n updatedAt: undefined,\n age: Infinity,\n valueChanged: true,\n forced: true,\n selected: 'none',\n state: this.placeholderState,\n }, overrides);\n }\n\n private paint(ref: RendererRef) {\n const renderer = this.renderers.resolve(ref);\n const layer = renderer && this.layersByName.get(renderer.layer);\n if (renderer && !layer && !this.warnedLayers.has(renderer.layer)) {\n this.warnedLayers.add(renderer.layer);\n console.warn(`canvas-grid: renderer draws on missing layer \"${renderer.layer}\"`);\n }\n if (!renderer || !layer) return;\n\n this.cell.ctx = layer.ctx;\n renderer.draw(this.cell);\n }\n\n private paintAll(refs: readonly RendererRef[]) {\n refs.forEach(ref => this.paint(ref));\n }\n\n private isAnimating(refs: readonly RendererRef[]) {\n return refs.some(ref => this.renderers.resolve(ref)?.isAnimating?.(this.cell) === true);\n }\n\n draw(forced = false) {\n if (this.edit) this.positionEditor();\n const now = new Date().valueOf();\n const redrawAll = forced || this.hasScrolled();\n this.cell.now = now;\n this.cell.dt = now - this.lastDraw;\n this.cell.isScrolling = this.isScrolling;\n this.lastDraw = now;\n // everything visible is painted again after a scroll, so custom layers start clean: a renderer that only clears its own cell\n // would leave what it drew at the old position in the gaps between cells\n if (!forced && this.hasScrolled()) this.clearCustomLayers();\n // the loading indicator animates until there is data\n let keepDrawing = this._dataCollection.length === 0;\n\n if ((forced || this.hasXScrolled() || this.headersDirty) && this.showHeaders) {\n this.renderHeaders();\n }\n\n const fakeRows = 200;\n if (forced && this.showRowNumbers && this._dataCollection.length === 0) {\n for (let fakeRowIndex= 0; fakeRowIndex <= fakeRows; fakeRowIndex++) {\n this.renderRowNumber({ index: fakeRowIndex }, (fakeRowIndex * this.cellHeight) + (this.showHeaders ? this.headerHeight : 0) - this.scrollYOffset);\n }\n }\n\n if (this._dataCollection.length === 0) {\n this.loadingIndicator.render();\n for (let fakeRowIndex= 0; fakeRowIndex <= fakeRows; fakeRowIndex++) {\n this.headers.forEach(header => {\n this.describe(\n Math.round(this.columnOffsets[header.index] + (this.showRowNumbers ? this.rowNumbersWidth : 0) - this.scrollXOffset),\n Math.round((fakeRowIndex * this.cellHeight) + (this.showHeaders ? this.headerHeight : 0) - this.scrollYOffset),\n header.width,\n this.cellHeight,\n { column: header, valueChanged: false },\n );\n this.paintAll(header.renderers ?? this.cellRenderers);\n });\n }\n }\n\n const originY = Math.round((this.showHeaders ? this.headerHeight : 0) - this.scrollYOffset);\n const xOffset = Math.round((this.showRowNumbers ? this.rowNumbersWidth : 0) - this.scrollXOffset);\n // only the rows overlapping the viewport: found by offset instead of walking from the first row\n const firstRow = this._dataCollection.indexAt(-originY);\n const visibleColumns = this.getVisibleColumns(xOffset);\n for (let rowIndex = firstRow; rowIndex < this._dataCollection.length; rowIndex++) {\n const row = this._dataCollection.at(rowIndex);\n const currentY = originY + this._dataCollection.topOf(rowIndex);\n if (!row || currentY >= this.viewportHeight) break;\n\n const { id: key, slot } = row;\n\n if ((forced || this.hasYScrolled() || this.headersDirty) && this.showRowNumbers) {\n this.renderRowNumber(row, currentY);\n }\n\n if (row.height + currentY > 0) {\n let entries = this.cellEntries.get(String(key));\n if (!entries) {\n entries = {};\n this.cellEntries.set(String(key), entries);\n }\n const cellRow = { id: key, index: row.index };\n\n for (const { header, id: columnKey, x, store } of visibleColumns) {\n const value = store?.get(slot);\n if (value === undefined) continue;\n\n const entry = entries[columnKey] ??= { value: undefined, formatted: undefined, animating: false, state: {} };\n // values are only formatted for the cells being drawn, and again only once they change\n const formatted = entry.formatted !== undefined && entry.value === value ? entry.formatted : header.valueFormatter(value);\n const valueChanged = entry.formatted !== formatted;\n const updatedAt = store?.getUpdatedAt(slot);\n\n const { cell } = this;\n cell.x = x;\n cell.y = currentY;\n cell.width = Math.round(header.width);\n cell.height = row.height;\n cell.row = cellRow;\n cell.column = header;\n cell.value = value;\n cell.formatted = formatted;\n cell.updatedAt = updatedAt;\n cell.age = updatedAt === undefined ? Infinity : now - updatedAt;\n cell.valueChanged = valueChanged;\n cell.forced = redrawAll;\n cell.selected = 'none';\n cell.state = entry.state;\n const refs = header.renderers ?? this.cellRenderers;\n const animating = this.isAnimating(refs);\n // an animation gets one last frame after it stops, so its final state is what stays on screen\n if (redrawAll || valueChanged || animating || entry.animating || this.hoverDirty.includes(rowIndex)) this.paintAll(refs);\n entry.animating = animating;\n entry.value = value;\n entry.formatted = formatted;\n keepDrawing ||= animating;\n }\n }\n }\n if (redrawAll || this.selectionDirty) this.renderSelection();\n if (this.scrollYOffset > 0 || this.scrollXOffset > 0) {\n this.renderBrick();\n }\n this.hoverDirty = [];\n this.selectionDirty = false;\n this.headersDirty = false;\n this.prevScrollYOffset = this.scrollYOffset;\n this.prevScrollXOffset = this.scrollXOffset;\n if (keepDrawing) this.requestRender();\n }\n\n /** The columns overlapping the viewport horizontally, with their x position and values; found once per draw, not per row. */\n private getVisibleColumns(xOffset: number) {\n const visible: { header: ColumnHeader; id: string; x: number; store: ColumnStore | undefined }[] = [];\n const { columnList, columnOffsets } = this;\n for (let index = Math.max(0, columnAt(columnOffsets, -xOffset)); index < columnList.length; index++) {\n const x = xOffset + columnOffsets[index];\n if (x > this.viewportWidth) break;\n\n const header = columnList[index];\n visible.push({ header, id: String(header.id), x, store: this.dataStore.columns.get(String(header.id)) });\n }\n return visible;\n }\n\n /** Columns in display order, and where each starts; rebuilt when columns or widths change. */\n private columnList: ColumnHeader[] = [];\n\n private columnOffsets: number[] = [0];\n\n private updateColumnLayout() {\n this.columnList = [];\n this.headers.forEach(header => this.columnList.push(header));\n this.columnOffsets = buildOffsets(this.columnList.map(header => header.width));\n }\n\n /** The selection must be drawn again on the next frame. */\n private selectionDirty = false;\n\n /** The headers and row numbers must be drawn again, because the selection they show changed. */\n private headersDirty = false;\n\n /** How much of a column is selected, for its header. */\n private columnSelection(index: number): SelectionLevel {\n const { ranges } = this.selectionModel;\n return ranges.length === 0 ? 'none' : columnLevel(ranges, index, this._dataCollection.length);\n }\n\n /** How much of a row is selected, for its row number. */\n private rowSelection(index: number): SelectionLevel {\n const { ranges } = this.selectionModel;\n return ranges.length === 0 ? 'none' : rowLevel(ranges, index, this.columnList.length);\n }\n\n /** Whether the selection layer holds anything, so a grid that never selects never clears it. */\n private selectionDrawn = false;\n\n /** Tints each selected range and outlines the active cell: one rectangle per range, however many cells it covers. */\n private renderSelection() {\n const { ranges, active } = this.selectionModel;\n if (ranges.length === 0 && !this.selectionDrawn) return;\n\n const layer = this.getLayer(builtIn.selection);\n if (!layer) return;\n\n const { ctx } = layer;\n layer.clear();\n this.selectionDrawn = ranges.length > 0;\n if (!this.selectionDrawn) return;\n\n const left = this.showRowNumbers ? this.rowNumbersWidth : 0;\n const top = this.showHeaders ? this.headerHeight : 0;\n const originX = left - this.scrollXOffset;\n const originY = top - this.scrollYOffset;\n const { _dataCollection: rows, columnOffsets } = this;\n const rectOf = (range: CellRange) => {\n const bounds = resolve(range, rows.length, this.columnList.length);\n if (!bounds) return undefined;\n\n const x = originX + columnOffsets[bounds.left];\n const y = originY + rows.topOf(bounds.top);\n return { x, y, width: originX + columnOffsets[bounds.right + 1] - x, height: originY + rows.topOf(bounds.bottom + 1) - y };\n };\n\n ctx.save();\n ctx.beginPath();\n ctx.rect(left, top, this.viewportWidth - left, this.viewportHeight - top);\n ctx.clip();\n ctx.fillStyle = this.selectionColor ?? this.theme.selection;\n ctx.strokeStyle = this.selectionBorderColor ?? this.theme.selectionBorder;\n ctx.lineWidth = 1;\n ranges.map(rectOf).forEach(rect => {\n if (!rect) return;\n ctx.fillRect(rect.x, rect.y, rect.width, rect.height);\n ctx.strokeRect(rect.x + 0.5, rect.y + 0.5, rect.width - 1, rect.height - 1);\n });\n const cell = active && rectOf({ rows: [active.row, active.row], columns: [active.column, active.column] });\n if (cell) {\n // the active cell is left untinted, like in a spreadsheet\n ctx.clearRect(cell.x, cell.y, cell.width, cell.height);\n ctx.lineWidth = 2;\n ctx.strokeRect(cell.x + 1, cell.y + 1, cell.width - 2, cell.height - 2);\n }\n ctx.restore();\n }\n\n renderRowNumber(row: { index: number; height?: number }, y: number) {\n if (!this.isInViewport(0, y, this.rowNumbersWidth, row.height)) return;\n this.describe(0, Math.ceil(y), this.rowNumbersWidth, row.height ?? 0, {\n row: { id: row.index, index: row.index },\n formatted: `${row.index + 1}`,\n selected: this.rowSelection(row.index),\n });\n this.paint(builtIn.headerRenderer);\n }\n\n private clearCustomLayers() {\n this.layers.filter(layer => !BUILT_IN_LAYERS.includes(layer.name)).forEach(layer => layer.clear());\n }\n\n forceDraw() {\n this.layers.forEach(layer => layer.clear());\n this.draw(true);\n }\n\n /** Viewport size in CSS pixels as of the last resize; cached because reading `clientWidth` per cell is slow. */\n viewportWidth = 0;\n\n viewportHeight = 0;\n\n /** Device pixels per CSS pixel; canvases are scaled by it to stay sharp on HiDPI screens. */\n get pixelRatio() {\n return window.devicePixelRatio || 1;\n }\n\n /** Resizes the layers when the size or pixel ratio changed, then redraws everything. */\n resize() {\n this.cancelRender();\n const { pixelRatio } = this;\n this.viewportWidth = this.clientWidth;\n this.viewportHeight = this.clientHeight;\n this.layers.forEach(layer => layer.resize(this.clientWidth, this.clientHeight, pixelRatio));\n if (this.cellValueRenderer.pixelRatio !== pixelRatio) {\n this.renderers.clearCaches();\n }\n this.cellValueRenderer.pixelRatio = pixelRatio;\n this.headerCellRenderer.pixelRatio = pixelRatio;\n this.forceDraw();\n }\n\n /** Redraws when the element changes size, instead of checking on every frame. */\n private observeSize() {\n this.resizeObserver ??= new ResizeObserver(() => this.resize());\n this.resizeObserver.observe(this);\n }\n\n /** The pixel ratio changes with browser zoom or when the window moves to another screen. */\n private watchPixelRatio = () => {\n this.pixelRatioQuery?.removeEventListener('change', this.watchPixelRatio);\n this.pixelRatioQuery = window.matchMedia(`(resolution: ${this.pixelRatio}dppx)`);\n this.pixelRatioQuery.addEventListener('change', this.watchPixelRatio, { once: true });\n this.resize();\n };\n\n private resizeObserver: ResizeObserver | undefined = undefined;\n\n private pixelRatioQuery: MediaQueryList | undefined = undefined;\n\n /** A row's position and height along with its values by column id, or undefined for an unknown row. */\n getRowData(rowId: RowId) {\n const row = this._dataCollection.get(rowId);\n if (!row) return undefined;\n\n const values: Record<string, unknown> = {};\n this.dataStore.columns.forEach((column, key) => {\n const value = column.get(row.slot);\n if (value !== undefined) values[key] = value;\n });\n return { id: row.id, index: row.index, height: row.height, values };\n }\n\n /** Orders the rows by the given columns, in priority order; an empty list restores the original order. */\n setSortModel(model: readonly SortKey[]) {\n this.dataStore.setSortModel(model);\n this.headerCellRenderer.setSortModel(model);\n this.forceDraw();\n }\n\n getSortModel() {\n return this.dataStore.getSortModel();\n }\n\n renderBrick() {\n if (this.showHeaders && this.showRowNumbers && this.headerBackgroundColor) {\n this.describe(0, 0, this.rowNumbersWidth, this.headerHeight, {});\n this.paint(builtIn.headerRenderer);\n }\n }\n\n renderHeaders() {\n const xOffset = (this.showRowNumbers ? this.rowNumbersWidth : 0) - this.scrollXOffset;\n\n this.getVisibleColumns(xOffset).forEach(({ header, x }) => {\n this.describe(x, 0, Math.round(header.width), this.headerHeight, {\n column: header,\n formatted: header.displayName ?? '',\n selected: this.columnSelection(header.index),\n });\n this.paint(header.headerRenderer);\n });\n\n if (this.scrollXOffset + this.rowNumbersWidth > 0) {\n this.renderBrick();\n }\n }\n\n getColumnHeader(key: Key) {\n return this.headers.get(key);\n }\n\n /** Redraws everything on the next frame, without waiting for the frame cap; for changes that move cells, like resizing. */\n private requestRelayout() {\n this.relayoutPending = true;\n this.requestRender();\n }\n\n private relayoutPending = false;\n\n private emitResized(type: 'columnresized' | 'columnresizing', column: ColumnHeader, source: ColumnResizeSource) {\n this.dispatchEvent(new CustomEvent<ColumnResizeDetail>(type, { detail: { columnId: column.id, width: column.width, source } }));\n }\n\n /** Sets the widths within each column's limits and refreshes the layout once; returns the columns that actually changed. */\n private applyColumnWidths(widths: Iterable<[Key, number]>) {\n const changed = Array.from(widths)\n .map(([id, width]) => ({ column: this.headers.get(id), width }))\n .filter(({ column, width }) => column !== undefined && clampWidth(width, column.minWidth, column.maxWidth) !== Math.round(column.width))\n .flatMap(({ column, width }) => (column === undefined ? [] : [{ column, width: clampWidth(width, column.minWidth, column.maxWidth) }]))\n .map(({ column, width }) => Object.assign(column, { width }));\n if (changed.length === 0) return changed;\n\n this.updateColumnLayout();\n this.refreshScrollbar();\n this.requestRelayout();\n return changed;\n }\n\n /** Sets a column's width in px, within its `minWidth` / `maxWidth`, and fires `columnresized` when it changed. Works for columns that are not `resizable`. */\n setColumnWidth(id: Key, width: number) {\n this.applyColumnWidths([[id, width]]).forEach(column => this.emitResized('columnresized', column, 'api'));\n }\n\n /** The widths of all columns, in display order; pass it to `setColumnState` to restore them. */\n getColumnState(): ColumnState[] {\n return this.columnList.map(({ id, width }) => ({ id, width: Math.round(width) }));\n }\n\n /** Restores widths from `getColumnState`; unknown columns are skipped. Fires `columnresized` for each column that changed. */\n setColumnState(state: readonly ColumnState[]) {\n this.applyColumnWidths(state.map(({ id, width }): [Key, number] => [id, width]))\n .forEach(column => this.emitResized('columnresized', column, 'api'));\n }\n\n private measureContext: CanvasRenderingContext2D | null | undefined = undefined;\n\n /**\n * Fits columns (all of them by default) to their content: the header and the rows in view, at most\n * `AUTO_SIZE_SAMPLE_ROWS` of them, so it stays fast with any number of rows. Fires `columnresized` for each that changed.\n */\n autoSizeColumns(ids?: readonly Key[]) {\n this.measureContext ??= document.createElement('canvas').getContext('2d');\n const ctx = this.measureContext;\n if (!ctx) return;\n\n const { scrollTop } = this.scrollArea;\n const rows: Row[] = [];\n for (let index = this._dataCollection.indexAt(scrollTop); index < this._dataCollection.length && rows.length < AUTO_SIZE_SAMPLE_ROWS; index++) {\n const row = this._dataCollection.at(index);\n if (!row || this._dataCollection.topOf(index) > scrollTop + this.viewportHeight) break;\n rows.push(row);\n }\n\n const padding = this.cellPadding.left + this.cellPadding.right + 1;\n const widest = (font: string, texts: Iterable<string>) => {\n ctx.font = font;\n return Math.max(0, ...Array.from(texts, text => ctx.measureText(text).width));\n };\n const widths = (ids ?? this.columnList.map(({ id }) => id))\n .flatMap(id => this.headers.get(id) ?? [])\n .map((column): [Key, number] => {\n const store = this.dataStore.columns.get(String(column.id));\n const texts = rows.flatMap(({ slot }) => store?.get(slot) ?? []).map(value => column.valueFormatter(value));\n const header = widest(column.headerFont ?? this.headerCellRenderer.font, [column.displayName ?? '']) + padding + SORT_INDICATOR_AREA;\n const content = widest(column.font ?? this.cellValueRenderer.font, texts) + padding;\n return [column.id, Math.ceil(Math.max(header, content))];\n });\n this.applyColumnWidths(widths).forEach(column => this.emitResized('columnresized', column, 'auto'));\n }\n\n /** Smallest row height the user can drag to, or a row-height function can return. */\n private static readonly MIN_ROW_HEIGHT = 8;\n\n /** Heights set for single rows by dragging or `setRowHeightById`, by row id; they win over `setRowHeight`'s function. */\n private readonly rowHeightOverrides = new Map<string, number>();\n\n private rowHeightOf: ((id: RowId) => number) | undefined = undefined;\n\n private heightOfRow(id: RowId) {\n const height = this.rowHeightOverrides.get(String(id)) ?? this.rowHeightOf?.(id) ?? this.cellHeight;\n return Math.max(CanvasGridComponent.MIN_ROW_HEIGHT, Math.round(height));\n }\n\n /** Only asked for rows being added, and only when it can differ from `cellHeight`. */\n private readonly newRowHeight = (id: RowId) =>\n this.rowHeightOverrides.size === 0 && this.rowHeightOf === undefined ? undefined : this.heightOfRow(id);\n\n private refreshRowHeights() {\n this.refreshScrollbar();\n this.requestRelayout();\n }\n\n private emitRowResized(type: 'rowresized' | 'rowresizing', rowId: RowId, source: RowResizeSource) {\n const height = this._dataCollection.get(rowId)?.height;\n if (height !== undefined) this.dispatchEvent(new CustomEvent<RowResizeDetail>(type, { detail: { rowId, height, source } }));\n }\n\n /**\n * Sets the height of every row: a number in px (also the height of rows added later), or a function of the row id\n * returning one, called for existing rows now and for rows as they are added once their values are stored.\n * Replaces the heights of rows resized one by one. Fires no events.\n */\n setRowHeight(height: number | ((id: RowId) => number)) {\n this.rowHeightOverrides.clear();\n if (typeof height === 'function') this.rowHeightOf = height;\n else {\n this.rowHeightOf = undefined;\n this._cellHeight = height;\n }\n this._dataCollection.setHeights(id => this.heightOfRow(id));\n this.refreshRowHeights();\n }\n\n /** Sets one row's height in px (at least 8) and fires `rowresized`; the height sticks to the row through sorting and updates. */\n setRowHeightById(id: RowId, height: number) {\n this.rowHeightOverrides.set(String(id), Math.max(CanvasGridComponent.MIN_ROW_HEIGHT, Math.round(height)));\n if (!this._dataCollection.setHeight(id, this.heightOfRow(id))) return;\n\n this.refreshRowHeights();\n this.emitRowResized('rowresized', id, 'api');\n }\n\n private resizeDrag: ResizeDrag | undefined = undefined;\n\n /** The column border or row border under the pointer, when it can be dragged. */\n private findResizeTarget(clientX: number, clientY: number, pointerType: string): ResizeTarget | undefined {\n const rect = this.getBoundingClientRect();\n const x = clientX - rect.left;\n const y = clientY - rect.top;\n const grab = pointerType === 'touch' ? RESIZE_GRAB.touch : RESIZE_GRAB.mouse;\n // not over the vertical scrollbar\n if (x < 0 || y < 0 || x > this.scrollArea.clientWidth) return undefined;\n\n const rowNumbers = this.showRowNumbers ? this.rowNumbersWidth : 0;\n const headers = this.showHeaders ? this.headerHeight : 0;\n if (this.showHeaders && y <= headers) return this.findColumnBorder(x - rowNumbers, grab);\n if (this.showRowNumbers && x < rowNumbers) return this.findRowBorder(y - headers, grab);\n return undefined;\n }\n\n private findColumnBorder(x: number, grab: number): ResizeTarget | undefined {\n if (x < 0) return undefined;\n\n const column = this.columnList[borderAt(this.columnOffsets, x + this.scrollArea.scrollLeft, grab)];\n return column === undefined || column.resizable === false ? undefined : { axis: 'column', column };\n }\n\n private findRowBorder(y: number, grab: number): ResizeTarget | undefined {\n const row = this._dataCollection.at(this._dataCollection.borderAt(y + this.scrollArea.scrollTop, grab));\n return row === undefined ? undefined : { axis: 'row', row };\n }\n\n private moveResizeGuide() {\n const { resizeDrag, resizeGuide } = this;\n resizeGuide.style.display = resizeDrag ? 'block' : 'none';\n if (!resizeDrag) return;\n\n const horizontal = resizeDrag.axis === 'row';\n resizeGuide.classList.toggle(classes.horizontalGuide, horizontal);\n const column = this.showRowNumbers ? this.rowNumbersWidth : 0;\n const header = this.showHeaders ? this.headerHeight : 0;\n resizeGuide.style.transform = resizeDrag.axis === 'row'\n ? `translateY(${header + this._dataCollection.topOf(resizeDrag.row.index) + resizeDrag.row.height - this.scrollArea.scrollTop}px)`\n : `translateX(${column + (this.columnOffsets[resizeDrag.column.index + 1] ?? 0) - this.scrollArea.scrollLeft}px)`;\n }\n\n private readonly resizeGuide = Object.assign(document.createElement('div'), { className: classes.resizeGuide });\n\n private readonly onResizePointerDown = (event: PointerEvent) => {\n const target = event.button === 0 ? this.findResizeTarget(event.clientX, event.clientY, event.pointerType) : undefined;\n if (!target) return;\n\n event.preventDefault();\n this.scrollArea.setPointerCapture(event.pointerId);\n this.resizeDrag = target.axis === 'row'\n ? { ...target, start: event.clientY, startSize: target.row.height, lastEvent: 0 }\n : { ...target, start: event.clientX, startSize: target.column.width, lastEvent: 0 };\n this.moveResizeGuide();\n };\n\n private readonly onResizePointerMove = (event: PointerEvent) => {\n const { resizeDrag } = this;\n if (!resizeDrag) {\n // the cursor follows the border; touch has no hover\n const target = this.findResizeTarget(event.clientX, event.clientY, event.pointerType);\n this.scrollArea.style.cursor = target === undefined ? '' : `${target.axis === 'row' ? 'row' : 'col'}-resize`;\n return;\n }\n\n if (resizeDrag.axis === 'row') this.dragRow(resizeDrag, event.clientY - resizeDrag.start);\n else this.dragColumn(resizeDrag, event.clientX - resizeDrag.start);\n this.moveResizeGuide();\n };\n\n private dragColumn(drag: ColumnDrag, delta: number) {\n const { column } = drag;\n this.applyColumnWidths([[column.id, drag.startSize + delta]]);\n if (!this.dueForLiveEvent(drag)) return;\n\n this.emitResized('columnresizing', column, 'drag');\n }\n\n private dragRow(drag: RowDrag, delta: number) {\n const { id } = drag.row;\n this.rowHeightOverrides.set(String(id), Math.max(CanvasGridComponent.MIN_ROW_HEIGHT, Math.round(drag.startSize + delta)));\n if (this._dataCollection.setHeight(id, this.heightOfRow(id))) this.refreshRowHeights();\n if (!this.dueForLiveEvent(drag)) return;\n\n this.emitRowResized('rowresizing', id, 'drag');\n }\n\n /** Whether enough time has passed since the last live event; counts this one as sent when it has. */\n private dueForLiveEvent(drag: ResizeDrag) {\n const now = performance.now();\n if (now - drag.lastEvent < RESIZE_EVENT_INTERVAL_MS) return false;\n\n drag.lastEvent = now;\n return true;\n }\n\n private readonly onResizePointerEnd = (event: PointerEvent) => {\n const { resizeDrag } = this;\n if (!resizeDrag) return;\n\n this.resizeDrag = undefined;\n this.scrollArea.releasePointerCapture(event.pointerId);\n this.moveResizeGuide();\n if (resizeDrag.axis === 'row' && resizeDrag.row.height !== resizeDrag.startSize) this.emitRowResized('rowresized', resizeDrag.row.id, 'drag');\n if (resizeDrag.axis === 'column' && resizeDrag.column.width !== resizeDrag.startSize) this.emitResized('columnresized', resizeDrag.column, 'drag');\n };\n\n private readonly onResizeDoubleClick = (event: MouseEvent) => {\n const target = this.findResizeTarget(event.clientX, event.clientY, 'mouse');\n if (target?.axis !== 'column') return;\n\n const { column } = target;\n if (column === this.columnList[this.columnList.length - 1] && this.fillRemainingSpace(column)) return;\n this.autoSizeColumns([column.id]);\n };\n\n /** Widens the last column to the right edge of the viewport when the columns leave it empty; returns whether there was room. */\n private fillRemainingSpace(column: ColumnHeader) {\n const free = this.scrollArea.clientWidth - (this.showRowNumbers ? this.rowNumbersWidth : 0) - this.columnOffsets[this.columnOffsets.length - 1];\n if (free <= 0) return false;\n\n this.applyColumnWidths([[column.id, column.width + free]]).forEach(changed => this.emitResized('columnresized', changed, 'auto'));\n return true;\n }\n\n /** Keeps a touch that starts on a border from scrolling the grid, so the pointer events can drag it instead. */\n private readonly onResizeTouchStart = (event: TouchEvent) => {\n const [touch] = Array.from(event.touches);\n if (event.touches.length === 1 && this.findResizeTarget(touch.clientX, touch.clientY, 'touch')) event.preventDefault();\n };\n\n private readonly selectionModel = new SelectionModel();\n\n private mode: SelectionMode = 'none';\n\n /**\n * What the user can select with the pointer: `'none'` (default), one `'cell'`, `'range'`s of cells with whole rows and columns\n * (like a spreadsheet), or whole `'row'`s or `'column'`s. `getSelection` and `setSelection` work in every mode; switching to `'none'` clears it.\n */\n set selectionMode(mode: SelectionMode) {\n if (mode === this.mode) return;\n\n this.mode = mode;\n this.updateTabIndex();\n if (mode === 'none') this.clearSelection();\n }\n\n /** Whether the grid put `tabindex` on itself, so it is only taken away again when it was not the page's. */\n private ownsTabIndex = false;\n\n /** A grid with selection takes keyboard focus; one without it stays out of the tab order, as before. */\n private updateTabIndex() {\n if (this.mode !== 'none' && !this.hasAttribute('tabindex')) {\n this.tabIndex = 0;\n this.ownsTabIndex = true;\n }\n if (this.mode === 'none' && this.ownsTabIndex) {\n this.removeAttribute('tabindex');\n this.ownsTabIndex = false;\n }\n }\n\n get selectionMode() {\n return this.mode;\n }\n\n /** The selected ranges and the active cell, by displayed position; the ranges are copies. */\n getSelection(): GridSelection {\n return this.selectionModel.snapshot();\n }\n\n /**\n * Selects the given ranges, with `active` in focus (the first cell of the last range by default). A range that leaves out `rows` or `columns`\n * covers all of them. Positions beyond the data are cut off when it changes. Fires `selectionchange`, and `cellfocus` when the active cell moved.\n */\n setSelection(ranges: readonly CellRange[], active?: CellPosition) {\n this.changeSelection(() => this.selectionModel.replace(ranges, active), false);\n }\n\n clearSelection() {\n this.changeSelection(() => this.selectionModel.clear(), false);\n }\n\n private emitSelectionChange(selecting: boolean) {\n this.dispatchEvent(new CustomEvent<SelectionChangeDetail>('selectionchange', { detail: { ...this.selectionModel.snapshot(), selecting } }));\n }\n\n private emitCellFocus() {\n const { active } = this.selectionModel;\n const row = active && this._dataCollection.at(active.row);\n const column = active && this.columnList[active.column];\n if (!active || !row || !column) return;\n\n this.dispatchEvent(new CustomEvent<CellFocusDetail>('cellfocus', {\n detail: { rowId: row.id, rowIndex: active.row, columnId: column.id, columnIndex: active.column },\n }));\n }\n\n /** Applies a change to the selection, then redraws it and fires the events if something differs. */\n private changeSelection(change: () => boolean, selecting: boolean) {\n const previous = this.selectionModel.active && { ...this.selectionModel.active };\n if (!change()) return false;\n\n // a canvas is only worth its memory and compositing once something is selected\n if (this.selectionModel.ranges.length > 0 && !this.getLayer(builtIn.selection)) this.addLayer(builtIn.selection, { before: builtIn.header });\n this.selectionDirty = true;\n this.headersDirty = true;\n this.requestRender();\n this.emitSelectionChange(selecting);\n const { active } = this.selectionModel;\n if (active && (active.row !== previous?.row || active.column !== previous.column)) this.emitCellFocus();\n return true;\n }\n\n /** Cuts the selection to the data after rows or columns changed, and redraws it: ranges that reach the end follow the data. */\n private refitSelection() {\n if (this.selectionModel.ranges.length === 0) return;\n\n this.changeSelection(() => this.selectionModel.clamp(this._dataCollection.length, this.columnList.length), false);\n this.selectionDirty = true;\n }\n\n private selectDrag: SelectionDrag | undefined = undefined;\n\n private touchTap: TouchTap | undefined = undefined;\n\n /** Where in the grid, in px from its top left, a point of the viewport is. */\n private offsetsOf(clientX: number, clientY: number) {\n const rect = this.getBoundingClientRect();\n const left = this.showRowNumbers ? this.rowNumbersWidth : 0;\n const top = this.showHeaders ? this.headerHeight : 0;\n return { x: clientX - rect.left, y: clientY - rect.top, left, top };\n }\n\n /** Index of the column at `contentX` px from the left of the first column, or undefined past the last one. */\n private columnIndexAt(contentX: number) {\n const column = columnAt(this.columnOffsets, contentX);\n return column < 0 || contentX >= this.columnOffsets[this.columnOffsets.length - 1] ? undefined : column;\n }\n\n /** Index of the row at `contentY` px from the top of the first row, or undefined past the last one. */\n private rowIndexAt(contentY: number) {\n const row = this._dataCollection.indexAt(contentY);\n return row >= this._dataCollection.length ? undefined : row;\n }\n\n /** What is under the pointer that a press can select: a cell, a column header, a row number or the corner. Scrollbars and empty space are nothing. */\n private hitAt(clientX: number, clientY: number): SelectionHit | undefined {\n const { x, y, left, top } = this.offsetsOf(clientX, clientY);\n if (x < 0 || y < 0 || x > this.scrollArea.clientWidth || y > this.scrollArea.clientHeight) return undefined;\n\n const inHeader = y < top;\n const inRowNumbers = x < left;\n const column = this.columnIndexAt(x - left + this.scrollArea.scrollLeft);\n const row = this.rowIndexAt(y - top + this.scrollArea.scrollTop);\n if (inHeader && inRowNumbers) return { zone: 'all' };\n if (inHeader) return column === undefined ? undefined : { zone: 'column', column };\n if (inRowNumbers) return row === undefined ? undefined : { zone: 'row', row };\n return column === undefined || row === undefined ? undefined : { zone: 'cell', row, column };\n }\n\n /** The cell nearest to the pointer, wherever it is: dragging past an edge selects up to that edge. */\n private nearestCell(clientX: number, clientY: number): CellPosition | undefined {\n const rows = this._dataCollection.length;\n if (rows === 0 || this.columnList.length === 0) return undefined;\n\n const { x, y, left, top } = this.offsetsOf(clientX, clientY);\n return {\n row: Math.min(rows - 1, this._dataCollection.indexAt(Math.max(0, y - top) + this.scrollArea.scrollTop)),\n column: columnAt(this.columnOffsets, Math.max(0, x - left) + this.scrollArea.scrollLeft),\n };\n }\n\n /** The row and column a header selection that was just made starts from: those at the top left of the viewport. */\n private firstVisible(axis: Axis) {\n return axis === 'column'\n ? this._dataCollection.indexAt(this.scrollArea.scrollTop)\n : Math.max(0, columnAt(this.columnOffsets, this.scrollArea.scrollLeft));\n }\n\n /**\n * Applies a press on a cell: plain selects it, shift extends from the active cell, ctrl or cmd adds a range.\n * Returns the cell a drag from here starts at.\n */\n private pressCell(cell: CellPosition, { extend, additive }: PointerModifiers, selecting: boolean) {\n const { selectionModel, mode } = this;\n const { active } = selectionModel;\n if (extend && active && mode !== 'cell') {\n const range = rangeFor(mode, active, cell);\n this.changeSelection(() => (additive ? selectionModel.extend(range, cell) : selectionModel.set(range, active, cell)), selecting);\n return { ...active };\n }\n\n const range = rangeFor(mode, cell, cell);\n this.changeSelection(() => (additive && mode !== 'cell' ? selectionModel.add(range, cell) : selectionModel.set(range, cell)), selecting);\n return cell;\n }\n\n /**\n * Applies a press on a column header or row number: it selects the whole column or row, shift extends from the active cell's,\n * ctrl or cmd adds one. Returns the cell a drag from here starts at.\n */\n private pressLine(axis: Axis, index: number, { extend, additive }: PointerModifiers, selecting: boolean) {\n const { selectionModel } = this;\n const { active } = selectionModel;\n if (extend && active) {\n const range = lineRange(axis, lineIndex(axis, active), index);\n const focus = linePosition(axis, index, crossIndex(axis, active));\n this.changeSelection(() => (additive ? selectionModel.extend(range, focus) : selectionModel.set(range, active, focus)), selecting);\n return { ...active };\n }\n\n const cell = linePosition(axis, index, this.firstVisible(axis));\n const range = lineRange(axis, index, index);\n this.changeSelection(() => (additive ? selectionModel.add(range, cell) : selectionModel.set(range, cell)), selecting);\n return cell;\n }\n\n /** Selects everything, keeping the active cell. */\n private selectEverything(selecting: boolean) {\n const active = this.selectionModel.active ?? { row: this.firstVisible('column'), column: this.firstVisible('row') };\n this.changeSelection(() => this.selectionModel.set({}, active), selecting);\n }\n\n /** Which modes a press in each part of the grid selects in; a column header does nothing when only rows can be selected, and so on. */\n private static readonly ZONE_MODES: Record<SelectionHit['zone'], readonly SelectionMode[]> = {\n cell: ['cell', 'range', 'row', 'column'],\n column: ['range', 'column'],\n row: ['range', 'row'],\n all: ['range', 'row', 'column'],\n };\n\n /** Applies a press wherever it landed. Returns the drag it starts, or undefined when there is nothing to drag. */\n private press(hit: SelectionHit, modifiers: PointerModifiers, selecting: boolean): Pick<SelectionDrag, 'anchor' | 'axis'> | undefined {\n if (!CanvasGridComponent.ZONE_MODES[hit.zone].includes(this.mode)) return undefined;\n if (hit.zone === 'all') {\n this.selectEverything(selecting);\n return undefined;\n }\n if (hit.zone === 'column') return { anchor: this.pressLine('column', hit.column, modifiers, selecting), axis: 'column' };\n if (hit.zone === 'row') return { anchor: this.pressLine('row', hit.row, modifiers, selecting), axis: 'row' };\n return { anchor: this.pressCell({ row: hit.row, column: hit.column }, modifiers, selecting), axis: undefined };\n }\n\n private dragSelectTo({ x, y, anchor, axis }: SelectionDrag) {\n const cell = this.nearestCell(x, y);\n if (!cell) return;\n\n if (axis) {\n const focus = linePosition(axis, lineIndex(axis, cell), crossIndex(axis, anchor));\n this.changeSelection(() => this.selectionModel.extend(lineRange(axis, lineIndex(axis, anchor), lineIndex(axis, cell)), focus), true);\n return;\n }\n if (this.mode === 'cell') return;\n\n const range = rangeFor(this.mode, anchor, cell);\n this.changeSelection(() => this.selectionModel.extend(range, cell), true);\n }\n\n private readonly onSelectPointerDown = (event: PointerEvent) => {\n if (this.mode === 'none' || event.button !== 0 || this.resizeDrag) return;\n\n const hit = this.hitAt(event.clientX, event.clientY);\n if (!hit) return;\n\n const modifiers = { extend: event.shiftKey, additive: event.ctrlKey || event.metaKey };\n if (event.pointerType === 'touch') {\n // a touch that moves scrolls, so it only selects when it ends where it started\n this.touchTap = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, hit, modifiers };\n return;\n }\n\n // cancelling the press also cancels the browser's own focusing, so the grid takes focus for the keyboard here\n event.preventDefault();\n this.focus({ preventScroll: true });\n const drag = this.press(hit, modifiers, true);\n if (!drag) return;\n\n this.scrollArea.setPointerCapture(event.pointerId);\n this.selectDrag = { ...drag, pointerId: event.pointerId, x: event.clientX, y: event.clientY, frame: undefined };\n };\n\n private readonly onSelectPointerMove = (event: PointerEvent) => {\n const { touchTap, selectDrag } = this;\n if (touchTap && Math.hypot(event.clientX - touchTap.x, event.clientY - touchTap.y) > TAP_SLOP) this.touchTap = undefined;\n if (!selectDrag || selectDrag.pointerId !== event.pointerId) return;\n\n selectDrag.x = event.clientX;\n selectDrag.y = event.clientY;\n this.dragSelectTo(selectDrag);\n selectDrag.frame ??= requestAnimationFrame(this.scrollWhileDragging);\n };\n\n /** Keeps scrolling, and extending the selection with it, for as long as the pointer is held outside the cells. */\n private readonly scrollWhileDragging = () => {\n const drag = this.selectDrag;\n if (!drag) return;\n\n drag.frame = undefined;\n const { x, y, left, top } = this.offsetsOf(drag.x, drag.y);\n // a drag along the headers only follows the pointer across, and one along the row numbers only down\n const dx = drag.axis === 'row' ? 0 : dragScrollSpeed(x, left, this.scrollArea.clientWidth);\n const dy = drag.axis === 'column' ? 0 : dragScrollSpeed(y, top, this.scrollArea.clientHeight);\n if (dx === 0 && dy === 0) return;\n\n this.scrollArea.scrollBy(dx, dy);\n this.dragSelectTo(drag);\n drag.frame = requestAnimationFrame(this.scrollWhileDragging);\n };\n\n private readonly onSelectPointerEnd = (event: PointerEvent) => {\n const { touchTap, selectDrag } = this;\n if (touchTap?.pointerId === event.pointerId) {\n this.touchTap = undefined;\n if (event.type === 'pointerup') {\n this.focus({ preventScroll: true });\n this.press(touchTap.hit, touchTap.modifiers, false);\n }\n return;\n }\n if (!selectDrag || selectDrag.pointerId !== event.pointerId) return;\n\n this.endSelectDrag();\n if (this.scrollArea.hasPointerCapture(event.pointerId)) this.scrollArea.releasePointerCapture(event.pointerId);\n this.emitSelectionChange(false);\n };\n\n private endSelectDrag() {\n if (this.selectDrag?.frame !== undefined) cancelAnimationFrame(this.selectDrag.frame);\n this.selectDrag = undefined;\n }\n\n /** Scrolls the least that brings a cell fully into view. */\n private revealCell({ row, column }: CellPosition) {\n const { scrollArea, _dataCollection: rows, columnOffsets } = this;\n const { left, top } = this.offsetsOf(0, 0);\n const scrollTop = revealOffset(rows.topOf(row), rows.topOf(row + 1), scrollArea.scrollTop, scrollArea.clientHeight - top);\n const scrollLeft = revealOffset(columnOffsets[column], columnOffsets[column + 1], scrollArea.scrollLeft, scrollArea.clientWidth - left);\n if (scrollTop !== scrollArea.scrollTop) scrollArea.scrollTop = scrollTop;\n if (scrollLeft !== scrollArea.scrollLeft) scrollArea.scrollLeft = scrollLeft;\n }\n\n private get gridSize() {\n const { top } = this.offsetsOf(0, 0);\n return {\n rowCount: this._dataCollection.length,\n columnCount: this.columnList.length,\n pageRows: Math.max(1, Math.floor((this.scrollArea.clientHeight - top) / this.cellHeight)),\n };\n }\n\n /** Selects one cell, or its whole row or column in those modes, and brings it into view. */\n private moveTo(cell: CellPosition) {\n const range = rangeFor(this.mode, cell, cell);\n this.changeSelection(() => this.selectionModel.set(range, cell), false);\n this.revealCell(cell);\n }\n\n /** Stretches the newest range to `cell`; it keeps being whole columns or whole rows when it was, and the active cell stays. */\n private extendTo(cell: CellPosition) {\n const { selectionModel, mode } = this;\n const { active, focus } = selectionModel;\n const last = selectionModel.ranges[selectionModel.ranges.length - 1];\n if (!active || !focus || !last) return;\n\n const shape = shapeOf(last);\n if (shape === 'all') return;\n if (shape === 'block') {\n const range = rangeFor(mode, active, cell);\n this.changeSelection(() => selectionModel.extend(range, cell), false);\n this.revealCell(cell);\n return;\n }\n\n const axis = shape;\n const range = lineRange(axis, lineIndex(axis, active), lineIndex(axis, cell));\n const moved = linePosition(axis, lineIndex(axis, cell), crossIndex(axis, focus));\n this.changeSelection(() => selectionModel.extend(range, moved), false);\n this.revealCell(moved);\n }\n\n /** Moves the active cell inside a selection of several cells; with one cell selected Enter moves the selection, and Tab is left to the page. */\n private stepActive(axis: Axis, backwards: boolean) {\n const { selectionModel } = this;\n const { active } = selectionModel;\n const last = selectionModel.ranges[selectionModel.ranges.length - 1];\n const bounds = last && resolve(last, this._dataCollection.length, this.columnList.length);\n if (!active) return false;\n if (bounds && (bounds.top !== bounds.bottom || bounds.left !== bounds.right)) {\n const next = stepWithin(bounds, active, axis, backwards);\n this.changeSelection(() => selectionModel.activate(next), false);\n this.revealCell(next);\n return true;\n }\n if (axis === 'column') return false;\n\n const target = moveTarget(active, backwards ? 'ArrowUp' : 'ArrowDown', false, this.gridSize);\n if (target) this.moveTo(target);\n return true;\n }\n\n /** Selects the whole column (ctrl+space) or row (shift+space) of the active cell. */\n private selectLineOfActive(axis: Axis) {\n const { active } = this.selectionModel;\n if (!active || !CanvasGridComponent.ZONE_MODES[axis].includes(this.mode)) return false;\n\n const range = lineRange(axis, lineIndex(axis, active), lineIndex(axis, active));\n this.changeSelection(() => this.selectionModel.set(range, active), false);\n return true;\n }\n\n /** Collapses the selection to its active cell. */\n private collapseSelection() {\n const { active } = this.selectionModel;\n if (!active) return false;\n\n const range = rangeFor(this.mode, active, active);\n return this.changeSelection(() => this.selectionModel.set(range, active), false);\n }\n\n /** Moves or extends the selection for a navigation key; the first press just selects the cell at the top left of the view. */\n private navigate(event: KeyboardEvent, ctrl: boolean) {\n const { active, focus } = this.selectionModel;\n const size = this.gridSize;\n if (size.rowCount === 0 || size.columnCount === 0) return false;\n\n const start = { row: this.firstVisible('column'), column: this.firstVisible('row') };\n const extend = event.shiftKey && this.mode !== 'cell';\n const target = moveTarget(active ? (extend && focus) || active : start, event.key, ctrl, size);\n if (!target) return false;\n\n if (!active) this.moveTo(start);\n else if (extend) this.extendTo(target);\n else this.moveTo(target);\n return true;\n }\n\n /** Returns whether the key was a selection key, which is then kept from also scrolling the page. */\n private handleSelectionKey(event: KeyboardEvent) {\n const ctrl = event.ctrlKey || event.metaKey;\n const { key, shiftKey } = event;\n if (ctrl && key.toLowerCase() === 'a') {\n if (!CanvasGridComponent.ZONE_MODES.all.includes(this.mode)) return false;\n this.selectEverything(false);\n return true;\n }\n if (key === ' ' && ctrl) return this.selectLineOfActive('column');\n if (key === ' ' && shiftKey) return this.selectLineOfActive('row');\n if (key === 'Enter') return this.stepActive('row', shiftKey);\n if (key === 'Tab') return this.stepActive('column', shiftKey);\n if (key === 'Escape') return this.collapseSelection();\n return this.navigate(event, ctrl);\n }\n\n private readonly onKeyDown = (event: KeyboardEvent) => {\n if (this.mode === 'none' || event.defaultPrevented || event.altKey) return;\n if (!this.handleEditKey(event) && !this.handleSelectionKey(event)) return;\n\n event.preventDefault();\n };\n\n /** The newest range as tab-separated text of the formatted values, as shown; undefined when nothing is selected. */\n private copiedSelection(): SelectionCopyDetail | undefined {\n const { ranges } = this.selectionModel;\n const range = ranges[ranges.length - 1];\n const bounds = range && resolve(range, this._dataCollection.length, this.columnList.length);\n if (!range || !bounds) return undefined;\n\n const columns = this.columnList.slice(bounds.left, bounds.right + 1)\n .map(header => ({ header, store: this.dataStore.columns.get(String(header.id)) }));\n const { text, truncated } = toTsv(bounds, (row, column) => {\n const { header, store } = columns[column - bounds.left];\n const value = store?.get(this._dataCollection.at(row)?.slot ?? -1);\n return value === undefined ? '' : header.valueFormatter(value);\n });\n return { text, range: { ...range }, truncated };\n }\n\n /** The selection as it is about to be copied, once `selectioncopy` let it through; undefined when there is nothing to copy or a listener cancelled. */\n private requestCopy() {\n const copied = this.mode === 'none' ? undefined : this.copiedSelection();\n if (!copied) return undefined;\n\n return this.dispatchEvent(new CustomEvent<SelectionCopyDetail>('selectioncopy', { detail: copied, cancelable: true })) ? copied : undefined;\n }\n\n /** Puts the selection on the clipboard when the user copies. `selectioncopy` can change the text or cancel the copy. */\n private readonly onCopy = (event: ClipboardEvent) => {\n const copied = event.clipboardData && this.requestCopy();\n if (!copied || !event.clipboardData) return;\n\n event.clipboardData.setData('text/plain', copied.text);\n event.preventDefault();\n };\n\n /**\n * Copies the newest selected range to the clipboard, as the copy shortcut does, `selectioncopy` included.\n * Resolves to whether anything was copied. Browsers allow it from a user action only, such as a click.\n */\n async copySelection() {\n const copied = this.requestCopy();\n if (!copied) return false;\n\n await navigator.clipboard.writeText(copied.text);\n return true;\n }\n\n /** The entries of the context menu. Replace them to change the menu; an empty list keeps the browser's own menu. */\n contextMenuItems: ContextMenuItem[] = [\n { id: 'edit', label: 'Edit', disabled: ({ row, column }) => !this.canEditAt(row, column), run: ({ row, column }) => void this.editAt(row, column) },\n { id: 'copy', label: 'Copy', disabled: () => this.selectionModel.ranges.length === 0, run: () => void this.copySelection() },\n ];\n\n private contextMenu: ContextMenu | undefined;\n\n private menuDetail: ContextMenuDetail | undefined;\n\n /** Whether a right click on this hit already has what it selects selected; those that do keep their selection. */\n private isSelected(hit: SelectionHit) {\n const { ranges } = this.selectionModel;\n if (hit.zone === 'cell') return ranges.some(range => contains(range, hit.row, hit.column));\n if (hit.zone === 'column') return columnLevel(ranges, hit.column, this._dataCollection.length) === 'full';\n if (hit.zone === 'row') return rowLevel(ranges, hit.row, this.columnList.length) === 'full';\n return ranges.some(range => shapeOf(range) === 'all');\n }\n\n /** Where the menu opens for a key press: the corner of the active cell, or of the grid's cells. */\n private menuAnchor(): { x: number; y: number } {\n const { x, y, left, top } = this.offsetsOf(0, 0);\n const { active } = this.selectionModel;\n if (!active) return { x: left - x, y: top - y };\n\n return {\n x: left - x + this.columnOffsets[active.column] - this.scrollArea.scrollLeft,\n y: top - y + this._dataCollection.topOf(active.row + 1) - this.scrollArea.scrollTop,\n };\n }\n\n /** Opens the context menu on a right click, a long press or the menu key, once `gridcontextmenu` let it. */\n private readonly onContextMenu = (event: MouseEvent) => {\n if (this.mode === 'none' || this.contextMenuItems.length === 0 || event.defaultPrevented) return;\n\n // the menu key and Shift+F10 report no button 2, and a position that is not where the user is looking\n const byPointer = event.button === 2;\n const hit = byPointer ? this.hitAt(event.clientX, event.clientY) : undefined;\n if (byPointer && !hit) return;\n\n event.preventDefault();\n this.focus({ preventScroll: true });\n if (hit && !this.isSelected(hit)) this.press(hit, { extend: false, additive: false }, false);\n\n const anchor = byPointer ? { x: event.clientX, y: event.clientY } : this.menuAnchor();\n const active = this.selectionModel.active;\n const detail: ContextMenuDetail = {\n ...this.selectionModel.snapshot(),\n ...anchor,\n row: hit ? (hit.zone === 'cell' || hit.zone === 'row' ? hit.row : undefined) : active?.row,\n column: hit ? (hit.zone === 'cell' || hit.zone === 'column' ? hit.column : undefined) : active?.column,\n items: [...this.contextMenuItems],\n };\n if (!this.dispatchEvent(new CustomEvent<ContextMenuDetail>('gridcontextmenu', { detail, cancelable: true }))) return;\n if (detail.items.length === 0) return;\n\n this.menuDetail = detail;\n this.contextMenu ??= new ContextMenu(this, id => this.menuDetail?.items.find(item => item.id === id)?.run(this.menuDetail));\n this.contextMenu.open(detail.x, detail.y, detail.items.map(({ id, label, disabled }) => ({\n id,\n label,\n disabled: typeof disabled === 'function' ? disabled(detail) : disabled ?? false,\n })));\n };\n\n /** What happens to an edit when its cell scrolls out of view: `'cancel'` (default) drops it, `'commit'` writes it, `'keep'` hides the editor until the cell is back. */\n editOutOfView: EditOutOfView = 'cancel';\n\n private edit: EditSession | undefined;\n\n private cellOf(rowId: RowId, columnId: Key): CellEditContext | undefined {\n const row = this._dataCollection.get(rowId);\n const column = this.headers.get(columnId);\n if (!row || !column) return undefined;\n\n return { rowId: row.id, rowIndex: row.index, columnId: column.id, columnIndex: column.index, value: this.dataStore.getValue(row.id, column.id) };\n }\n\n private canEdit(cell: CellEditContext) {\n const editable = this.headers.get(cell.columnId)?.editable;\n return typeof editable === 'function' ? editable(cell) : editable === true;\n }\n\n /**\n * Puts an editor over a cell, committing the edit in progress first. Returns whether one opened: the cell has to exist and be `editable`,\n * and a cancelled `celleditstart` or an edit that cannot be committed stop it. The cell is scrolled into view.\n */\n startEditing(rowId: RowId, columnId: Key) {\n return this.openEditor(rowId, columnId, undefined);\n }\n\n /** Ends the edit in progress: commits it, or drops it with `cancel`. Returns false when there was none, or the value is invalid or rejected, which keeps the editor open. */\n stopEditing(cancel = false) {\n return this.finishEdit(cancel);\n }\n\n private openEditor(rowId: RowId, columnId: Key, initialText: string | undefined) {\n const cell = this.cellOf(rowId, columnId);\n if (!cell || !this.canEdit(cell) || !this.finishEditIfOpen()) return false;\n if (!this.dispatchEvent(new CustomEvent<CellEditStartDetail>('celleditstart', { detail: cell, cancelable: true }))) return false;\n\n this.revealCell({ row: cell.rowIndex, column: cell.columnIndex });\n const instance = createEditor(this.headers.get(columnId)?.cellEditor, {\n ...cell,\n initialText,\n commit: () => void this.finishEdit(false),\n cancel: () => void this.finishEdit(true),\n });\n const wrapper = document.createElement('div');\n wrapper.className = 'cellEditor';\n wrapper.style.colorScheme = this.themeName;\n // the resolved theme, which also covers a page that sets the theme by option rather than by CSS\n wrapper.style.background = this.backgroundColor;\n wrapper.style.color = this.textColor;\n wrapper.style.outlineColor = this.theme.selectionBorder;\n // for parts that leave the wrapper, such as the dropdown's list in the top layer\n wrapper.style.setProperty('--cg-editor-background', this.backgroundColor);\n wrapper.style.setProperty('--cg-editor-text', this.textColor);\n wrapper.style.setProperty('--cg-editor-border', this.theme.border);\n wrapper.style.setProperty('--cg-editor-accent', this.theme.selectionBorder);\n wrapper.style.setProperty('--cg-editor-highlight', this.theme.selection);\n wrapper.style.setProperty('--cg-editor-padding-left', `${this.cellPadding.left}px`);\n wrapper.style.setProperty('--cg-editor-padding-right', `${this.cellPadding.right}px`);\n wrapper.style.font = this.headers.get(columnId)?.font ?? this.font;\n wrapper.append(instance.element);\n wrapper.addEventListener('keydown', this.onEditorKeyDown);\n wrapper.addEventListener('focusout', this.onEditorFocusOut);\n wrapper.addEventListener('input', () => this.showValidity());\n wrapper.addEventListener('change', () => this.showValidity());\n this.append(wrapper);\n this.edit = { cell, instance, wrapper };\n this.positionEditor();\n if (instance.focus) instance.focus();\n else instance.element.focus({ preventScroll: true });\n return true;\n }\n\n private finishEditIfOpen() {\n return !this.edit || this.finishEdit(false);\n }\n\n /** The editor's value parsed and validated against the value the cell holds now. */\n private checkEdit(edit: EditSession): EditResult {\n const column = this.headers.get(edit.cell.columnId);\n const oldValue = this.dataStore.getValue(edit.cell.rowId, edit.cell.columnId);\n return resolveEdit(\n edit.instance.getValue(),\n column?.cellEditor,\n { parse: column?.valueParser, validate: column?.validator },\n { ...edit.cell, value: oldValue, oldValue },\n );\n }\n\n private showValidity(result?: EditResult) {\n const { edit } = this;\n if (!edit) return;\n\n const { ok, message } = { message: undefined, ...(result ?? this.checkEdit(edit)) };\n edit.wrapper.classList.toggle('invalid', !ok);\n edit.wrapper.title = message ?? '';\n edit.instance.element.setAttribute('aria-invalid', String(!ok));\n }\n\n /** Writes a committed value, through the column's `valueSetter` when it has one. Returns false when that rejected it. */\n private applyEdit(edit: EditSession, newValue: unknown) {\n const { cell } = edit;\n const oldValue = this.dataStore.getValue(cell.rowId, cell.columnId);\n // an untouched cell is left alone, so a value streamed in meanwhile is not overwritten by the stale one the editor started from\n if (newValue === cell.value) return true;\n\n const setter = this.headers.get(cell.columnId)?.valueSetter;\n if (setter && setter({ ...cell, value: oldValue, oldValue, newValue }) === false) return false;\n if (!setter && this.dataStore.setValue(cell.rowId, cell.columnId, newValue)) this.forceDraw();\n if (!setter) this.requestRender();\n this.dispatchEvent(new CustomEvent<CellValueChangedDetail>('cellvaluechanged', { detail: { ...cell, value: newValue, oldValue, newValue } }));\n return true;\n }\n\n private finishEdit(cancel: boolean) {\n const { edit } = this;\n if (!edit) return false;\n\n const result = cancel ? undefined : this.checkEdit(edit);\n if (result && !result.ok) {\n this.showValidity(result);\n return false;\n }\n const newValue = result?.ok ? result.value : undefined;\n if (result && !this.applyEdit(edit, newValue)) {\n this.showValidity({ ok: false, message: 'Rejected' });\n return false;\n }\n\n this.closeEditor(edit);\n this.dispatchEvent(new CustomEvent<CellEditEndDetail>('celleditend', { detail: { ...edit.cell, cancelled: cancel, newValue } }));\n return true;\n }\n\n private closeEditor({ wrapper, instance }: EditSession) {\n const hadFocus = wrapper.contains(document.activeElement);\n this.edit = undefined;\n instance.destroy?.();\n wrapper.remove();\n if (hadFocus) this.focus({ preventScroll: true });\n }\n\n /** Keeps the editor on its cell as the grid scrolls, resizes or re-sorts; applies `editOutOfView` once the cell is gone from the view. */\n private positionEditor() {\n const { edit, scrollArea, columnOffsets } = this;\n if (!edit) return;\n\n const cell = this.cellOf(edit.cell.rowId, edit.cell.columnId);\n if (!cell) {\n this.finishEdit(true);\n return;\n }\n edit.cell.rowIndex = cell.rowIndex;\n edit.cell.columnIndex = cell.columnIndex;\n\n const { left, top } = this.offsetsOf(0, 0);\n const rows = this._dataCollection;\n const x = left + columnOffsets[cell.columnIndex] - Math.round(scrollArea.scrollLeft);\n const y = top + rows.topOf(cell.rowIndex) - Math.round(scrollArea.scrollTop);\n const width = columnOffsets[cell.columnIndex + 1] - columnOffsets[cell.columnIndex];\n const height = rows.topOf(cell.rowIndex + 1) - rows.topOf(cell.rowIndex);\n // the part under the headers, the row numbers or the scrollbars is cut off, so the editor never covers them\n const cut = {\n top: Math.max(0, top - y),\n right: Math.max(0, x + width - scrollArea.clientWidth),\n bottom: Math.max(0, y + height - scrollArea.clientHeight),\n left: Math.max(0, left - x),\n };\n const hidden = cut.top >= height || cut.bottom >= height || cut.left >= width || cut.right >= width;\n if (hidden && this.editOutOfView !== 'keep' && this.finishEdit(this.editOutOfView === 'cancel')) return;\n\n const { style } = edit.wrapper;\n style.left = `${x}px`;\n style.top = `${y}px`;\n style.width = `${width}px`;\n style.height = `${height}px`;\n // clipped rather than hidden, which would take the focus away\n style.clipPath = hidden ? 'inset(100%)' : `inset(${cut.top}px ${cut.right}px ${cut.bottom}px ${cut.left}px)`;\n style.pointerEvents = hidden ? 'none' : '';\n edit.instance.place?.(!hidden);\n }\n\n /** Enter and Tab commit and move the selection on, Escape drops the edit; the keys stay inside the editor, which the grid would otherwise act on. */\n private readonly onEditorKeyDown = (event: KeyboardEvent) => {\n event.stopPropagation();\n const { edit } = this;\n const { key, shiftKey } = event;\n if (!edit || event.isComposing || !['Escape', 'Enter', 'Tab'].includes(key)) return;\n\n event.preventDefault();\n const { rowIndex: row, columnIndex: column } = edit.cell;\n if (!this.finishEdit(key === 'Escape') || key === 'Escape' || this.mode === 'none') return;\n\n const target = stepAfterEdit({ row, column }, key === 'Enter' ? 'row' : 'column', shiftKey, this.gridSize);\n this.moveTo(target);\n };\n\n /** Leaving the editor commits it, or drops it when its value is invalid. Switching windows leaves it be. */\n private readonly onEditorFocusOut = (event: FocusEvent) => {\n const { edit } = this;\n if (!edit || !document.hasFocus() || (event.relatedTarget instanceof Node && edit.wrapper.contains(event.relatedTarget))) return;\n if (!this.finishEdit(false)) this.finishEdit(true);\n };\n\n /** The cell at a displayed row and column, when both exist. */\n private cellAt(row: number | undefined, column: number | undefined) {\n const rowData = row === undefined ? undefined : this._dataCollection.at(row);\n const header = column === undefined ? undefined : this.columnList[column];\n return rowData && header ? this.cellOf(rowData.id, header.id) : undefined;\n }\n\n private canEditAt(row: number | undefined, column: number | undefined) {\n const cell = this.cellAt(row, column);\n return cell !== undefined && this.canEdit(cell);\n }\n\n private editAt(row: number | undefined, column: number | undefined) {\n const cell = this.cellAt(row, column);\n return cell !== undefined && this.openEditor(cell.rowId, cell.columnId, undefined);\n }\n\n private readonly onEditDoubleClick = (event: MouseEvent) => {\n const hit = this.hitAt(event.clientX, event.clientY);\n if (hit?.zone === 'cell') this.editAt(hit.row, hit.column);\n };\n\n /** Starts editing the active cell for F2, Enter (with a single cell selected) or a typed character, which begins the text. */\n private handleEditKey(event: KeyboardEvent) {\n const { active, ranges } = this.selectionModel;\n const row = active && this._dataCollection.at(active.row);\n const column = active && this.columnList[active.column];\n if (!row || !column) return false;\n\n const { key, shiftKey } = event;\n const bounds = ranges.length === 1 ? resolve(ranges[0], this._dataCollection.length, this.columnList.length) : undefined;\n const single = bounds !== undefined && bounds.top === bounds.bottom && bounds.left === bounds.right;\n const typed = key.length === 1 && !event.ctrlKey && !event.metaKey && !(key === ' ' && shiftKey);\n if (key === 'F2' || (key === 'Enter' && !shiftKey && single)) return this.openEditor(row.id, column.id, undefined);\n return typed && startsByTyping(column.cellEditor) && this.openEditor(row.id, column.id, key);\n }\n\n get totalHeight() {\n return this._dataCollection.totalHeight;\n }\n\n refreshScrollbar() {\n const height = this.totalHeight + this.headerHeight;\n this.scrollHelper.style.height = `${height}px`;\n const width = this.columnOffsets[this.columnOffsets.length - 1];\n this.scrollHelper.style.width = `${width}px`;\n }\n\n queueUpdate(row: RowInput) {\n this.dataStore.queueUpdate(row);\n this.throttleTransation();\n }\n\n queueRemove(row: RowInput) {\n this.dataStore.queueRemove(row);\n this.throttleTransation();\n }\n\n transaction({ add = [], remove = [], update = [] }: Transaction) {\n if (Array.isArray(add)) {\n add.forEach(row => this.queueUpdate(row));\n }\n\n if (Array.isArray(update)) {\n update.forEach(row => this.queueUpdate(row));\n }\n\n if (Array.isArray(remove)) {\n remove.forEach(row => this.queueRemove(row));\n }\n }\n\n clearValues() {\n this.dataStore.clear();\n this.cellEntries.clear();\n }\n\n formatValue(key: Key, value: unknown) {\n return this.headers.get(key)?.valueFormatter(value) ?? String(value);\n }\n\n setValues(data: RowInput[]) {\n this.throttleTransation.cancel();\n this.clearValues();\n if (!Array.isArray(data)) return;\n this.dataStore.setRows(data);\n this.refreshScrollbar();\n this.refitSelection();\n this.forceDraw();\n }\n\n setColumns(columns: ColumnDefinition[]) {\n if (Array.isArray(columns)) {\n this.headers.clear();\n // cached formatted values belong to the previous formatters\n this.cellEntries.clear();\n const defaults = {\n width: 100,\n valueFormatter: (v: unknown) => String(v),\n headerRenderer: builtIn.headerRenderer,\n };\n columns.forEach((column, index) => {\n if (typeof column === 'string' || typeof column === 'number') {\n const columnId = column + '';\n this.headers.set(columnId, {\n ...defaults,\n index: index,\n id: column,\n displayName: columnId,\n });\n }\n if (typeof column === 'object') {\n this.headers.set(column.id + '', {\n ...defaults,\n index: index,\n ...column,\n });\n }\n });\n this.updateColumnLayout();\n this.refreshScrollbar();\n this.refitSelection();\n this.forceDraw();\n }\n }\n\n disconnectedCallback() {\n this.finishEdit(true);\n this.cancelRender();\n this.endSelectDrag();\n document.removeEventListener('visibilitychange', this.onVisibilityChange);\n this.resizeObserver?.disconnect();\n this.pixelRatioQuery?.removeEventListener('change', this.watchPixelRatio);\n this.unwatchTheme();\n document.fonts?.removeEventListener('loadingdone', this.onFontsLoaded);\n clearTimeout(this.fontsTimeout);\n }\n}\n\nif (window && window.customElements) {\n injectStyles();\n customElements.define('canvas-grid', CanvasGridComponent);\n}\n\nexport default CanvasGridComponent;\n"],"ignoreList":[0,1],"mappings":"C,8xBAUA,IAAI4B,EAAkB,sBAGlBC,EAAM,IAMNC,EAAS,aAGTC,EAAa,qBAGbC,EAAa,aAGbC,EAAY,cAGZC,EAAe,SAGfC,EAAa,OAAO,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