@toolbox-web/grid 2.0.0-rc.1 → 2.0.0-rc.3

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 (110) hide show
  1. package/README.md +23 -6
  2. package/all.js +2 -2
  3. package/all.js.map +1 -1
  4. package/index.js +1 -1
  5. package/index.js.map +1 -1
  6. package/lib/core/internal/diagnostics.d.ts +9 -1
  7. package/lib/core/internal/sorting.d.ts +4 -0
  8. package/lib/core/plugin/base-plugin.d.ts +31 -0
  9. package/lib/core/plugin/plugin-manager.d.ts +4 -1
  10. package/lib/core/plugin/types.d.ts +2 -0
  11. package/lib/core/types.d.ts +20 -1
  12. package/lib/features/registry.js.map +1 -1
  13. package/lib/plugins/clipboard/ClipboardPlugin.d.ts +8 -1
  14. package/lib/plugins/clipboard/index.js +1 -1
  15. package/lib/plugins/clipboard/index.js.map +1 -1
  16. package/lib/plugins/column-virtualization/index.js +1 -1
  17. package/lib/plugins/column-virtualization/index.js.map +1 -1
  18. package/lib/plugins/context-menu/index.js +1 -1
  19. package/lib/plugins/context-menu/index.js.map +1 -1
  20. package/lib/plugins/editing/index.js +1 -1
  21. package/lib/plugins/editing/index.js.map +1 -1
  22. package/lib/plugins/export/ExportPlugin.d.ts +8 -1
  23. package/lib/plugins/export/index.js +1 -1
  24. package/lib/plugins/export/index.js.map +1 -1
  25. package/lib/plugins/filtering/index.js +1 -1
  26. package/lib/plugins/filtering/index.js.map +1 -1
  27. package/lib/plugins/grouping-columns/index.js +1 -1
  28. package/lib/plugins/grouping-columns/index.js.map +1 -1
  29. package/lib/plugins/grouping-rows/GroupingRowsPlugin.d.ts +46 -22
  30. package/lib/plugins/grouping-rows/grouping-rows.d.ts +15 -1
  31. package/lib/plugins/grouping-rows/index.js +2 -2
  32. package/lib/plugins/grouping-rows/index.js.map +1 -1
  33. package/lib/plugins/grouping-rows/types.d.ts +7 -35
  34. package/lib/plugins/master-detail/MasterDetailPlugin.d.ts +30 -0
  35. package/lib/plugins/master-detail/index.js +1 -1
  36. package/lib/plugins/master-detail/index.js.map +1 -1
  37. package/lib/plugins/multi-sort/index.js +1 -1
  38. package/lib/plugins/multi-sort/index.js.map +1 -1
  39. package/lib/plugins/pinned-columns/index.js +1 -1
  40. package/lib/plugins/pinned-columns/index.js.map +1 -1
  41. package/lib/plugins/pinned-rows/index.js +1 -1
  42. package/lib/plugins/pinned-rows/index.js.map +1 -1
  43. package/lib/plugins/pivot/PivotPlugin.d.ts +10 -0
  44. package/lib/plugins/pivot/index.js +1 -1
  45. package/lib/plugins/pivot/index.js.map +1 -1
  46. package/lib/plugins/print/index.js +1 -1
  47. package/lib/plugins/print/index.js.map +1 -1
  48. package/lib/plugins/reorder-columns/index.js +1 -1
  49. package/lib/plugins/reorder-columns/index.js.map +1 -1
  50. package/lib/plugins/reorder-rows/RowReorderPlugin.d.ts +3 -0
  51. package/lib/plugins/reorder-rows/index.js +1 -1
  52. package/lib/plugins/reorder-rows/index.js.map +1 -1
  53. package/lib/plugins/responsive/index.js +1 -1
  54. package/lib/plugins/responsive/index.js.map +1 -1
  55. package/lib/plugins/selection/index.js +1 -1
  56. package/lib/plugins/selection/index.js.map +1 -1
  57. package/lib/plugins/server-side/ServerSidePlugin.d.ts +48 -14
  58. package/lib/plugins/server-side/datasource-types.d.ts +189 -0
  59. package/lib/plugins/server-side/datasource.d.ts +5 -5
  60. package/lib/plugins/server-side/index.d.ts +1 -1
  61. package/lib/plugins/server-side/index.js +1 -1
  62. package/lib/plugins/server-side/index.js.map +1 -1
  63. package/lib/plugins/server-side/types.d.ts +8 -82
  64. package/lib/plugins/tooltip/index.js +1 -1
  65. package/lib/plugins/tooltip/index.js.map +1 -1
  66. package/lib/plugins/tree/TreePlugin.d.ts +26 -4
  67. package/lib/plugins/tree/index.js +1 -1
  68. package/lib/plugins/tree/index.js.map +1 -1
  69. package/lib/plugins/tree/tree-datasource.d.ts +13 -0
  70. package/lib/plugins/tree/types.d.ts +19 -0
  71. package/lib/plugins/undo-redo/index.js +1 -1
  72. package/lib/plugins/undo-redo/index.js.map +1 -1
  73. package/lib/plugins/visibility/index.js +1 -1
  74. package/lib/plugins/visibility/index.js.map +1 -1
  75. package/package.json +1 -1
  76. package/public.d.ts +3 -0
  77. package/umd/grid.all.umd.js +1 -1
  78. package/umd/grid.all.umd.js.map +1 -1
  79. package/umd/grid.umd.js +1 -1
  80. package/umd/grid.umd.js.map +1 -1
  81. package/umd/plugins/clipboard.umd.js +1 -1
  82. package/umd/plugins/clipboard.umd.js.map +1 -1
  83. package/umd/plugins/context-menu.umd.js +1 -1
  84. package/umd/plugins/context-menu.umd.js.map +1 -1
  85. package/umd/plugins/editing.umd.js +1 -1
  86. package/umd/plugins/editing.umd.js.map +1 -1
  87. package/umd/plugins/export.umd.js +1 -1
  88. package/umd/plugins/export.umd.js.map +1 -1
  89. package/umd/plugins/filtering.umd.js +1 -1
  90. package/umd/plugins/filtering.umd.js.map +1 -1
  91. package/umd/plugins/grouping-rows.umd.js +1 -1
  92. package/umd/plugins/grouping-rows.umd.js.map +1 -1
  93. package/umd/plugins/master-detail.umd.js +1 -1
  94. package/umd/plugins/master-detail.umd.js.map +1 -1
  95. package/umd/plugins/multi-sort.umd.js +1 -1
  96. package/umd/plugins/multi-sort.umd.js.map +1 -1
  97. package/umd/plugins/pinned-columns.umd.js +1 -1
  98. package/umd/plugins/pinned-columns.umd.js.map +1 -1
  99. package/umd/plugins/pivot.umd.js +1 -1
  100. package/umd/plugins/pivot.umd.js.map +1 -1
  101. package/umd/plugins/reorder-rows.umd.js +1 -1
  102. package/umd/plugins/reorder-rows.umd.js.map +1 -1
  103. package/umd/plugins/selection.umd.js +1 -1
  104. package/umd/plugins/selection.umd.js.map +1 -1
  105. package/umd/plugins/server-side.umd.js +1 -1
  106. package/umd/plugins/server-side.umd.js.map +1 -1
  107. package/umd/plugins/tooltip.umd.js +1 -1
  108. package/umd/plugins/tooltip.umd.js.map +1 -1
  109. package/umd/plugins/tree.umd.js +1 -1
  110. package/umd/plugins/tree.umd.js.map +1 -1
@@ -128,7 +128,15 @@ export declare const STYLE_EXTRACT_FAILED: "TBW120";
128
128
  export declare const STYLE_NOT_FOUND: "TBW121";
129
129
  /** Invalid JSON in an HTML attribute. */
130
130
  export declare const INVALID_ATTRIBUTE_JSON: "TBW130";
131
- export type DiagnosticCode = typeof MISSING_PLUGIN | typeof MISSING_PLUGIN_CONFIG | typeof CONFIG_RULE_ERROR | typeof CONFIG_RULE_WARN | typeof MISSING_DEPENDENCY | typeof OPTIONAL_DEPENDENCY | typeof INCOMPATIBLE_PLUGINS | typeof PLUGIN_EVENT_ERROR | typeof FEATURE_REREGISTERED | typeof FEATURE_NOT_IMPORTED | typeof FEATURE_MISSING_DEP | typeof MISSING_ROW_ID | typeof ROW_NOT_FOUND | typeof INVALID_COLUMN_WIDTH | typeof ROW_CLASS_ERROR | typeof CELL_CLASS_ERROR | typeof FORMAT_ERROR | typeof VIEW_MOUNT_ERROR | typeof VIEW_DISPATCH_ERROR | typeof TOOL_PANEL_MISSING_ATTR | typeof NO_TOOL_PANELS | typeof TOOL_PANEL_NOT_FOUND | typeof TOOL_PANEL_DUPLICATE | typeof HEADER_CONTENT_DUPLICATE | typeof TOOLBAR_CONTENT_DUPLICATE | typeof EDITOR_MOUNT_ERROR | typeof PRINT_IN_PROGRESS | typeof PRINT_NO_GRID | typeof PRINT_FAILED | typeof PRINT_DUPLICATE_ID | typeof CLIPBOARD_FAILED | typeof MISSING_BREAKPOINT | typeof TRANSACTION_IN_PROGRESS | typeof NO_TRANSACTION | typeof COLUMN_GROUP_NO_ID | typeof COLUMN_GROUPS_CONFLICT | typeof STYLE_EXTRACT_FAILED | typeof STYLE_NOT_FOUND | typeof INVALID_ATTRIBUTE_JSON;
131
+ /** ServerSidePlugin: getRows() rejected. */
132
+ export declare const DATASOURCE_FETCH_ERROR: "TBW140";
133
+ /** ServerSidePlugin: getChildRows() rejected. */
134
+ export declare const DATASOURCE_CHILD_FETCH_ERROR: "TBW141";
135
+ /** ServerSidePlugin: getChildRows() not implemented but a plugin queried for children. */
136
+ export declare const DATASOURCE_NO_CHILD_HANDLER: "TBW142";
137
+ /** ServerSidePlugin: concurrent request limit reached, request deferred. */
138
+ export declare const DATASOURCE_THROTTLED: "TBW143";
139
+ export type DiagnosticCode = typeof MISSING_PLUGIN | typeof MISSING_PLUGIN_CONFIG | typeof CONFIG_RULE_ERROR | typeof CONFIG_RULE_WARN | typeof MISSING_DEPENDENCY | typeof OPTIONAL_DEPENDENCY | typeof INCOMPATIBLE_PLUGINS | typeof PLUGIN_EVENT_ERROR | typeof FEATURE_REREGISTERED | typeof FEATURE_NOT_IMPORTED | typeof FEATURE_MISSING_DEP | typeof MISSING_ROW_ID | typeof ROW_NOT_FOUND | typeof INVALID_COLUMN_WIDTH | typeof ROW_CLASS_ERROR | typeof CELL_CLASS_ERROR | typeof FORMAT_ERROR | typeof VIEW_MOUNT_ERROR | typeof VIEW_DISPATCH_ERROR | typeof TOOL_PANEL_MISSING_ATTR | typeof NO_TOOL_PANELS | typeof TOOL_PANEL_NOT_FOUND | typeof TOOL_PANEL_DUPLICATE | typeof HEADER_CONTENT_DUPLICATE | typeof TOOLBAR_CONTENT_DUPLICATE | typeof EDITOR_MOUNT_ERROR | typeof PRINT_IN_PROGRESS | typeof PRINT_NO_GRID | typeof PRINT_FAILED | typeof PRINT_DUPLICATE_ID | typeof CLIPBOARD_FAILED | typeof MISSING_BREAKPOINT | typeof TRANSACTION_IN_PROGRESS | typeof NO_TRANSACTION | typeof COLUMN_GROUP_NO_ID | typeof COLUMN_GROUPS_CONFLICT | typeof STYLE_EXTRACT_FAILED | typeof STYLE_NOT_FOUND | typeof INVALID_ATTRIBUTE_JSON | typeof DATASOURCE_FETCH_ERROR | typeof DATASOURCE_CHILD_FETCH_ERROR | typeof DATASOURCE_NO_CHILD_HANDLER | typeof DATASOURCE_THROTTLED;
132
140
  /**
133
141
  * Format a diagnostic message with prefix, code, and docs link.
134
142
  *
@@ -74,5 +74,9 @@ export declare function reapplyCoreSort<T>(grid: InternalGrid<T>, rows: T[]): T[
74
74
  *
75
75
  * Uses custom sortHandler from gridConfig if provided, otherwise uses built-in sorting.
76
76
  * Supports both sync and async handlers (for server-side sorting).
77
+ *
78
+ * When row-model plugins are active (grouping, tree, pivot), delegates to the render
79
+ * scheduler so the full pipeline (reapplyCoreSort → processRows) runs on base rows.
80
+ * This prevents sorting from corrupting plugin-generated row structures.
77
81
  */
78
82
  export declare function applySort(grid: GridHost, col: ColumnConfig<any>, dir: 1 | -1): void;
@@ -274,6 +274,18 @@ export interface PluginManifest<TConfig = unknown> {
274
274
  * ```
275
275
  */
276
276
  events?: EventDefinition[];
277
+ /**
278
+ * Whether this plugin's `processRows` hook injects or removes rows
279
+ * (group headers, tree nodes, pivot aggregates, placeholders, etc.).
280
+ *
281
+ * When true, the core sorting module delegates to the render scheduler
282
+ * instead of sorting `_rows` in-place, because `_rows` may contain
283
+ * plugin-generated marker objects that would be corrupted by a direct sort.
284
+ *
285
+ * Plugins that only **filter** or **reorder** existing rows (e.g. Filtering,
286
+ * MultiSort) should leave this unset or set it to `false`.
287
+ */
288
+ modifiesRowStructure?: boolean;
277
289
  }
278
290
  /** Convert camelCase icon key to kebab-case data-icon attribute value. */
279
291
  export declare function toIconAttr(key: string): string;
@@ -496,6 +508,25 @@ export declare abstract class BaseGridPlugin<TConfig = unknown> implements GridP
496
508
  * ```
497
509
  */
498
510
  protected emitPluginEvent<T>(eventType: string, detail: T): void;
511
+ /**
512
+ * Emit an event to **both** the plugin Event Bus (for inter-plugin communication)
513
+ * **and** the DOM (for external consumers via `addEventListener`).
514
+ *
515
+ * Use this when a state change is relevant to both other plugins and external
516
+ * consumers. For example, `sort-change` needs to invalidate Selection (plugin bus)
517
+ * and notify the host application (DOM event).
518
+ *
519
+ * @category Plugin Development
520
+ * @param eventType - The event type to broadcast
521
+ * @param detail - The event payload
522
+ *
523
+ * @example
524
+ * ```typescript
525
+ * // Notify both plugins and consumers of a sort change
526
+ * this.broadcast('sort-change', { sortModel: [...this.sortModel] });
527
+ * ```
528
+ */
529
+ protected broadcast<T>(eventType: string, detail: T): void;
499
530
  /**
500
531
  * Request a re-render of the grid.
501
532
  * Uses ROWS phase - does NOT trigger processColumns hooks.
@@ -24,7 +24,10 @@ export declare class PluginManager {
24
24
  /** Cached hook presence flags — invalidated on plugin attach/detach */
25
25
  private _hasAfterCellRender;
26
26
  private _hasAfterRowRender;
27
- private _hasProcessRows;
27
+ /** Whether any plugin has a processRows hook. */
28
+ _hasProcessRows: boolean;
29
+ /** Whether any plugin with `modifiesRowStructure` is attached. Exposed for the sorting module. */
30
+ _hasRowStructurePlugins: boolean;
28
31
  /**
29
32
  * Event listeners indexed by event type.
30
33
  * Maps event type → Map<plugin instance → callback>.
@@ -329,6 +329,8 @@ export interface GridElementRef {
329
329
  subscribe(plugin: unknown, eventType: string, callback: (detail: unknown) => void): void;
330
330
  unsubscribe(plugin: unknown, eventType: string): void;
331
331
  emitPluginEvent<T>(eventType: string, detail: T): void;
332
+ /** Whether any attached plugin injects/removes rows (group headers, tree nodes, etc.). */
333
+ _hasRowStructurePlugins: boolean;
332
334
  };
333
335
  /**
334
336
  * Query plugins with a simplified API.
@@ -462,6 +462,10 @@ export interface InternalGrid<T = any> extends PublicGrid<T>, GridConfig<T> {
462
462
  __hasSpecialColumns?: boolean;
463
463
  /** Cached flag for whether any plugin has renderRow hooks. @internal */
464
464
  __hasRenderRowPlugins?: boolean;
465
+ /** @internal Access the plugin manager's cached state. */
466
+ _pluginManager?: {
467
+ _hasRowStructurePlugins: boolean;
468
+ };
465
469
  _gridTemplate: string;
466
470
  _virtualization: VirtualState;
467
471
  _focusRow: number;
@@ -1192,6 +1196,19 @@ export interface CellRenderContext<TRow = any, TValue = any> {
1192
1196
  field: keyof TRow & string;
1193
1197
  /** Column configuration reference. */
1194
1198
  column: ColumnConfig<TRow>;
1199
+ /**
1200
+ * The grid element that owns this cell.
1201
+ * Use to access public grid API (e.g., `getPluginByName()`) from custom renderers.
1202
+ *
1203
+ * @example
1204
+ * ```typescript
1205
+ * const renderer: ColumnViewRenderer<MyRow> = (ctx) => {
1206
+ * const tree = ctx.grid?.getPluginByName('tree');
1207
+ * // ...
1208
+ * };
1209
+ * ```
1210
+ */
1211
+ grid?: DataGridElement;
1195
1212
  /**
1196
1213
  * The cell DOM element being rendered into.
1197
1214
  * Framework adapters can use this to cache per-cell state (e.g., React roots).
@@ -1433,9 +1450,11 @@ export interface FrameworkAdapter {
1433
1450
  * Used by Angular's `GridTypeRegistry` and React's `GridTypeProvider`.
1434
1451
  *
1435
1452
  * @param type - The column type (e.g., 'date', 'currency', 'country')
1453
+ * @param gridEl - The owning `<tbw-grid>` element. Helps adapters resolve
1454
+ * the correct context provider in multi-grid scenarios.
1436
1455
  * @returns Type defaults for renderer/editor, or undefined if not registered
1437
1456
  */
1438
- getTypeDefault?<TRow = unknown>(type: string): TypeDefault<TRow> | undefined;
1457
+ getTypeDefault?<TRow = unknown>(type: string, gridEl?: HTMLElement): TypeDefault<TRow> | undefined;
1439
1458
  /**
1440
1459
  * Pre-process a grid config before the grid core applies it.
1441
1460
  * Framework adapters use this to convert framework-specific component references
@@ -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/** Error thrown inside a plugin event handler. */\nexport const PLUGIN_EVENT_ERROR = 'TBW024' 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\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_EVENT_ERROR\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\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 { 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\nconst featureRegistry = new Map<string, RegistryEntry>();\nconst warnedFeatures = 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/**\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 */\nexport function registerFeature<K extends FeatureName>(name: K, factory: PluginFactory<FeatureConfig[K]>): void;\nexport function registerFeature(name: string, factory: PluginFactory): void;\nexport function registerFeature(name: string, factory: PluginFactory): void {\n if (isDev() && featureRegistry.has(name)) {\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 (selection before clipboard)\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 plugins: 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\n validateDependencies(enabledFeatures);\n\n // Create plugins in dependency order: dep-targets first, then the rest\n const dependencyOrder: string[] = [\n 'selection',\n 'editing',\n ...enabledFeatures.filter((f) => f !== 'selection' && f !== 'editing'),\n ];\n const orderedFeatures = [...new Set(dependencyOrder)].filter((f) => enabledFeatures.includes(f));\n\n for (const featureName of orderedFeatures) {\n const config = features[featureName];\n if (config === undefined || config === false) continue;\n\n const plugin = createPluginFromFeature(featureName, config);\n if (plugin) {\n plugins.push(plugin);\n }\n }\n\n return plugins;\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","featureRegistry","Map","warnedFeatures","Set","isDev","window","location","hostname","registerFeature","name","factory","has","set","isFeatureRegistered","getFeatureFactory","get","getRegisteredFeatures","Array","from","keys","PLUGIN_DEPENDENCIES","undoRedo","clipboard","createPluginFromFeature","config","entry","add","kebab","replace","createPluginsFromFeatures","features","plugins","enabledFeatures","key","value","Object","entries","push","featureNames","featureSet","feature","deps","dep","validateDependencies","dependencyOrder","filter","f","orderedFeatures","includes","featureName","plugin","clearFeatureRegistry","clear","setFeatureResolver"],"mappings":"uDAgQO,SAASA,EAAeC,EAAsBC,EAAiBC,EAAiBC,GACrFC,QAAQC,KAtBH,SAA0BL,EAAsBC,GAErD,MAAO,cAAaD,MAASC,uBApB/B,SAAiBD,GACf,MAAO,qCAAgBA,EAAKM,eAC9B,CAkB4DC,CAAQP,IACpE,CAmBeQ,CAAiBR,EAAMC,GACtC,CC9MA,MAAMQ,qBAAsBC,IACtBC,qBAAqBC,IAOrBC,EAAQ,IACM,oBAAXC,SACwB,cAA9BA,OAAOC,UAAUC,UAA0D,cAA9BF,OAAOC,UAAUC,UAW1D,SAASC,EAAgBC,EAAcC,GACxCN,KAAWJ,EAAgBW,IAAIF,IACjCnB,EDYgC,SCZK,YAAYmB,4DAEnDT,EAAgBY,IAAIH,EAAM,CAAEC,UAASD,QACvC,CAKO,SAASI,EAAoBJ,GAClC,OAAOT,EAAgBW,IAAIF,EAC7B,CAKO,SAASK,EAAkBL,GAChC,OAAOT,EAAgBe,IAAIN,IAAOC,OACpC,CAKO,SAASM,IACd,OAAOC,MAAMC,KAAKlB,EAAgBmB,OACpC,CAUA,MAAMC,EAAgD,CACpDC,SAAU,CAAC,WACXC,UAAW,CAAC,cAOP,SAASC,EAAwBd,EAAce,GACpD,MAAMC,EAAQzB,EAAgBe,IAAIN,GAElC,GAAKgB,EAcL,OAAOA,EAAMf,QAAQc,GAbnB,GAAIpB,MAAYF,EAAeS,IAAIF,GAAO,CACxCP,EAAewB,IAAIjB,GACnB,MAAMkB,EAAQlB,EAAKmB,QAAQ,kBAAmB,SAAS/B,cACvDP,EDpC8B,SCsC5B,YAAYmB,+GAE8BkB,QAE9C,CAKJ,CAoCO,SAASE,EAA0BC,GACxC,MAAMC,EAAwB,GACxBC,EAA4B,GAGlC,IAAA,MAAYC,EAAKC,KAAUC,OAAOC,QAAQN,QAC1B,IAAVI,IAAiC,IAAVA,GAC3BF,EAAgBK,KAAKJ,IAtCzB,SAA8BK,GAC5B,MAAMC,EAAa,IAAIpC,IAAImC,GAE3B,IAAA,MAAWE,KAAWF,EAAc,CAClC,MAAMG,EAAOrB,EAAoBoB,GACjC,GAAKC,EAEL,IAAA,MAAWC,KAAOD,EACXF,EAAW5B,IAAI+B,IACdtC,KACFd,ED5DyB,SC8DvB,YAAYkD,gBAAsBE,0BAAiCA,qCAK7E,CACF,CAwBEC,CAAqBX,GAGrB,MAAMY,EAA4B,CAChC,YACA,aACGZ,EAAgBa,OAAQC,GAAY,cAANA,GAA2B,YAANA,IAElDC,EAAkB,IAAI,IAAI5C,IAAIyC,IAAkBC,OAAQC,GAAMd,EAAgBgB,SAASF,IAE7F,IAAA,MAAWG,KAAeF,EAAiB,CACzC,MAAMvB,EAASM,EAASmB,GACxB,QAAe,IAAXzB,IAAmC,IAAXA,EAAkB,SAE9C,MAAM0B,EAAS3B,EAAwB0B,EAAazB,GAChD0B,GACFnB,EAAQM,KAAKa,EAEjB,CAEA,OAAOnB,CACT,CAkBO,SAASoB,IACdnD,EAAgBoD,QAChBlD,EAAekD,OACjB,CAbAC,EAAmBxB"}
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/** Error thrown inside a plugin event handler. */\nexport const PLUGIN_EVENT_ERROR = 'TBW024' 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_EVENT_ERROR\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 { 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\nconst featureRegistry = new Map<string, RegistryEntry>();\nconst warnedFeatures = 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/**\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 */\nexport function registerFeature<K extends FeatureName>(name: K, factory: PluginFactory<FeatureConfig[K]>): void;\nexport function registerFeature(name: string, factory: PluginFactory): void;\nexport function registerFeature(name: string, factory: PluginFactory): void {\n if (isDev() && featureRegistry.has(name)) {\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 (selection before clipboard)\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 plugins: 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\n validateDependencies(enabledFeatures);\n\n // Create plugins in dependency order: dep-targets first, then the rest\n const dependencyOrder: string[] = [\n 'selection',\n 'editing',\n ...enabledFeatures.filter((f) => f !== 'selection' && f !== 'editing'),\n ];\n const orderedFeatures = [...new Set(dependencyOrder)].filter((f) => enabledFeatures.includes(f));\n\n for (const featureName of orderedFeatures) {\n const config = features[featureName];\n if (config === undefined || config === false) continue;\n\n const plugin = createPluginFromFeature(featureName, config);\n if (plugin) {\n plugins.push(plugin);\n }\n }\n\n return plugins;\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","featureRegistry","Map","warnedFeatures","Set","isDev","window","location","hostname","registerFeature","name","factory","has","set","isFeatureRegistered","getFeatureFactory","get","getRegisteredFeatures","Array","from","keys","PLUGIN_DEPENDENCIES","undoRedo","clipboard","createPluginFromFeature","config","entry","add","kebab","replace","createPluginsFromFeatures","features","plugins","enabledFeatures","key","value","Object","entries","push","featureNames","featureSet","feature","deps","dep","validateDependencies","dependencyOrder","filter","f","orderedFeatures","includes","featureName","plugin","clearFeatureRegistry","clear","setFeatureResolver"],"mappings":"uDA8QO,SAASA,EAAeC,EAAsBC,EAAiBC,EAAiBC,GACrFC,QAAQC,KAtBH,SAA0BL,EAAsBC,GAErD,MAAO,cAAaD,MAASC,uBApB/B,SAAiBD,GACf,MAAO,qCAAgBA,EAAKM,eAC9B,CAkB4DC,CAAQP,IACpE,CAmBeQ,CAAiBR,EAAMC,GACtC,CC5NA,MAAMQ,qBAAsBC,IACtBC,qBAAqBC,IAOrBC,EAAQ,IACM,oBAAXC,SACwB,cAA9BA,OAAOC,UAAUC,UAA0D,cAA9BF,OAAOC,UAAUC,UAW1D,SAASC,EAAgBC,EAAcC,GACxCN,KAAWJ,EAAgBW,IAAIF,IACjCnB,EDYgC,SCZK,YAAYmB,4DAEnDT,EAAgBY,IAAIH,EAAM,CAAEC,UAASD,QACvC,CAKO,SAASI,EAAoBJ,GAClC,OAAOT,EAAgBW,IAAIF,EAC7B,CAKO,SAASK,EAAkBL,GAChC,OAAOT,EAAgBe,IAAIN,IAAOC,OACpC,CAKO,SAASM,IACd,OAAOC,MAAMC,KAAKlB,EAAgBmB,OACpC,CAUA,MAAMC,EAAgD,CACpDC,SAAU,CAAC,WACXC,UAAW,CAAC,cAOP,SAASC,EAAwBd,EAAce,GACpD,MAAMC,EAAQzB,EAAgBe,IAAIN,GAElC,GAAKgB,EAcL,OAAOA,EAAMf,QAAQc,GAbnB,GAAIpB,MAAYF,EAAeS,IAAIF,GAAO,CACxCP,EAAewB,IAAIjB,GACnB,MAAMkB,EAAQlB,EAAKmB,QAAQ,kBAAmB,SAAS/B,cACvDP,EDpC8B,SCsC5B,YAAYmB,+GAE8BkB,QAE9C,CAKJ,CAoCO,SAASE,EAA0BC,GACxC,MAAMC,EAAwB,GACxBC,EAA4B,GAGlC,IAAA,MAAYC,EAAKC,KAAUC,OAAOC,QAAQN,QAC1B,IAAVI,IAAiC,IAAVA,GAC3BF,EAAgBK,KAAKJ,IAtCzB,SAA8BK,GAC5B,MAAMC,EAAa,IAAIpC,IAAImC,GAE3B,IAAA,MAAWE,KAAWF,EAAc,CAClC,MAAMG,EAAOrB,EAAoBoB,GACjC,GAAKC,EAEL,IAAA,MAAWC,KAAOD,EACXF,EAAW5B,IAAI+B,IACdtC,KACFd,ED5DyB,SC8DvB,YAAYkD,gBAAsBE,0BAAiCA,qCAK7E,CACF,CAwBEC,CAAqBX,GAGrB,MAAMY,EAA4B,CAChC,YACA,aACGZ,EAAgBa,OAAQC,GAAY,cAANA,GAA2B,YAANA,IAElDC,EAAkB,IAAI,IAAI5C,IAAIyC,IAAkBC,OAAQC,GAAMd,EAAgBgB,SAASF,IAE7F,IAAA,MAAWG,KAAeF,EAAiB,CACzC,MAAMvB,EAASM,EAASmB,GACxB,QAAe,IAAXzB,IAAmC,IAAXA,EAAkB,SAE9C,MAAM0B,EAAS3B,EAAwB0B,EAAazB,GAChD0B,GACFnB,EAAQM,KAAKa,EAEjB,CAEA,OAAOnB,CACT,CAkBO,SAASoB,IACdnD,EAAgBoD,QAChBlD,EAAekD,OACjB,CAbAC,EAAmBxB"}
@@ -1,4 +1,4 @@
1
- import { BaseGridPlugin, GridElement, PluginDependency } from '../../core/plugin/base-plugin';
1
+ import { BaseGridPlugin, GridElement, PluginDependency, PluginManifest, PluginQuery } from '../../core/plugin/base-plugin';
2
2
  import { ClipboardConfig, CopyOptions } from './types';
3
3
  /**
4
4
  * Clipboard Plugin for tbw-grid
@@ -72,6 +72,11 @@ import { ClipboardConfig, CopyOptions } from './types';
72
72
  */
73
73
  export declare class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {
74
74
  #private;
75
+ /**
76
+ * Plugin manifest — declares queries for inter-plugin communication.
77
+ * @internal
78
+ */
79
+ static readonly manifest: PluginManifest;
75
80
  /**
76
81
  * Plugin dependencies - ClipboardPlugin works best with SelectionPlugin.
77
82
  *
@@ -91,6 +96,8 @@ export declare class ClipboardPlugin extends BaseGridPlugin<ClipboardConfig> {
91
96
  /** @internal */
92
97
  detach(): void;
93
98
  /** @internal */
99
+ handleQuery(query: PluginQuery): unknown;
100
+ /** @internal */
94
101
  onKeyDown(event: KeyboardEvent): boolean;
95
102
  /**
96
103
  * Get the text representation of the current selection (or specified data)
@@ -1,2 +1,2 @@
1
- function e(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function t(t,n,r,o){return`${e(r,o)} ${t}: ${n}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(t)}`}["__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"].map(e=>e.split("").reverse().join(""));const n=/* @__PURE__ */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"]),r=/^on\w+$/i,o=/* @__PURE__ */new Set(["href","src","action","formaction","data","srcdoc","xlink:href","poster","srcset"]),i=/^\s*(javascript|vbscript|data|blob):/i;function s(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=[],s=e.querySelectorAll("*");for(const l of s){const e=l.tagName.toLowerCase();if(n.has(e)){t.push(l);continue}if("svg"===e||"http://www.w3.org/2000/svg"===l.namespaceURI){if(Array.from(l.attributes).some(e=>r.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(l);continue}}const s=[];for(const t of l.attributes){const e=t.name.toLowerCase();r.test(e)?s.push(t.name):(o.has(e)&&i.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&s.push(t.name)}s.forEach(e=>l.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}const l='<svg viewBox="0 0 16 16" width="12" height="12"><path fill="currentColor" d="M6 10.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5z"/></svg>',a={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:l,filterActive:l,print:"🖨️"};class c{static dependencies;static manifest;aliases;version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}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)}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{...a,...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=s(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(n,r){void 0!==r?console.warn(t(n,r,this.gridElement.id,this.name)):console.warn(`${e(this.gridElement.id,this.name)} ${n}`)}throwDiagnostic(e,n){throw new Error(t(e,n,this.gridElement.id,this.name))}}function d(e,t,n=!0){let r=e;if(n&&(r=r.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.meta?.utility)),t?.length){const e=new Set(t);r=r.filter(t=>e.has(t.field))}return r}async function u(e){try{return await navigator.clipboard.writeText(e),!0}catch(s){n="TBW100",r=`Clipboard API failed: ${s}`,console.warn(t(n,r,o,i));const l=document.createElement("textarea");l.value=e,l.style.position="fixed",l.style.opacity="0",l.style.pointerEvents="none",document.body.appendChild(l),l.select();const a=document.execCommand("copy");return document.body.removeChild(l),a}var n,r,o,i}function h(e,t){const n=t.delimiter??"\t",r=t.newline??"\n",o=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),i=[];let s=[],l="",a=!1;for(let c=0;c<o.length;c++){const e=o[c];'"'!==e||a?'"'===e&&a?'"'===o[c+1]?(l+='"',c++):a=!1:e!==n||a?e!==r||a?l+=e:(s.push(l),l="",(s.length>1||s.some(e=>""!==e.trim()))&&i.push(s),s=[]):(s.push(l),l=""):a=!0}return s.push(l),(s.length>1||s.some(e=>""!==e.trim()))&&i.push(s),i}function f(e,t){const{rows:n,target:r,fields:o}=e;if(!r)return;const i=t.rows,s=t.effectiveConfig.columns??[],l=s.map(e=>e.field),a=/* @__PURE__ */new Map;s.forEach(e=>{a.set(e.field,!0===e.editable)});const c=[...i],d=r.bounds?r.bounds.endRow:1/0;n.forEach((e,t)=>{const n=r.row+t;if(!(n>d)){if(r.bounds){if(n>=c.length)return}else for(;n>=c.length;){const e={};l.forEach(t=>e[t]=""),c.push(e)}c[n]={...c[n]},e.forEach((e,t)=>{const r=o[t];r&&a.get(r)&&(c[n][r]=e)})}}),t.rows=c}class g extends c{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;attach(e){super.attach(e),e.addEventListener("paste",e=>this.#n(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=null}onKeyDown(e){return!(!e.ctrlKey&&!e.metaKey||"c"!==e.key)&&(e.preventDefault(),this.#r(e.target),!0)}#r(e){const t=this.#o();if(t&&0===t.ranges.length){const t=this.#i(e);if(!t)return;const n=this.columns[t.col];if(!n)return;return void this.copy({rowIndices:[t.row],columns:[n.field]})}this.copy()}#n(e){const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const n=h(t,this.config),r=this.#o(),o=r?.ranges?.[0],i=o?.from.row??0,s=o?.from.col??0,l=o&&("range"===r?.mode||"row"===r?.mode)&&(o.from.row!==o.to.row||o.from.col!==o.to.col)?{endRow:o.to.row,endCol:o.to.col}:null,a=l?.endCol??this.visibleColumns.length-1,c=this.visibleColumns[s],d=c?{row:i,col:s,field:c.field,bounds:l}:null,u=[],f=n[0]?.length??0;for(let h=0;h<f&&s+h<=a;h++){const e=this.visibleColumns[s+h];e&&u.push(e.field)}const g={rows:n,text:t,target:d,fields:u};this.emit("paste",g),this.#s(g)}#s(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??f)(e,this.grid)}#o(){const e=this.grid?.query("getSelection");return e?.[0]}#l(e){const t=this.#o();let n,r;if(e?.columns)n=d(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=d(this.visibleColumns.slice(r,o+1))}else n=d(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}}#a(e,t,n){const r=n?.delimiter??this.config.delimiter??"\t",o=n?.newline??this.config.newline??"\n",i=n?.includeHeaders??this.config.includeHeaders??!1,s=n?.processCell??this.config.processCell,l=[];i&&l.push(e.map(e=>e.header||e.field).join(r));for(const a of t){const t=e.map(e=>{const t=a[e.field];return s?s(t,e.field,a):this.#c(e,t,a)});l.push(t.join(r))}return l.join(o)}#c(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.#d(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)}#d(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}#i(e){const t=e.closest("[data-field-cache]");if(!t)return null;const n=t.dataset.fieldCache,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.#l(e);return 0===t.length||0===n.length?"":this.#a(t,n,e)}async copy(e){const{columns:t,rows:n}=this.#l(e);if(0===t.length||0===n.length)return"";const r=this.#a(t,n,e);return await u(r),this.lastCopied={text:r,timestamp:Date.now()},this.emit("copy",{text:r,rowCount:n.length,columnCount:t.length}),r}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?h(e,this.config):null}getLastCopied(){return this.lastCopied}}export{g as ClipboardPlugin,f as defaultPasteHandler};
1
+ function e(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function t(t,n,r,o){return`${e(r,o)} ${t}: ${n}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(t)}`}["__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"].map(e=>e.split("").reverse().join(""));const n=/* @__PURE__ */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"]),r=/^on\w+$/i,o=/* @__PURE__ */new Set(["href","src","action","formaction","data","srcdoc","xlink:href","poster","srcset"]),i=/^\s*(javascript|vbscript|data|blob):/i;function s(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=[],s=e.querySelectorAll("*");for(const l of s){const e=l.tagName.toLowerCase();if(n.has(e)){t.push(l);continue}if("svg"===e||"http://www.w3.org/2000/svg"===l.namespaceURI){if(Array.from(l.attributes).some(e=>r.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(l);continue}}const s=[];for(const t of l.attributes){const e=t.name.toLowerCase();r.test(e)?s.push(t.name):(o.has(e)&&i.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&s.push(t.name)}s.forEach(e=>l.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}const l='<svg viewBox="0 0 16 16" width="12" height="12"><path fill="currentColor" d="M6 10.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5z"/></svg>',a={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:l,filterActive:l,print:"🖨️"};class c{static dependencies;static manifest;aliases;version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}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{...a,...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=s(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(n,r){void 0!==r?console.warn(t(n,r,this.gridElement.id,this.name)):console.warn(`${e(this.gridElement.id,this.name)} ${n}`)}throwDiagnostic(e,n){throw new Error(t(e,n,this.gridElement.id,this.name))}}function d(e,t,n=!0){let r=e;if(n&&(r=r.filter(e=>!e.hidden&&!e.field.startsWith("__")&&!0!==e.meta?.utility)),t?.length){const e=new Set(t);r=r.filter(t=>e.has(t.field))}return r}async function u(e){try{return await navigator.clipboard.writeText(e),!0}catch(s){n="TBW100",r=`Clipboard API failed: ${s}`,console.warn(t(n,r,o,i));const l=document.createElement("textarea");l.value=e,l.style.position="fixed",l.style.opacity="0",l.style.pointerEvents="none",document.body.appendChild(l),l.select();const a=document.execCommand("copy");return document.body.removeChild(l),a}var n,r,o,i}function h(e,t){const n=t.delimiter??"\t",r=t.newline??"\n",o=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),i=[];let s=[],l="",a=!1;for(let c=0;c<o.length;c++){const e=o[c];'"'!==e||a?'"'===e&&a?'"'===o[c+1]?(l+='"',c++):a=!1:e!==n||a?e!==r||a?l+=e:(s.push(l),l="",(s.length>1||s.some(e=>""!==e.trim()))&&i.push(s),s=[]):(s.push(l),l=""):a=!0}return s.push(l),(s.length>1||s.some(e=>""!==e.trim()))&&i.push(s),i}function f(e,t){const{rows:n,target:r,fields:o}=e;if(!r)return;const i=t.rows,s=t.effectiveConfig.columns??[],l=s.map(e=>e.field),a=/* @__PURE__ */new Map;s.forEach(e=>{a.set(e.field,!0===e.editable)});const c=[...i],d=r.bounds?r.bounds.endRow:1/0;n.forEach((e,t)=>{const n=r.row+t;if(!(n>d)){if(r.bounds){if(n>=c.length)return}else for(;n>=c.length;){const e={};l.forEach(t=>e[t]=""),c.push(e)}c[n]={...c[n]},e.forEach((e,t)=>{const r=o[t];r&&a.get(r)&&(c[n][r]=e)})}}),t.rows=c}class g extends c{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;attach(e){super.attach(e),e.addEventListener("paste",e=>this.#n(e),{signal:this.disconnectSignal})}detach(){this.lastCopied=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.#r(e.target),!0)}#r(e){const t=this.#o();if(t&&0===t.ranges.length){const t=this.#i(e);if(!t)return;const n=this.columns[t.col];if(!n)return;return void this.copy({rowIndices:[t.row],columns:[n.field]})}this.copy()}#n(e){const t=e.clipboardData?.getData("text/plain");if(!t)return;e.preventDefault();const n=h(t,this.config),r=this.#o(),o=r?.ranges?.[0],i=o?.from.row??0,s=o?.from.col??0,l=o&&("range"===r?.mode||"row"===r?.mode)&&(o.from.row!==o.to.row||o.from.col!==o.to.col)?{endRow:o.to.row,endCol:o.to.col}:null,a=l?.endCol??this.visibleColumns.length-1,c=this.visibleColumns[s],d=c?{row:i,col:s,field:c.field,bounds:l}:null,u=[],f=n[0]?.length??0;for(let h=0;h<f&&s+h<=a;h++){const e=this.visibleColumns[s+h];e&&u.push(e.field)}const g={rows:n,text:t,target:d,fields:u};this.emit("paste",g),this.#s(g)}#s(e){if(!this.grid)return;const{pasteHandler:t}=this.config;if(null===t)return;(t??f)(e,this.grid)}#o(){const e=this.grid?.query("getSelection");return e?.[0]}#l(e){const t=this.#o();let n,r;if(e?.columns)n=d(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=d(this.visibleColumns.slice(r,o+1))}else n=d(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}}#a(e,t,n){const r=n?.delimiter??this.config.delimiter??"\t",o=n?.newline??this.config.newline??"\n",i=n?.includeHeaders??this.config.includeHeaders??!1,s=n?.processCell??this.config.processCell,l=[];i&&l.push(e.map(e=>e.header||e.field).join(r));for(const a of t){const t=e.map(e=>{const t=a[e.field];return s?s(t,e.field,a):this.#c(e,t,a)});l.push(t.join(r))}return l.join(o)}#c(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.#d(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)}#d(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}#i(e){const t=e.closest("[data-field-cache]");if(!t)return null;const n=t.dataset.fieldCache,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.#l(e);return 0===t.length||0===n.length?"":this.#a(t,n,e)}async copy(e){const{columns:t,rows:n}=this.#l(e);if(0===t.length||0===n.length)return"";const r=this.#a(t,n,e);return await u(r),this.lastCopied={text:r,timestamp:Date.now()},this.emit("copy",{text:r,rowCount:n.length,columnCount:t.length}),r}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?h(e,this.config):null}getLastCopied(){return this.lastCopied}}export{g as ClipboardPlugin,f as defaultPasteHandler};
2
2
  //# sourceMappingURL=index.js.map