-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathpluginToHTMLBridge.js
More file actions
729 lines (694 loc) · 32.7 KB
/
pluginToHTMLBridge.js
File metadata and controls
729 lines (694 loc) · 32.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
// @flow
//-----------------------------------------------------------------------------
// Bridging functions for Dashboard plugin -- both ways!
// Last updated 2025-12-08 for v2.4.0.b by @jgclark
//-----------------------------------------------------------------------------
import pluginJson from '../plugin.json'
import { handleBannerTestClick } from './bannerClickHandlers'
import {
doAddItem,
doAddItemToFuture,
doAddTaskAnywhere,
doCancelChecklist,
doCancelTask,
doContentUpdate,
doCompleteTask,
doCompleteTaskThen,
doCompleteChecklist,
doCyclePriorityStateDown,
doCyclePriorityStateUp,
doDeleteItem,
doEvaluateString,
doDashboardSettingsChanged,
doShowNoteInEditorFromFilename,
doShowNoteInEditorFromTitle,
doShowLineInEditorFromFilename,
doToggleType,
doUnscheduleItem,
doWindowResized,
} from './clickHandlers'
import { allCalendarSectionCodes, allSectionCodes, WEBVIEW_WINDOW_ID } from './constants'
import {
doAddNewPerspective,
doCopyPerspective,
doDeletePerspective,
doRenamePerspective,
doSavePerspective,
doSwitchToPerspective,
doPerspectiveSettingsChanged,
} from './perspectiveClickHandlers'
import { incrementallyRefreshSomeSections, refreshSomeSections } from './refreshClickHandlers'
import {
doAddProgressUpdate,
doCancelProject,
doCompleteProject,
doTogglePauseProject,
doReviewFinished,
doSetNewReviewInterval,
doSetNextReviewDate,
doStartReviews,
} from './projectClickHandlers'
import { doMoveFromCalToCal, doMoveToNote, doRescheduleItem } from './moveClickHandlers'
import { scheduleAllOverdueOpenToToday, scheduleTodayToTomorrow, scheduleYesterdayOpenToToday } from './moveDayClickHandlers'
import { scheduleAllLastWeekThisWeek, scheduleAllThisWeekNextWeek } from './moveWeekClickHandlers'
import { findSectionItems, getDashboardSettings, getListOfEnabledSections, setPluginData } from './dashboardHelpers'
// import { showDashboardReact } from './reactMain' // Note: fixed circ dep here by changing to using an x-callback instead 😫
import { copyUpdatedSectionItemData } from './dataGeneration'
import { externallyStartSearch } from './dataGenerationSearch'
import type { MessageDataObject, TActionType, TBridgeClickHandlerResult, TParagraphForDashboard, TPluginCommandSimplified } from './types'
import { clo, clof, logDebug, logError, logInfo, logWarn, JSP, logTimer } from '@helpers/dev'
import { sendToHTMLWindow, getGlobalSharedData, sendBannerMessage, themeHasChanged } from '@helpers/HTMLView'
import { getNoteByFilename } from '@helpers/note'
import { formatReactError } from '@helpers/react/reactDev'
//-----------------------------------------------------------------
/**
* HTML View requests running a plugin command
* TODO(@dbw): can this be removed -- there's something with the same name in np.Shared/Root.jsx
* @param {TPluginCommandSimplified} data object with plugin details
*/
export async function runPluginCommand(data: TPluginCommandSimplified) {
try {
// clo(data, 'runPluginCommand received data object')
logDebug('pluginToHTMLBridge/runPluginCommand', `running ${data.commandName} in ${data.pluginID}`)
await DataStore.invokePluginCommandByName(data.commandName, data.pluginID, data.commandArgs)
} catch (error) {
logError(pluginJson, JSP(error))
}
}
/**
* Somebody clicked on a something in the HTML React view
* NOTE: processActionOnReturn will be called for each item after the CASES based on TBridgeClickHandlerResult
* @param {MessageDataObject} data - details of the item clicked
*/
export async function bridgeClickDashboardItem(data: MessageDataObject) {
try {
const startTime = new Date()
const actionType: TActionType = data.actionType
const logMessage = data.logMessage ?? ''
const filename = data.item?.para?.filename ?? '<no filename found>'
let content = data.item?.para?.content ?? '<no content found>'
const updatedContent = data.updatedContent ?? ''
// set default return value for each call; mostly overridden below with success
let result: TBridgeClickHandlerResult = { success: false }
logInfo(`************* bridgeClickDashboardItem: ${actionType}${logMessage ? `: "${logMessage}"` : ''} *************`)
// clo(data, 'bridgeClickDashboardItem received data object; data=')
if (actionType !== 'refreshEnabledSections' && (!content || !filename)) throw new Error('No content or filename provided for refresh')
// Allow for a combination of button click and a content update
if (updatedContent && data.actionType !== 'updateItemContent') {
logDebug('bCDI', `content updated with another button press; need to update content first; new content: "${updatedContent}"`)
// $FlowIgnore[incompatible-call]
result = doContentUpdate(data)
if (result.success) {
// update the content so it can be found in the cache now that it's changed - this is for all the cases below that don't use data for the content - TODO(later): ultimately delete this
content = result.updatedParagraph?.content ?? ''
// update the data object with the new content so it can be found in the cache now that it's changed - this is for jgclark's new handlers that use data instead
data.item?.para?.content ? (data.item.para.content = content) : null
logDebug('bCDI / updateItemContent', `-> successful call to doContentUpdate()`)
// The following line is important because it updates the React window with the changed content before the next action is taken
// This will help Dashboard find the item to update in the JSON with the revised content
await updateReactWindowFromLineChange(result, data, ['para.content'])
}
}
switch (actionType) {
case 'refreshEnabledSections': {
const sectionCodesToUse = data.sectionCodes ? data.sectionCodes : allSectionCodes
logInfo('bCDI / refreshEnabledSections', `sectionCodesToUse: ${String(sectionCodesToUse)}`)
result = await incrementallyRefreshSomeSections({ ...data, sectionCodes: sectionCodesToUse }, false, true)
// result = { success: true } // TODO: TEST: remove this
break
}
case 'refreshSomeSections': {
result = await refreshSomeSections(data)
break
}
case 'incrementallyRefreshSomeSections': {
// Note: Only used by Dashboard after first section loaded.
logInfo('bCDI / incrementallyRefreshSomeSections', `calling incrementallyRefreshSomeSections with data.sectionCodes = ${String(data.sectionCodes)} ...`)
result = await incrementallyRefreshSomeSections(data)
break
}
case 'windowReload': {
// Used by 'Hard Refresh' button for devs
const useDemoData = false
// Using Plugin command invocation rather than `await showDashboardReact('full', useDemoData)` to avoid circular dependency
await DataStore.invokePluginCommandByName('Show Dashboard', 'jgclark.Dashboard', ['full', useDemoData])
result = { success: true }
return
}
case 'completeTask': {
result = await doCompleteTask(data)
break
}
case 'completeTaskThen': {
result = await doCompleteTaskThen(data)
break
}
case 'cancelTask': {
result = doCancelTask(data)
break
}
case 'completeChecklist': {
result = await doCompleteChecklist(data)
break
}
case 'cancelChecklist': {
result = doCancelChecklist(data)
break
}
case 'deleteItem': {
result = await doDeleteItem(data)
break
}
case 'unscheduleItem': {
result = await doUnscheduleItem(data)
break
}
case 'updateItemContent': {
result = doContentUpdate(data)
break
}
case 'toggleType': {
result = await doToggleType(data)
break
}
case 'cyclePriorityStateUp': {
result = await doCyclePriorityStateUp(data)
break
}
case 'cyclePriorityStateDown': {
result = await doCyclePriorityStateDown(data)
break
}
case 'setNextReviewDate': {
result = await doSetNextReviewDate(data)
break
}
case 'reviewFinished': {
result = await doReviewFinished(data)
break
}
case 'startReviews': {
result = await doStartReviews()
break
}
case 'cancelProject': {
result = await doCancelProject(data)
break
}
case 'completeProject': {
result = await doCompleteProject(data)
break
}
case 'togglePauseProject': {
result = await doTogglePauseProject(data)
break
}
case 'setNewReviewInterval': {
result = await doSetNewReviewInterval(data)
break
}
case 'addProgress': {
result = await doAddProgressUpdate(data)
break
}
case 'evaluateString': {
result = await doEvaluateString(data)
break
}
case 'windowResized': {
result = await doWindowResized()
break
}
case 'showNoteInEditorFromFilename': {
result = await doShowNoteInEditorFromFilename(data)
break
}
case 'showNoteInEditorFromTitle': {
result = await doShowNoteInEditorFromTitle(data)
break
}
case 'showLineInEditorFromFilename': {
result = await doShowLineInEditorFromFilename(data)
break
}
case 'moveToNote': {
result = await doMoveToNote(data)
break
}
case 'moveFromCalToCal': {
result = await doMoveFromCalToCal(data)
break
}
case 'rescheduleItem': {
result = await doRescheduleItem(data)
break
}
case 'dashboardSettingsChanged': {
result = await doDashboardSettingsChanged(data, 'dashboardSettings')
break
}
case 'perspectiveSettingsChanged': {
result = await doPerspectiveSettingsChanged(data)
break
}
case 'addNewPerspective': {
result = await doAddNewPerspective(data)
break
}
case 'copyPerspective': {
result = await doCopyPerspective(data)
break
}
case 'deletePerspective': {
result = await doDeletePerspective(data)
break
}
case 'switchToPerspective': {
result = await doSwitchToPerspective(data)
break
}
case 'savePerspective': {
result = await doSavePerspective(data)
break
}
case 'savePerspectiveAs': {
result = await doAddNewPerspective(data)
break
}
case 'renamePerspective': {
result = await doRenamePerspective(data)
break
}
// case 'setSpecificDate': {
// result = await doSetSpecificDate(data)
// break
// }
case 'addChecklist': {
result = await doAddItem(data)
break
}
case 'addTask': {
result = await doAddItem(data)
break
}
case 'addTaskAnywhere': {
// Note: calls Quick Capture plugin /qath command which doesn't return anything
await doAddTaskAnywhere()
result = { success: true }
break
}
case 'addTaskToFuture': {
result = await doAddItemToFuture(data)
break
}
case 'moveAllTodayToTomorrow': {
result = await scheduleTodayToTomorrow(data)
break
}
case 'moveOnlyShownTodayToTomorrow': {
result = await scheduleTodayToTomorrow(data, true) // true = move only shown items
break
}
case 'moveAllYesterdayToToday': {
result = await scheduleYesterdayOpenToToday(data)
break
}
case 'moveOnlyShownYesterdayToToday': {
result = await scheduleYesterdayOpenToToday(data, true) // true = move only shown items
break
}
case 'moveAllLastWeekThisWeek': {
result = await scheduleAllLastWeekThisWeek(data)
break
}
case 'moveOnlyShownLastWeekThisWeek': {
result = await scheduleAllLastWeekThisWeek(data, true) // true = move only shown items
break
}
case 'moveAllThisWeekNextWeek': {
result = await scheduleAllThisWeekNextWeek(data)
break
}
case 'moveOnlyShownThisWeekNextWeek': {
result = await scheduleAllThisWeekNextWeek(data, true) // true = move only shown items
break
}
case 'scheduleAllOverdueToday': {
result = await scheduleAllOverdueOpenToToday(data)
break
}
case 'scheduleOnlyShownOverdueToday': {
result = await scheduleAllOverdueOpenToToday(data, true) // true = move only shown items
break
}
case 'startSearch': {
console.log(`pluginToHTMLBridge: startSearch: data:${JSP(data)}`)
await externallyStartSearch(data.stringToEvaluate ?? '')
result = {
success: true,
sectionCodes: ['SEARCH'],
actionsOnSuccess: [],
errorMsg: '',
}
break
}
case 'closeSearchSection': {
result = {
success: true,
actionsOnSuccess: ['CLOSE_SEARCH_SECTION'],
errorMsg: '',
}
break
}
// TODO(later): remove these once we have a proper banner system
case 'testBannerInfo': {
result = await handleBannerTestClick({ actionType: 'testBannerInfo', sectionCodes: data.sectionCodes })
break
}
case 'testBannerError': {
result = await handleBannerTestClick({ actionType: 'testBannerError' })
break
}
case 'testBannerWarning': {
result = await handleBannerTestClick({ actionType: 'testBannerWarning' })
break
}
case 'testRemoveBanner': {
result = await handleBannerTestClick({ actionType: 'testRemoveBanner' })
break
}
default: {
result = {
success: false,
errorMsg: `Can't yet handle type ${actionType}`,
}
logWarn('bridgeClickDashboardItem', `bridgeClickDashboardItem: can't yet handle type ${actionType}`)
}
}
logTimer('bridgeClickDashboardItem', startTime, `for bridgeClickDashboardItem: "${data.actionType}" before processActionOnReturn()`, 1000)
if (result) {
await processActionOnReturn(result, data) // process all actions based on result of handler
} else {
logWarn('bridgeClickDashboardItem', `false result from call`)
}
logTimer('bridgeClickDashboardItem', startTime, `total runtime for bridgeClickDashboardItem: "${data.actionType}"`, 1000)
} catch (error) {
logError(pluginJson, `pluginToHTMLBridge / bridgeClickDashboardItem: ${JSP(error)}`)
}
}
/**
* One function to handle all actions on return from the various handlers.
* @param {TBridgeClickHandlerResult} handlerResult
* @param {MessageDataObject} data
*/
async function processActionOnReturn(handlerResultIn: TBridgeClickHandlerResult, data: MessageDataObject) {
try {
// check to see if the theme has changed and if so, update it
const config: any = await getDashboardSettings()
const themeChanged = await themeHasChanged(WEBVIEW_WINDOW_ID, config.dashboardTheme)
if (themeChanged) {
logDebug('processActionOnReturn', `Theme changed; forcing a refresh of the dashboard`)
DataStore.invokePluginCommandByName('showDashboardReact', 'jgclark.Dashboard', ['full'])
}
if (!handlerResultIn) return
const handlerResult = handlerResultIn
const { success, updatedParagraph } = handlerResult
const enabledSections = getListOfEnabledSections(config)
if (!success) {
logDebug('processActionOnReturn', `-> failed handlerResult(false) ${handlerResult.errorMsg || ''}`)
await sendBannerMessage(
WEBVIEW_WINDOW_ID,
`Sorry; something's gone wrong for "${data.actionType}" ${handlerResult.errorMsg || ''}. This is most often caused by changing a task in NotePlan since the last time the Dashboard was refreshed. If it persists, please report it to the developer.`,
'WARN',
)
return
}
// Handle the different success cases
const actionsOnSuccess = handlerResult.actionsOnSuccess ?? []
if (actionsOnSuccess.length === 0) {
logDebug('processActionOnReturn', `note: no post process actions to perform`)
return
}
const isProject = data.item?.itemType === 'project'
const actsOnALine = actionsOnSuccess.some((str) => str.includes('LINE'))
const filename: string = isProject ? data.item?.project?.filename ?? '' : data.item?.para?.filename ?? ''
logDebug('processActionOnReturn',
isProject ? `item.ID: ${data.item?.ID ?? '?'} = PROJECT: ${data.item?.project?.title || 'no project title'}` : `item.ID: ${data.item?.ID ?? '?'} = TASK: updatedParagraph "${updatedParagraph?.content ?? 'N/A'}"`,
)
if (actsOnALine && filename === '') {
logWarn('processActionOnReturn', `Starting with no filename`)
}
if (filename !== '') {
// update the cache for the note, as it might have changed
const thisNote = getNoteByFilename(filename)
if (thisNote) {
const res = await DataStore.updateCache(thisNote, false) /* Note: added await in case Eduard makes it an async at some point */
}
}
if (actionsOnSuccess.includes('REMOVE_LINE_FROM_JSON')) {
const reactWindowData = await getGlobalSharedData(WEBVIEW_WINDOW_ID)
const sections = reactWindowData.pluginData.sections
logDebug('processActionOnReturn', `Starting REMOVE_LINE_FROM_JSON with active sections: ${String(sections.map((s) => s.sectionCode).join(','))}`)
if (isProject) {
const thisProject = data.item?.project
const projFilename = data.item?.project?.filename
if (!projFilename) throw new Error(`unable to find data.item.project.filename`)
logDebug('processActionOnReturn', `REMOVE_LINE_FROM_JSON: for ID:${data?.item?.ID || ''} project:"${thisProject?.title || '?'}"`)
// Find the item(s) from its filename.
// Note: currently this will only update 1 project item. But leaving this multi-item code here for now.
const indexes = findSectionItems(sections,
['itemType', 'project.filename'],
{ itemType: 'project', 'project.filename': projFilename })
logDebug('processActionOnReturn', `-> found ${indexes.length} items to remove: ${String(indexes.map((i) => `s[${i.sectionIndex}_${sections[i.sectionIndex].sectionCode}]:si[${i.itemIndex}]`).join(', '))}`)
indexes.reverse().forEach((index) => {
const { sectionIndex, itemIndex } = index
sections[sectionIndex].sectionItems.splice(itemIndex, 1)
// clo(sections[sectionIndex],`processActionOnReturn After splicing sections[${sectionIndex}]`)
})
} else {
// Handle Task or Message types
const { content: oldContent = '', filename: oldFilename = '' } = data.item?.para ?? { content: 'error', filename: 'error' }
// Find all references to this content (could be in multiple sections)
const indexes = findSectionItems(sections, ['itemType', 'para.filename', 'para.content'], {
itemType: /open|checklist/,
'para.filename': oldFilename,
'para.content': oldContent,
})
if (indexes.length) {
logInfo('processActionOnReturn', `-> found ${indexes.length} items to remove: ${String(indexes.map((i) => `s[${i.sectionIndex}_${sections[i.sectionIndex].sectionCode}]:si[${i.itemIndex}]`).join(', '))}`)
indexes.reverse().forEach((index) => {
const { sectionIndex, itemIndex } = index
logDebug('processActionOnReturn', `-> removing item ${data.item?.ID || '?'} from sections[${sectionIndex}].sectionItems[${itemIndex}]`)
sections[sectionIndex].sectionItems.splice(itemIndex, 1)
})
} else {
logWarn('processActionOnReturn', `-> no items found to remove for content="${oldContent}" filename="${oldFilename}"`)
}
}
logDebug('processActionOnReturn', `-> NOT asking for any further refresh: hopefully React will do its stuff!`)
// Send the updated data to React window
await sendToHTMLWindow(WEBVIEW_WINDOW_ID, 'UPDATE_DATA', reactWindowData, `Removed item ${data.item?.ID || '?'}`)
}
if (actionsOnSuccess.includes('UPDATE_LINE_IN_JSON')) {
if (isProject) {
// For Project items
logDebug('processActionOnReturn', `UPDATE_LINE_IN_JSON for Project '${filename}': calling updateReactWindowFromLineChange()`)
await updateReactWindowFromLineChange(handlerResult, data, ['filename', 'itemType', 'project'])
} else {
// Handle Task or Message types
// Find all references to this content (could be in multiple sections)
const reactWindowData = await getGlobalSharedData(WEBVIEW_WINDOW_ID)
let sections = reactWindowData.pluginData.sections
const { content: oldContent = '', filename: oldFilename = '' } = data.item?.para ?? { content: 'error', filename: 'error' }
const indexes = findSectionItems(sections, ['itemType', 'para.filename', 'para.content'], {
itemType: /open|checklist/,
'para.filename': oldFilename,
'para.content': oldContent,
})
if (indexes.length) {
const itemsToUpdateStr = indexes.map((i) => `s[${i.sectionIndex}_${sections[i.sectionIndex].sectionCode}]:si[${i.itemIndex}]`).join(', ')
logInfo('processActionOnReturn', `-> found ${indexes.length} items to update: ${itemsToUpdateStr}`)
indexes.reverse().forEach((index) => {
const { sectionIndex, itemIndex } = index
logDebug('processActionOnReturn', `-> updating item sections[${sectionIndex}].sectionItems[${itemIndex}]`)
console.log(`before: ${JSP(sections[sectionIndex].sectionItems[itemIndex])}`)
console.log(`updatedParagraph: ${JSP(updatedParagraph)}`)
// Note: simpler methods don't work here; need to use copyUpdatedSectionItemData()
const fieldPathsToUpdate = ['itemType', 'para.content', 'para.rawContent', 'para.type', 'para.priority']
sections = copyUpdatedSectionItemData(indexes, fieldPathsToUpdate, { para: updatedParagraph }, sections)
console.log(`after: ${JSP(sections[sectionIndex].sectionItems[itemIndex])}`)
})
await sendToHTMLWindow(WEBVIEW_WINDOW_ID, 'UPDATE_DATA', reactWindowData, `Updated items ${itemsToUpdateStr} following change in ${data.item?.ID || '?'}`)
} else {
logWarn('processActionOnReturn', `-> no items found to update for content="${oldContent}" filename="${oldFilename}"`)
}
}
}
// FIXME: Probably works, but it looks like enabledSections is not being updated before this is called.
if (actionsOnSuccess.includes('CLOSE_UNNEEDED_SECTIONS')) {
// Identify which sections to close
const reactWindowData = await getGlobalSharedData(WEBVIEW_WINDOW_ID)
const sections = reactWindowData.pluginData.sections
const enabledSectionIDs = enabledSections.map((s) => sections.find((section) => section.sectionCode === s)?.ID ?? '')
logDebug('processActionOnReturn', `CLOSE_UNNEEDED_SECTIONS: currently enabled sections: [${String(enabledSections)}]`)
logDebug('processActionOnReturn', `CLOSE_UNNEEDED_SECTIONS: currently enabled sectiond IDs: [${String(enabledSectionIDs)}]`)
// Handle sections that are not enabled
const sectionIDsToClose = sections.filter(section => !enabledSections.includes(section.sectionCode)).map(section => section.ID)
logDebug('processActionOnReturn', `CLOSE_UNNEEDED_SECTIONS: will close sections: [${sectionIDsToClose.join(',')}]`)
const actuallyClosed: Array<string> = []
for (const sectionID of sectionIDsToClose) {
const sectionIndex = sections.findIndex((section) => section.ID === sectionID)
if (sectionIndex !== -1) {
logDebug('processActionOnReturn', `Closing section ID: ${sectionID}`)
sections.splice(sectionIndex, 1)
actuallyClosed.push(sectionID)
}
}
await sendToHTMLWindow(
WEBVIEW_WINDOW_ID,
'UPDATE_DATA',
reactWindowData,
`Closed section(s): [${actuallyClosed.join(',')}]`
)
}
if (actionsOnSuccess.includes('CLOSE_SEARCH_SECTION')) {
logDebug('processActionOnReturn', `CLOSE_SEARCH_SECTION: closing section: [SEARCH]`)
const reactWindowData = await getGlobalSharedData(WEBVIEW_WINDOW_ID)
const sectionToClose = 'SEARCH'
const actuallyClosed: Array<string> = []
const sectionIndex = reactWindowData.pluginData.sections.findIndex((section) => section.sectionCode === sectionToClose)
if (sectionIndex !== -1) {
logDebug('processActionOnReturn', `Closing section: ${sectionToClose}`)
reactWindowData.pluginData.sections.splice(sectionIndex, 1)
actuallyClosed.push(sectionToClose)
}
await sendToHTMLWindow(
WEBVIEW_WINDOW_ID,
'UPDATE_DATA',
reactWindowData,
`Closed section: [${actuallyClosed.join(',')}]`
)
}
if (actionsOnSuccess.includes('INCREMENT_DONE_COUNT')) {
const reactWindowData = await getGlobalSharedData(WEBVIEW_WINDOW_ID)
// Update the total done count for all sections
const incrementedCount = reactWindowData.pluginData.totalDoneCount + 1
logDebug('processActionOnReturn', `INCREMENT_DONE_COUNT to ${String(incrementedCount)}`)
reactWindowData.pluginData.totalDoneCount = incrementedCount
await sendToHTMLWindow(WEBVIEW_WINDOW_ID, 'UPDATE_DATA', reactWindowData, `Incrementing done counts (ahead of proper background refresh)`)
}
if (actionsOnSuccess.includes('REFRESH_ALL_ENABLED_SECTIONS')) {
logDebug('processActionOnReturn', `REFRESH_ALL_ENABLED_SECTIONS: calling incrementallyRefreshSomeSections (for ${String(enabledSections)}) ...`)
await incrementallyRefreshSomeSections({ ...data, sectionCodes: enabledSections })
} else if (actionsOnSuccess.includes('PERSPECTIVE_CHANGED')) {
logDebug('processActionOnReturn', `PERSPECTIVE_CHANGED: calling incrementallyRefreshSomeSections (for ${String(enabledSections)}) ...`)
await setPluginData({ perspectiveChanging: true }, `Starting perspective change`)
await incrementallyRefreshSomeSections({ ...data, sectionCodes: enabledSections })
logDebug('processActionOnReturn', `PERSPECTIVE_CHANGED finished (should hide modal spinner)`)
await setPluginData({ perspectiveChanging: false }, `Ending perspective change`)
} else if (actionsOnSuccess.includes('REFRESH_ALL_SECTIONS')) {
logDebug('processActionOnReturn', `REFRESH_ALL_SECTIONS: calling incrementallyRefreshSomeSections ...`)
await incrementallyRefreshSomeSections({ ...data, sectionCodes: allSectionCodes })
} else if (actionsOnSuccess.includes('REFRESH_ALL_CALENDAR_SECTIONS')) {
// Note: only used by doMoveFromCalToCal(), as at 2.3.0.b15
logDebug('processActionOnReturn', `REFRESH_ALL_CALENDAR_SECTIONS: calling incrementallyRefreshSomeSections (for ${String(allCalendarSectionCodes)}) ..`)
for (const sectionCode of allCalendarSectionCodes) {
// await refreshSomeSections({ ...data, sectionCodes: [sectionCode] })
await incrementallyRefreshSomeSections({ ...data, sectionCodes: [sectionCode] })
}
} else {
// At least update TB section (if enabled) to make sure its as up to date as possible
if (enabledSections.includes('TB')) {
logDebug('processActionOnReturn', `Adding REFRESH_SECTION_IN_JSON for TB ...`)
if (!actionsOnSuccess.includes('REFRESH_SECTION_IN_JSON')) {
actionsOnSuccess.push('REFRESH_SECTION_IN_JSON')
if (!handlerResult.sectionCodes) {
handlerResult.sectionCodes = []
}
if (!handlerResult.sectionCodes.includes('TB')) {
handlerResult.sectionCodes?.push('TB')
}
}
logDebug('processActionOnReturn', `... -> ${String(handlerResult.sectionCodes)}`)
}
}
if (actionsOnSuccess.includes('REFRESH_SECTION_IN_JSON')) {
const wantedsectionCodes = handlerResult.sectionCodes ?? []
if (!wantedsectionCodes?.length) logError('processActionOnReturn', `REFRESH_SECTION_IN_JSON: no sectionCodes provided`)
logDebug('processActionOnReturn', `REFRESH_SECTION_IN_JSON: calling getSomeSectionsData (for ['${String(wantedsectionCodes)}']) ...`)
await incrementallyRefreshSomeSections({ ...data, sectionCodes: wantedsectionCodes })
}
if (actionsOnSuccess.includes('START_DELAYED_REFRESH_TIMER')) {
// TEST: turning this off for now
logDebug('processActionOnReturn', `START_DELAYED_REFRESH_TIMER: 😳 NOT NOW setting startDelayedRefreshTimer in pluginData`)
// const reactWindowData = await getGlobalSharedData(WEBVIEW_WINDOW_ID)
// reactWindowData.pluginData.startDelayedRefreshTimer = true
// await sendToHTMLWindow(WEBVIEW_WINDOW_ID, 'UPDATE_DATA', reactWindowData, `Setting startDelayedRefreshTimer`)
}
} catch (error) {
logError('processActionOnReturn', `error: ${JSP(error)}: \n${JSP(formatReactError(error))}`)
clo(data.item, `- data.item at error:`)
}
}
/**
* Update React window data based on the result of handling item content update.
* Purpose: provides a more responsive user experience, by updating the React window's data structure to reflect changes made to individual items without requiring a full refresh of all sections.
* Called from processActionOnReturn() function following:
* - Content Updates (Most Common)
* - Item Type Changes
* - Project Updates
*
* Note: REMOVE_LINE_FROM_JSON is now handled entirely in processActionOnReturn() to avoid duplication.
*
* @param {TBridgeClickHandlerResult} handlerResult The result of handling item content update.
* @param {MessageDataObject} data The data of the item that was updated.
* @param {Array<string>} fieldPathsToUpdate The field paths to update in React window data -- paths are in SectionItem fields (e.g. "ID" or "para.content")
*/
export async function updateReactWindowFromLineChange(handlerResult: TBridgeClickHandlerResult, data: MessageDataObject, fieldPathsToUpdate: Array<string>): Promise<void> {
try {
clo(handlerResult, 'updateReactWindowFLC: handlerResult')
const { errorMsg, success, updatedParagraph } = handlerResult
const actionsOnSuccess = handlerResult.actionsOnSuccess ?? []
const { ID } = data.item ?? { ID: '?' }
if (!success) {
throw new Error(`handlerResult indicates failure with item: ID ${ID}, so won't update window. ${errorMsg || ''}`)
}
const isProject = data.item?.itemType === 'project'
const reactWindowData = await getGlobalSharedData(WEBVIEW_WINDOW_ID)
let sections = reactWindowData.pluginData.sections
logDebug('updateReactWindowFLC', `for item ID: ${ID} will do [${String(actionsOnSuccess)}] ...`)
if (updatedParagraph) {
logDebug(`updateReactWindowFLC`, ` -> updatedParagraph: "${updatedParagraph.content}"`)
const { content: oldContent = '', filename: oldFilename = '' } = data.item?.para ?? { content: 'error', filename: 'error' }
// TEST:
// const newPara: TParagraphForDashboard = makeDashboardParas([updatedParagraph])[0]
const newPara: TParagraphForDashboard = updatedParagraph
// get a reference so we can overwrite it later
// find all references to this content (could be in multiple sections)
const indexes = findSectionItems(sections, ['itemType', 'para.filename', 'para.content'], {
itemType: /open|checklist/,
'para.filename': oldFilename,
'para.content': oldContent,
})
if (indexes.length) {
logInfo('updateReactWindowFLC', `-> found ${indexes.length} items to update: ${String(indexes.map((i) => `s[${i.sectionIndex}_${sections[i.sectionIndex].sectionCode}]:si[${i.itemIndex}]`).join(', '))}`)
// Apply the update to all the found sectionItems
sections = copyUpdatedSectionItemData(indexes, fieldPathsToUpdate, { itemType: newPara.type, para: newPara }, sections)
clo(reactWindowData.pluginData.sections[0]?.sectionItems[0], 'updateReactWindowFLC: NEW reactWindow JSON sectionItem before sendToHTMLWindow()')
} else {
throw new Error(`updateReactWindowFLC: unable to find item to update: ID ${ID} was looking for: content="${oldContent}" filename="${oldFilename}" : ${errorMsg || ''}`)
}
} else if (isProject) {
// For Project items
const { filename = '' } = data.item?.project ?? { filename: 'error' }
logInfo('updateReactWindowFLC', `UPDATE_LINE_IN_JSON for '${ID}' = Project '${filename}'. Will sendToHTMLWindow()`)
} else {
// No updatedParagraph provided - this should only happen for project updates or other special cases
throw new Error(`no updatedParagraph param was given, and its not a Project update. So cannot update react window content for: ID=${ID}. errorMsg=${errorMsg || '-'}`)
}
await sendToHTMLWindow(WEBVIEW_WINDOW_ID, 'UPDATE_DATA', reactWindowData, `Single item updated on ID ${ID}`)
} catch (error) {
logError('updateReactWindowFLC', error.message)
clo(data.item, `- data.item at error:`)
}
}