|
| 1 | +import { |
| 2 | + removeTableDevtoolsTarget, |
| 3 | + upsertTableDevtoolsTarget, |
| 4 | +} from '@tanstack/table-devtools' |
| 5 | +import { |
| 6 | + APP_ID, |
| 7 | + DestroyRef, |
| 8 | + Injectable, |
| 9 | + Injector, |
| 10 | + assertInInjectionContext, |
| 11 | + effect, |
| 12 | + inject, |
| 13 | +} from '@angular/core' |
| 14 | +import type { RowData, Table, TableFeatures } from '@tanstack/table-core' |
| 15 | + |
| 16 | +export interface InjectTanStackTableDevtoolsOptions { |
| 17 | + enabled?: () => boolean |
| 18 | + injector?: Injector |
| 19 | +} |
| 20 | + |
| 21 | +function normalizeName(name?: string) { |
| 22 | + const trimmedName = name?.trim() |
| 23 | + return trimmedName ? trimmedName : undefined |
| 24 | +} |
| 25 | + |
| 26 | +let autoId = 0 |
| 27 | +function generateId(): string { |
| 28 | + const appId = inject(APP_ID) |
| 29 | + return `tanstacktable-${appId}_${autoId++}${Date.now().toString(36)}` |
| 30 | +} |
| 31 | + |
| 32 | +export function injectTanStackTableDevtools< |
| 33 | + TFeatures extends TableFeatures = TableFeatures, |
| 34 | + TData extends RowData = RowData, |
| 35 | +>( |
| 36 | + table: () => Table<TFeatures, TData> | undefined, |
| 37 | + name?: string, |
| 38 | + options?: InjectTanStackTableDevtoolsOptions, |
| 39 | +): void { |
| 40 | + const registrationId = generateId() |
| 41 | + const enabled = () => options?.enabled?.() ?? true |
| 42 | + assertInInjectionContext(injectTanStackTableDevtools) |
| 43 | + const injector = options?.injector ?? inject(Injector) |
| 44 | + const destroyRef = inject(DestroyRef) |
| 45 | + |
| 46 | + effect( |
| 47 | + (onCleanup) => { |
| 48 | + const enabledValue = enabled() |
| 49 | + const tableValue = table() |
| 50 | + if (!enabledValue || !tableValue) { |
| 51 | + removeTableDevtoolsTarget(registrationId) |
| 52 | + } |
| 53 | + upsertTableDevtoolsTarget({ |
| 54 | + id: registrationId, |
| 55 | + table: tableValue, |
| 56 | + name: normalizeName(name), |
| 57 | + }) |
| 58 | + onCleanup(() => { |
| 59 | + removeTableDevtoolsTarget(registrationId) |
| 60 | + }) |
| 61 | + }, |
| 62 | + { injector }, |
| 63 | + ) |
| 64 | + |
| 65 | + destroyRef.onDestroy(() => { |
| 66 | + removeTableDevtoolsTarget(registrationId) |
| 67 | + }) |
| 68 | +} |
| 69 | + |
| 70 | +export function injectTanStackTableDevtoolsNoOp< |
| 71 | + TFeatures extends TableFeatures = TableFeatures, |
| 72 | + TData extends RowData = RowData, |
| 73 | +>( |
| 74 | + _table: Table<TFeatures, TData> | undefined, |
| 75 | + _name?: string, |
| 76 | + _options?: InjectTanStackTableDevtoolsOptions, |
| 77 | +): void {} |
0 commit comments