@datagrok/peptides 1.27.10 → 1.28.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 (65) hide show
  1. package/.auth.json +1 -0
  2. package/.grokignore +2 -0
  3. package/.turbo/turbo-build.log +26 -0
  4. package/.vscode/settings.json +16 -0
  5. package/CHANGELOG.md +28 -0
  6. package/CLAUDE.md +69 -5
  7. package/dist/659.js +2 -0
  8. package/dist/659.js.map +1 -0
  9. package/dist/806.js +2 -0
  10. package/dist/806.js.map +1 -0
  11. package/dist/package-test.js +396 -1
  12. package/dist/package-test.js.map +1 -1
  13. package/dist/package.js +361 -1
  14. package/dist/package.js.map +1 -1
  15. package/e2e/.auth.json +1 -0
  16. package/e2e/.auth.public.json +1 -0
  17. package/files/aligned_3.csv +6 -6
  18. package/package.json +32 -58
  19. package/rspack.config.js +3 -0
  20. package/src/demo/fasta.ts +0 -1
  21. package/src/model.ts +245 -131
  22. package/src/package-api.ts +18 -10
  23. package/src/package.g.ts +1 -0
  24. package/src/package.ts +19 -24
  25. package/src/tests/core.ts +6 -6
  26. package/src/tests/misc.ts +20 -0
  27. package/src/tests/model.ts +56 -6
  28. package/src/tests/table-view.ts +4 -4
  29. package/src/tests/utils.ts +56 -0
  30. package/src/tests/viewers.ts +270 -14
  31. package/src/tests/widgets.ts +13 -12
  32. package/src/utils/cell-renderer.ts +7 -6
  33. package/src/utils/constants.ts +10 -0
  34. package/src/utils/misc.ts +3 -3
  35. package/src/utils/statistics.ts +2 -2
  36. package/src/viewers/cluster-max-activity-viewer.ts +44 -11
  37. package/src/viewers/logo-summary.ts +126 -40
  38. package/src/viewers/mutation-cliffs-viewer.ts +56 -28
  39. package/src/viewers/peptide-generation-viewer.ts +7 -0
  40. package/src/viewers/position-statistics-viewer.ts +26 -4
  41. package/src/viewers/sar-viewer-status.ts +145 -0
  42. package/src/viewers/sar-viewer.ts +134 -42
  43. package/src/viewers/viewer-render-state.ts +68 -0
  44. package/src/widgets/distribution.ts +1 -1
  45. package/src/widgets/manual-alignment.ts +9 -22
  46. package/src/widgets/peptides.ts +101 -100
  47. package/src/widgets/selection.ts +1 -1
  48. package/src/widgets/settings.ts +11 -9
  49. package/test-playwright-report.json +73 -0
  50. package/test-report-playwright.csv +2 -0
  51. package/tsconfig.json +15 -69
  52. package/.eslintrc.json +0 -53
  53. package/dist/216.js +0 -2
  54. package/dist/216.js.map +0 -1
  55. package/dist/682.js +0 -2
  56. package/dist/682.js.map +0 -1
  57. package/dist/705.js +0 -2
  58. package/dist/705.js.map +0 -1
  59. package/dist/774.js +0 -2
  60. package/dist/774.js.map +0 -1
  61. package/dist/8473fcbfb6e85ca6c852.wasm +0 -0
  62. package/test-console-output-1.log +0 -603
  63. package/test-record-1.mp4 +0 -0
  64. package/webpack.config.js +0 -60
  65. /package/dist/{9a8fbf37666e32487835.wasm → wasmDbscan.wasm} +0 -0
@@ -6,6 +6,7 @@ import wu from 'wu';
6
6
  import $ from 'cash-dom';
7
7
  import {PeptideUtils} from '../peptideUtils';
8
8
  import {TAGS as bioTAGS, MONOMER_MOTIF_SPLITTER} from '@datagrok-libraries/bio/src/utils/macromolecule';
9
+ import {ViewerRenderState} from './viewer-render-state';
9
10
 
10
11
  export const POSITION_HIDDEN_NAME = '~sequence_position_monomers';
11
12
 
@@ -16,6 +17,24 @@ export class SequencePositionStatsViewer extends DG.JsViewer {
16
17
  private _boxPlotViewer?: DG.Viewer;
17
18
  public valueColumnName: string;
18
19
  public showPositionInfo: boolean = true;
20
+ private readonly renderState = new ViewerRenderState();
21
+ private renderedPositions: number[] = [];
22
+
23
+ get isRenderPending(): boolean { return this.renderState.isPending; }
24
+ get onRendered() { return this.renderState.rendered.asObservable(); }
25
+ get immediateRendering(): boolean { return this.renderState.immediateRendering; }
26
+ set immediateRendering(value: boolean) { this.renderState.immediateRendering = value; }
27
+
28
+ getWidgetStatus(): any {
29
+ const status = (this._boxPlotViewer as any)?.getWidgetStatus() ?? {};
30
+ return {...status, values: {...status.values, positions: this.renderedPositions.join(', ')}};
31
+ }
32
+
33
+ detach(): void {
34
+ this.renderState.dispose();
35
+ this._boxPlotViewer = undefined;
36
+ super.detach();
37
+ }
19
38
  constructor() {
20
39
  super();
21
40
  this.positions = this.string('positions', '1', {description: 'Comma-separated sequence positions (1-based) to analyze'});
@@ -73,12 +92,12 @@ export class SequencePositionStatsViewer extends DG.JsViewer {
73
92
  this.getProperty('valueColumnName')!.set(this, wu(this.dataFrame.columns.numerical).next().value.name);
74
93
  this.getProperty('positions')!.set(this, String(this.getPositionFromColumn()));
75
94
 
76
- this.subs.push(DG.debounce(this.dataFrame.onMetadataChanged, 200).subscribe((_) => {
95
+ this.subs.push(this.dataFrame.onMetadataChanged.subscribe(() => this.renderState.defer('metadata', () => {
77
96
  const curPosition = this.getPositionFromColumn();
78
97
  const currentPositions = this.parsePositions();
79
98
  if (!currentPositions.includes(curPosition))
80
99
  this._setPositions([curPosition]);
81
- }));
100
+ }, 200)));
82
101
  }
83
102
 
84
103
  render(): void {
@@ -87,7 +106,8 @@ export class SequencePositionStatsViewer extends DG.JsViewer {
87
106
  return;
88
107
 
89
108
  $(this.root).empty();
90
- this._boxPlotViewer?.detach();
109
+ if (this._boxPlotViewer)
110
+ this.renderState.remove(this._boxPlotViewer);
91
111
  const seqHelper = PeptideUtils.getSeqHelper();
92
112
  const sequenceColumn = this.dataFrame.col(this.sequenceColumnName)!;
93
113
  const seqHandler = seqHelper.getSeqHandler(sequenceColumn);
@@ -101,6 +121,8 @@ export class SequencePositionStatsViewer extends DG.JsViewer {
101
121
  legendVisibility: DG.VisibilityMode.Never, markerColorColumnName: this._positionColumn.name, title: 'Sequence Position Statistics',
102
122
  autoLayout: false, labelOrientation: 'Vert',
103
123
  });
124
+ this.renderedPositions = positions;
125
+ this.renderState.add(this._boxPlotViewer);
104
126
 
105
127
  if (this.showPositionInfo) {
106
128
  const selectorDiv = this._renderPositionSelector(positions, maxPos);
@@ -115,7 +137,7 @@ export class SequencePositionStatsViewer extends DG.JsViewer {
115
137
  this._boxPlotViewer.sub(this._boxPlotViewer.onPropertyValueChanged.subscribe((_e) => {
116
138
  if (this._boxPlotViewer?.props?.valueColumnName && this._boxPlotViewer?.props?.valueColumnName !== this.valueColumnName) {
117
139
  const value = this._boxPlotViewer.props.valueColumnName;
118
- setTimeout(() => this.getProperty('valueColumnName')!.set(this, value), 10);
140
+ this.renderState.defer('value column', () => this.getProperty('valueColumnName')!.set(this, value), 10);
119
141
  }
120
142
  }));
121
143
  }
@@ -0,0 +1,145 @@
1
+ import * as DG from 'datagrok-api/dg';
2
+ import {SARViewer, MonomerPosition, MostPotentResidues, SELECTION_MODE} from './sar-viewer';
3
+ import {COLUMNS_NAMES, TAGS} from '../utils/constants';
4
+
5
+ export function sarViewerStatus(viewer: SARViewer): DG.IWidgetStatus {
6
+ const grid = viewer._viewerGrid;
7
+ const visible = grid && viewer.root.contains(grid.root) && grid.canvas.getBoundingClientRect().width > 0 &&
8
+ grid.canvas.getBoundingClientRect().height > 0;
9
+ const inner = visible ? grid.getWidgetStatus() : null;
10
+ const hitAreas: DG.IWidgetStatus['hitAreas'] = {};
11
+ const values: NonNullable<DG.IWidgetStatus['values']> = {
12
+ 'activity scaling': viewer.activityScaling,
13
+ 'data source': viewer.dataSource,
14
+ };
15
+ const status: DG.IWidgetStatus = {
16
+ parts: {root: viewer.root, ...inner?.parts},
17
+ hitAreas, values, shortcuts: {}, events: [], description: null,
18
+ error: viewer.root.textContent?.includes('Please, select a sequence and activity columns') ?
19
+ 'Please, select a sequence and activity columns in the viewer properties' : null,
20
+ };
21
+ if (viewer.dataFrame)
22
+ values['rows shown'] = viewer.dataSource === 'All' ? viewer.dataFrame.rowCount : viewer.dataFrame.filter.trueCount;
23
+ if (viewer._positionColumns)
24
+ values.positions = viewer._positionColumns.length;
25
+
26
+ const stats = viewer._monomerPositionStats;
27
+ if (stats) {
28
+ let cells = 0;
29
+ const monomers = new Set<string>();
30
+ for (const [position, positionStats] of Object.entries(stats)) {
31
+ if (position === 'general')
32
+ continue;
33
+ for (const [monomer, cell] of Object.entries(positionStats)) {
34
+ if (monomer === 'general' || !('count' in cell) || cell.count <= 0)
35
+ continue;
36
+ cells++;
37
+ monomers.add(monomer);
38
+ }
39
+ }
40
+ values['cells with stats'] = cells;
41
+ values.monomers = monomers.size;
42
+ }
43
+
44
+ const cliffs = viewer._mutationCliffs;
45
+ if (cliffs) {
46
+ let cells = 0;
47
+ let pairs = 0;
48
+ const uniquePairs = new Set<string>();
49
+ for (const positions of cliffs.values()) {
50
+ for (const indexes of positions.values()) {
51
+ if (indexes.size > 0)
52
+ cells++;
53
+ for (const [from, targets] of indexes) {
54
+ pairs += targets.length;
55
+ for (const to of targets)
56
+ uniquePairs.add(from < to ? `${from}-${to}` : `${to}-${from}`);
57
+ }
58
+ }
59
+ }
60
+ values['cliff cells'] = cells;
61
+ values['cliff pairs'] = pairs;
62
+ values['unique cliff pairs'] = uniquePairs.size;
63
+ }
64
+
65
+ const mode = viewer instanceof MonomerPosition && viewer.dataFrame ? viewer.mode : SELECTION_MODE.INVARIANT_MAP;
66
+ if (viewer instanceof MonomerPosition)
67
+ values.mode = mode;
68
+ const selection = mode === SELECTION_MODE.MUTATION_CLIFFS ?
69
+ viewer._mutationCliffsSelection : viewer._invariantMapSelection;
70
+ values['selected monomer-positions'] = Object.entries(selection ?? {})
71
+ .flatMap(([position, monomers]) => monomers.map((monomer) => `${position}:${monomer}`)).join(', ');
72
+
73
+ if (!inner || !grid)
74
+ return status;
75
+
76
+ const canvasBounds = grid.canvas.getBoundingClientRect();
77
+ hitAreas.view = {x: 0, y: 0, width: canvasBounds.width, height: canvasBounds.height};
78
+ status.shortcuts.ContextMenu = 'view';
79
+ for (const [name, bounds] of Object.entries(inner.hitAreas)) {
80
+ if (name.startsWith('header ') || name.includes('scroll '))
81
+ hitAreas[name] = bounds;
82
+ const cell = /^cell (\d+) of (.+)$/.exec(name);
83
+ if (!cell)
84
+ continue;
85
+ const row = Number(cell[1]) - 1;
86
+ const column = cell[2];
87
+ const monomer = grid.dataFrame.get(COLUMNS_NAMES.MONOMER, row) as string;
88
+ if (viewer instanceof MonomerPosition) {
89
+ if (column === COLUMNS_NAMES.MONOMER)
90
+ hitAreas[`monomer ${monomer}`] = bounds;
91
+ const cellStats = stats?.[column]?.[monomer];
92
+ if (!viewer._positionColumns?.some((position) => position.name === column) || !cellStats?.count)
93
+ continue;
94
+ const key = `cell ${monomer} at ${column}`;
95
+ hitAreas[key] = bounds;
96
+ values[`count of ${key}`] = cellStats.count;
97
+ values[`mean difference of ${key}`] = cellStats.meanDifference;
98
+ values[`p-value of ${key}`] = cellStats.pValue ?? '';
99
+ values[`value of ${key}`] = cellStats.aggValue ?? cellStats.count;
100
+ if (cliffs) {
101
+ const indexes = cliffs.get(monomer)?.get(column);
102
+ values[`cliffs of ${key}`] = indexes ? Array.from(indexes.values())
103
+ .reduce((sum, targets) => sum + targets.length, 0) : 0;
104
+ }
105
+ if (mode === SELECTION_MODE.INVARIANT_MAP) {
106
+ const position = viewer._positionColumns.find((position) => position.name === column)!;
107
+ const color = position.temp[TAGS.INVARIANT_MAP_COLOR_CACHE]?.[monomer];
108
+ if (color !== undefined)
109
+ values[`color of ${key}`] = DG.Color.toHtml(color);
110
+ }
111
+ } else if (viewer instanceof MostPotentResidues) {
112
+ const position = grid.dataFrame.get(COLUMNS_NAMES.POSITION, row);
113
+ if (column === 'Diff')
114
+ hitAreas[`position ${position}`] = bounds;
115
+ else if (column === COLUMNS_NAMES.MONOMER)
116
+ hitAreas[`monomer of position ${position}`] = bounds;
117
+ }
118
+ }
119
+
120
+ if (viewer instanceof MonomerPosition && viewer.monomerSearchInput.input.getBoundingClientRect().width > 0) {
121
+ const bounds = viewer.monomerSearchInput.input.getBoundingClientRect();
122
+ hitAreas.search = {x: bounds.left - canvasBounds.left, y: bounds.top - canvasBounds.top,
123
+ width: bounds.width, height: bounds.height};
124
+ }
125
+ if (viewer instanceof MostPotentResidues) {
126
+ const table = grid.dataFrame;
127
+ values.positions = table.rowCount;
128
+ values['rows shown'] = table.filter.trueCount;
129
+ const columns = {
130
+ 'monomer': COLUMNS_NAMES.MONOMER,
131
+ 'mean difference': COLUMNS_NAMES.MEAN_DIFFERENCE,
132
+ 'p-value': COLUMNS_NAMES.P_VALUE,
133
+ 'count': COLUMNS_NAMES.COUNT,
134
+ 'ratio': COLUMNS_NAMES.RATIO,
135
+ };
136
+ for (let row = 0; row < table.rowCount; row++) {
137
+ const position = table.get(COLUMNS_NAMES.POSITION, row);
138
+ for (const [reading, name] of Object.entries(columns)) {
139
+ const column = table.getCol(name);
140
+ values[`${reading} at ${position}`] = column.isNone(row) ? '' : column.get(row);
141
+ }
142
+ }
143
+ }
144
+ return status;
145
+ }
@@ -4,6 +4,8 @@ import * as ui from 'datagrok-api/ui';
4
4
  import * as DG from 'datagrok-api/dg';
5
5
 
6
6
  import $ from 'cash-dom';
7
+ import * as rxjs from 'rxjs';
8
+ import {debounce as debounceEvent, tap} from 'rxjs/operators';
7
9
  import * as C from '../utils/constants';
8
10
  import {COLUMN_NAME} from '../utils/constants';
9
11
  import * as CR from '../utils/cell-renderer';
@@ -27,7 +29,6 @@ import {
27
29
  debounce,
28
30
  extractColInfo,
29
31
  getTotalAggColumns,
30
- highlightMonomerPosition,
31
32
  initSelection,
32
33
  isApplicableDataframe,
33
34
  isSelectionEmpty,
@@ -44,6 +45,7 @@ import {PeptideUtils} from '../peptideUtils';
44
45
  import {StringDictionary} from '@datagrok-libraries/utils/src/type-declarations';
45
46
  import {SeqTemps} from '@datagrok-libraries/bio/src/utils/macromolecule/seq-handler';
46
47
  import {getSeparator} from '../utils/misc';
48
+ import {sarViewerStatus} from './sar-viewer-status';
47
49
 
48
50
  export enum SELECTION_MODE {
49
51
  MUTATION_CLIFFS = 'Mutation Cliffs',
@@ -102,6 +104,7 @@ export interface ISARViewer {
102
104
  /** Abstract class for MonomerPosition and MostPotentResidues viewers. */
103
105
 
104
106
  export abstract class SARViewer extends DG.JsViewer implements ISARViewer {
107
+ abstract get name(): string;
105
108
  keyPressed: boolean = false;
106
109
  sequenceColumnName: string;
107
110
  activityColumnName: string;
@@ -157,7 +160,12 @@ export abstract class SARViewer extends DG.JsViewer implements ISARViewer {
157
160
 
158
161
  this.mutationCliffsDebouncer = debounce(
159
162
  async (activityArray: type.RawData, monomerInfoArray: type.RawColumn[], options?: MutationCliffsOptions) => {
160
- return await findMutations(activityArray, monomerInfoArray, options);
163
+ this._cliffsRunning++;
164
+ try {
165
+ return await findMutations(activityArray, monomerInfoArray, options);
166
+ } finally {
167
+ this._cliffsRunning--;
168
+ }
161
169
  });
162
170
 
163
171
  // this.targetCategoryInput = ui.input.choice('Category', {value: null, items: [], nullable: true,
@@ -183,13 +191,72 @@ export abstract class SARViewer extends DG.JsViewer implements ISARViewer {
183
191
  }
184
192
 
185
193
  _viewerGrid: DG.Grid | null = null;
194
+ private _gridSubscriptions: rxjs.Subscription[] = [];
195
+ protected _onRendered = new rxjs.Subject<void>();
196
+ private _cliffsGeneration = 0;
197
+ private _cliffsPending = false;
198
+ private _cliffsRunning = 0;
199
+ private _filterPending = false;
200
+ private _cellPending = false;
201
+ private _repaintTimer: ReturnType<typeof setTimeout> | null = null;
202
+
203
+ get onRendered(): rxjs.Observable<void> { return this._onRendered; }
204
+
205
+ get isRenderPending(): boolean {
206
+ return this._cliffsPending || this._cliffsRunning > 0 || this._filterPending || this._cellPending || this._repaintTimer !== null ||
207
+ (this._viewerGrid?.isRenderPending ?? false);
208
+ }
209
+
210
+ get immediateRendering(): boolean { return super.immediateRendering; }
211
+
212
+ set immediateRendering(value: boolean) {
213
+ super.immediateRendering = value;
214
+ if (this._viewerGrid)
215
+ this._viewerGrid.immediateRendering = value;
216
+ }
217
+
218
+ getWidgetStatus(): DG.IWidgetStatus { return sarViewerStatus(this); }
219
+
220
+ protected onCurrentGridCellChanged(grid: DG.Grid, action: (cell: DG.GridCell) => void): void {
221
+ this._gridSubscriptions.push(grid.onCurrentCellChanged.pipe(
222
+ tap(() => this._cellPending = true),
223
+ debounceEvent(() => rxjs.timer(this.immediateRendering ? 0 : 500)),
224
+ ).subscribe((cell) => {
225
+ try {
226
+ action(cell);
227
+ } finally {
228
+ this._cellPending = false;
229
+ }
230
+ }));
231
+ }
232
+
233
+ protected repaintGridLater(grid: DG.Grid): void {
234
+ if (this._repaintTimer !== null)
235
+ clearTimeout(this._repaintTimer);
236
+ this._repaintTimer = setTimeout(() => {
237
+ this._repaintTimer = null;
238
+ grid.invalidate();
239
+ }, this.immediateRendering ? 0 : 300);
240
+ }
186
241
 
187
242
  /**
188
243
  * Returns SARViewer grid. Creates a new one if it is null.
189
244
  * @return - SARViewer grid.
190
245
  */
191
246
  get viewerGrid(): DG.Grid {
192
- this._viewerGrid ??= this.createViewerGrid();
247
+ if (!this._viewerGrid) {
248
+ for (const sub of this._gridSubscriptions)
249
+ sub.unsubscribe();
250
+ this._gridSubscriptions = [];
251
+ this._cellPending = false;
252
+ if (this._repaintTimer !== null)
253
+ clearTimeout(this._repaintTimer);
254
+ this._repaintTimer = null;
255
+ this._viewerGrid = this.createViewerGrid();
256
+ this._viewerGrid.root.setAttribute('name', `${this.name.replace(/ /g, '-')}-grid`);
257
+ this._viewerGrid.immediateRendering = this.immediateRendering;
258
+ this._gridSubscriptions.push(this._viewerGrid.onAfterDrawContent.subscribe(() => this._onRendered.next()));
259
+ }
193
260
  return this._viewerGrid;
194
261
  }
195
262
 
@@ -349,21 +416,20 @@ export abstract class SARViewer extends DG.JsViewer implements ISARViewer {
349
416
  */
350
417
  set mutationCliffs(mc: type.MutationCliffs) {
351
418
  this._mutationCliffs = mc;
352
- this.viewerGrid.invalidate();
419
+ if (!this.isDetached)
420
+ this.viewerGrid.invalidate();
353
421
  }
354
422
 
355
423
  get cliffStats(): type.MutationCliffStats | null {
356
424
  if (!this._mutationCliffStats && this.mutationCliffs && this.activityColumnName &&
357
- this.sequenceColumnName && this.dataFrame.col(this.activityColumnName)) {
358
- const activityCol = this.dataFrame.col(this.activityColumnName)!;
359
- const activityData = activityCol.getRawData();
360
- this._mutationCliffStats = calculateCliffsStatistics(this.mutationCliffs, activityData);
361
- }
425
+ this.sequenceColumnName && this.dataFrame.col(this.activityColumnName))
426
+ this._mutationCliffStats = calculateCliffsStatistics(this.mutationCliffs, this.getScaledActivityColumn().getRawData());
362
427
  return this._mutationCliffStats;
363
428
  }
364
429
  set cliffStats(stats: type.MutationCliffStats | null) {
365
430
  this._mutationCliffStats = stats;
366
- this.viewerGrid.invalidate();
431
+ if (!this.isDetached)
432
+ this.viewerGrid.invalidate();
367
433
  }
368
434
 
369
435
  _mutationCliffsSelection: type.Selection | null = null;
@@ -651,9 +717,11 @@ export abstract class SARViewer extends DG.JsViewer implements ISARViewer {
651
717
  diffCol.setTag(DG.TAGS.CELL_RENDERER, 'MacromoleculeDifference');
652
718
  diffCol.temp[SeqTemps.notationProvider] = alignedSeqCol.temp[SeqTemps.notationProvider];
653
719
 
654
- const act1Col = DG.Column.fromList(DG.COLUMN_TYPE.FLOAT, `Seq 1 ${this.activityColumnName}`, act1Array);
655
- const act2Col = DG.Column.fromList(DG.COLUMN_TYPE.FLOAT, `Seq 2 ${this.activityColumnName}`, act2Array);
656
- const deltaCol = DG.Column.fromList(DG.COLUMN_TYPE.FLOAT, 'Delta', deltaArray);
720
+ // fromList stores floats in Float32Array by default, rounding the original IC50 values.
721
+ const doubles = (values: (number | null)[]): Float64Array => Float64Array.from(values, (value) => value ?? DG.FLOAT_NULL);
722
+ const act1Col = DG.Column.fromFloat64Array(`Seq 1 ${this.activityColumnName}`, doubles(act1Array));
723
+ const act2Col = DG.Column.fromFloat64Array(`Seq 2 ${this.activityColumnName}`, doubles(act2Array));
724
+ const deltaCol = DG.Column.fromFloat64Array('Delta', doubles(deltaArray));
657
725
 
658
726
  const columns: DG.Column[] = [seq1Col, seq2Col, diffCol, act1Col, act2Col, deltaCol];
659
727
 
@@ -705,6 +773,12 @@ export abstract class SARViewer extends DG.JsViewer implements ISARViewer {
705
773
  /** Removes all the active subscriptions. */
706
774
  detach(): void {
707
775
  this.subs.forEach((sub) => sub.unsubscribe());
776
+ for (const sub of this._gridSubscriptions)
777
+ sub.unsubscribe();
778
+ if (this._repaintTimer !== null)
779
+ clearTimeout(this._repaintTimer);
780
+ this._onRendered.complete();
781
+ super.detach();
708
782
  }
709
783
 
710
784
  protected _monomerMetaColumns: Set<string> = new Set();
@@ -747,7 +821,11 @@ export abstract class SARViewer extends DG.JsViewer implements ISARViewer {
747
821
  }, {isChecked: (meta) => this._monomerMetaColumns.has(meta)});
748
822
  });
749
823
  }));
750
- this.subs.push(DG.debounce(this.dataFrame.onFilterChanged, 300).subscribe(() => {
824
+ this.subs.push(this.dataFrame.onFilterChanged.pipe(
825
+ tap(() => this._filterPending = true),
826
+ debounceEvent(() => rxjs.timer(this.immediateRendering ? 0 : 300)),
827
+ ).subscribe(() => {
828
+ this._filterPending = false;
751
829
  if (this.dataSource === 'Filtered') {
752
830
  // this._monomerPositionStats = null;
753
831
  // this._invariantMapSelection = null;
@@ -759,6 +837,9 @@ export abstract class SARViewer extends DG.JsViewer implements ISARViewer {
759
837
  this.onFilterChanged(true, false);
760
838
  }
761
839
  }));
840
+ // Not debounced: a hover before the reset would highlight with a stale-length mask
841
+ this.subs.push(rxjs.merge(this.dataFrame.onRowsRemoved, this.dataFrame.onRowsAdded)
842
+ .subscribe(() => this.onFilterChanged(true, false)));
762
843
  } else {
763
844
  const msg = 'PeptidesError: dataframe is missing Macromolecule or numeric columns';
764
845
  grok.log.error(msg);
@@ -773,6 +854,7 @@ export abstract class SARViewer extends DG.JsViewer implements ISARViewer {
773
854
  this._mutationCliffStats = null;
774
855
  this._mutationCliffsSelection = null;
775
856
  this._mutationCliffs = null;
857
+ this._scaledActivityColumn = null;
776
858
  if (onlySetNulls)
777
859
  return;
778
860
 
@@ -792,20 +874,28 @@ export abstract class SARViewer extends DG.JsViewer implements ISARViewer {
792
874
  * @return - mutation cliffs.
793
875
  */
794
876
  async calculateMutationCliffs(): Promise<{cliffs: MutationCliffs, cliffStats: type.MutationCliffStats}> {
795
- const scaledActivityCol: DG.Column<number> = this.dataFrame.getCol(this.activityColumnName);
796
- //TODO: set categories ordering the same to share compare indexes instead of strings
797
- const monomerCols: type.RawColumn[] = this.positionColumns.map(extractColInfo);
798
- const filter = (this.dataSource === 'Filtered' && this.dataFrame.filter.anyFalse) ?
799
- this.dataFrame.filter : null;
800
-
801
- const options: MutationCliffsOptions = {
802
- maxMutations: this.maxMutations, minActivityDelta: this.minActivityDelta, filter: (filter?.getBuffer() as unknown as Uint32Array) ?? undefined,
803
- };
804
- const activityRawData = scaledActivityCol.getRawData();
877
+ const generation = ++this._cliffsGeneration;
878
+ this._cliffsPending = true;
879
+ try {
880
+ const scaledActivityCol = this.getScaledActivityColumn();
881
+ //TODO: set categories ordering the same to share compare indexes instead of strings
882
+ const monomerCols: type.RawColumn[] = this.positionColumns.map(extractColInfo);
883
+ const filter = (this.dataSource === 'Filtered' && this.dataFrame.filter.anyFalse) ?
884
+ this.dataFrame.filter : null;
805
885
 
806
- const mutRes = await this.mutationCliffsDebouncer(activityRawData, monomerCols, options);
807
- const mutStatistics = calculateCliffsStatistics(mutRes, activityRawData);
808
- return {cliffs: mutRes, cliffStats: mutStatistics};
886
+ const options: MutationCliffsOptions = {
887
+ maxMutations: this.maxMutations, minActivityDelta: this.minActivityDelta, filter: (filter?.getBuffer() as unknown as Uint32Array) ?? undefined,
888
+ };
889
+ const activityRawData = scaledActivityCol.getRawData();
890
+
891
+ const mutRes = await this.mutationCliffsDebouncer(activityRawData, monomerCols, options);
892
+ const mutStatistics = calculateCliffsStatistics(mutRes, activityRawData);
893
+ return {cliffs: mutRes, cliffStats: mutStatistics};
894
+ } finally {
895
+ // A superseded debounce never resolves, so only the newest request owns this flag.
896
+ if (generation === this._cliffsGeneration)
897
+ this._cliffsPending = false;
898
+ }
809
899
  }
810
900
  }
811
901
 
@@ -1092,8 +1182,7 @@ export class MonomerPosition extends SARViewer {
1092
1182
  return true;
1093
1183
  }
1094
1184
  const monomerPosition = this.getMonomerPosition(gridCell);
1095
- highlightMonomerPosition(monomerPosition, this.dataFrame, this.monomerPositionStats);
1096
- this.model.isHighlighting = true;
1185
+ this.model.highlight(monomerPosition, this.monomerPositionStats);
1097
1186
  const columnEntries = this.getTotalViewerAggColumns();
1098
1187
  const postfixes: StringDictionary = {};
1099
1188
  const additionalStats: StringDictionary = {};
@@ -1123,7 +1212,7 @@ export class MonomerPosition extends SARViewer {
1123
1212
  });
1124
1213
  });
1125
1214
  grid.root.addEventListener('mouseleave', (_ev) => this.model.unhighlight());
1126
- DG.debounce(grid.onCurrentCellChanged, 500).subscribe((gridCell: DG.GridCell) => {
1215
+ this.onCurrentGridCellChanged(grid, (gridCell: DG.GridCell) => {
1127
1216
  try {
1128
1217
  if (!gridCell || !gridCell.dart || !gridCell?.cell?.column?.name || this._monomerMetaColumns.has(gridCell.cell.column.name) || gridCell.cell.column.name == C.COLUMNS_NAMES.TOTAL_COUNT ||!gridCell.isTableCell)
1129
1218
  return;
@@ -1172,7 +1261,7 @@ export class MonomerPosition extends SARViewer {
1172
1261
  }
1173
1262
 
1174
1263
  grid.invalidate();
1175
- setTimeout(() => grid?.invalidate(), 300);
1264
+ this.repaintGridLater(grid);
1176
1265
  } catch (e) {
1177
1266
  console.error(e);
1178
1267
  } finally {
@@ -1190,12 +1279,12 @@ export class MonomerPosition extends SARViewer {
1190
1279
  return;
1191
1280
 
1192
1281
 
1193
- if (ev.key === 'Escape' || (ev.code === 'KeyA' && ev.ctrlKey && ev.shiftKey)) {
1282
+ if (ev.key === 'Escape' || (ev.code === 'KeyA' && (ev.ctrlKey || ev.metaKey) && ev.shiftKey)) {
1194
1283
  if (this.mode === SELECTION_MODE.INVARIANT_MAP)
1195
1284
  this._invariantMapSelection = initSelection(this.positionColumns);
1196
1285
  else
1197
1286
  this._mutationCliffsSelection = initSelection(this.positionColumns);
1198
- } else if (ev.code === 'KeyA' && ev.ctrlKey) {
1287
+ } else if (ev.code === 'KeyA' && (ev.ctrlKey || ev.metaKey)) {
1199
1288
  const positions = Object.keys(this.monomerPositionStats).filter((pos) => pos !== 'general');
1200
1289
  for (const position of positions) {
1201
1290
  const monomers = Object.keys(this.monomerPositionStats[position]!)
@@ -1229,7 +1318,7 @@ export class MonomerPosition extends SARViewer {
1229
1318
 
1230
1319
  const monomerPosition = this.getMonomerPosition(gridCell);
1231
1320
  if (this.mode === SELECTION_MODE.INVARIANT_MAP) {
1232
- this.modifyInvariantMapSelection(monomerPosition, {shiftPressed: ev.shiftKey, ctrlPressed: ev.ctrlKey});
1321
+ this.modifyInvariantMapSelection(monomerPosition, {shiftPressed: ev.shiftKey, ctrlPressed: (ev.ctrlKey || ev.metaKey)});
1233
1322
  if (isSelectionEmpty(this.invariantMapSelection))
1234
1323
  monomerPositionDf.currentRowIdx = -1;
1235
1324
  } else {
@@ -1237,7 +1326,7 @@ export class MonomerPosition extends SARViewer {
1237
1326
  ?.get(monomerPosition.positionOrClusterType)?.size;
1238
1327
  if (hasMutationCliffs) {
1239
1328
  this.modifyMutationCliffsSelection(monomerPosition,
1240
- {shiftPressed: ev.shiftKey, ctrlPressed: ev.ctrlKey});
1329
+ {shiftPressed: ev.shiftKey, ctrlPressed: (ev.ctrlKey || ev.metaKey)});
1241
1330
  }
1242
1331
  }
1243
1332
  grid.invalidate();
@@ -1282,6 +1371,7 @@ export class MonomerPosition extends SARViewer {
1282
1371
  $(this.root).empty();
1283
1372
  if (!this.dataFrame || !this.activityColumnName || !this.sequenceColumnName) {
1284
1373
  this.root.appendChild(ui.divText('Please, select a sequence and activity columns in the viewer properties'));
1374
+ this._onRendered.next();
1285
1375
  return;
1286
1376
  }
1287
1377
  // Backward compatability with 1.16.0
@@ -1319,7 +1409,8 @@ export class MonomerPosition extends SARViewer {
1319
1409
  setDefaultProperties(invariantMapMode);
1320
1410
 
1321
1411
  switchHost = ui.divH([mutationCliffsMode.root, invariantMapMode.root], {id: 'pep-viewer-title'});
1322
- $(switchHost).css('width', 'auto').css('align-self', 'center');
1412
+ $(switchHost).css('width', 'auto').css('align-self', 'center').css('max-width', '100%').css('flex-wrap', 'wrap')
1413
+ .css('height', 'auto').css('justify-content', 'center');
1323
1414
  }
1324
1415
  const viewerRoot = this.viewerGrid.root;
1325
1416
  viewerRoot.style.width = 'auto';
@@ -1382,6 +1473,7 @@ export class MostPotentResidues extends SARViewer {
1382
1473
  this._mutationCliffStats = null;
1383
1474
  this._mutationCliffsSelection = null;
1384
1475
  this._mutationCliffs = null;
1476
+ this._scaledActivityColumn = null;
1385
1477
  if (onlySetNulls)
1386
1478
  return;
1387
1479
  this._viewerGrid = null;
@@ -1517,8 +1609,7 @@ export class MostPotentResidues extends SARViewer {
1517
1609
  return true;
1518
1610
  }
1519
1611
  const monomerPosition = this.getMonomerPosition(gridCell);
1520
- highlightMonomerPosition(monomerPosition, this.dataFrame, this.monomerPositionStats);
1521
- this.model.isHighlighting = true;
1612
+ this.model.highlight(monomerPosition, this.monomerPositionStats);
1522
1613
 
1523
1614
  if (gridCell.tableColumn?.name === C.COLUMNS_NAMES.MONOMER)
1524
1615
  monomerPosition.positionOrClusterType = C.COLUMNS_NAMES.MONOMER;
@@ -1535,7 +1626,7 @@ export class MostPotentResidues extends SARViewer {
1535
1626
  aggrColValues: aggrValues,
1536
1627
  });
1537
1628
  });
1538
- DG.debounce(grid.onCurrentCellChanged, 500).subscribe((gridCell: DG.GridCell) => {
1629
+ this.onCurrentGridCellChanged(grid, (gridCell: DG.GridCell) => {
1539
1630
  try {
1540
1631
  if (gridCell.gridRow === -1) {
1541
1632
  this._mutationCliffsSelection = initSelection(this.positionColumns);
@@ -1575,9 +1666,9 @@ export class MostPotentResidues extends SARViewer {
1575
1666
  return;
1576
1667
 
1577
1668
 
1578
- if (ev.key === 'Escape' || (ev.code === 'KeyA' && ev.ctrlKey && ev.shiftKey))
1669
+ if (ev.key === 'Escape' || (ev.code === 'KeyA' && (ev.ctrlKey || ev.metaKey) && ev.shiftKey))
1579
1670
  this._mutationCliffsSelection = initSelection(this.positionColumns);
1580
- else if (ev.code === 'KeyA' && ev.ctrlKey) {
1671
+ else if (ev.code === 'KeyA' && (ev.ctrlKey || ev.metaKey)) {
1581
1672
  for (let rowIdx = 0; rowIdx < mprDf.rowCount; ++rowIdx) {
1582
1673
  const monomerPosition = this.getMonomerPosition(grid.cell('Diff', rowIdx));
1583
1674
  this.modifyInvariantMapSelection(monomerPosition, {shiftPressed: true, ctrlPressed: false}, false);
@@ -1603,7 +1694,7 @@ export class MostPotentResidues extends SARViewer {
1603
1694
  return;
1604
1695
 
1605
1696
 
1606
- this.modifyInvariantMapSelection(monomerPosition, {shiftPressed: ev.shiftKey, ctrlPressed: ev.ctrlKey});
1697
+ this.modifyInvariantMapSelection(monomerPosition, {shiftPressed: ev.shiftKey, ctrlPressed: (ev.ctrlKey || ev.metaKey)});
1607
1698
  grid.invalidate();
1608
1699
  });
1609
1700
 
@@ -1642,6 +1733,7 @@ export class MostPotentResidues extends SARViewer {
1642
1733
  $(this.root).empty();
1643
1734
  if (!this.dataFrame || !this.activityColumnName || !this.sequenceColumnName) {
1644
1735
  this.root.appendChild(ui.divText('Please, select a sequence and activity columns in the viewer properties'));
1736
+ this._onRendered.next();
1645
1737
  return;
1646
1738
  }
1647
1739
 
@@ -0,0 +1,68 @@
1
+ import * as DG from 'datagrok-api/dg';
2
+ import {Observable, Subject, Subscription} from 'rxjs';
3
+
4
+ export class ViewerRenderState {
5
+ readonly rendered = new Subject<void>();
6
+ private readonly children = new Map<DG.Viewer, Subscription>();
7
+ private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
8
+ private running = 0;
9
+ private immediate = false;
10
+ private disposed = false;
11
+
12
+ get isPending(): boolean {
13
+ return this.timers.size > 0 || this.running > 0 ||
14
+ Array.from(this.children.keys()).some((viewer) => viewer.root.isConnected && (viewer as any).isRenderPending);
15
+ }
16
+
17
+ get immediateRendering(): boolean { return this.immediate; }
18
+ set immediateRendering(value: boolean) {
19
+ this.immediate = value;
20
+ for (const viewer of this.children.keys())
21
+ (viewer as any).immediateRendering = value;
22
+ }
23
+
24
+ add(viewer: DG.Viewer, rendered: Observable<unknown> = (viewer as any).onAfterDrawScene): void {
25
+ (viewer as any).immediateRendering = this.immediate;
26
+ this.children.set(viewer, rendered.subscribe(() => this.rendered.next()));
27
+ }
28
+
29
+ remove(viewer: DG.Viewer): void {
30
+ this.children.get(viewer)?.unsubscribe();
31
+ this.children.delete(viewer);
32
+ viewer.detach();
33
+ }
34
+
35
+ defer(key: string, action: () => void | Promise<void>, delay: number): void {
36
+ this.cancel(key);
37
+ if (this.disposed)
38
+ return;
39
+ this.timers.set(key, setTimeout(() => {
40
+ this.timers.delete(key);
41
+ void this.run(action);
42
+ }, this.immediate ? 0 : delay));
43
+ }
44
+
45
+ cancel(key: string): void {
46
+ clearTimeout(this.timers.get(key));
47
+ this.timers.delete(key);
48
+ }
49
+
50
+ async run(action: () => void | Promise<void>): Promise<void> {
51
+ this.running++;
52
+ try {
53
+ await action();
54
+ } finally {
55
+ this.running--;
56
+ this.rendered.next();
57
+ }
58
+ }
59
+
60
+ dispose(): void {
61
+ this.disposed = true;
62
+ for (const key of this.timers.keys())
63
+ this.cancel(key);
64
+ for (const viewer of this.children.keys())
65
+ this.remove(viewer);
66
+ this.rendered.complete();
67
+ }
68
+ }
@@ -105,7 +105,7 @@ export function getActivityDistribution(
105
105
  showColumnSelector: false,
106
106
  showRangeSlider: false,
107
107
  showBinSelector: false,
108
- backColor: isTooltip ? '#fdffe5' : '#fffff',
108
+ backColor: isTooltip ? DG.Color.fromHtml('#fdffe5') : DG.Color.white,
109
109
  // @ts-ignore TODO: fix after api update
110
110
  }) as DG.Viewer<DG.IHistogramSettings>;
111
111
  hist.root.style.width = 'auto';