@toolbox-web/grid 3.0.0-beta.4 → 3.0.0-rc.0

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.
Files changed (63) hide show
  1. package/all.js +1 -1
  2. package/all.js.map +1 -1
  3. package/index.js +1 -1
  4. package/index.js.map +1 -1
  5. package/lib/features/registry.js +1 -1
  6. package/lib/features/registry.js.map +1 -1
  7. package/lib/plugins/clipboard/index.js +1 -1
  8. package/lib/plugins/clipboard/index.js.map +1 -1
  9. package/lib/plugins/column-virtualization/index.js +1 -1
  10. package/lib/plugins/column-virtualization/index.js.map +1 -1
  11. package/lib/plugins/context-menu/index.js +1 -1
  12. package/lib/plugins/context-menu/index.js.map +1 -1
  13. package/lib/plugins/editing/index.js +1 -1
  14. package/lib/plugins/editing/index.js.map +1 -1
  15. package/lib/plugins/export/index.js +1 -1
  16. package/lib/plugins/export/index.js.map +1 -1
  17. package/lib/plugins/filtering/index.js +1 -1
  18. package/lib/plugins/filtering/index.js.map +1 -1
  19. package/lib/plugins/grouping-columns/index.js +1 -1
  20. package/lib/plugins/grouping-columns/index.js.map +1 -1
  21. package/lib/plugins/grouping-rows/index.js +1 -1
  22. package/lib/plugins/grouping-rows/index.js.map +1 -1
  23. package/lib/plugins/master-detail/index.js +1 -1
  24. package/lib/plugins/master-detail/index.js.map +1 -1
  25. package/lib/plugins/multi-sort/index.js +1 -1
  26. package/lib/plugins/multi-sort/index.js.map +1 -1
  27. package/lib/plugins/pinned-columns/index.js +1 -1
  28. package/lib/plugins/pinned-columns/index.js.map +1 -1
  29. package/lib/plugins/pinned-rows/index.js +1 -1
  30. package/lib/plugins/pinned-rows/index.js.map +1 -1
  31. package/lib/plugins/pivot/index.js +1 -1
  32. package/lib/plugins/pivot/index.js.map +1 -1
  33. package/lib/plugins/print/index.js +1 -1
  34. package/lib/plugins/print/index.js.map +1 -1
  35. package/lib/plugins/reorder-columns/index.js +1 -1
  36. package/lib/plugins/reorder-columns/index.js.map +1 -1
  37. package/lib/plugins/responsive/index.js +1 -1
  38. package/lib/plugins/responsive/index.js.map +1 -1
  39. package/lib/plugins/row-drag-drop/index.js +1 -1
  40. package/lib/plugins/row-drag-drop/index.js.map +1 -1
  41. package/lib/plugins/selection/index.js +1 -1
  42. package/lib/plugins/selection/index.js.map +1 -1
  43. package/lib/plugins/server-side/index.js +1 -1
  44. package/lib/plugins/server-side/index.js.map +1 -1
  45. package/lib/plugins/shell/index.js +1 -1
  46. package/lib/plugins/shell/index.js.map +1 -1
  47. package/lib/plugins/sticky-rows/index.js +1 -1
  48. package/lib/plugins/sticky-rows/index.js.map +1 -1
  49. package/lib/plugins/tooltip/index.js +1 -1
  50. package/lib/plugins/tooltip/index.js.map +1 -1
  51. package/lib/plugins/tree/index.js +1 -1
  52. package/lib/plugins/tree/index.js.map +1 -1
  53. package/lib/plugins/undo-redo/index.js +1 -1
  54. package/lib/plugins/undo-redo/index.js.map +1 -1
  55. package/lib/plugins/visibility/index.js +1 -1
  56. package/lib/plugins/visibility/index.js.map +1 -1
  57. package/package.json +1 -1
  58. package/umd/grid.all.umd.js +1 -1
  59. package/umd/grid.all.umd.js.map +1 -1
  60. package/umd/grid.umd.js +1 -1
  61. package/umd/grid.umd.js.map +1 -1
  62. package/umd/plugins/selection.umd.js +1 -1
  63. package/umd/plugins/selection.umd.js.map +1 -1
@@ -1,2 +1,2 @@
1
- import{setFeatureResolver as o}from"@toolbox-web/grid";function t(o,t,e,n){console.warn(function(o,t){return`[tbw-grid] ${o}: ${t}\n\n → More info: ${function(o){return`https://toolboxjs.com/grid/errors#${o.toLowerCase()}`}(o)}`}(o,t))}const e="3.0.0-beta.4",n=/* @__PURE__ */Symbol.for(`@toolbox-web/grid:feature-registry@${e}/v1`),r=/* @__PURE__ */Symbol.for(`@toolbox-web/grid:feature-registry-warned@${e}/v1`);function s(o,t){let e=Reflect.get(globalThis,o);return void 0===e&&(e=t(),Reflect.set(globalThis,o,e)),e}const i=s(n,()=>/* @__PURE__ */new Map),c=s(r,()=>/* @__PURE__ */new Set),f=()=>"undefined"!=typeof window&&("localhost"===window.location?.hostname||"127.0.0.1"===window.location?.hostname);function a(o,e,n){f()&&i.has(o)&&!n?.override&&t("TBW030",`Feature "${o}" was re-registered. Previous registration overwritten.`),i.set(o,{factory:e,name:o})}function u(o){return i.has(o)}function d(o){return i.get(o)?.factory}function l(){return Array.from(i.keys())}const w={undoRedo:["editing"],clipboard:["selection"]};function g(o,e){const n=i.get(o);if(n)return n.factory(e);if(f()&&!c.has(o)){c.add(o);const e=o.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();t("TBW031",`Feature "${o}" is configured but not registered.\nAdd this import to enable it:\n\n import '@toolbox-web/grid/features/${e}';\n`)}}function b(o){const e=[];for(const[t,r]of Object.entries(o))void 0!==r&&!1!==r&&e.push(t);!function(o){const e=new Set(o);for(const n of o){const o=w[n];if(o)for(const r of o)e.has(r)||f()&&t("TBW032",`Feature "${n}" requires "${r}" to be enabled. Add "${r}" to your features configuration.`)}}(e);const n=[];for(const t of e){const e=g(t,o[t]);e&&n.push(e)}return function(o){if(o.length<2)return o;const t=/* @__PURE__ */new Map;for(const i of o)t.set(i.name,i);const e=[],n=/* @__PURE__ */new Set,r=/* @__PURE__ */new Set,s=o=>{if(n.has(o)||r.has(o))return;r.add(o);const i=o.constructor.dependencies??[];for(const e of i){const o=t.get(e.name);o&&s(o)}r.delete(o),n.add(o),e.push(o)};for(const i of o)s(i);return e}(n)}function h(){i.clear(),c.clear()}o(b);export{h as clearFeatureRegistry,g as createPluginFromFeature,b as createPluginsFromFeatures,d as getFeatureFactory,l as getRegisteredFeatures,u as isFeatureRegistered,a as registerFeature};
1
+ import{setFeatureResolver as o}from"@toolbox-web/grid";function t(o,t,e,n){console.warn(function(o,t){return`[tbw-grid] ${o}: ${t}\n\n → More info: ${function(o){return`https://toolboxjs.com/grid/errors#${o.toLowerCase()}`}(o)}`}(o,t))}const e="3.0.0-rc.0",n=/* @__PURE__ */Symbol.for(`@toolbox-web/grid:feature-registry@${e}/v1`),r=/* @__PURE__ */Symbol.for(`@toolbox-web/grid:feature-registry-warned@${e}/v1`);function s(o,t){let e=Reflect.get(globalThis,o);return void 0===e&&(e=t(),Reflect.set(globalThis,o,e)),e}const i=s(n,()=>/* @__PURE__ */new Map),c=s(r,()=>/* @__PURE__ */new Set),f=()=>"undefined"!=typeof window&&("localhost"===window.location?.hostname||"127.0.0.1"===window.location?.hostname);function a(o,e,n){f()&&i.has(o)&&!n?.override&&t("TBW030",`Feature "${o}" was re-registered. Previous registration overwritten.`),i.set(o,{factory:e,name:o})}function u(o){return i.has(o)}function d(o){return i.get(o)?.factory}function l(){return Array.from(i.keys())}const w={undoRedo:["editing"],clipboard:["selection"]};function g(o,e){const n=i.get(o);if(n)return n.factory(e);if(f()&&!c.has(o)){c.add(o);const e=o.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();t("TBW031",`Feature "${o}" is configured but not registered.\nAdd this import to enable it:\n\n import '@toolbox-web/grid/features/${e}';\n`)}}function b(o){const e=[];for(const[t,r]of Object.entries(o))void 0!==r&&!1!==r&&e.push(t);!function(o){const e=new Set(o);for(const n of o){const o=w[n];if(o)for(const r of o)e.has(r)||f()&&t("TBW032",`Feature "${n}" requires "${r}" to be enabled. Add "${r}" to your features configuration.`)}}(e);const n=[];for(const t of e){const e=g(t,o[t]);e&&n.push(e)}return function(o){if(o.length<2)return o;const t=/* @__PURE__ */new Map;for(const i of o)t.set(i.name,i);const e=[],n=/* @__PURE__ */new Set,r=/* @__PURE__ */new Set,s=o=>{if(n.has(o)||r.has(o))return;r.add(o);const i=o.constructor.dependencies??[];for(const e of i){const o=t.get(e.name);o&&s(o)}r.delete(o),n.add(o),e.push(o)};for(const i of o)s(i);return e}(n)}function h(){i.clear(),c.clear()}o(b);export{h as clearFeatureRegistry,g as createPluginFromFeature,b as createPluginsFromFeatures,d as getFeatureFactory,l as getRegisteredFeatures,u as isFeatureRegistered,a as registerFeature};
2
2
  //# sourceMappingURL=registry.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"registry.js","sources":["../../../../../libs/grid/src/lib/core/internal/diagnostics.ts","../../../../../libs/grid/src/lib/features/registry.ts"],"sourcesContent":["/**\n * Centralized diagnostic messages for @toolbox-web/grid.\n *\n * Every user-facing warning, error, or info message in the grid has a unique\n * diagnostic code (e.g. `TBW001`). Each code maps to a section on the online\n * troubleshooting page, giving developers a direct link to resolution steps.\n *\n * ## Usage\n *\n * ```ts\n * import { MISSING_BREAKPOINT, warnDiagnostic, throwDiagnostic } from './diagnostics';\n *\n * // Warn with a code\n * warnDiagnostic(MISSING_BREAKPOINT, 'Set a breakpoint...', gridId);\n *\n * // Throw with a code\n * throwDiagnostic(MISSING_ROW_ID, 'Configure getRowId...', gridId);\n * ```\n *\n * Plugins should prefer `this.warn(MISSING_BREAKPOINT, message)` via BaseGridPlugin\n * instead of importing this module directly.\n *\n * @internal\n */\n\n// #region Grid Prefix\n\n/**\n * Build the `[tbw-grid]` or `[tbw-grid#my-id]` log prefix.\n * Pass `pluginName` for a scoped prefix like `[tbw-grid:SelectionPlugin]`.\n */\nexport function gridPrefix(gridId?: string, pluginName?: string): string {\n const id = gridId ? `#${gridId}` : '';\n const plugin = pluginName ? `:${pluginName}` : '';\n return `[tbw-grid${id}${plugin}]`;\n}\n\n// #endregion\n\n// #region Diagnostic Codes\n\n/**\n * Diagnostic codes used across the grid library.\n *\n * Each code is an individual export so that unused codes are tree-shaken\n * from bundles that don't reference them (esbuild can't tree-shake\n * properties from a single object).\n *\n * Naming: TBW + 3-digit number.\n * Ranges:\n * 001–019 Configuration validation (missing plugins, bad config)\n * 020–029 Plugin lifecycle (dependencies, incompatibilities, deprecation)\n * 030–039 Feature registry\n * 040–049 Row operations (row ID, row mutations)\n * 050–059 Column operations (width, template)\n * 060–069 Rendering (callbacks, formatters, external views)\n * 070–079 Shell (tool panels, header/toolbar content)\n * 080–089 Editing & editors\n * 090–099 Print\n * 100–109 Clipboard\n * 110–119 Plugin-specific (responsive, undo-redo, grouping-columns)\n * 120–129 Style injection\n * 130–139 Attribute parsing\n */\n\n// --- Config validation (001–019) ---\n/** Column uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN = 'TBW001' as const;\n/** Grid config uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN_CONFIG = 'TBW002' as const;\n/** Plugin config rule violation (error severity). */\nexport const CONFIG_RULE_ERROR = 'TBW003' as const;\n/** Plugin config rule violation (warning severity). */\nexport const CONFIG_RULE_WARN = 'TBW004' as const;\n\n// --- Plugin lifecycle (020–029) ---\n/** Required plugin dependency is missing. */\nexport const MISSING_DEPENDENCY = 'TBW020' as const;\n/** Optional plugin dependency is missing. */\nexport const OPTIONAL_DEPENDENCY = 'TBW021' as const;\n/** Two loaded plugins are incompatible. */\nexport const INCOMPATIBLE_PLUGINS = 'TBW022' as const;\n/** Two plugin instances resolve to the same canonical name (alias collapse). */\nexport const PLUGIN_ALIAS_COLLAPSE = 'TBW023' as const;\n/** Error thrown inside a plugin event handler. */\nexport const PLUGIN_EVENT_ERROR = 'TBW024' as const;\n/** Conflicting config values found while merging alias-collapsed plugin instances. */\nexport const PLUGIN_ALIAS_CONFIG_CONFLICT = 'TBW025' as const;\n\n// --- Feature registry (030–039) ---\n/** Feature was re-registered (overwritten). */\nexport const FEATURE_REREGISTERED = 'TBW030' as const;\n/** Feature configured but not imported. */\nexport const FEATURE_NOT_IMPORTED = 'TBW031' as const;\n/** Feature depends on another feature that is not enabled. */\nexport const FEATURE_MISSING_DEP = 'TBW032' as const;\n\n// --- Row operations (040–049) ---\n/** Cannot determine row ID (no getRowId and no id property). */\nexport const MISSING_ROW_ID = 'TBW040' as const;\n/** Row with given ID not found. */\nexport const ROW_NOT_FOUND = 'TBW041' as const;\n\n// --- Column operations (050–059) ---\n/** Column has an invalid CSS width value. */\nexport const INVALID_COLUMN_WIDTH = 'TBW050' as const;\n\n// --- Rendering callbacks (060–069) ---\n/** rowClass callback threw an error. */\nexport const ROW_CLASS_ERROR = 'TBW060' as const;\n/** cellClass callback threw an error. */\nexport const CELL_CLASS_ERROR = 'TBW061' as const;\n/** Column format function threw an error. */\nexport const FORMAT_ERROR = 'TBW062' as const;\n/** External view mount() threw an error. */\nexport const VIEW_MOUNT_ERROR = 'TBW063' as const;\n/** External view event dispatch error. */\nexport const VIEW_DISPATCH_ERROR = 'TBW064' as const;\n\n// --- Shell (070–079) ---\n/** Tool panel missing required id or title. */\nexport const TOOL_PANEL_MISSING_ATTR = 'TBW070' as const;\n/** No tool panels registered. */\nexport const NO_TOOL_PANELS = 'TBW071' as const;\n/** Tool panel section not found. */\nexport const TOOL_PANEL_NOT_FOUND = 'TBW072' as const;\n/** Tool panel already registered. */\nexport const TOOL_PANEL_DUPLICATE = 'TBW073' as const;\n/** Header content already registered. */\nexport const HEADER_CONTENT_DUPLICATE = 'TBW074' as const;\n/** Toolbar content already registered. */\nexport const TOOLBAR_CONTENT_DUPLICATE = 'TBW075' as const;\n\n// --- Editing & editors (080–089) ---\n/** External editor mount() threw an error. */\nexport const EDITOR_MOUNT_ERROR = 'TBW080' as const;\n\n// --- Print (090–099) ---\n/** Print already in progress. */\nexport const PRINT_IN_PROGRESS = 'TBW090' as const;\n/** Grid not available for printing. */\nexport const PRINT_NO_GRID = 'TBW091' as const;\n/** Print operation failed. */\nexport const PRINT_FAILED = 'TBW092' as const;\n/** Multiple elements share the same grid ID (print isolation issue). */\nexport const PRINT_DUPLICATE_ID = 'TBW093' as const;\n\n// --- Clipboard (100–109) ---\n/** Clipboard API write failed. */\nexport const CLIPBOARD_FAILED = 'TBW100' as const;\n\n// --- Plugin-specific (110–119) ---\n/** ResponsivePlugin: no breakpoint configured. */\nexport const MISSING_BREAKPOINT = 'TBW110' as const;\n/** UndoRedoPlugin: transaction already in progress. */\nexport const TRANSACTION_IN_PROGRESS = 'TBW111' as const;\n/** UndoRedoPlugin: no transaction in progress. */\nexport const NO_TRANSACTION = 'TBW112' as const;\n/** GroupingColumnsPlugin: missing id or header on column group definition. */\nexport const COLUMN_GROUP_NO_ID = 'TBW113' as const;\n/** GroupingColumnsPlugin: conflicting columnGroups sources. */\nexport const COLUMN_GROUPS_CONFLICT = 'TBW114' as const;\n\n// --- Style injection (120–129) ---\n/** Failed to extract grid.css from document stylesheets. */\nexport const STYLE_EXTRACT_FAILED = 'TBW120' as const;\n/** Could not find grid.css in document.styleSheets. */\nexport const STYLE_NOT_FOUND = 'TBW121' as const;\n\n// --- Attribute parsing (130–139) ---\n/** Invalid JSON in an HTML attribute. */\nexport const INVALID_ATTRIBUTE_JSON = 'TBW130' as const;\n\n// --- DataSource / ServerSide (140–149) ---\n/** ServerSidePlugin: getRows() rejected. */\nexport const DATASOURCE_FETCH_ERROR = 'TBW140' as const;\n/** ServerSidePlugin: getChildRows() rejected. */\nexport const DATASOURCE_CHILD_FETCH_ERROR = 'TBW141' as const;\n/** ServerSidePlugin: getChildRows() not implemented but a plugin queried for children. */\nexport const DATASOURCE_NO_CHILD_HANDLER = 'TBW142' as const;\n/** ServerSidePlugin: concurrent request limit reached, request deferred. */\nexport const DATASOURCE_THROTTLED = 'TBW143' as const;\n\nexport type DiagnosticCode =\n | typeof MISSING_PLUGIN\n | typeof MISSING_PLUGIN_CONFIG\n | typeof CONFIG_RULE_ERROR\n | typeof CONFIG_RULE_WARN\n | typeof MISSING_DEPENDENCY\n | typeof OPTIONAL_DEPENDENCY\n | typeof INCOMPATIBLE_PLUGINS\n | typeof PLUGIN_ALIAS_COLLAPSE\n | typeof PLUGIN_EVENT_ERROR\n | typeof PLUGIN_ALIAS_CONFIG_CONFLICT\n | typeof FEATURE_REREGISTERED\n | typeof FEATURE_NOT_IMPORTED\n | typeof FEATURE_MISSING_DEP\n | typeof MISSING_ROW_ID\n | typeof ROW_NOT_FOUND\n | typeof INVALID_COLUMN_WIDTH\n | typeof ROW_CLASS_ERROR\n | typeof CELL_CLASS_ERROR\n | typeof FORMAT_ERROR\n | typeof VIEW_MOUNT_ERROR\n | typeof VIEW_DISPATCH_ERROR\n | typeof TOOL_PANEL_MISSING_ATTR\n | typeof NO_TOOL_PANELS\n | typeof TOOL_PANEL_NOT_FOUND\n | typeof TOOL_PANEL_DUPLICATE\n | typeof HEADER_CONTENT_DUPLICATE\n | typeof TOOLBAR_CONTENT_DUPLICATE\n | typeof EDITOR_MOUNT_ERROR\n | typeof PRINT_IN_PROGRESS\n | typeof PRINT_NO_GRID\n | typeof PRINT_FAILED\n | typeof PRINT_DUPLICATE_ID\n | typeof CLIPBOARD_FAILED\n | typeof MISSING_BREAKPOINT\n | typeof TRANSACTION_IN_PROGRESS\n | typeof NO_TRANSACTION\n | typeof COLUMN_GROUP_NO_ID\n | typeof COLUMN_GROUPS_CONFLICT\n | typeof STYLE_EXTRACT_FAILED\n | typeof STYLE_NOT_FOUND\n | typeof INVALID_ATTRIBUTE_JSON\n | typeof DATASOURCE_FETCH_ERROR\n | typeof DATASOURCE_CHILD_FETCH_ERROR\n | typeof DATASOURCE_NO_CHILD_HANDLER\n | typeof DATASOURCE_THROTTLED;\n\n// #endregion\n\n// #region Docs URL\n\nconst DOCS_BASE = 'https://toolboxjs.com/grid/errors';\n\n/** Build a direct link to the troubleshooting section for a code. */\nfunction docsUrl(code: DiagnosticCode): string {\n return `${DOCS_BASE}#${code.toLowerCase()}`;\n}\n\n// #endregion\n\n// #region Formatting\n\n/**\n * Format a diagnostic message with prefix, code, and docs link.\n *\n * Output format:\n * ```\n * [tbw-grid#my-id] TBW001: Your message here.\n *\n * → More info: https://toolboxjs.com/grid/errors#tbw001\n * ```\n */\nexport function formatDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): string {\n const prefix = gridPrefix(gridId, pluginName);\n return `${prefix} ${code}: ${message}\\n\\n → More info: ${docsUrl(code)}`;\n}\n\n// #endregion\n\n// #region Public API\n\n/**\n * Throw an error with a diagnostic code and docs link.\n * Use for configuration errors and API misuse that should halt execution.\n */\nexport function throwDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): never {\n throw new Error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a warning with a diagnostic code and docs link.\n * Use for recoverable issues the developer should fix.\n */\nexport function warnDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.warn(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a debug message with a diagnostic code and docs link.\n * Use for optional/soft dependency notifications — visible only when\n * the browser DevTools \"Verbose\" log level is enabled.\n */\nexport function debugDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.debug(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log an error with a diagnostic code and docs link.\n * Use for non-throwing errors (e.g., failed async operations).\n */\nexport function errorDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n// #endregion\n","/**\n * Core Feature Registry for @toolbox-web/grid\n *\n * This module provides a framework-agnostic registry for plugin factories.\n * Features are registered via side-effect imports, enabling tree-shaking\n * while maintaining a clean declarative API.\n *\n * @example\n * ```typescript\n * // Import features you need (side-effect imports)\n * import '@toolbox-web/grid/features/selection';\n * import '@toolbox-web/grid/features/filtering';\n *\n * // Configure grid declaratively\n * grid.gridConfig = {\n * features: {\n * selection: 'range',\n * filtering: { debounceMs: 200 },\n * },\n * };\n * ```\n *\n * @packageDocumentation\n * @module Features\n */\n\nimport {\n FEATURE_MISSING_DEP,\n FEATURE_NOT_IMPORTED,\n FEATURE_REREGISTERED,\n warnDiagnostic,\n} from '../core/internal/diagnostics';\nimport { setFeatureResolver } from '../core/internal/feature-hook';\nimport type { PluginDependency } from '../core/plugin/base-plugin';\nimport type { FeatureConfig, GridPlugin } from '../core/types';\n\n// #region Types\n\n/** Feature name — keys of the augmented FeatureConfig interface. */\nexport type FeatureName = keyof FeatureConfig;\n\n/** Factory function that creates a plugin from a feature config value. */\nexport type PluginFactory<TConfig = unknown> = (config: TConfig) => GridPlugin;\n\ninterface RegistryEntry {\n factory: PluginFactory;\n name: string;\n}\n\n// #endregion\n\n// #region Registry State\n\n/*\n * Cross-bundle singleton (version-scoped).\n *\n * The custom-elements registry is realm-global, but `import` graphs are not:\n * when two micro-frontend widgets on the same page bundle their own copy of\n * `@toolbox-web/grid`, each copy gets its own `featureRegistry` Map. The\n * `<tbw-grid>` class is realm-global (see `registerDataGrid()` in\n * `core/grid.ts`), so the *running* class resolves features via the resolver\n * its own bundle wired up — which closes over the *local* Map. Side-effect\n * imports from any other bundle (`import '@toolbox-web/grid/features/tree'`)\n * land in a different Map that the running class never reads, producing\n * spurious TBW031 \"feature not registered\" warnings.\n *\n * Fix: persist the Map on `globalThis` under a `Symbol.for(...)` key so every\n * loaded copy of this module reads and writes the same instance.\n *\n * The key embeds `__GRID_VERSION__` so **only same-version** bundles share a\n * registry. `registerDataGrid()` already isolates differently-versioned grid\n * classes by registering them under suffixed tag names — the version is\n * sanitized to ASCII letters/digits/dashes, so `2.14.0` becomes the tag\n * `tbw-grid-v2-14-0` (issue #339). The feature registry must mirror that\n * isolation, otherwise the last-loaded bundle's plugin factories would\n * overwrite earlier versions' entries and the running grid would attach\n * plugin instances built against a different internal contract. The trailing\n * `/v1` is a schema version for the slot shape — bump if the stored value's\n * shape changes incompatibly.\n *\n * Issue: planning #9 (two Roma widgets each bundling their own grid copy).\n */\ndeclare const __GRID_VERSION__: string;\nconst GRID_VERSION = typeof __GRID_VERSION__ !== 'undefined' ? __GRID_VERSION__ : 'dev';\nconst REGISTRY_KEY = Symbol.for(`@toolbox-web/grid:feature-registry@${GRID_VERSION}/v1`);\nconst WARNED_KEY = Symbol.for(`@toolbox-web/grid:feature-registry-warned@${GRID_VERSION}/v1`);\n\nfunction getOrCreateGlobal<T>(key: symbol, make: () => T): T {\n let value = Reflect.get(globalThis, key) as T | undefined;\n if (value === undefined) {\n value = make();\n Reflect.set(globalThis, key, value);\n }\n return value;\n}\n\nconst featureRegistry = getOrCreateGlobal(REGISTRY_KEY, () => new Map<string, RegistryEntry>());\nconst warnedFeatures = getOrCreateGlobal(WARNED_KEY, () => new Set<string>());\n\n// #endregion\n\n// #region Registration API\n\n/** Runtime dev-mode check (localhost or 127.0.0.1). */\nconst isDev = (): boolean =>\n typeof window !== 'undefined' &&\n (window.location?.hostname === 'localhost' || window.location?.hostname === '127.0.0.1');\n\n/** Optional flags passed to {@link registerFeature}. */\nexport interface RegisterFeatureOptions {\n /**\n * Set to `true` when the registration is intentionally overwriting an\n * existing entry (e.g. a framework adapter wrapping the vanilla factory\n * with reactive bridging). Suppresses the TBW030 dev-mode warning.\n */\n override?: boolean;\n}\n\n/**\n * Register a feature's plugin factory.\n * Called by side-effect feature imports (e.g., `import '@toolbox-web/grid/features/selection'`).\n *\n * @param name - The feature name (matches a key on FeatureConfig)\n * @param factory - Function that creates a plugin instance from config\n * @param options - Pass `{ override: true }` for intentional re-registration\n * (framework adapters bridging the vanilla factory) to suppress TBW030.\n */\nexport function registerFeature<K extends FeatureName>(\n name: K,\n factory: PluginFactory<FeatureConfig[K]>,\n options?: RegisterFeatureOptions,\n): void;\nexport function registerFeature(name: string, factory: PluginFactory, options?: RegisterFeatureOptions): void;\nexport function registerFeature(name: string, factory: PluginFactory, options?: RegisterFeatureOptions): void {\n if (isDev() && featureRegistry.has(name) && !options?.override) {\n warnDiagnostic(FEATURE_REREGISTERED, `Feature \"${name}\" was re-registered. Previous registration overwritten.`);\n }\n featureRegistry.set(name, { factory, name });\n}\n\n/**\n * Check if a feature has been registered.\n */\nexport function isFeatureRegistered(name: string): boolean {\n return featureRegistry.has(name);\n}\n\n/**\n * Get a registered feature's factory. Returns undefined if not registered.\n */\nexport function getFeatureFactory(name: string): PluginFactory | undefined {\n return featureRegistry.get(name)?.factory;\n}\n\n/**\n * Get all registered feature names.\n */\nexport function getRegisteredFeatures(): string[] {\n return Array.from(featureRegistry.keys());\n}\n\n// #endregion\n\n// #region Plugin Creation\n\n/**\n * Plugin dependency declarations.\n * Some plugins require others to be loaded first.\n */\nconst PLUGIN_DEPENDENCIES: Record<string, string[]> = {\n undoRedo: ['editing'],\n clipboard: ['selection'],\n};\n\n/**\n * Create a plugin instance for a single feature.\n * Shows a warning if the feature is not registered.\n */\nexport function createPluginFromFeature(name: string, config: unknown): GridPlugin | undefined {\n const entry = featureRegistry.get(name);\n\n if (!entry) {\n if (isDev() && !warnedFeatures.has(name)) {\n warnedFeatures.add(name);\n const kebab = name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n warnDiagnostic(\n FEATURE_NOT_IMPORTED,\n `Feature \"${name}\" is configured but not registered.\\n` +\n `Add this import to enable it:\\n\\n` +\n ` import '@toolbox-web/grid/features/${kebab}';\\n`,\n );\n }\n return undefined;\n }\n\n return entry.factory(config);\n}\n\n/**\n * Validate feature dependencies and log warnings for missing ones.\n */\nfunction validateDependencies(featureNames: string[]): void {\n const featureSet = new Set(featureNames);\n\n for (const feature of featureNames) {\n const deps = PLUGIN_DEPENDENCIES[feature];\n if (!deps) continue;\n\n for (const dep of deps) {\n if (!featureSet.has(dep)) {\n if (isDev()) {\n warnDiagnostic(\n FEATURE_MISSING_DEP,\n `Feature \"${feature}\" requires \"${dep}\" to be enabled. ` + `Add \"${dep}\" to your features configuration.`,\n );\n }\n }\n }\n }\n}\n\n/**\n * Create plugin instances from a features configuration object.\n *\n * Handles:\n * - Dependency validation (clipboard needs selection)\n * - Dependency ordering, derived programmatically from each plugin's declared\n * `static dependencies` (selection before clipboard, shell before visibility)\n * - Skipping false/undefined values\n *\n * @param features - Partial FeatureConfig object\n * @returns Array of plugin instances ready for gridConfig.plugins\n */\nexport function createPluginsFromFeatures(features: Record<string, unknown>): GridPlugin[] {\n const enabledFeatures: string[] = [];\n\n // Collect enabled feature names\n for (const [key, value] of Object.entries(features)) {\n if (value === undefined || value === false) continue;\n enabledFeatures.push(key);\n }\n\n // Validate dependencies (dev-only warnings for missing feature deps)\n validateDependencies(enabledFeatures);\n\n // Instantiate each enabled feature's plugin in declared (config) order...\n const plugins: GridPlugin[] = [];\n for (const featureName of enabledFeatures) {\n const plugin = createPluginFromFeature(featureName, features[featureName]);\n if (plugin) plugins.push(plugin);\n }\n\n // ...then reorder so every plugin's declared `static dependencies` attach\n // before it (see orderPluginsByDependencies).\n return orderPluginsByDependencies(plugins);\n}\n\n/**\n * Topologically order plugin instances so each plugin's declared\n * `static dependencies` precede it. The dependency list is read straight off\n * the plugin constructor — the SAME metadata `validatePluginDependencies`\n * consumes at attach time — so the resolved order satisfies the dependency\n * validator regardless of `features` key order, and third-party plugins that\n * declare their own `static dependencies` are sequenced correctly with no\n * hardcoded table.\n *\n * Independent plugins keep their original (config) order. Edges pointing at\n * plugins that aren't enabled are ignored (a missing required dependency is\n * reported separately by the validator at attach time). Cycles are broken\n * gracefully — the partial order is preserved rather than looping forever.\n */\nfunction orderPluginsByDependencies(plugins: GridPlugin[]): GridPlugin[] {\n if (plugins.length < 2) return plugins;\n\n const byName = new Map<string, GridPlugin>();\n for (const plugin of plugins) byName.set(plugin.name, plugin);\n\n const ordered: GridPlugin[] = [];\n const done = new Set<GridPlugin>();\n const onStack = new Set<GridPlugin>();\n\n const visit = (plugin: GridPlugin): void => {\n if (done.has(plugin) || onStack.has(plugin)) return;\n onStack.add(plugin);\n const deps = (plugin.constructor as { dependencies?: PluginDependency[] }).dependencies ?? [];\n for (const dep of deps) {\n const depPlugin = byName.get(dep.name);\n if (depPlugin) visit(depPlugin);\n }\n onStack.delete(plugin);\n done.add(plugin);\n ordered.push(plugin);\n };\n\n for (const plugin of plugins) visit(plugin);\n return ordered;\n}\n\n// #endregion\n\n// #region Auto-Registration\n\n// Wire feature resolver into grid core so `gridConfig.features` is handled automatically.\n// This runs when any feature module is imported (they all import this registry).\nsetFeatureResolver(createPluginsFromFeatures as (features: Record<string, unknown>) => GridPlugin[]);\n\n// #endregion\n\n// #region Testing Utilities\n\n/**\n * Clear the registry. For testing only.\n * @internal\n */\nexport function clearFeatureRegistry(): void {\n featureRegistry.clear();\n warnedFeatures.clear();\n}\n\n// #endregion\n"],"names":["warnDiagnostic","code","message","gridId","pluginName","console","warn","toLowerCase","docsUrl","formatDiagnostic","GRID_VERSION","REGISTRY_KEY","Symbol","for","WARNED_KEY","getOrCreateGlobal","key","make","value","Reflect","get","globalThis","set","featureRegistry","Map","warnedFeatures","Set","isDev","window","location","hostname","registerFeature","name","factory","options","has","override","isFeatureRegistered","getFeatureFactory","getRegisteredFeatures","Array","from","keys","PLUGIN_DEPENDENCIES","undoRedo","clipboard","createPluginFromFeature","config","entry","add","kebab","replace","createPluginsFromFeatures","features","enabledFeatures","Object","entries","push","featureNames","featureSet","feature","deps","dep","validateDependencies","plugins","featureName","plugin","length","byName","ordered","done","onStack","visit","constructor","dependencies","depPlugin","delete","orderPluginsByDependencies","clearFeatureRegistry","clear","setFeatureResolver"],"mappings":"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"}
1
+ {"version":3,"file":"registry.js","sources":["../../../../../libs/grid/src/lib/core/internal/diagnostics.ts","../../../../../libs/grid/src/lib/features/registry.ts"],"sourcesContent":["/**\n * Centralized diagnostic messages for @toolbox-web/grid.\n *\n * Every user-facing warning, error, or info message in the grid has a unique\n * diagnostic code (e.g. `TBW001`). Each code maps to a section on the online\n * troubleshooting page, giving developers a direct link to resolution steps.\n *\n * ## Usage\n *\n * ```ts\n * import { MISSING_BREAKPOINT, warnDiagnostic, throwDiagnostic } from './diagnostics';\n *\n * // Warn with a code\n * warnDiagnostic(MISSING_BREAKPOINT, 'Set a breakpoint...', gridId);\n *\n * // Throw with a code\n * throwDiagnostic(MISSING_ROW_ID, 'Configure getRowId...', gridId);\n * ```\n *\n * Plugins should prefer `this.warn(MISSING_BREAKPOINT, message)` via BaseGridPlugin\n * instead of importing this module directly.\n *\n * @internal\n */\n\n// #region Grid Prefix\n\n/**\n * Build the `[tbw-grid]` or `[tbw-grid#my-id]` log prefix.\n * Pass `pluginName` for a scoped prefix like `[tbw-grid:SelectionPlugin]`.\n */\nexport function gridPrefix(gridId?: string, pluginName?: string): string {\n const id = gridId ? `#${gridId}` : '';\n const plugin = pluginName ? `:${pluginName}` : '';\n return `[tbw-grid${id}${plugin}]`;\n}\n\n// #endregion\n\n// #region Diagnostic Codes\n\n/**\n * Diagnostic codes used across the grid library.\n *\n * Each code is an individual export so that unused codes are tree-shaken\n * from bundles that don't reference them (esbuild can't tree-shake\n * properties from a single object).\n *\n * Naming: TBW + 3-digit number.\n * Ranges:\n * 001–019 Configuration validation (missing plugins, bad config)\n * 020–029 Plugin lifecycle (dependencies, incompatibilities, deprecation)\n * 030–039 Feature registry\n * 040–049 Row operations (row ID, row mutations)\n * 050–059 Column operations (width, template)\n * 060–069 Rendering (callbacks, formatters, external views)\n * 070–079 Shell (tool panels, header/toolbar content)\n * 080–089 Editing & editors\n * 090–099 Print\n * 100–109 Clipboard\n * 110–119 Plugin-specific (responsive, undo-redo, grouping-columns)\n * 120–129 Style injection\n * 130–139 Attribute parsing\n */\n\n// --- Config validation (001–019) ---\n/** Column uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN = 'TBW001' as const;\n/** Grid config uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN_CONFIG = 'TBW002' as const;\n/** Plugin config rule violation (error severity). */\nexport const CONFIG_RULE_ERROR = 'TBW003' as const;\n/** Plugin config rule violation (warning severity). */\nexport const CONFIG_RULE_WARN = 'TBW004' as const;\n\n// --- Plugin lifecycle (020–029) ---\n/** Required plugin dependency is missing. */\nexport const MISSING_DEPENDENCY = 'TBW020' as const;\n/** Optional plugin dependency is missing. */\nexport const OPTIONAL_DEPENDENCY = 'TBW021' as const;\n/** Two loaded plugins are incompatible. */\nexport const INCOMPATIBLE_PLUGINS = 'TBW022' as const;\n/** Two plugin instances resolve to the same canonical name (alias collapse). */\nexport const PLUGIN_ALIAS_COLLAPSE = 'TBW023' as const;\n/** Error thrown inside a plugin event handler. */\nexport const PLUGIN_EVENT_ERROR = 'TBW024' as const;\n/** Conflicting config values found while merging alias-collapsed plugin instances. */\nexport const PLUGIN_ALIAS_CONFIG_CONFLICT = 'TBW025' as const;\n\n// --- Feature registry (030–039) ---\n/** Feature was re-registered (overwritten). */\nexport const FEATURE_REREGISTERED = 'TBW030' as const;\n/** Feature configured but not imported. */\nexport const FEATURE_NOT_IMPORTED = 'TBW031' as const;\n/** Feature depends on another feature that is not enabled. */\nexport const FEATURE_MISSING_DEP = 'TBW032' as const;\n\n// --- Row operations (040–049) ---\n/** Cannot determine row ID (no getRowId and no id property). */\nexport const MISSING_ROW_ID = 'TBW040' as const;\n/** Row with given ID not found. */\nexport const ROW_NOT_FOUND = 'TBW041' as const;\n\n// --- Column operations (050–059) ---\n/** Column has an invalid CSS width value. */\nexport const INVALID_COLUMN_WIDTH = 'TBW050' as const;\n\n// --- Rendering callbacks (060–069) ---\n/** rowClass callback threw an error. */\nexport const ROW_CLASS_ERROR = 'TBW060' as const;\n/** cellClass callback threw an error. */\nexport const CELL_CLASS_ERROR = 'TBW061' as const;\n/** Column format function threw an error. */\nexport const FORMAT_ERROR = 'TBW062' as const;\n/** External view mount() threw an error. */\nexport const VIEW_MOUNT_ERROR = 'TBW063' as const;\n/** External view event dispatch error. */\nexport const VIEW_DISPATCH_ERROR = 'TBW064' as const;\n\n// --- Shell (070–079) ---\n/** Tool panel missing required id or title. */\nexport const TOOL_PANEL_MISSING_ATTR = 'TBW070' as const;\n/** No tool panels registered. */\nexport const NO_TOOL_PANELS = 'TBW071' as const;\n/** Tool panel section not found. */\nexport const TOOL_PANEL_NOT_FOUND = 'TBW072' as const;\n/** Tool panel already registered. */\nexport const TOOL_PANEL_DUPLICATE = 'TBW073' as const;\n/** Header content already registered. */\nexport const HEADER_CONTENT_DUPLICATE = 'TBW074' as const;\n/** Toolbar content already registered. */\nexport const TOOLBAR_CONTENT_DUPLICATE = 'TBW075' as const;\n\n// --- Editing & editors (080–089) ---\n/** External editor mount() threw an error. */\nexport const EDITOR_MOUNT_ERROR = 'TBW080' as const;\n\n// --- Print (090–099) ---\n/** Print already in progress. */\nexport const PRINT_IN_PROGRESS = 'TBW090' as const;\n/** Grid not available for printing. */\nexport const PRINT_NO_GRID = 'TBW091' as const;\n/** Print operation failed. */\nexport const PRINT_FAILED = 'TBW092' as const;\n/** Multiple elements share the same grid ID (print isolation issue). */\nexport const PRINT_DUPLICATE_ID = 'TBW093' as const;\n\n// --- Clipboard (100–109) ---\n/** Clipboard API write failed. */\nexport const CLIPBOARD_FAILED = 'TBW100' as const;\n\n// --- Plugin-specific (110–119) ---\n/** ResponsivePlugin: no breakpoint configured. */\nexport const MISSING_BREAKPOINT = 'TBW110' as const;\n/** UndoRedoPlugin: transaction already in progress. */\nexport const TRANSACTION_IN_PROGRESS = 'TBW111' as const;\n/** UndoRedoPlugin: no transaction in progress. */\nexport const NO_TRANSACTION = 'TBW112' as const;\n/** GroupingColumnsPlugin: missing id or header on column group definition. */\nexport const COLUMN_GROUP_NO_ID = 'TBW113' as const;\n/** GroupingColumnsPlugin: conflicting columnGroups sources. */\nexport const COLUMN_GROUPS_CONFLICT = 'TBW114' as const;\n\n// --- Style injection (120–129) ---\n/** Failed to extract grid.css from document stylesheets. */\nexport const STYLE_EXTRACT_FAILED = 'TBW120' as const;\n/** Could not find grid.css in document.styleSheets. */\nexport const STYLE_NOT_FOUND = 'TBW121' as const;\n\n// --- Attribute parsing (130–139) ---\n/** Invalid JSON in an HTML attribute. */\nexport const INVALID_ATTRIBUTE_JSON = 'TBW130' as const;\n\n// --- DataSource / ServerSide (140–149) ---\n/** ServerSidePlugin: getRows() rejected. */\nexport const DATASOURCE_FETCH_ERROR = 'TBW140' as const;\n/** ServerSidePlugin: getChildRows() rejected. */\nexport const DATASOURCE_CHILD_FETCH_ERROR = 'TBW141' as const;\n/** ServerSidePlugin: getChildRows() not implemented but a plugin queried for children. */\nexport const DATASOURCE_NO_CHILD_HANDLER = 'TBW142' as const;\n/** ServerSidePlugin: concurrent request limit reached, request deferred. */\nexport const DATASOURCE_THROTTLED = 'TBW143' as const;\n\nexport type DiagnosticCode =\n | typeof MISSING_PLUGIN\n | typeof MISSING_PLUGIN_CONFIG\n | typeof CONFIG_RULE_ERROR\n | typeof CONFIG_RULE_WARN\n | typeof MISSING_DEPENDENCY\n | typeof OPTIONAL_DEPENDENCY\n | typeof INCOMPATIBLE_PLUGINS\n | typeof PLUGIN_ALIAS_COLLAPSE\n | typeof PLUGIN_EVENT_ERROR\n | typeof PLUGIN_ALIAS_CONFIG_CONFLICT\n | typeof FEATURE_REREGISTERED\n | typeof FEATURE_NOT_IMPORTED\n | typeof FEATURE_MISSING_DEP\n | typeof MISSING_ROW_ID\n | typeof ROW_NOT_FOUND\n | typeof INVALID_COLUMN_WIDTH\n | typeof ROW_CLASS_ERROR\n | typeof CELL_CLASS_ERROR\n | typeof FORMAT_ERROR\n | typeof VIEW_MOUNT_ERROR\n | typeof VIEW_DISPATCH_ERROR\n | typeof TOOL_PANEL_MISSING_ATTR\n | typeof NO_TOOL_PANELS\n | typeof TOOL_PANEL_NOT_FOUND\n | typeof TOOL_PANEL_DUPLICATE\n | typeof HEADER_CONTENT_DUPLICATE\n | typeof TOOLBAR_CONTENT_DUPLICATE\n | typeof EDITOR_MOUNT_ERROR\n | typeof PRINT_IN_PROGRESS\n | typeof PRINT_NO_GRID\n | typeof PRINT_FAILED\n | typeof PRINT_DUPLICATE_ID\n | typeof CLIPBOARD_FAILED\n | typeof MISSING_BREAKPOINT\n | typeof TRANSACTION_IN_PROGRESS\n | typeof NO_TRANSACTION\n | typeof COLUMN_GROUP_NO_ID\n | typeof COLUMN_GROUPS_CONFLICT\n | typeof STYLE_EXTRACT_FAILED\n | typeof STYLE_NOT_FOUND\n | typeof INVALID_ATTRIBUTE_JSON\n | typeof DATASOURCE_FETCH_ERROR\n | typeof DATASOURCE_CHILD_FETCH_ERROR\n | typeof DATASOURCE_NO_CHILD_HANDLER\n | typeof DATASOURCE_THROTTLED;\n\n// #endregion\n\n// #region Docs URL\n\nconst DOCS_BASE = 'https://toolboxjs.com/grid/errors';\n\n/** Build a direct link to the troubleshooting section for a code. */\nfunction docsUrl(code: DiagnosticCode): string {\n return `${DOCS_BASE}#${code.toLowerCase()}`;\n}\n\n// #endregion\n\n// #region Formatting\n\n/**\n * Format a diagnostic message with prefix, code, and docs link.\n *\n * Output format:\n * ```\n * [tbw-grid#my-id] TBW001: Your message here.\n *\n * → More info: https://toolboxjs.com/grid/errors#tbw001\n * ```\n */\nexport function formatDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): string {\n const prefix = gridPrefix(gridId, pluginName);\n return `${prefix} ${code}: ${message}\\n\\n → More info: ${docsUrl(code)}`;\n}\n\n// #endregion\n\n// #region Public API\n\n/**\n * Throw an error with a diagnostic code and docs link.\n * Use for configuration errors and API misuse that should halt execution.\n */\nexport function throwDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): never {\n throw new Error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a warning with a diagnostic code and docs link.\n * Use for recoverable issues the developer should fix.\n */\nexport function warnDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.warn(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a debug message with a diagnostic code and docs link.\n * Use for optional/soft dependency notifications — visible only when\n * the browser DevTools \"Verbose\" log level is enabled.\n */\nexport function debugDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.debug(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log an error with a diagnostic code and docs link.\n * Use for non-throwing errors (e.g., failed async operations).\n */\nexport function errorDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n// #endregion\n","/**\n * Core Feature Registry for @toolbox-web/grid\n *\n * This module provides a framework-agnostic registry for plugin factories.\n * Features are registered via side-effect imports, enabling tree-shaking\n * while maintaining a clean declarative API.\n *\n * @example\n * ```typescript\n * // Import features you need (side-effect imports)\n * import '@toolbox-web/grid/features/selection';\n * import '@toolbox-web/grid/features/filtering';\n *\n * // Configure grid declaratively\n * grid.gridConfig = {\n * features: {\n * selection: 'range',\n * filtering: { debounceMs: 200 },\n * },\n * };\n * ```\n *\n * @packageDocumentation\n * @module Features\n */\n\nimport {\n FEATURE_MISSING_DEP,\n FEATURE_NOT_IMPORTED,\n FEATURE_REREGISTERED,\n warnDiagnostic,\n} from '../core/internal/diagnostics';\nimport { setFeatureResolver } from '../core/internal/feature-hook';\nimport type { PluginDependency } from '../core/plugin/base-plugin';\nimport type { FeatureConfig, GridPlugin } from '../core/types';\n\n// #region Types\n\n/** Feature name — keys of the augmented FeatureConfig interface. */\nexport type FeatureName = keyof FeatureConfig;\n\n/** Factory function that creates a plugin from a feature config value. */\nexport type PluginFactory<TConfig = unknown> = (config: TConfig) => GridPlugin;\n\ninterface RegistryEntry {\n factory: PluginFactory;\n name: string;\n}\n\n// #endregion\n\n// #region Registry State\n\n/*\n * Cross-bundle singleton (version-scoped).\n *\n * The custom-elements registry is realm-global, but `import` graphs are not:\n * when two micro-frontend widgets on the same page bundle their own copy of\n * `@toolbox-web/grid`, each copy gets its own `featureRegistry` Map. The\n * `<tbw-grid>` class is realm-global (see `registerDataGrid()` in\n * `core/grid.ts`), so the *running* class resolves features via the resolver\n * its own bundle wired up — which closes over the *local* Map. Side-effect\n * imports from any other bundle (`import '@toolbox-web/grid/features/tree'`)\n * land in a different Map that the running class never reads, producing\n * spurious TBW031 \"feature not registered\" warnings.\n *\n * Fix: persist the Map on `globalThis` under a `Symbol.for(...)` key so every\n * loaded copy of this module reads and writes the same instance.\n *\n * The key embeds `__GRID_VERSION__` so **only same-version** bundles share a\n * registry. `registerDataGrid()` already isolates differently-versioned grid\n * classes by registering them under suffixed tag names — the version is\n * sanitized to ASCII letters/digits/dashes, so `2.14.0` becomes the tag\n * `tbw-grid-v2-14-0` (issue #339). The feature registry must mirror that\n * isolation, otherwise the last-loaded bundle's plugin factories would\n * overwrite earlier versions' entries and the running grid would attach\n * plugin instances built against a different internal contract. The trailing\n * `/v1` is a schema version for the slot shape — bump if the stored value's\n * shape changes incompatibly.\n *\n * Issue: planning #9 (two Roma widgets each bundling their own grid copy).\n */\ndeclare const __GRID_VERSION__: string;\nconst GRID_VERSION = typeof __GRID_VERSION__ !== 'undefined' ? __GRID_VERSION__ : 'dev';\nconst REGISTRY_KEY = Symbol.for(`@toolbox-web/grid:feature-registry@${GRID_VERSION}/v1`);\nconst WARNED_KEY = Symbol.for(`@toolbox-web/grid:feature-registry-warned@${GRID_VERSION}/v1`);\n\nfunction getOrCreateGlobal<T>(key: symbol, make: () => T): T {\n let value = Reflect.get(globalThis, key) as T | undefined;\n if (value === undefined) {\n value = make();\n Reflect.set(globalThis, key, value);\n }\n return value;\n}\n\nconst featureRegistry = getOrCreateGlobal(REGISTRY_KEY, () => new Map<string, RegistryEntry>());\nconst warnedFeatures = getOrCreateGlobal(WARNED_KEY, () => new Set<string>());\n\n// #endregion\n\n// #region Registration API\n\n/** Runtime dev-mode check (localhost or 127.0.0.1). */\nconst isDev = (): boolean =>\n typeof window !== 'undefined' &&\n (window.location?.hostname === 'localhost' || window.location?.hostname === '127.0.0.1');\n\n/** Optional flags passed to {@link registerFeature}. */\nexport interface RegisterFeatureOptions {\n /**\n * Set to `true` when the registration is intentionally overwriting an\n * existing entry (e.g. a framework adapter wrapping the vanilla factory\n * with reactive bridging). Suppresses the TBW030 dev-mode warning.\n */\n override?: boolean;\n}\n\n/**\n * Register a feature's plugin factory.\n * Called by side-effect feature imports (e.g., `import '@toolbox-web/grid/features/selection'`).\n *\n * @param name - The feature name (matches a key on FeatureConfig)\n * @param factory - Function that creates a plugin instance from config\n * @param options - Pass `{ override: true }` for intentional re-registration\n * (framework adapters bridging the vanilla factory) to suppress TBW030.\n */\nexport function registerFeature<K extends FeatureName>(\n name: K,\n factory: PluginFactory<FeatureConfig[K]>,\n options?: RegisterFeatureOptions,\n): void;\nexport function registerFeature(name: string, factory: PluginFactory, options?: RegisterFeatureOptions): void;\nexport function registerFeature(name: string, factory: PluginFactory, options?: RegisterFeatureOptions): void {\n if (isDev() && featureRegistry.has(name) && !options?.override) {\n warnDiagnostic(FEATURE_REREGISTERED, `Feature \"${name}\" was re-registered. Previous registration overwritten.`);\n }\n featureRegistry.set(name, { factory, name });\n}\n\n/**\n * Check if a feature has been registered.\n */\nexport function isFeatureRegistered(name: string): boolean {\n return featureRegistry.has(name);\n}\n\n/**\n * Get a registered feature's factory. Returns undefined if not registered.\n */\nexport function getFeatureFactory(name: string): PluginFactory | undefined {\n return featureRegistry.get(name)?.factory;\n}\n\n/**\n * Get all registered feature names.\n */\nexport function getRegisteredFeatures(): string[] {\n return Array.from(featureRegistry.keys());\n}\n\n// #endregion\n\n// #region Plugin Creation\n\n/**\n * Plugin dependency declarations.\n * Some plugins require others to be loaded first.\n */\nconst PLUGIN_DEPENDENCIES: Record<string, string[]> = {\n undoRedo: ['editing'],\n clipboard: ['selection'],\n};\n\n/**\n * Create a plugin instance for a single feature.\n * Shows a warning if the feature is not registered.\n */\nexport function createPluginFromFeature(name: string, config: unknown): GridPlugin | undefined {\n const entry = featureRegistry.get(name);\n\n if (!entry) {\n if (isDev() && !warnedFeatures.has(name)) {\n warnedFeatures.add(name);\n const kebab = name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n warnDiagnostic(\n FEATURE_NOT_IMPORTED,\n `Feature \"${name}\" is configured but not registered.\\n` +\n `Add this import to enable it:\\n\\n` +\n ` import '@toolbox-web/grid/features/${kebab}';\\n`,\n );\n }\n return undefined;\n }\n\n return entry.factory(config);\n}\n\n/**\n * Validate feature dependencies and log warnings for missing ones.\n */\nfunction validateDependencies(featureNames: string[]): void {\n const featureSet = new Set(featureNames);\n\n for (const feature of featureNames) {\n const deps = PLUGIN_DEPENDENCIES[feature];\n if (!deps) continue;\n\n for (const dep of deps) {\n if (!featureSet.has(dep)) {\n if (isDev()) {\n warnDiagnostic(\n FEATURE_MISSING_DEP,\n `Feature \"${feature}\" requires \"${dep}\" to be enabled. ` + `Add \"${dep}\" to your features configuration.`,\n );\n }\n }\n }\n }\n}\n\n/**\n * Create plugin instances from a features configuration object.\n *\n * Handles:\n * - Dependency validation (clipboard needs selection)\n * - Dependency ordering, derived programmatically from each plugin's declared\n * `static dependencies` (selection before clipboard, shell before visibility)\n * - Skipping false/undefined values\n *\n * @param features - Partial FeatureConfig object\n * @returns Array of plugin instances ready for gridConfig.plugins\n */\nexport function createPluginsFromFeatures(features: Record<string, unknown>): GridPlugin[] {\n const enabledFeatures: string[] = [];\n\n // Collect enabled feature names\n for (const [key, value] of Object.entries(features)) {\n if (value === undefined || value === false) continue;\n enabledFeatures.push(key);\n }\n\n // Validate dependencies (dev-only warnings for missing feature deps)\n validateDependencies(enabledFeatures);\n\n // Instantiate each enabled feature's plugin in declared (config) order...\n const plugins: GridPlugin[] = [];\n for (const featureName of enabledFeatures) {\n const plugin = createPluginFromFeature(featureName, features[featureName]);\n if (plugin) plugins.push(plugin);\n }\n\n // ...then reorder so every plugin's declared `static dependencies` attach\n // before it (see orderPluginsByDependencies).\n return orderPluginsByDependencies(plugins);\n}\n\n/**\n * Topologically order plugin instances so each plugin's declared\n * `static dependencies` precede it. The dependency list is read straight off\n * the plugin constructor — the SAME metadata `validatePluginDependencies`\n * consumes at attach time — so the resolved order satisfies the dependency\n * validator regardless of `features` key order, and third-party plugins that\n * declare their own `static dependencies` are sequenced correctly with no\n * hardcoded table.\n *\n * Independent plugins keep their original (config) order. Edges pointing at\n * plugins that aren't enabled are ignored (a missing required dependency is\n * reported separately by the validator at attach time). Cycles are broken\n * gracefully — the partial order is preserved rather than looping forever.\n */\nfunction orderPluginsByDependencies(plugins: GridPlugin[]): GridPlugin[] {\n if (plugins.length < 2) return plugins;\n\n const byName = new Map<string, GridPlugin>();\n for (const plugin of plugins) byName.set(plugin.name, plugin);\n\n const ordered: GridPlugin[] = [];\n const done = new Set<GridPlugin>();\n const onStack = new Set<GridPlugin>();\n\n const visit = (plugin: GridPlugin): void => {\n if (done.has(plugin) || onStack.has(plugin)) return;\n onStack.add(plugin);\n const deps = (plugin.constructor as { dependencies?: PluginDependency[] }).dependencies ?? [];\n for (const dep of deps) {\n const depPlugin = byName.get(dep.name);\n if (depPlugin) visit(depPlugin);\n }\n onStack.delete(plugin);\n done.add(plugin);\n ordered.push(plugin);\n };\n\n for (const plugin of plugins) visit(plugin);\n return ordered;\n}\n\n// #endregion\n\n// #region Auto-Registration\n\n// Wire feature resolver into grid core so `gridConfig.features` is handled automatically.\n// This runs when any feature module is imported (they all import this registry).\nsetFeatureResolver(createPluginsFromFeatures as (features: Record<string, unknown>) => GridPlugin[]);\n\n// #endregion\n\n// #region Testing Utilities\n\n/**\n * Clear the registry. For testing only.\n * @internal\n */\nexport function clearFeatureRegistry(): void {\n featureRegistry.clear();\n warnedFeatures.clear();\n}\n\n// #endregion\n"],"names":["warnDiagnostic","code","message","gridId","pluginName","console","warn","toLowerCase","docsUrl","formatDiagnostic","GRID_VERSION","REGISTRY_KEY","Symbol","for","WARNED_KEY","getOrCreateGlobal","key","make","value","Reflect","get","globalThis","set","featureRegistry","Map","warnedFeatures","Set","isDev","window","location","hostname","registerFeature","name","factory","options","has","override","isFeatureRegistered","getFeatureFactory","getRegisteredFeatures","Array","from","keys","PLUGIN_DEPENDENCIES","undoRedo","clipboard","createPluginFromFeature","config","entry","add","kebab","replace","createPluginsFromFeatures","features","enabledFeatures","Object","entries","push","featureNames","featureSet","feature","deps","dep","validateDependencies","plugins","featureName","plugin","length","byName","ordered","done","onStack","visit","constructor","dependencies","depPlugin","delete","orderPluginsByDependencies","clearFeatureRegistry","clear","setFeatureResolver"],"mappings":"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"}
@@ -1,2 +1,2 @@
1
- const e=/* @__PURE__ */new WeakMap;function t(t,n,r=-1){if(!n.valueAccessor)return t?.[n.field];if("object"!=typeof t||null===t)return n.valueAccessor({row:t,column:n,rowIndex:r});const o=t,i=n.field;let s=e.get(o);if(s){const e=s.get(i);if(void 0!==e)return e.v}else s=/* @__PURE__ */new Map,e.set(o,s);const l=n.valueAccessor({row:t,column:n,rowIndex:r});return s.set(i,{v:l}),l}function n(t,n){t&&(n?e.get(t)?.delete(n):e.delete(t))}function r(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function o(e,t,n,o){return`${r(n,o)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}const i="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(e=>e.split("").reverse().join(""));new RegExp(`__(proto|defineGetter|defineSetter)|${i.slice(3).join("|")}|this\\b`);const s=new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing".split("|")),l=/^on\w+$/i,a=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),c=/^\s*(javascript|vbscript|data|blob):/i;function u(e){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return t.innerHTML=e,function(e){const t=[],n=e.querySelectorAll("*");for(const r of n){const e=r.tagName.toLowerCase();if(s.has(e)){t.push(r);continue}if("svg"===e||"http://www.w3.org/2000/svg"===r.namespaceURI){if(Array.from(r.attributes).some(e=>l.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(r);continue}}const n=[];for(const t of r.attributes){const e=t.name.toLowerCase();l.test(e)?n.push(t.name):(a.has(e)&&c.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&n.push(t.name)}n.forEach(e=>r.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}const d={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};class h{static dependencies;static manifest;aliases;version="3.0.0-beta.4";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},n={};for(const r of Object.keys(t))n[r]=this;for(const r of e){const e=r.userConfig;for(const[i,s]of Object.entries(e)){if(void 0===s)continue;if(!(i in t)){t[i]=s,n[i]=r;continue}if(t[i]===s)continue;const e=n[i]?.constructor.name??this.constructor.name,l=r.constructor.name,a=o("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${i}" supplied by both ${e} and ${l}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(a)}}Object.assign(this.userConfig,t)}refreshUserConfigFrom(e){const t=this.userConfig,n={...e.userConfig};for(const r of Object.keys(t))delete t[r];Object.assign(t,n)}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const n=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(n),n.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}broadcast(e,t){this.emitPluginEvent(e,t),this.emit(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...d,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),n=parseInt(t,10);if(!isNaN(n))return n}return 200}setIcon(e,t,n){e.dataset.icon=t.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const r=this.#t(t,n);void 0!==r?"string"==typeof r?e.innerHTML=u(r):r instanceof HTMLElement&&(e.innerHTML="",e.appendChild(r.cloneNode(!0))):e.innerHTML=""}#t(e,t){return void 0!==t?t:this.grid?.gridConfig?.icons?.[e]}updateSortIndicator(e,t){e.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const n=document.createElement("span");n.setAttribute("part","sort-indicator"),n.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(n,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(n,"sortNone"));const r=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return r?e.insertBefore(n,r):e.appendChild(n),n}warn(e,t){void 0!==t?console.warn(o(e,t,this.gridElement.id,this.name)):console.warn(`${r(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(o(e,t,this.gridElement.id,this.name))}}function f(e,t,n=!0){let r=e;if(n&&(r=r.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.utility)),t?.length){const e=new Set(t);r=r.filter(t=>e.has(t.field))}return r}const g="data-tbw-clip";const p=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function m(e,t,n){const r=e?`<thead><tr>${e.map(e=>`<th>${p(e)}</th>`).join("")}</tr></thead>`:"",o=`<tbody>${t.map(e=>`<tr>${e.map(e=>`<td>${p(e)}</td>`).join("")}</tr>`).join("")}</tbody>`;return`<table ${g}="${function(e){return btoa(encodeURIComponent(JSON.stringify(e)))}(n)}">${r}${o}</table>`}async function w(e,t){if(t&&"undefined"!=typeof ClipboardItem&&navigator.clipboard?.write)try{return await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([e],{type:"text/plain"}),"text/html":new Blob([t],{type:"text/html"})})]),!0}catch{}try{return await navigator.clipboard.writeText(e),!0}catch(l){n="TBW100",r=`Clipboard API failed: ${l}`,console.warn(o(n,r,i,s));const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",t.style.pointerEvents="none",document.body.appendChild(t),t.select();const a=document.execCommand("copy");return document.body.removeChild(t),a}var n,r,i,s}function b(e,t){const n=t.delimiter??"\t",r=t.newline??"\n",o=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),i=o.length,s=[];let l=[],a=0,c=!1,u=!1;const d=e=>{const t=o.slice(a,e);return u?function(e){let t="",n=!1;for(let r=0;r<e.length;r++){const o=e[r];'"'===o?n?'"'===e[r+1]?(t+='"',r++):n=!1:n=!0:t+=o}return t}(t):t},h=()=>{(l.length>1||l.some(e=>""!==e.trim()))&&s.push(l),l=[]};for(let f=0;f<i;f++){const e=o[f];'"'===e?(u=!0,c?'"'===o[f+1]?f++:c=!1:c=!0):e!==n||c?e!==r||c||(l.push(d(f)),a=f+1,u=!1,h()):(l.push(d(f)),a=f+1,u=!1)}return l.push(d(i)),h(),s}function C(e,t){const{rows:r,rawRows:o,target:i,fields:s,fillSelection:l}=e;if(!i||0===r.length)return;const a=o??r,c=t.rows,u=(t.effectiveConfig.columns??[]).map(e=>e.field),[d=()=>!1]=t.query("getCellEditableResolver"),h=/* @__PURE__ */new Map;let f=c.length;const g=(e,t,n,r)=>{if(!t||!d(t,r))return;let o=h.get(e);o||(o={},h.set(e,o)),o[t]=y(n)};if(l&&i.bounds){const e=a.length;for(let t=i.row;t<=i.bounds.endRow&&!(t>=c.length);t++){const n=a[(t-i.row)%e],r=n.length;if(0===r)continue;const o=c[t];s.forEach((e,i)=>g(t,e,n[i%r],o))}}else{const e=i.bounds?i.bounds.endRow:1/0;a.forEach((t,n)=>{const r=i.row+n;if(r>e)return;if(i.bounds&&r>=c.length)return;!i.bounds&&r>=f&&(f=r+1);const o=c[r]??{};t.forEach((e,t)=>g(r,s[t],e,o))})}if(0===h.size&&f===c.length)return;if(f>c.length){const e=[...c];for(;e.length<f;){const t={};u.forEach(e=>t[e]=""),e.push(t)}t.rows=e}const p=t.rows,m=[];let w=!1;for(const[b,C]of h){const e=p[b];if(!e)continue;let r;try{r=t.getRowId(e)}catch{r=void 0}if(null==r){for(const[t,r]of Object.entries(C))e[t]=r,n(e,t);w=!0}else m.push({id:r,changes:C})}m.length>0?t.updateRows(m,"api"):w&&f===c.length&&(t.rows=[...p])}function y(e){if(null===e||"object"!=typeof e)return e;try{return structuredClone(e)}catch{return e}}class v extends h{static manifest={queries:[{type:"clipboard:copy",description:"Triggers a copy operation and returns the copied text"}]};static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:"\t",newline:"\n",quoteStrings:!1}}lastCopied=null;#n=null;attach(e){super.attach(e),e.addEventListener("paste",e=>this.#r(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null,this.#n=null}handleQuery(e){if("clipboard:copy"===e.type)return this.copy(),!0}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#o(e.target),!0)}#o(e){const t=this.#i();if(t&&0===t.ranges.length){let n,r;if(t.anchor)n=t.anchor.row,r=this.visibleColumns[t.anchor.col]?.field;else{const t=this.#s(e);t&&(n=t.row,r=this.columns[t.col]?.field)}if(null==n||null==r)return;return void this.copy({rowIndices:[n],columns:[r]})}this.copy()}#r(e){if(this.#l(e.target))return;const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const n=b(t,this.config),r=this.#i(),o=r?.ranges??[],i=o[0];let s=1/0,l=1/0,a=-1/0,c=-1/0;for(const g of o)s=Math.min(s,g.from.row,g.to.row),a=Math.max(a,g.from.row,g.to.row),l=Math.min(l,g.from.col,g.to.col),c=Math.max(c,g.from.col,g.to.col);const u=r?.anchor??null,d=i?s:u?.row??0,h=i?l:u?.col??0,f=!(!i||"range"!==r?.mode&&"row"!==r?.mode||s===a&&l===c)?{endRow:a,endCol:c}:null,p=f?.endCol??this.visibleColumns.length-1;let m;if(this.#a(n),this.#n&&this.#n.text===t&&this.#n.rawRows.length===n.length)m=this.#n.rawRows;else{const t=function(e){if(!e||-1===e.indexOf(g))return null;try{const t=e.match(new RegExp(`${g}="([A-Za-z0-9+/=]*)"`)),n=t?.[1];if(!n)return null;const r=JSON.parse(decodeURIComponent(atob(n)));return r&&Array.isArray(r.rows)&&Array.isArray(r.fields)?r:null}catch{return null}}(e.clipboardData?.getData("text/html"));t&&t.rows.length===n.length&&(m=t.rows)}const w=this.visibleColumns[h],C=w?{row:d,col:h,field:w.field,bounds:f}:null,y=!0===this.config.fillSelection&&null!==f,v=[],x=n[0]?.length??0,E=y?p-h+1:x;for(let g=0;g<E&&h+g<=p;g++){const e=this.visibleColumns[h+g];e&&v.push(e.field)}const S={rows:n,text:t,target:C,fields:v,fillSelection:y,rawRows:m};this.emit("paste",S),this.#c(S)}#c(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??C)(e,this.grid)}#a(e){if(!this.config.includeHeaders)return;if(e.length<=1)return;const t=e[0];if(0===t.length)return;const n=this.#u();for(const r of t)if(!n.has(r))return;e.shift()}#u(){const e=/* @__PURE__ */new Set;for(const t of this.columns){const n=t.header||t.field;n&&e.add(n)}return e}#l(e){return e instanceof Element&&!!e.closest('input, textarea, select, [contenteditable=""], [contenteditable="true"]')}#i(){const e=this.grid?.query("getSelection");return e?.[0]}#d(e){const t=this.#i();let n,r;if(e?.columns)n=f(this.columns,e.columns);else if(t?.ranges.length&&"row"!==t.mode){const e=t.ranges[t.ranges.length-1],r=Math.min(e.from.col,e.to.col),o=Math.max(e.from.col,e.to.col);n=f(this.visibleColumns.slice(r,o+1))}else n=f(this.columns);if(e?.rowIndices)r=function(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}(this.rows,e.rowIndices);else if(t?.ranges.length){const e=t.ranges[t.ranges.length-1],n=Math.min(e.from.row,e.to.row),o=Math.max(e.from.row,e.to.row);r=[];for(let t=n;t<=o;t++){const e=this.rows[t];e&&r.push(e)}}else r=this.rows;return{columns:n,rows:r}}#h(e,t,n){return this.#f(this.#g(e,t,n),n)}#g(e,n,r){const o=r?.includeHeaders??this.config.includeHeaders??!1,i=r?.processCell??this.config.processCell;return{header:o?e.map(e=>e.header||e.field):null,rows:n.map(n=>e.map(e=>{const r=t(n,e);return i?i(r,e.field,n):this.#p(e,r,n)}))}}#f(e,t){const n=t?.delimiter??this.config.delimiter??"\t",r=t?.newline??this.config.newline??"\n",o=[];e.header&&o.push(e.header.join(n));for(const i of e.rows)o.push(i.join(n));return o.join(r)}#p(e,t,n){if(e.format)try{const r=e.format(t,n);return null==r?"":String(r)}catch{}if(e.renderer||e.viewRenderer){const t=this.#m(e.field,n);if(null!=t)return t}return function(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}(t)}#m(e,t){const n=this.gridElement;if(!n)return null;const r=this.rows.indexOf(t);if(-1===r)return null;const o=n.querySelector(`.cell[data-row="${r}"][data-field="${e}"]`);return o?o.textContent?.trim()??null:null}#s(e){const t=e.closest(".cell[data-field]");if(!t)return null;const n=t.dataset.field,r=t.dataset.row;if(!n||!r)return null;const o=parseInt(r,10);if(isNaN(o))return null;const i=this.columns.findIndex(e=>e.field===n);return-1===i?null:{row:o,col:i}}getSelectionAsText(e){const{columns:t,rows:n}=this.#d(e);return 0===t.length||0===n.length?"":this.#h(t,n,e)}async copy(e){const{columns:n,rows:r}=this.#d(e);if(0===n.length||0===r.length)return"";const o=this.#g(n,r,e),i=this.#f(o,e),s=r.map(e=>n.map(n=>y(t(e,n)))),l=n.map(e=>e.field);return await w(i,m(o.header,o.rows,{v:1,fields:l,rows:s})),this.lastCopied={text:i,timestamp:Date.now()},this.#n={text:i,rawRows:s},this.emit("copy",{text:i,rowCount:r.length,columnCount:n.length}),i}async copyRows(e,t){return 0===e.length?"":this.copy({...t,rowIndices:e})}async paste(){const e=await async function(){try{return await navigator.clipboard.readText()}catch{return""}}();return e?b(e,this.config):null}getLastCopied(){return this.lastCopied}}export{v as ClipboardPlugin,C as defaultPasteHandler};
1
+ const e=/* @__PURE__ */new WeakMap;function t(t,n,r=-1){if(!n.valueAccessor)return t?.[n.field];if("object"!=typeof t||null===t)return n.valueAccessor({row:t,column:n,rowIndex:r});const o=t,i=n.field;let s=e.get(o);if(s){const e=s.get(i);if(void 0!==e)return e.v}else s=/* @__PURE__ */new Map,e.set(o,s);const l=n.valueAccessor({row:t,column:n,rowIndex:r});return s.set(i,{v:l}),l}function n(t,n){t&&(n?e.get(t)?.delete(n):e.delete(t))}function r(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function o(e,t,n,o){return`${r(n,o)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}const i="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(e=>e.split("").reverse().join(""));new RegExp(`__(proto|defineGetter|defineSetter)|${i.slice(3).join("|")}|this\\b`);const s=new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing".split("|")),l=/^on\w+$/i,a=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),c=/^\s*(javascript|vbscript|data|blob):/i;function u(e){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return t.innerHTML=e,function(e){const t=[],n=e.querySelectorAll("*");for(const r of n){const e=r.tagName.toLowerCase();if(s.has(e)){t.push(r);continue}if("svg"===e||"http://www.w3.org/2000/svg"===r.namespaceURI){if(Array.from(r.attributes).some(e=>l.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(r);continue}}const n=[];for(const t of r.attributes){const e=t.name.toLowerCase();l.test(e)?n.push(t.name):(a.has(e)&&c.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&n.push(t.name)}n.forEach(e=>r.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}const d={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};class h{static dependencies;static manifest;aliases;version="3.0.0-rc.0";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},n={};for(const r of Object.keys(t))n[r]=this;for(const r of e){const e=r.userConfig;for(const[i,s]of Object.entries(e)){if(void 0===s)continue;if(!(i in t)){t[i]=s,n[i]=r;continue}if(t[i]===s)continue;const e=n[i]?.constructor.name??this.constructor.name,l=r.constructor.name,a=o("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${i}" supplied by both ${e} and ${l}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(a)}}Object.assign(this.userConfig,t)}refreshUserConfigFrom(e){const t=this.userConfig,n={...e.userConfig};for(const r of Object.keys(t))delete t[r];Object.assign(t,n)}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const n=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(n),n.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}broadcast(e,t){this.emitPluginEvent(e,t),this.emit(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...d,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),n=parseInt(t,10);if(!isNaN(n))return n}return 200}setIcon(e,t,n){e.dataset.icon=t.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const r=this.#t(t,n);void 0!==r?"string"==typeof r?e.innerHTML=u(r):r instanceof HTMLElement&&(e.innerHTML="",e.appendChild(r.cloneNode(!0))):e.innerHTML=""}#t(e,t){return void 0!==t?t:this.grid?.gridConfig?.icons?.[e]}updateSortIndicator(e,t){e.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const n=document.createElement("span");n.setAttribute("part","sort-indicator"),n.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(n,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(n,"sortNone"));const r=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return r?e.insertBefore(n,r):e.appendChild(n),n}warn(e,t){void 0!==t?console.warn(o(e,t,this.gridElement.id,this.name)):console.warn(`${r(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(o(e,t,this.gridElement.id,this.name))}}function f(e,t,n=!0){let r=e;if(n&&(r=r.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.utility)),t?.length){const e=new Set(t);r=r.filter(t=>e.has(t.field))}return r}const g="data-tbw-clip";const p=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function m(e,t,n){const r=e?`<thead><tr>${e.map(e=>`<th>${p(e)}</th>`).join("")}</tr></thead>`:"",o=`<tbody>${t.map(e=>`<tr>${e.map(e=>`<td>${p(e)}</td>`).join("")}</tr>`).join("")}</tbody>`;return`<table ${g}="${function(e){return btoa(encodeURIComponent(JSON.stringify(e)))}(n)}">${r}${o}</table>`}async function w(e,t){if(t&&"undefined"!=typeof ClipboardItem&&navigator.clipboard?.write)try{return await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([e],{type:"text/plain"}),"text/html":new Blob([t],{type:"text/html"})})]),!0}catch{}try{return await navigator.clipboard.writeText(e),!0}catch(l){n="TBW100",r=`Clipboard API failed: ${l}`,console.warn(o(n,r,i,s));const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",t.style.pointerEvents="none",document.body.appendChild(t),t.select();const a=document.execCommand("copy");return document.body.removeChild(t),a}var n,r,i,s}function b(e,t){const n=t.delimiter??"\t",r=t.newline??"\n",o=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),i=o.length,s=[];let l=[],a=0,c=!1,u=!1;const d=e=>{const t=o.slice(a,e);return u?function(e){let t="",n=!1;for(let r=0;r<e.length;r++){const o=e[r];'"'===o?n?'"'===e[r+1]?(t+='"',r++):n=!1:n=!0:t+=o}return t}(t):t},h=()=>{(l.length>1||l.some(e=>""!==e.trim()))&&s.push(l),l=[]};for(let f=0;f<i;f++){const e=o[f];'"'===e?(u=!0,c?'"'===o[f+1]?f++:c=!1:c=!0):e!==n||c?e!==r||c||(l.push(d(f)),a=f+1,u=!1,h()):(l.push(d(f)),a=f+1,u=!1)}return l.push(d(i)),h(),s}function C(e,t){const{rows:r,rawRows:o,target:i,fields:s,fillSelection:l}=e;if(!i||0===r.length)return;const a=o??r,c=t.rows,u=(t.effectiveConfig.columns??[]).map(e=>e.field),[d=()=>!1]=t.query("getCellEditableResolver"),h=/* @__PURE__ */new Map;let f=c.length;const g=(e,t,n,r)=>{if(!t||!d(t,r))return;let o=h.get(e);o||(o={},h.set(e,o)),o[t]=y(n)};if(l&&i.bounds){const e=a.length;for(let t=i.row;t<=i.bounds.endRow&&!(t>=c.length);t++){const n=a[(t-i.row)%e],r=n.length;if(0===r)continue;const o=c[t];s.forEach((e,i)=>g(t,e,n[i%r],o))}}else{const e=i.bounds?i.bounds.endRow:1/0;a.forEach((t,n)=>{const r=i.row+n;if(r>e)return;if(i.bounds&&r>=c.length)return;!i.bounds&&r>=f&&(f=r+1);const o=c[r]??{};t.forEach((e,t)=>g(r,s[t],e,o))})}if(0===h.size&&f===c.length)return;if(f>c.length){const e=[...c];for(;e.length<f;){const t={};u.forEach(e=>t[e]=""),e.push(t)}t.rows=e}const p=t.rows,m=[];let w=!1;for(const[b,C]of h){const e=p[b];if(!e)continue;let r;try{r=t.getRowId(e)}catch{r=void 0}if(null==r){for(const[t,r]of Object.entries(C))e[t]=r,n(e,t);w=!0}else m.push({id:r,changes:C})}m.length>0?t.updateRows(m,"api"):w&&f===c.length&&(t.rows=[...p])}function y(e){if(null===e||"object"!=typeof e)return e;try{return structuredClone(e)}catch{return e}}class v extends h{static manifest={queries:[{type:"clipboard:copy",description:"Triggers a copy operation and returns the copied text"}]};static dependencies=[{name:"selection",required:!1,reason:"Enables copy/paste of selected cells instead of entire grid"}];name="clipboard";get defaultConfig(){return{includeHeaders:!1,delimiter:"\t",newline:"\n",quoteStrings:!1}}lastCopied=null;#n=null;attach(e){super.attach(e),e.addEventListener("paste",e=>this.#r(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null,this.#n=null}handleQuery(e){if("clipboard:copy"===e.type)return this.copy(),!0}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#o(e.target),!0)}#o(e){const t=this.#i();if(t&&0===t.ranges.length){let n,r;if(t.anchor)n=t.anchor.row,r=this.visibleColumns[t.anchor.col]?.field;else{const t=this.#s(e);t&&(n=t.row,r=this.columns[t.col]?.field)}if(null==n||null==r)return;return void this.copy({rowIndices:[n],columns:[r]})}this.copy()}#r(e){if(this.#l(e.target))return;const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const n=b(t,this.config),r=this.#i(),o=r?.ranges??[],i=o[0];let s=1/0,l=1/0,a=-1/0,c=-1/0;for(const g of o)s=Math.min(s,g.from.row,g.to.row),a=Math.max(a,g.from.row,g.to.row),l=Math.min(l,g.from.col,g.to.col),c=Math.max(c,g.from.col,g.to.col);const u=r?.anchor??null,d=i?s:u?.row??0,h=i?l:u?.col??0,f=!(!i||"range"!==r?.mode&&"row"!==r?.mode||s===a&&l===c)?{endRow:a,endCol:c}:null,p=f?.endCol??this.visibleColumns.length-1;let m;if(this.#a(n),this.#n&&this.#n.text===t&&this.#n.rawRows.length===n.length)m=this.#n.rawRows;else{const t=function(e){if(!e||-1===e.indexOf(g))return null;try{const t=e.match(new RegExp(`${g}="([A-Za-z0-9+/=]*)"`)),n=t?.[1];if(!n)return null;const r=JSON.parse(decodeURIComponent(atob(n)));return r&&Array.isArray(r.rows)&&Array.isArray(r.fields)?r:null}catch{return null}}(e.clipboardData?.getData("text/html"));t&&t.rows.length===n.length&&(m=t.rows)}const w=this.visibleColumns[h],C=w?{row:d,col:h,field:w.field,bounds:f}:null,y=!0===this.config.fillSelection&&null!==f,v=[],x=n[0]?.length??0,E=y?p-h+1:x;for(let g=0;g<E&&h+g<=p;g++){const e=this.visibleColumns[h+g];e&&v.push(e.field)}const S={rows:n,text:t,target:C,fields:v,fillSelection:y,rawRows:m};this.emit("paste",S),this.#c(S)}#c(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??C)(e,this.grid)}#a(e){if(!this.config.includeHeaders)return;if(e.length<=1)return;const t=e[0];if(0===t.length)return;const n=this.#u();for(const r of t)if(!n.has(r))return;e.shift()}#u(){const e=/* @__PURE__ */new Set;for(const t of this.columns){const n=t.header||t.field;n&&e.add(n)}return e}#l(e){return e instanceof Element&&!!e.closest('input, textarea, select, [contenteditable=""], [contenteditable="true"]')}#i(){const e=this.grid?.query("getSelection");return e?.[0]}#d(e){const t=this.#i();let n,r;if(e?.columns)n=f(this.columns,e.columns);else if(t?.ranges.length&&"row"!==t.mode){const e=t.ranges[t.ranges.length-1],r=Math.min(e.from.col,e.to.col),o=Math.max(e.from.col,e.to.col);n=f(this.visibleColumns.slice(r,o+1))}else n=f(this.columns);if(e?.rowIndices)r=function(e,t){return t?.length?[...t].sort((e,t)=>e-t).map(t=>e[t]).filter(e=>null!=e):e}(this.rows,e.rowIndices);else if(t?.ranges.length){const e=t.ranges[t.ranges.length-1],n=Math.min(e.from.row,e.to.row),o=Math.max(e.from.row,e.to.row);r=[];for(let t=n;t<=o;t++){const e=this.rows[t];e&&r.push(e)}}else r=this.rows;return{columns:n,rows:r}}#h(e,t,n){return this.#f(this.#g(e,t,n),n)}#g(e,n,r){const o=r?.includeHeaders??this.config.includeHeaders??!1,i=r?.processCell??this.config.processCell;return{header:o?e.map(e=>e.header||e.field):null,rows:n.map(n=>e.map(e=>{const r=t(n,e);return i?i(r,e.field,n):this.#p(e,r,n)}))}}#f(e,t){const n=t?.delimiter??this.config.delimiter??"\t",r=t?.newline??this.config.newline??"\n",o=[];e.header&&o.push(e.header.join(n));for(const i of e.rows)o.push(i.join(n));return o.join(r)}#p(e,t,n){if(e.format)try{const r=e.format(t,n);return null==r?"":String(r)}catch{}if(e.renderer||e.viewRenderer){const t=this.#m(e.field,n);if(null!=t)return t}return function(e){return null==e?"":e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e)}(t)}#m(e,t){const n=this.gridElement;if(!n)return null;const r=this.rows.indexOf(t);if(-1===r)return null;const o=n.querySelector(`.cell[data-row="${r}"][data-field="${e}"]`);return o?o.textContent?.trim()??null:null}#s(e){const t=e.closest(".cell[data-field]");if(!t)return null;const n=t.dataset.field,r=t.dataset.row;if(!n||!r)return null;const o=parseInt(r,10);if(isNaN(o))return null;const i=this.columns.findIndex(e=>e.field===n);return-1===i?null:{row:o,col:i}}getSelectionAsText(e){const{columns:t,rows:n}=this.#d(e);return 0===t.length||0===n.length?"":this.#h(t,n,e)}async copy(e){const{columns:n,rows:r}=this.#d(e);if(0===n.length||0===r.length)return"";const o=this.#g(n,r,e),i=this.#f(o,e),s=r.map(e=>n.map(n=>y(t(e,n)))),l=n.map(e=>e.field);return await w(i,m(o.header,o.rows,{v:1,fields:l,rows:s})),this.lastCopied={text:i,timestamp:Date.now()},this.#n={text:i,rawRows:s},this.emit("copy",{text:i,rowCount:r.length,columnCount:n.length}),i}async copyRows(e,t){return 0===e.length?"":this.copy({...t,rowIndices:e})}async paste(){const e=await async function(){try{return await navigator.clipboard.readText()}catch{return""}}();return e?b(e,this.config):null}getLastCopied(){return this.lastCopied}}export{v as ClipboardPlugin,C as defaultPasteHandler};
2
2
  //# sourceMappingURL=index.js.map