diff --git a/flow-typed/Noteplan.js b/flow-typed/Noteplan.js index ad6f3b128..a0917500a 100644 --- a/flow-typed/Noteplan.js +++ b/flow-typed/Noteplan.js @@ -1721,6 +1721,7 @@ lineIndex: number; /** * Paragraph.indents * Get/Set the amount of indentations. + * WARNING: Long-standing BUG: updateParagraph() keeps .indents for type 'text', and drops it when the line is recognized as 'list' or 'quote' (content starts with `- ` or `> `). See https://github.com/NotePlan/plugins/issues/803, raised 2026-12-04 */ indents: number; /** @@ -1754,7 +1755,8 @@ lineIndex: number; * If it returns undefined, it means there has been a failure. * Note: Available from v3.3 * Note: this can become inaccurate if other content changes in the note; it is not automatically recalculated. Re-fetch paragraphs to avoid this. - * BUG (NotePlan Beta 3.22.1, 2026-12-03): after note.updateParagraph() on this same object, if the new content is shorter than the old content (priority `!!` -> `!`, `!` -> none, `>>` -> none), contentRange is left at the old end. children() then returns one phantom child: the next line, indent 0, empty content and rawContent, and a zero-width contentRange (start === end). Lengthening the line does not do this. Loading the paragraph again from the note returns the real children. + * WARNING: BUG (NotePlan Beta 3.22.1, 2026-12-03): after note.updateParagraph() on this same object, if the new content is shorter than the old content (priority `!!` -> `!`, `!` -> none, `>>` -> none), contentRange is left at the old end. children() then returns one phantom child: the next line, indent 0, empty content and rawContent, and a zero-width contentRange (start === end). Lengthening the line does not do this. Loading the paragraph again from the note returns the real children. + * TODO: @EduardMe reports that is fixed in the next beta after b1556 (3.22.1). Test and then remove workarounds and this warning. * Workaround: helpers/parentsAndChildren.js childrenExcludingStalePhantoms() drops entries whose content and rawContent are both empty. Callers that have just written the paragraph should also re-read it from the note before calling children() (Dashboard rereadParagraph()). * WARNING: appears to be unreliable on iOS. * @return {$ReadOnlyArray | void} diff --git a/helpers/__tests__/headings.test.js b/helpers/__tests__/headings.test.js index 48b306c62..948e99475 100644 --- a/helpers/__tests__/headings.test.js +++ b/helpers/__tests__/headings.test.js @@ -205,6 +205,41 @@ describe('helpers/headings', () => { }) }) + describe('getHeadingHierarchyForThisPara', () => { + test('walks from the paragraph position when lineIndex is stale after an insert', () => { + const note = { + filename: '20261204.md', + paragraphs: [ + { type: 'title', content: 'Home', headingLevel: 2, lineIndex: 0 }, + { type: 'open', content: 'older', lineIndex: 1 }, + { type: 'open', content: 'Give feedback on Books app manual tracking', lineIndex: 4 }, + { type: 'title', content: 'NotePlan', headingLevel: 2, lineIndex: 3 }, + { type: 'open', content: 'other', lineIndex: 4 }, + ], + } + note.paragraphs.forEach((p) => { + p.note = note + }) + // lineIndex 4 is the following section. The task itself sits under Home. + expect(h.getHeadingHierarchyForThisPara(note.paragraphs[2])).toEqual(['Home']) + }) + + test('falls back to lineIndex when the paragraph object is not in the note array', () => { + const note = { + filename: '20261204.md', + paragraphs: [ + { type: 'title', content: 'Home', headingLevel: 2, lineIndex: 0 }, + { type: 'open', content: 'older', lineIndex: 1 }, + ], + } + note.paragraphs.forEach((p) => { + p.note = note + }) + const orphan = { type: 'open', content: 'x', lineIndex: 1, note } + expect(h.getHeadingHierarchyForThisPara(orphan)).toEqual(['Home']) + }) + }) + describe('stripFoldedHeadingEllipsis', () => { test('strips unicode ellipsis', () => { expect(h.stripFoldedHeadingEllipsis('Done …')).toBe('Done') diff --git a/helpers/headings.js b/helpers/headings.js index 6cd9c63c8..3ea4c8579 100644 --- a/helpers/headings.js +++ b/helpers/headings.js @@ -52,7 +52,6 @@ export function isParaAMatchForHeading(para: TParagraph, headingName: string, he * @returns {Array} array of headings, lowest (e.g. H4) to highest (e.g. H1) */ export function getHeadingHierarchyForThisPara(para: TParagraph): Array { - let lineIndex = para.lineIndex const noteFilename = para.note?.filename ?? '?' // logDebug('getHeadingHierarchyForThisPara', `Finding headings for line #${String(lineIndex)} in note ${noteFilename}:`) const thisNote = para.note @@ -61,11 +60,15 @@ export function getHeadingHierarchyForThisPara(para: TParagraph): Array logWarn('getHeadingHierarchyForThisPara', `-> no note paras found for ${noteFilename}`) return [] } + // lineIndex is not recalculated when another line is inserted, and Editor vs Note differ when the note has frontmatter. + // Walk from this paragraph's place in note.paragraphs so a just-added task is still under its real heading. + let lineIndex = noteParas.indexOf(para) + if (lineIndex < 0 && typeof para.lineIndex === 'number') lineIndex = para.lineIndex let currentHeadingLevel = 5 const theseHeadings = [] while (lineIndex >= 0) { const thisPara = noteParas[lineIndex] - if (thisPara.type === 'title') { + if (thisPara && thisPara.type === 'title') { const thisHeadingLevel = thisPara.headingLevel if (thisHeadingLevel < currentHeadingLevel) { theseHeadings.push(thisPara.content) diff --git a/helpers/react/EditableInput.jsx b/helpers/react/EditableInput.jsx index a9a417a5a..c43ce2032 100644 --- a/helpers/react/EditableInput.jsx +++ b/helpers/react/EditableInput.jsx @@ -19,6 +19,9 @@ type Props = { onEnterPress?: () => void, /** Optional boolean to automatically focus the input when mounted */ autofocusMe?: boolean, + /** Optional callbacks when the input gains / loses focus */ + onFocus?: () => void, + onBlur?: () => void, } type RefType = { @@ -91,6 +94,7 @@ const EditableInputBox: any = React.forwardRef((props, ref) => { if (divRef.current && !divRef.current.textContent) { divRef.current.innerHTML = `${props.placeholder || ''}` } + if (props.onBlur) props.onBlur() } const handleFocus = () => { @@ -98,6 +102,7 @@ const EditableInputBox: any = React.forwardRef((props, ref) => { // Cast: the `querySelector()` call in the guard invalidates Flow's null-refinement of divRef.current; it is still non-null here (divRef.current: any).innerHTML = '' } + if (props.onFocus) props.onFocus() } React.useImperativeHandle(ref, () => ({ @@ -131,6 +136,8 @@ const EditableInputBox: any = React.forwardRef((props, ref) => { value={inputValue} onChange={handleChange} onKeyDown={onKeyDown} + onFocus={props.onFocus} + onBlur={props.onBlur} /> ) }) diff --git a/jgclark.Dashboard/CHANGELOG.md b/jgclark.Dashboard/CHANGELOG.md index 23b5f7659..6de5da208 100644 --- a/jgclark.Dashboard/CHANGELOG.md +++ b/jgclark.Dashboard/CHANGELOG.md @@ -3,6 +3,25 @@ For more details see the [plugin's documentation](https://noteplan.co/plugins/jg +## [2.7.0] 2026-12-04 +### Changes +- Fix: #tag and Search sections no longer include tasks from the `@Templates` folder. This aligns with all other sections. (thanks, @dwertheimer; closes #802) +- Change: Redesigned Edit / Interactive Processing dialog for Tasks, Reminders and Projects items. It should be more responsive on smaller devices, and provides clearer button labels. (Thanks for the code, @dwertheimer.) Changes include: + - The item text shows more formatting, as on Dashboard rows (links, tags and priorities styled). Click the text to edit the raw text, with the cursor where you clicked (or use the pencil in its footer); the eye button, Revert or Update go back to the formatted view. + - Some move/reschedule-to dates are now in a "Later" sub-menu. + - On iPhone/iPad the dialog no longer opens with the keyboard showing. + - The 'Type' and 'Later' menus open upward when there isn't room below. + - The editor footer shows when the item is due or how overdue it is, using the due date (`!date`) when there is one. + - New: 'Add text note' asks for text, then inserts it under the item (after any children it already has), indented one level deeper. (for @Doug) + - 'Complete' is now the primary button, and 'Complete then' instead shows the date it was scheduled to (e.g. 'Done Jul 15') if available. + - On iPhone/iPad, swipe the Interactive Processing dialog left to skip to the next item. + - Interactive Processing now animates between items, not just into the first item. + - Opening the date picker keeps the top of the dialog where it is and only extends it downward. + - 'New Task' now opens the Dashboard's own Add dialog instead of the Quick Capture command sheet. The button is labelled 'Add item', and on a checklist it opens with Checklist selected. 'Add item' and 'Add text note' sit on their own 'Add' row. + - The reminder dialog has an 'Add item' button on its own 'Add' row. It opens the same Add dialog as the top bar, with Reminder already selected, then returns to this reminder. That Add dialog stays where the reminder dialog was, shifted up only far enough that the whole form stays on screen. +- Fix: A task added from Dashboard's Add dialog now shows in Today (or the other section that was refreshed) without waiting for a full refresh. The refresh was reading the note before the new line's heading was reliable, so a perspective that only shows one calendar heading (such as Home) left the task out. +- Change: To match Priority markers in the main app, more than three leading `!`s are no longer are treated as a priority indicator. For NotePlan only recognises `!`, `!!`, `!!!` and `>>`. + ## [2.6.2] 2026-12-03 - Fix: Automatic refresh could stop working if the Time Block section was on after waking the device from sleep or changing to being the foreground window. dev: A second Time Block refresh was allowed to start while the first was still running, and both then stuck the plugin thread. The idle timer also skipped a refresh when its check ran late (sleep, or the window in the background) and started the wait over. - Fix: A task that starts with a due date (e.g. `!>date`) is no longer treated as priority 1. diff --git a/jgclark.Dashboard/README.md b/jgclark.Dashboard/README.md index 7354fea52..89024ee71 100644 --- a/jgclark.Dashboard/README.md +++ b/jgclark.Dashboard/README.md @@ -319,7 +319,7 @@ This is a Dashboard-wide setting (the same for all Perspectives), not stored per The settings in "What to Include and Exclude" control what Spaces, folders and items are included and excluded in Dashboard's many sections. It includes the folders from the first setting, and then removes any specified from the next setting. Reminder list selection lives under **Reminders Section** (below). Finally, individual lines in notes can be ignored by adding terms: - **Folders to Include**: Comma-separated list of folder(s) to include when searching for open or closed tasks/checklists. The matches ared partial, so 'Home' will include 'Home' and 'The Home Areas' etc. If left blank, all folders are included. Note: Calendar notes are always included, where relevant. -- **Folders to Exclude**: Comma-separated list of folder(s) to ignore when searching for open or closed tasks/checklists. The matches are partial, so 'Work' will exclude 'Work' and 'Work/CompanyA' etc. Where there is a conflict, exclusions will take precedence over inclusions. To ignore notes at the top-level (not in a folder), include '/' in the list. (@Trash is always ignored, but other special folders need to be specified, e.g. @Archive, @Templates.) +- **Folders to Exclude**: Comma-separated list of folder(s) to ignore when searching for open or closed tasks/checklists. The matches are partial, so 'Work' will exclude 'Work' and 'Work/CompanyA' etc. Where there is a conflict, exclusions will take precedence over inclusions. To ignore notes at the top-level (not in a folder), include '/' in the list. (@Trash and @Templates are always ignored. Other special folders need to be specified where a section can show them, e.g. @Archive in a #tag section.) - **Calendar note terms to include**: Comma-separated list of terms for calendar notes only. A task is included if any heading above it starts with one of these values (case-insensitive prefix; e.g. `Wins` matches `Wins for 2026 Q2`), or if the task text itself contains the term (e.g. `#acme`, `@acme`, or `acme`). The destination of a labeled markdown link `[label](url)` is ignored (the label is still matched), and the contents of `[[note links]]` are ignored. If left blank, all calendar items are included. Short terms can over-match. When this is set and Hide Duplicates is on, matching items stay in calendar / Overdue sections rather than only in a TAG section. Useful for Perspective focus (e.g. an ACME perspective with `acme` or `#acme`). - **Ignore items in notes with these term(s)**: If set, open tasks/checklists with this word or tag will be ignored, and not counted as open or closed. (This check is not case sensitive.) This is useful for situations where completing the item is outside your control. - Apply to sections under headings in Calendar notes? If turned on, then all content in Calendar notes under headings that contains any of those phrases will be ignored. This applies to the preceding headings all the way up the H5->H1 hierarchy of section headings for that line. For example in the following note: @@ -343,7 +343,7 @@ _The settings in the 'Moving/Scheduling Items' section are covered above_. - Show referenced items in separate section? Whether to show Today's open tasks and checklists in two separate sections: first from the daily note itself, and second referenced from project notes. The same also goes for Weekly/Monthly/Quarterly notes. - Show completed task count?: Show the number of tasks completed today at the top of the Dashboard. This total is not filtered by the current Perspective (see [Other notes about the Dashboard display](#other-notes-about-the-dashboard-display)). Note: For this to work, you need to have enabled "Append Completion Date" in the NotePlan Preferences/Todo section. - How to show progress in Calendar sections?: If set to 'number closed', shows how many tasks were completed in the section heading (with a progress circle). If set to 'number open', shows how many tasks are still open instead. These counts are not filtered by the current Perspective. Today’s progress is tasks for today completed today; other calendar periods use `@done` dates inside that period in that calendar note. The header total remains all tasks completed today anywhere. Set to 'none' to hide. -- Hide priority markers? Hide the `>>`, `!!`, `!`, and `!!` priority markers (if your theme uses priorities markers). +- Hide priority markers? Hide the `>>`, `!!!`, `!!`, and `!` priority markers (if your theme uses priorities markers). - Show note link for tasks? Whether to show the note link for an open task or checklist. - Show folder name in note link? Whether to include the folder name when showing a note link - Show scheduled date for tasks? Whether to display scheduled >dates for tasks in dashboard view. @@ -371,7 +371,7 @@ _The settings in the 'Moving/Scheduling Items' section are covered above_. ### Interactive Processing settings - Enable interactive processing for each section? If enabled, the Dashboard will display a button that will loop through all the open items in a given section and prompt you to act on them. - Open note and highlight task when processing? If enabled, the Dashboard will open the note in the Editor and highlight the task in the note when it is processed. If this is turned, off, you can always open the note by clicking the task title in the dialog window -- Show interactive processing transitions? By default, interactive processing will show a shrink/grow transition between each item to be processed. You can turn these off if you prefer. +- Show interactive processing transitions? By default, interactive processing animates each change of item: the dialog grows in when it opens, and each new item slides in from the side. You can turn these off if you prefer. On iPhone/iPad you can also swipe the dialog left to skip to the next item. ### Filter Menu The Filter menu includes the following toggles: diff --git a/jgclark.Dashboard/plugin.json b/jgclark.Dashboard/plugin.json index b283d98ab..20fc5b6d4 100644 --- a/jgclark.Dashboard/plugin.json +++ b/jgclark.Dashboard/plugin.json @@ -7,10 +7,10 @@ "plugin.iconColor": "red-600", "plugin.description": "A Dashboard for NotePlan, that in one place can show:\n- a compact list of open tasks and checklists from today's note, and scheduled ones from other notes.\n- similarly for yesterday's note, tomorrow's note, and the weekly, monthly and quarterly notes too (if used)\n- open Apple Reminders\n- any timeblocks for today\n- all overdue tasks\n- all open tasks and checklists that contain particular @tags or #mentions of your choosing\n- the next notes ready to review (if you use the 'Projects and Reviews' plugin).\nIt includes many other ways of speeding up managing your tasks: see the website for more details.", "plugin.author": "@jgclark", - "plugin.version": "2.6.2", + "plugin.version": "2.7.0", "plugin.releaseStatus": "full", "plugin.hidden": false, - "plugin.lastUpdateInfo": "2.6.2: Changing a task's priority no longer deletes due dates or other '!' in the line. A due date at the start of a line is not treated as priority 1. A priority marker counts only with whitespace after it.\n2.6.1: Calendar-note !date deadlines follow the same start-through-due rules as !>. Improvements to display and handling of indented sub-tasks; new parent/child markers.\n2.6.0: Add support for Due dates. The 'add' button on topbar now offers Task, Checklist, or Reminder in one dialog. More reliable perspective switching, and related Dashboard fixes.\n2.5.2: Add Interactive Processing for Reminders/Timeblock section.\nThe task dialog 'Change to' button is now a 'Change type' menu.\nTwo small bug fixes.\n2.5.1: Minor bug fixes and performance improvements.\n2.5.0: Performance improvements on Priority note-index cache.\nNew 'Compact' Display mode.\nInteractive Processing for Active/Review Projects.\nLots of other small UX improvements.\n2.4.6: Overdue move-all fix; auto-load Shared Resources.\n2.4.5: Responsive while tag/mention cache rebuilds.\n2.4.4: Tag/mention cache in np.Shared; TAG refresh performance.\n2.4.2: Reminder edit dialog and IP for Reminders.\n2.4.0: Reminders, Active Projects, Wins, Spaces. See changelog.", + "plugin.lastUpdateInfo": "2.7.0: Redesigned task / Interactive Processing dialog: text wraps, phone-friendly layout, 'Later' menu, due/overdue footer, 'Complete' as primary action, progress and swipe-to-skip in Interactive Processing, and 'New Task' uses the Dashboard's Add dialog.\n2.6.2: Changing a task's priority no longer deletes due dates or other '!' in the line. A due date at the start of a line is not treated as priority 1. A priority marker counts only with whitespace after it.\n2.6.1: Calendar-note !date deadlines follow the same start-through-due rules as !>. Improvements to display and handling of indented sub-tasks; new parent/child markers.\n2.6.0: Add support for Due dates. The 'add' button on topbar now offers Task, Checklist, or Reminder in one dialog. More reliable perspective switching, and related Dashboard fixes.\n2.5.2: Add Interactive Processing for Reminders/Timeblock section.\nThe task dialog 'Change to' button is now a 'Change type' menu.\nTwo small bug fixes.\n2.5.1: Minor bug fixes and performance improvements.\n2.5.0: Performance improvements on Priority note-index cache.\nNew 'Compact' Display mode.\nInteractive Processing for Active/Review Projects.\nLots of other small UX improvements.\n2.4.6: Overdue move-all fix; auto-load Shared Resources.\n2.4.5: Responsive while tag/mention cache rebuilds.\n2.4.4: Tag/mention cache in np.Shared; TAG refresh performance.\n2.4.2: Reminder edit dialog and IP for Reminders.\n2.4.0: Reminders, Active Projects, Wins, Spaces. See changelog.", "plugin.script": "script.js", "plugin.url": "https://noteplan.co/plugins/jgclark.Dashboard", "plugin.changelog": "https://github.com/NotePlan/plugins/blob/main/jgclark.Dashboard/CHANGELOG.md", diff --git a/jgclark.Dashboard/src/__tests__/templateFolderExclusion.test.js b/jgclark.Dashboard/src/__tests__/templateFolderExclusion.test.js new file mode 100644 index 000000000..f698cf37a --- /dev/null +++ b/jgclark.Dashboard/src/__tests__/templateFolderExclusion.test.js @@ -0,0 +1,18 @@ +// @flow +/* globals describe, expect, test */ + +import { withTemplatesFolderAlwaysExcluded } from '../templateFolderExclusion.js' + +describe('withTemplatesFolderAlwaysExcluded', () => { + test('adds @Templates when the perspective exclude list omits it', () => { + expect(withTemplatesFolderAlwaysExcluded(['Work', '@Archive'])).toEqual(['Work', '@Archive', '@Templates']) + }) + + test('does not add a second entry when it is already listed', () => { + expect(withTemplatesFolderAlwaysExcluded(['@templates', 'Work'])).toEqual(['@templates', 'Work']) + }) + + test('adds @Templates to an empty list', () => { + expect(withTemplatesFolderAlwaysExcluded([])).toEqual(['@Templates']) + }) +}) diff --git a/jgclark.Dashboard/src/clickHandlers.js b/jgclark.Dashboard/src/clickHandlers.js index 547de77fe..b6b6d38fe 100644 --- a/jgclark.Dashboard/src/clickHandlers.js +++ b/jgclark.Dashboard/src/clickHandlers.js @@ -45,6 +45,7 @@ import { sendToHTMLWindow } from '@helpers/HTMLView' import { coreAddChecklistToNoteHeading, coreAddTaskToNoteHeading } from '@helpers/NPAddItems' import { smartOpenNoteInEditorFromFilename, smartShowLineInEditorFromFilename } from '@helpers/NPEditor' import { cancelItem, completeItem, completeItemEarlier, deleteItem, findParaFromStringAndFilename } from '@helpers/NPParagraph' +import { getIndentLevelFromRawContent } from '@helpers/paragraph' import { addAppleReminder, buildOpenTaskContentFromReminder, completeReminderById, deleteReminderById, mapCalendarItemToReminder, mapNotePlanPriorityToAppleReminder, parseLeadingPriorityFromReminderText, updateReminderById, type TUpdateAppleReminderParams } from '@helpers/NPReminders' import { unscheduleItem } from '@helpers/NPScheduleItems' import { generateCSSFromTheme } from '@helpers/NPThemeToCSS' @@ -482,7 +483,11 @@ export async function doRescheduleReminder(data: MessageDataObject): Promise ${newDateStr}`) const preserveTime = data.updatedTime !== undefined ? String(data.updatedTime).trim() : (reminder.time || '') @@ -503,8 +508,9 @@ export async function doRescheduleReminder(data: MessageDataObject): Promise last.lineIndex) last = child + } + return last +} + +/** + * Text of a comment line with a list or quote marker removed, so we can find the paragraph after NotePlan parses it. + * @param {string} line + * @returns {string} + */ +function commentLineBody(line: string): string { + if (line.startsWith('- ')) return line.slice(2) + if (line.startsWith('> ')) return line.slice(2) + if (line.startsWith('>')) return line.slice(1).trimStart() + return line +} + +/** + * True when this paragraph is the comment line we just inserted. + * NotePlan may keep the marker in content, or move it into the paragraph type and leave only the body. + * @param {TParagraph} para + * @param {string} line - the comment line as typed, without the indent we add + * @returns {boolean} + */ +function paragraphIsInsertedComment(para: TParagraph, line: string): boolean { + const raw = String(para.rawContent || '') + const body = String(para.content || '') + const markerStripped = commentLineBody(line) + return body === line || body === markerStripped || raw.endsWith(line) || (markerStripped !== '' && raw.endsWith(markerStripped)) +} + +/** + * Add one or more indented paragraphs under the item (a comment). + * The comment text arrives in userInputObj.commentText, not updatedContent, so a pending edit of the item itself still applies first. + * Leading tabs are part of the inserted text. Setting .indents and then updateParagraph keeps the indent for plain text, + * but drops it when the line is recognized as a list (`-`) or a quote (`>`). + * @param {MessageDataObject} data + * @returns {Promise} + */ +export async function doAddComment(data: MessageDataObject): Promise { + const validated = validateMessageDataForHandler(data, 'doAddComment') + if (!validated.ok) return validated.result + const { filename, content, sectionCode } = validated.data + const commentInput = data.userInputObj + const rawComment = commentInput && typeof commentInput.commentText === 'string' ? commentInput.commentText : '' + const lines = rawComment.split('\n').map((line) => line.trim()).filter((line) => line !== '') + if (lines.length === 0) { + logWarn('doAddComment', 'No comment text') + return handlerResult(false, [], { errorMsg: 'Type a comment to add under this item.', errorMessageLevel: 'WARN' }) + } + + const possiblePara = findParaFromStringAndFilename(filename, content) + if (typeof possiblePara === 'boolean' || !possiblePara) { + logWarn('doAddComment', `unable to find para {${content}} in filename ${filename}`) + return handlerResult(false, ['REFRESH_SECTION_IN_JSON'], { sectionCodes: [sectionCode], errorMsg: `Unable to find para "${content}" in filename: "${filename}". I will refresh this section, then please try again.`, errorMessageLevel: 'WARN' }) + } + const note = possiblePara.note + if (!note) { + return handlerResult(false, ['REFRESH_SECTION_IN_JSON'], { sectionCodes: [sectionCode], errorMsg: `Could not get note for filename ${filename}.`, errorMessageLevel: 'ERROR' }) + } + + try { + const parentIndents = Math.max( + typeof possiblePara.indents === 'number' ? possiblePara.indents : 0, + getIndentLevelFromRawContent(String(possiblePara.rawContent || '')), + ) + const childIndents = parentIndents + 1 + const indentPrefix = '\t'.repeat(childIndents) + let anchor = paragraphToInsertCommentAfter(possiblePara) + for (const line of lines) { + const insertedAt = anchor.lineIndex + 1 + // Tabs go in the inserted text. updateParagraph after setting .indents rewrites list and quote lines without them. + // The API is typed as void but resolves asynchronously in the app. + await note.insertParagraphAfterParagraph(`${indentPrefix}${line}`, anchor, 'text') + const newPara = note.paragraphs[insertedAt] + if (!newPara || !paragraphIsInsertedComment(newPara, line)) { + throw new Error(`Inserted comment was not found under "${content}"`) + } + anchor = newPara + } + DataStore.updateCache(note, false) + logDebug('doAddComment', `added ${lines.length} comment line(s) under "${content}" at indent ${childIndents}`) + return handlerResult(true, ['UPDATE_LINE_IN_JSON', 'REFRESH_SECTION_IN_JSON'], { + updatedParagraph: makeDashboardParas([rereadParagraph(possiblePara)])[0], + sectionCodes: [sectionCode], + }) + } catch (error) { + logError('doAddComment', error.message) + return handlerResult(false, ['REFRESH_SECTION_IN_JSON'], { sectionCodes: [sectionCode], errorMsg: `${error.message}. I will refresh this Section; please then try again.`, errorMessageLevel: 'ERROR' }) + } +} + /** * Send a request to unscheduleItem to plugin * @param {MessageDataObject} data - The data object containing item info diff --git a/jgclark.Dashboard/src/dashboardSettings.js b/jgclark.Dashboard/src/dashboardSettings.js index 7ef3fbce9..645659434 100644 --- a/jgclark.Dashboard/src/dashboardSettings.js +++ b/jgclark.Dashboard/src/dashboardSettings.js @@ -123,7 +123,7 @@ export const dashboardSettingDefs: Array = [ key: 'excludedFolders', label: 'Folders to Exclude', description: - "Comma-separated list of folder(s) to ignore when selecting open tasks/checklists to show. The matches are partial, so 'Work' will exclude 'Work' and 'Work/CompanyA' etc. To ignore notes at the top-level (not in a folder), include '/' in the list. (@Trash is always ignored, but other special folders need to be specified, e.g. @Archive, @Templates.)", + "Comma-separated list of folder(s) to ignore when selecting open tasks/checklists to show. The matches are partial, so 'Work' will exclude 'Work' and 'Work/CompanyA' etc. To ignore notes at the top-level (not in a folder), include '/' in the list. (@Trash and @Templates are always ignored. Other special folders need to be specified where a section can show them, e.g. @Archive in a #tag section.)", type: 'input', default: '@Archive, @Templates, @Searches, @WindowSets', compactDisplay: true, @@ -537,7 +537,7 @@ export const dashboardSettingDefs: Array = [ { key: 'enableInteractiveProcessingTransitions', label: 'Show interactive processing transitions?', - description: 'By default, interactive processing will show a shrink/grow transition between each item to be processed. You can turn these off if you prefer.', + description: 'By default, interactive processing animates each change of item: the dialog grows in when it opens, and each new item slides in from the side. You can turn these off if you prefer.', type: 'switch', dependsOnKey: 'enableInteractiveProcessing', default: true, diff --git a/jgclark.Dashboard/src/dataGeneration.js b/jgclark.Dashboard/src/dataGeneration.js index 4dfe3851d..cb824e0e3 100644 --- a/jgclark.Dashboard/src/dataGeneration.js +++ b/jgclark.Dashboard/src/dataGeneration.js @@ -237,7 +237,7 @@ export async function getSomeSectionsData( if (placement.homeless.length > 0) { const parts = placement.homeless.map((h) => `${String(h.count)} ${h.label}`) - logWarn('getSomeSectionsData', `- ${parts.join('; ')} reminder(s) have no visible section and will not be shown anywhere`) + logInfo('getSomeSectionsData', `- ${parts.join('; ')} reminder(s) have no visible section and will not be shown anywhere`) } // DT and TB sections are generated separately but share paragraph data fetching. diff --git a/jgclark.Dashboard/src/dataGenerationSearch.js b/jgclark.Dashboard/src/dataGenerationSearch.js index 56b6e8717..58b76a295 100644 --- a/jgclark.Dashboard/src/dataGenerationSearch.js +++ b/jgclark.Dashboard/src/dataGenerationSearch.js @@ -20,6 +20,7 @@ import { setPluginData, } from './dashboardHelpers' import { getActivePerspectiveName, loadPerspectiveDefsFromPluginSettings } from './perspectiveHelpers' +import { withTemplatesFolderAlwaysExcluded } from './templateFolderExclusion' import { stringListOrArrayToArray } from '@helpers/dataManipulation' import { filenameIsInFuture, getTodaysDateHyphenated, includesScheduledFutureDate } from '@helpers/dateTime' import { JSP, clo, logDebug, logError, logInfo, logTimer, logWarn } from '@helpers/dev' @@ -53,6 +54,8 @@ export async function buildDashboardSearchOptions( ): Promise { const foldersToExcludePlusArchive = config.applyCurrentFilteringToSearch && config.excludedFolders ? stringListOrArrayToArray(config.excludedFolders, ',') : [] foldersToExcludePlusArchive.push('@Archive') + // @Templates is always ignored, same as tag sections. @Archive was already always added here. + const foldersToExclude = withTemplatesFolderAlwaysExcluded(foldersToExcludePlusArchive) const noteTypesToIncludeArr: Array = noteTypesToIncludeStr === 'both' ? ['notes', 'calendar'] : stringListOrArrayToArray(noteTypesToIncludeStr, ',') const SEConfig = await getSearchSettings() const caseSensitiveSearching = SEConfig?.caseSensitiveSearching ?? false @@ -62,7 +65,7 @@ export async function buildDashboardSearchOptions( noteTypesToInclude: noteTypesToIncludeArr, paraTypesToInclude: config.ignoreChecklistItems ? ['open', 'scheduled'] : ['open', 'scheduled', 'checklist', 'checklistScheduled'], foldersToInclude: config.applyCurrentFilteringToSearch && config.includedFolders ? stringListOrArrayToArray(config.includedFolders, ',') : [], - foldersToExclude: foldersToExcludePlusArchive, + foldersToExclude: foldersToExclude, caseSensitiveSearching: caseSensitiveSearching, fullWordSearching: fullWordSearching, fromDateStr: fromDateStr, @@ -294,7 +297,7 @@ export async function getSavedSearchResults( caseSensitiveSearching: false, fullWordSearching: true, foldersToInclude: config.includedFolders ? stringListOrArrayToArray(config.includedFolders, ',') : [], - foldersToExclude: config.excludedFolders ? stringListOrArrayToArray(config.excludedFolders, ',') : [], + foldersToExclude: withTemplatesFolderAlwaysExcluded(config.excludedFolders ? stringListOrArrayToArray(config.excludedFolders, ',') : []), fromDateStr: '', toDateStr: '', } diff --git a/jgclark.Dashboard/src/dataGenerationTags.js b/jgclark.Dashboard/src/dataGenerationTags.js index e5421a0fd..ee5254de7 100644 --- a/jgclark.Dashboard/src/dataGenerationTags.js +++ b/jgclark.Dashboard/src/dataGenerationTags.js @@ -16,6 +16,7 @@ import { scheduleTagMentionCacheGeneration, WANTED_PARA_TYPES, } from './tagMentionCache' +import { withTemplatesFolderAlwaysExcluded } from './templateFolderExclusion' import { filenameIsInFuture, includesScheduledFutureDate } from '@helpers/dateTime' import { stringListOrArrayToArray } from '@helpers/dataManipulation' import { clo, logDebug, logError, logInfo, logTimer, logWarn, timer } from '@helpers/dev' @@ -116,10 +117,14 @@ export async function getTaggedSectionData( source = 'using API' } - // Get the included and excluded folders + // Get the included and excluded folders. + // excludeSpecialFolders stays false so a perspective can still show other @ folders (for example @Archive). + // @Templates is always excluded, even when this perspective's Folders to Exclude list omits it. const includedFolders = config.includedFolders ? stringListOrArrayToArray(config.includedFolders, ',').map((folder) => folder.trim()) : [] - const excludedFolders = config.excludedFolders ? stringListOrArrayToArray(config.excludedFolders, ',').map((folder) => folder.trim()) : [] - const allowedFolders = getFoldersMatching(includedFolders,false, excludedFolders) + const excludedFolders = withTemplatesFolderAlwaysExcluded( + config.excludedFolders ? stringListOrArrayToArray(config.excludedFolders, ',').map((folder) => folder.trim()) : [], + ) + const allowedFolders = getFoldersMatching(includedFolders, false, excludedFolders) // Get allowed teamspaces const allowedTeamspaceIDs = resolveAllowedTeamspaceIDs(config) diff --git a/jgclark.Dashboard/src/pluginToHTMLBridge.js b/jgclark.Dashboard/src/pluginToHTMLBridge.js index 3d85a2a47..819e6ecc1 100644 --- a/jgclark.Dashboard/src/pluginToHTMLBridge.js +++ b/jgclark.Dashboard/src/pluginToHTMLBridge.js @@ -30,6 +30,7 @@ import { doShowNoteInEditorFromFilename, doShowNoteInEditorFromTitle, doShowLineInEditorFromFilename, + doAddComment, doChangeParagraphType, doUnscheduleItem, doWindowResized, @@ -378,6 +379,10 @@ export async function bridgeClickDashboardItem(data: MessageDataObject) { result = await doChangeParagraphType(data) break } + case 'addTextNote': { + result = await doAddComment(data) + break + } case 'cyclePriorityStateUp': { result = await doCyclePriorityStateUp(data) break diff --git a/jgclark.Dashboard/src/react/components/CalendarPicker.jsx b/jgclark.Dashboard/src/react/components/CalendarPicker.jsx index f639fa713..3b73e28cd 100644 --- a/jgclark.Dashboard/src/react/components/CalendarPicker.jsx +++ b/jgclark.Dashboard/src/react/components/CalendarPicker.jsx @@ -2,7 +2,7 @@ //---------------------------------------------------------- // Calendar Picker component. // Used in DialogFor*Items components. -// Last updated 2026-05-04 for v2.4.0.b31 by @CursorAI +// Last updated 2026-12-03 by @CursorAI //---------------------------------------------------------- import React, { useState, useEffect } from 'react' import { DayPicker } from 'react-day-picker' @@ -18,9 +18,20 @@ type Props = { positionFunction?: () => void, // Function to call to reposition the dialog because it will be taller when calendar is open resetDateToDefault?: boolean, shouldStartOpen?: boolean, // Default is false, so the calendar is closed when it is first rendered + buttonText?: string, // Text shown before the icon in the trigger button + iconClassName?: string, // Icon classes for the trigger button (callers that space icons themselves can drop the pad-* classes) } -const CalendarPicker = ({ onSelectDate, numberOfMonths = 2, startingSelectedDate, positionFunction, resetDateToDefault, shouldStartOpen = false }: Props): React.Node => { +const CalendarPicker = ({ + onSelectDate, + numberOfMonths = 2, + startingSelectedDate, + positionFunction, + resetDateToDefault, + shouldStartOpen = false, + buttonText = '', + iconClassName = 'fa-regular fa-calendar-plus pad-left pad-right', +}: Props): React.Node => { const [selectedDate, setSelectedDate] = useState (startingSelectedDate) const [isOpen, setIsOpen] = useState(shouldStartOpen) @@ -50,7 +61,8 @@ const CalendarPicker = ({ onSelectDate, numberOfMonths = 2, startingSelectedDate return ( <> {isOpen && (
diff --git a/jgclark.Dashboard/src/react/components/Dialog.jsx b/jgclark.Dashboard/src/react/components/Dialog.jsx index 2bbbe0afd..fca3957fd 100644 --- a/jgclark.Dashboard/src/react/components/Dialog.jsx +++ b/jgclark.Dashboard/src/react/components/Dialog.jsx @@ -1,10 +1,10 @@ // @flow //-------------------------------------------------------------------------- // Dashboard React component to show the Item Control and Project dialogs. -// Last updated 2026-08-21 for v2.4.1 by @jgclark + @CursorAI +// Last updated 2026-12-05 for v2.7.0 by @jgclark & @CursorAI (hide while Add item's Add dialog is open) //-------------------------------------------------------------------------- -import React, { useEffect } from 'react' +import React, { useEffect, useState } from 'react' import { type TClickPosition } from '../../types' import DialogForProjectItems from './DialogForProjectItems.jsx' import DialogForReminderItems from './DialogForReminderItems.jsx' @@ -34,6 +34,12 @@ type Props = { const Dialog = ({ isOpen, onClose, isTask, details }: Props): React.Node => { const { reactSettings, pluginData } = useAppContext() + // True while the task or reminder dialog has handed over to the Add dialog: hidden, but kept mounted so IP carries on after + const [hiddenForAdd, setHiddenForAdd] = useState(false) + useEffect(() => { + if (!isOpen) setHiddenForAdd(false) + }, [isOpen]) + function onDialogClose(xWasClicked: boolean) { onClose(xWasClicked) // do nothing special here; pass it on to Dashboard::handleDialogClose } @@ -103,7 +109,8 @@ const Dialog = ({ isOpen, onClose, isTask, details }: Props): React.Node => { useEffect(() => { function handleKeyDown(event: KeyboardEvent) { - if (event.key === 'Escape') { + // While hidden for the Add dialog, Escape belongs to that dialog + if (event.key === 'Escape' && !hiddenForAdd) { onDialogClose(true) } } @@ -115,18 +122,19 @@ const Dialog = ({ isOpen, onClose, isTask, details }: Props): React.Node => { return () => { document.removeEventListener('keydown', handleKeyDown) } - }, [isOpen]) + }, [isOpen, hiddenForAdd]) const isReminderDialog = details?.item?.itemType === 'reminder' return isOpen ? ( - onDialogClose(true)}> + onDialogClose(true)} hidden={hiddenForAdd}> {isReminderDialog ? ( ) : isTask ? ( { onClose={onDialogClose} details={details} positionDialog={positionDialog} + setHiddenForAdd={setHiddenForAdd} /> ) : ( , notOnMobile: boolean, // If true, the button will only be shown on macOS, because of limitations on iOS/iPadOS + /** Skip-offset buttons sit together in one segment; omitted for Start / Finish. */ + group?: 'skip', } /** Actions that open the project note / editor and should not advance IP. */ @@ -62,7 +65,7 @@ const DialogForProjectItems = ({ details: detailsMessageObject, onClose, positio : enableInteractiveProcessingTransitions !== false const isDesktop = pluginData.platform === 'macOS' - const monthsToShow = (pluginData.platform === 'iOS') ? 1 : 2 + const monthsToShow = 2 // fits on phones too, with the smaller cells set in DashboardDialog.css const thisItem = detailsMessageObject?.item const sectionCode: TSectionCode | '' = thisItem?.sectionCode || detailsMessageObject?.sectionCodes?.[0] || '' @@ -142,6 +145,21 @@ const DialogForProjectItems = ({ details: detailsMessageObject, onClose, positio setReactSettings((prevSettings) => buildReactSettingsForIPBackNavigate(prevSettings)) }, [reactSettings?.interactiveProcessing, setReactSettings]) + /** + * When the embedded calendar opens the dialog grows downward. Keep its top where it is, + * and only lift it if the new bottom would run off the viewport. + * (Calling positionDialog() here re-centred the taller dialog on the original click, so the top jumped up.) + */ + const repositionCalendarForPicker = useCallback(() => { + const dialog = dialogRef.current + if (!dialog) return + const rect = dialog.getBoundingClientRect() + const headerHeight = parseInt(getComputedStyle((document.documentElement: any)).getPropertyValue('--noteplan-header-height') || '0', 10) + const newTop = getTopAfterDialogGrows(rect.top, rect.height, window.visualViewport?.height ?? window.innerHeight, 40 + headerHeight, 12) + logDebug('DialogForProjectItems', `calendar opened: top ${rect.top} -> ${newTop} (height ${rect.height})`) + if (newTop !== rect.top) dialog.style.top = `${newTop}px` + }, []) + // Handle the date selected from CalendarPicker const handleDateSelect = useCallback( (date: Date) => { @@ -238,10 +256,10 @@ const DialogForProjectItems = ({ details: detailsMessageObject, onClose, positio let reviewButtons: Array = [ { label: 'Start', controlStr: 'start', description: 'Open the project note in the Editor', handlingFunction: 'startReview', icons: [{ className: 'fa-solid fa-play', position: 'left' }], notOnMobile: false }, { label: 'Finish Review', controlStr: 'finish', description: 'Update the @review(...) date on the project to today', handlingFunction: 'reviewFinished', icons: [{ className: 'fa-regular fa-calendar-check', position: 'left' }], notOnMobile: false }, - { label: 'Skip 1w', controlStr: 'nr+1w', description: 'Add a @nextReview(...) date for 1 week to the project metadata', handlingFunction: 'setNextReviewDate', icons: [{ className: 'fa-solid fa-forward', position: 'left' }], notOnMobile: false }, - { label: 'Skip 2w', controlStr: 'nr+2w', description: 'Add a @nextReview(...) date for 2 weeks to the project metadata', handlingFunction: 'setNextReviewDate', icons: [{ className: 'fa-solid fa-forward', position: 'left' }], notOnMobile: false }, - { label: 'Skip 1m', controlStr: 'nr+1m', description: 'Add a @nextReview(...) date for 1 month to the project metadata', handlingFunction: 'setNextReviewDate', icons: [{ className: 'fa-solid fa-forward', position: 'left' }], notOnMobile: false }, - { label: 'Skip 1q', controlStr: 'nr+1q', description: 'Add a @nextReview(...) date for 1 quarter to the project metadata', handlingFunction: 'setNextReviewDate', icons: [{ className: 'fa-solid fa-forward', position: 'left' }], notOnMobile: false }, + { label: 'Skip 1w', group: 'skip', controlStr: 'nr+1w', description: 'Add a @nextReview(...) date for 1 week to the project metadata', handlingFunction: 'setNextReviewDate', icons: [{ className: 'fa-solid fa-forward', position: 'left' }], notOnMobile: false }, + { label: '2w', group: 'skip', controlStr: 'nr+2w', description: 'Add a @nextReview(...) date for 2 weeks to the project metadata', handlingFunction: 'setNextReviewDate', notOnMobile: false }, + { label: '1m', group: 'skip', controlStr: 'nr+1m', description: 'Add a @nextReview(...) date for 1 month to the project metadata', handlingFunction: 'setNextReviewDate', notOnMobile: false }, + { label: '1q', group: 'skip', controlStr: 'nr+1q', description: 'Add a @nextReview(...) date for 1 quarter to the project metadata', handlingFunction: 'setNextReviewDate', notOnMobile: false }, ] let projectButtons: Array = [ @@ -263,6 +281,36 @@ const DialogForProjectItems = ({ details: detailsMessageObject, onClose, positio projectButtons = projectButtons.filter((button) => !button.notOnMobile) } + // Skip offsets sit together, like the task dialog's day buttons. Start / Finish stay separate. + const reviewSkipButtons = reviewButtons.filter((button) => button.group === 'skip') + const reviewActionButtons = reviewButtons.filter((button) => button.group !== 'skip') + + const ipPosition = typeof currentIPIndex === 'number' ? currentIPIndex + 1 : 0 + const showIPStatus = Boolean(interactiveProcessing) && ipPosition > 0 + const ipProgressPercent = showIPStatus && totalTasks ? Math.min(100, Math.round((ipPosition / totalTasks) * 1000) / 10) : 0 + + // Render one action button from its config (icons left/right of the label) + const renderActionButton = (button: DialogButtonProps, extraClassName: string = ''): React.Node => ( + + ) + return ( <> {/* CSS for this part is in DashboardDialog.css */} @@ -302,97 +350,74 @@ const DialogForProjectItems = ({ details: detailsMessageObject, onClose, positio
- {interactiveProcessing && currentIPIndex !== undefined && ( + {showIPStatus && ( {showBackNavigate && ( )} - {currentIPIndex + 1}/{totalTasks} + + {ipPosition} of {totalTasks} + )} -
+ {showIPStatus ? ( +
+ +
+ ) : null} {/* Body area ---------------- */} -
-
- {/* line1 ---------------- */} -
Review:
-
- {reviewButtons.map((button, index) => ( - - ))} +
+
+
Review
+
+ {reviewActionButtons.map((button) => renderActionButton(button))} + {reviewSkipButtons.length > 0 ? ( +
+ {reviewSkipButtons.map((button) => renderActionButton(button))} +
+ ) : null} + {/* TODO: Ideally combine this into the "Skip review" group above */} positionDialog(dialogRef)} + positionFunction={repositionCalendarForPicker} numberOfMonths={monthsToShow} resetDateToDefault={resetCalendar} startingSelectedDate={new Date()} - shouldStartOpen={shouldStartCalendarOpen} /> + shouldStartOpen={shouldStartCalendarOpen} + iconClassName="fa-regular fa-calendar-plus" + buttonText="Skip to Date" + />
+
- {/* line2: Project Actions ---------------- */} -
Project:
-
- {projectButtons.map((button, index) => ( - - ))} +
+
Project
+
+ {projectButtons.map((button) => renderActionButton(button, button.controlStr === 'complete' ? 'primaryAction' : ''))}
+
- {/* line3: Progress ---------------- */} -
Progress:
-
- {progressButtons.map((button, index) => ( - - ))} - {lastProgressText && ( - // div required for visual cohesion -
+
+
Progress
+
+ {progressButtons.map((button) => renderActionButton(button))} + {lastProgressText ? ( +
Latest: {lastProgressText}
- )} + ) : null}
diff --git a/jgclark.Dashboard/src/react/components/DialogForReminderItems.jsx b/jgclark.Dashboard/src/react/components/DialogForReminderItems.jsx index 6f9b9ef6b..2bb43970a 100644 --- a/jgclark.Dashboard/src/react/components/DialogForReminderItems.jsx +++ b/jgclark.Dashboard/src/react/components/DialogForReminderItems.jsx @@ -2,7 +2,7 @@ //-------------------------------------------------------------------------- // Dashboard React dialog for Apple Reminder items (Interactive Processing + actions). // Edit title/notes/time, reschedule, complete / convert to today / delete / open in Reminders. -// Last updated 2026-10-02 for v2.5.1 by @CursorAI +// Last updated 2026-12-05 for v2.7.0 by @jgclark & @CursorAI (Add item opens the header Add dialog) //-------------------------------------------------------------------------- import React, { useRef, useLayoutEffect, useState, useCallback } from 'react' @@ -10,9 +10,12 @@ import type { MessageDataObject, TSectionCode, TSectionCodeOrLogical } from '../ import { useAppContext } from './AppContext.jsx' import CalendarPicker from './CalendarPicker.jsx' import { resolveSectionCodesToRefresh } from './dialogRefreshHelpers.js' +import { playDialogEnterAnimation, playDialogExitAnimation } from './dialogTransitions.js' +import { canOpenAddDialog, requestOpenAddDialog } from './Header/openAddDialog' import { buildReactSettingsAfterIPAdvance, buildReactSettingsForIPBackNavigate, canNavigateBackInIP } from './interactiveProcessingHelpers.js' +import { daysFromToday, getDueStatus, getTopAfterDialogGrows } from './taskDialogHelpers.js' import { getAppleRemindersOpenURL } from '@helpers/NPReminders' -import { getDateObjFromDateString, hyphenatedDateString } from '@helpers/dateTime' +import { getDateObjFromDateString, getTodaysDateHyphenated, hyphenatedDateString } from '@helpers/dateTime' import { logDebug, logWarn } from '@helpers/dev' import EditableInput from '@helpers/react/EditableInput.jsx' import { extractModifierKeys } from '@helpers/react/reactMouseKeyboard.js' @@ -24,6 +27,7 @@ type Props = { onClose: (xWasClicked: boolean) => void, details: MessageDataObject, positionDialog: (dialogRef: { current: ?HTMLElement }) => void, + setHiddenForAdd?: (hidden: boolean) => void, // hide this dialog (kept mounted) while Add item's Add dialog is open } type DialogButtonProps = { @@ -37,25 +41,33 @@ type DialogButtonProps = { type EditableInputHandle = { getValue: () => string } +/** The reminder's editable fields, as last saved (or as loaded) */ +type TReminderFields = { title: string, notes: string, time: string } + /** * Reminder actions dialog used by Interactive Processing and by the row edit icon (non-IP). * Does not use validateAndFlattenMessageObject (that helper requires a note filename / para). * @param {Props} props * @returns {?React.Node} */ -const DialogForReminderItems = ({ details: detailsMessageObject, onClose, positionDialog }: Props): React.Node => { +const DialogForReminderItems = ({ details: detailsMessageObject, onClose, positionDialog, setHiddenForAdd }: Props): React.Node => { //---------------------------------------------------------------------- // Refs & state (before any early return - Rules of Hooks) //---------------------------------------------------------------------- const dialogRef: React$RefObject = useRef(null) - const inputRef: React$RefObject = useRef (null) - const notesInputRef: React$RefObject = useRef (null) - const timeInputRef: React$RefObject = useRef (null) + const inputRef: React$RefObject = useRef(null) + const notesInputRef: React$RefObject = useRef(null) + const timeInputRef: React$RefObject = useRef(null) + const prevIPIndexRef: { current: ?number } = useRef(null) + const exitAnimationRef: { current: any } = useRef(null) const [animationClass, setAnimationClass] = useState('') const [resetCalendar, setResetCalendar] = useState(false) - const [contentHasChanged, setContentHasChanged] = useState(false) - const [notesHasChanged, setNotesHasChanged] = useState(false) - const [timeHasChanged, setTimeHasChanged] = useState(false) + const [titleChanged, setTitleChanged] = useState(false) + const [notesChanged, setNotesChanged] = useState(false) + const [timeChanged, setTimeChanged] = useState(false) + const [editorKey, setEditorKey] = useState(0) // bumped to remount the inputs (Revert) + // What Update last saved, so the dialog shows and compares against it (the item in dialogData still has the old values) + const [savedFields, setSavedFields] = useState(null) const { sendActionToPlugin, reactSettings, setReactSettings, dashboardSettings, pluginData } = useAppContext() const { interactiveProcessing } = reactSettings ?? {} @@ -65,13 +77,23 @@ const DialogForReminderItems = ({ details: detailsMessageObject, onClose, positi const item = detailsMessageObject?.item const reminder = item?.reminder + const reminderId = reminder?.id ?? '' // Prefer TSectionCode | '' (not | string) so unshift into Array type-checks after the truthiness guard. const sectionCode: TSectionCode | '' = item?.sectionCode || detailsMessageObject.sectionCodes?.[0] || '' const canOpenInReminders = Boolean(pluginData?.appleAppCallbacksAvailable && reminder?.id) - const monthsToShow = pluginData.platform === 'iOS' ? 1 : 2 + const isDesktop = pluginData?.platform === 'macOS' + const isTouchDevice = pluginData?.platform === 'iOS' || pluginData?.platform === 'iPadOS' + const monthsToShow = 2 // fits on phones too, with the smaller cells set in DashboardDialog.css const shouldStartCalendarOpen = Boolean(detailsMessageObject.modifierKey) const startingSelectedDate = reminder?.date ? getDateObjFromDateString(reminder.date) : new Date() + const baseline: TReminderFields = savedFields ?? { title: reminder?.title || '', notes: reminder?.notes || '', time: reminder?.time || '' } + const hasChanges = titleChanged || notesChanged || timeChanged + + //---------------------------------------------------------------------- + // Effects + //---------------------------------------------------------------------- + useLayoutEffect(() => { positionDialog(dialogRef) }, [positionDialog]) @@ -87,38 +109,74 @@ const DialogForReminderItems = ({ details: detailsMessageObject, onClose, positi } }, [showAnimations]) - const getCurrentTitle = useCallback((): string => reminder?.title || '', [reminder?.title]) + // A different reminder (the next IP item): forget the last one's saved values and edits + useLayoutEffect(() => { + setSavedFields(null) + setTitleChanged(false) + setNotesChanged(false) + setTimeChanged(false) + }, [reminderId]) + + // Moving to another IP item keeps this dialog mounted, so the zoom above only plays on first open. + // Slide the new item in, as the task dialog does (from the right going forward, from the left going back). + useLayoutEffect(() => { + const prevIndex = prevIPIndexRef.current + prevIPIndexRef.current = typeof currentIPIndex === 'number' ? currentIPIndex : null + const dialog = dialogRef.current + if (!dialog) return + if (exitAnimationRef.current) { + exitAnimationRef.current.cancel() + exitAnimationRef.current = null + } + if (!showAnimations || typeof prevIndex !== 'number' || typeof currentIPIndex !== 'number' || prevIndex === currentIPIndex) return + playDialogEnterAnimation(dialog, currentIPIndex > prevIndex) + }, [currentIPIndex]) - const getCurrentNotes = useCallback((): string => reminder?.notes || '', [reminder?.notes]) + //---------------------------------------------------------------------- + // Edits + //---------------------------------------------------------------------- - const getCurrentTime = useCallback((): string => reminder?.time || '', [reminder?.time]) + const getEditedFields = (): TReminderFields => ({ + title: inputRef?.current?.getValue() || baseline.title, + notes: notesInputRef?.current?.getValue() ?? baseline.notes, + time: timeInputRef?.current?.value ?? baseline.time, + }) - const getEditedTitle = useCallback((): string => inputRef?.current?.getValue() || getCurrentTitle(), [getCurrentTitle]) + /** The reminder as the plugin should see it: with anything Update already saved */ + const getItemForAction = () => ({ + ...item, + sectionCode: item?.sectionCode || sectionCode, + reminder: savedFields && reminder ? { ...reminder, title: savedFields.title, notes: savedFields.notes, time: savedFields.time || undefined } : reminder, + }) - const getEditedNotes = useCallback((): string => notesInputRef?.current?.getValue() ?? getCurrentNotes(), [getCurrentNotes]) + /** + * Unsaved edits to send along with an action (only the fields that changed). + * Omit updatedContent when the title is unchanged. An empty string is applied as the new title + * and fails with "Reminder text cannot be empty" (notes-only and time-only Updates). + */ + const getPendingEdits = (): {| updatedContent?: string, updatedNotes?: string, updatedTime?: string |} => { + const edited = getEditedFields() + const payload: {| updatedContent?: string, updatedNotes?: string, updatedTime?: string |} = {} + if (edited.title !== baseline.title) payload.updatedContent = edited.title + if (edited.notes !== baseline.notes) payload.updatedNotes = edited.notes + if (edited.time !== baseline.time) payload.updatedTime = edited.time + return payload + } - const getEditedTime = useCallback((): string => timeInputRef?.current?.value ?? getCurrentTime(), [getCurrentTime]) + const clearChangeFlags = () => { + setTitleChanged(false) + setNotesChanged(false) + setTimeChanged(false) + } - const buildUpdatedPayload = useCallback((): {| updatedContent: string, updatedNotes ?: string, updatedTime ?: string |} => { - const editedTitle = getEditedTitle() - const editedNotes = getEditedNotes() - const editedTime = getEditedTime() - const payload: {| updatedContent: string, updatedNotes?: string, updatedTime?: string |} = { updatedContent: editedTitle } -if (notesHasChanged || editedNotes !== getCurrentNotes()) { - payload.updatedNotes = editedNotes -} -if (timeHasChanged || editedTime !== getCurrentTime()) { - payload.updatedTime = editedTime -} -return payload - }, [getCurrentNotes, getCurrentTime, getEditedNotes, getEditedTime, getEditedTitle, notesHasChanged, timeHasChanged]) + //---------------------------------------------------------------------- + // IP navigation & closing + //---------------------------------------------------------------------- const handleIPItemProcessed = useCallback( (skippedItem?: boolean = false, skipForward?: boolean = true) => { logDebug('DialogForReminderItems', `handleIPItemProcessed skipped=${String(skippedItem)} skipForward=${String(skipForward)}`) - setContentHasChanged(false) - setNotesHasChanged(false) - setTimeHasChanged(false) + clearChangeFlags() setReactSettings((prevSettings) => buildReactSettingsAfterIPAdvance(prevSettings, { skippedItem, @@ -152,169 +210,206 @@ return payload if (showAnimations) { setAnimationClass('zoom-out') } - setTimeout(() => { - setReactSettings((prevSettings) => ({ - ...prevSettings, - dialogData: { - ...prevSettings.dialogData, - isOpen: false, - isTask: true, - }, - })) - onClose(forceClose) - }, showAnimations ? 300 : 0) + setTimeout( + () => { + setReactSettings((prevSettings) => ({ + ...prevSettings, + dialogData: { + ...prevSettings.dialogData, + isOpen: false, + isTask: true, + }, + })) + onClose(forceClose) + }, + showAnimations ? 300 : 0, + ) }, [handleIPItemProcessed, onClose, reactSettings?.interactiveProcessing, setReactSettings, showAnimations], ) - const handleSkipClick = useCallback( - (skipForward: boolean) => { - if (!reactSettings?.interactiveProcessing) return - handleIPItemProcessed(true, skipForward) - }, - [handleIPItemProcessed, reactSettings?.interactiveProcessing], - ) + const handleSkipClick = (skipForward: boolean) => { + if (!reactSettings?.interactiveProcessing) return + handleIPItemProcessed(true, skipForward) + } - const handleBackNavigateClick = useCallback(() => { + const handleBackNavigateClick = () => { if (!reactSettings?.interactiveProcessing) return logDebug('DialogForReminderItems', 'handleBackNavigateClick') setReactSettings((prevSettings) => buildReactSettingsForIPBackNavigate(prevSettings)) - }, [reactSettings?.interactiveProcessing, setReactSettings]) + } -const handleTimeChange = useCallback(() => { - setTimeHasChanged(true) -}, []) + //---------------------------------------------------------------------- + // Actions + //---------------------------------------------------------------------- - const handleButtonClick = useCallback( - (event: MouseEvent, controlStr: string, handlingFunction: string, sectionCodesToRefresh: Array = []) => { - const { metaKey } = extractModifierKeys(event) - logDebug('DialogForReminderItems/handleButtonClick', `controlStr=${controlStr} handlingFunction=${handlingFunction}`) + const handleButtonClick = (event: MouseEvent, controlStr: string, handlingFunction: string, sectionCodesToRefresh: Array = []) => { + const { metaKey } = extractModifierKeys(event) + logDebug('DialogForReminderItems/handleButtonClick', `controlStr=${controlStr} handlingFunction=${handlingFunction}`) - if (!item || !reminder) { - logWarn('DialogForReminderItems', 'Button click with no reminder item') - return - } + if (!item || !reminder) { + logWarn('DialogForReminderItems', 'Button click with no reminder item') + return + } - const currentTitle = getCurrentTitle() - const editedTitle = getEditedTitle() - const editedNotes = getEditedNotes() - const editedTime = getEditedTime() - const titleActuallyChanged = editedTitle !== currentTitle - const notesActuallyChanged = editedNotes !== getCurrentNotes() - const timeActuallyChanged = editedTime !== getCurrentTime() - const hasPendingEdits = - titleActuallyChanged || notesActuallyChanged || timeActuallyChanged || contentHasChanged || notesHasChanged || timeHasChanged - - // Resolve ITEM_ORIG_SECTION -> sectionCode; no longer auto-prepend source section - const sectionCodesToSend = resolveSectionCodesToRefresh(sectionCodesToRefresh, sectionCode) - - const itemForAction = { - ...item, - sectionCode: item.sectionCode || sectionCode, - } + // Resolve ITEM_ORIG_SECTION -> sectionCode; no longer auto-prepend source section + const sectionCodesToSend = resolveSectionCodesToRefresh(sectionCodesToRefresh, sectionCode) + const itemForAction = getItemForAction() - if (handlingFunction === 'openURL') { - if (!reminder.id) { - logWarn('DialogForReminderItems', 'openURL requested but reminder.id missing') - return - } - const url = getAppleRemindersOpenURL(reminder.id) - sendActionToPlugin( - 'openURL', - { ...detailsMessageObject, actionType: 'openURL', controlStr, url, item: itemForAction }, - 'Dialog open reminder in Reminders app', - true, - ) + if (handlingFunction === 'openURL') { + if (!reminder.id) { + logWarn('DialogForReminderItems', 'openURL requested but reminder.id missing') return } + const url = getAppleRemindersOpenURL(reminder.id) + sendActionToPlugin('openURL', { ...detailsMessageObject, actionType: 'openURL', controlStr, url, item: itemForAction }, 'Dialog open reminder in Reminders app', true) + return + } + + const pendingEdits = getPendingEdits() + const hasPendingEdits = pendingEdits.updatedContent !== undefined || pendingEdits.updatedNotes !== undefined || pendingEdits.updatedTime !== undefined + if (handlingFunction === 'updateReminderContent' && !hasPendingEdits) { + logDebug('DialogForReminderItems/handleButtonClick', `skipping no-op updateReminderContent`) + clearChangeFlags() + return + } - const editPayload = hasPendingEdits ? buildUpdatedPayload() : { updatedContent: '' } - const dataToSend = { + sendActionToPlugin( + handlingFunction, + { ...detailsMessageObject, actionType: handlingFunction, controlStr, item: itemForAction, sectionCodes: sectionCodesToSend, - ...editPayload, - } - - if (handlingFunction === 'updateReminderContent') { - if (!titleActuallyChanged && !notesActuallyChanged && !timeActuallyChanged && !contentHasChanged && !notesHasChanged && !timeHasChanged) { - logDebug('DialogForReminderItems/handleButtonClick', `skipping no-op updateReminderContent`) - setContentHasChanged(false) - setNotesHasChanged(false) - setTimeHasChanged(false) - return - } - } - - sendActionToPlugin(handlingFunction, dataToSend, `Dialog requesting ${handlingFunction}`, true) - setContentHasChanged(false) - setNotesHasChanged(false) - setTimeHasChanged(false) - - if (controlStr === 'openreminder') { - return - } - - if (!reactSettings?.interactiveProcessing) { - setAnimationClass('zoom-out') - } - if (!metaKey) { - setTimeout(() => { - closeDialog(false) - }, 300) - } else { + ...pendingEdits, + }, + `Dialog requesting ${handlingFunction}`, + true, + ) + clearChangeFlags() + + if (!reactSettings?.interactiveProcessing) { + setAnimationClass('zoom-out') + } + if (!metaKey) { + setTimeout(() => { closeDialog(false) - } - }, - [ - buildUpdatedPayload, - closeDialog, - contentHasChanged, - detailsMessageObject, - getCurrentNotes, - getCurrentTime, - getCurrentTitle, - getEditedNotes, - getEditedTime, - getEditedTitle, - item, - notesHasChanged, - reactSettings?.interactiveProcessing, - reminder, - sectionCode, - sendActionToPlugin, - timeHasChanged, - ], - ) + }, 300) + } else { + closeDialog(false) + } + } -const handleEnterPress = useCallback(() => { - handleButtonClick(({}: any), 'updateReminderContent', 'updateReminderContent', ['ITEM_ORIG_SECTION']) - }, [handleButtonClick]) + /** Update: save the text, notes and time, and keep the dialog open to do something else with the reminder */ + const handleSaveAndStay = () => { + if (!item || !reminder) return + const pendingEdits = getPendingEdits() + const edited = getEditedFields() + sendActionToPlugin( + 'updateReminderContent', + { + ...detailsMessageObject, + actionType: 'updateReminderContent', + controlStr: 'updateReminderContent', + item: getItemForAction(), + sectionCodes: resolveSectionCodesToRefresh(['ITEM_ORIG_SECTION'], sectionCode), + ...pendingEdits, + }, + 'Dialog saving reminder edits (staying open)', + true, + ) + setSavedFields(edited) + clearChangeFlags() + // Dismiss the on-screen keyboard, so the rest of the dialog is visible again + const active: any = document.activeElement + if (isTouchDevice && active?.blur) active.blur() + } -const handleContentChange = useCallback((_updatedContent: string) => { - setContentHasChanged(true) -}, []) + /** Return: save and close (or go on to the next item in Interactive Processing) */ + const handleEnterPress = () => { + handleButtonClick(({}: any), 'updateReminderContent', 'updateReminderContent', ['ITEM_ORIG_SECTION']) + } -const handleNotesChange = useCallback((_updatedNotes: string) => { - setNotesHasChanged(true) -}, []) + const handleRevert = () => { + clearChangeFlags() + setEditorKey((k) => k + 1) + } -const handleDateSelect = useCallback( - (date: Date) => { + const handleDateSelect = (date: Date) => { if (!date) return const isoDateStr = hyphenatedDateString(date) handleButtonClick(({}: any), isoDateStr, 'rescheduleReminder', ['ITEM_ORIG_SECTION']) -setResetCalendar(true) -setTimeout(() => setResetCalendar(false), 0) - }, -[handleButtonClick], - ) + setResetCalendar(true) + setTimeout(() => setResetCalendar(false), 0) + } + + /** + * Add item: show the header's Add dialog (task, checklist, or reminder) in place of this one, + * then bring this dialog back on the same reminder when it is submitted or cancelled. + */ + const openAddDialogForAddItem = () => { + if (!setHiddenForAdd || !canOpenAddDialog()) { + logWarn('DialogForReminderItems', 'Add item clicked but the Add dialog is not available') + return + } + const active: any = document.activeElement + if (isTouchDevice && active?.blur) active.blur() + const dialog = dialogRef.current + const rect = dialog?.getBoundingClientRect() + + // Bring this dialog back where it was, sliding in from the left (the way it went out) + const comeBack = (added: boolean) => { + logDebug('DialogForReminderItems', `Add dialog closed (added=${String(added)}); showing this dialog again`) + setHiddenForAdd(false) + requestAnimationFrame(() => { + if (exitAnimationRef.current) { + exitAnimationRef.current.cancel() + exitAnimationRef.current = null + } + const shown = dialogRef.current + if (shown) playDialogEnterAnimation(shown, false) + }) + } + + let handedOver = false + const handOver = () => { + if (handedOver) return + handedOver = true + const opened = requestOpenAddDialog({ + itemKind: 'reminder', + // Same top and left edge as this dialog, so it reads as one dialog changing + anchor: rect ? { top: rect.top, left: rect.left } : undefined, + onDone: comeBack, + }) + if (opened) { + setHiddenForAdd(true) + } else if (exitAnimationRef.current) { + exitAnimationRef.current.cancel() + exitAnimationRef.current = null + } + } + + // Slide this dialog out to the left, then the Add dialog slides in from the right in its place + const exit = dialog ? playDialogExitAnimation(dialog) : null + if (exit) { + exitAnimationRef.current = exit + exit.onfinish = handOver + setTimeout(handOver, 400) // in case onfinish never fires + } else { + handOver() + } + } -const repositionCalendarForPicker = useCallback((): void => { - positionDialog(dialogRef) -}, [positionDialog]) + /** When the calendar opens the dialog grows downward: keep its top where it is unless it would run off the bottom */ + const repositionCalendarForPicker = (): void => { + const dialog = dialogRef.current + if (!dialog) return + const rect = dialog.getBoundingClientRect() + const headerHeight = parseInt(getComputedStyle((document.documentElement: any)).getPropertyValue('--noteplan-header-height') || '0', 10) + const newTop = getTopAfterDialogGrows(rect.top, rect.height, window.visualViewport?.height ?? window.innerHeight, 40 + headerHeight, 12) + if (newTop !== rect.top) dialog.style.top = `${newTop}px` + } //---------------------------------------------------------------------- // Validate after hooks @@ -325,166 +420,221 @@ const repositionCalendarForPicker = useCallback((): void => { return null } -// Day-scale reschedule only (week/month/quarter shortcuts omitted for reminders) -// ITEM_ORIG_SECTION resolves at click time to the open item's sectionCode (source section to refresh). -const moveButtons: Array = [ - { label: 'today', controlStr: 't', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'DT', 'TB'], handlingFunction: 'rescheduleReminder', description: 'Re-schedule to today' }, - { label: '+1d', controlStr: '+1d', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'DO'], handlingFunction: 'rescheduleReminder', description: 'Re-schedule to tomorrow' }, - { label: '+1b', controlStr: '+1b', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'DO'], handlingFunction: 'rescheduleReminder', description: 'Re-schedule to next business day' }, - { label: '+2d', controlStr: '+2d', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], handlingFunction: 'rescheduleReminder', description: 'Re-schedule to 2 days later' }, - { label: '+3d', controlStr: '+3d', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], handlingFunction: 'rescheduleReminder', description: 'Re-schedule to 3 days later' }, - { label: 'Unsched', controlStr: 'unsched', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'REM'], handlingFunction: 'rescheduleReminder', description: 'Remove due date from this reminder' }, -] - -if (sectionCode === 'DT') { - moveButtons.splice(0, 1) // remove 'today' when already in Today -} - -const actionButtons: Array = [ - { - label: '', - controlStr: 'completereminder', - description: 'Complete reminder', - handlingFunction: 'completeReminder', - icons: [{ className: 'fa-regular fa-circle-check', position: 'left' }], - sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], - }, - { - label: 'Convert to', - controlStr: 'converttotoday', - description: "Convert to task in today's note (and delete reminder)", - handlingFunction: 'convertReminderToTask', - icons: [{ className: 'fa-regular fa-circle', position: 'right' }], - sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'DT', 'TB'], - }, -] - -if (canOpenInReminders) { - actionButtons.push({ - label: 'Open', - controlStr: 'openreminder', - description: 'Open in Apple Reminders', - handlingFunction: 'openURL', - icons: [{ className: 'fa-regular fa-arrow-up-right-from-square', position: 'right' }], - sectionCodesToRefresh: [], - }) -} + // Day-scale reschedule only (week/month/quarter shortcuts omitted for reminders) + // ITEM_ORIG_SECTION resolves at click time to the open item's sectionCode (source section to refresh). + const dayButtons: Array = [ + { label: 'today', controlStr: 't', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'DT', 'TB'], handlingFunction: 'rescheduleReminder', description: 'Re-schedule to today' }, + { label: '+1d', controlStr: '+1d', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'DO'], handlingFunction: 'rescheduleReminder', description: 'Re-schedule to tomorrow' }, + { label: '+1b', controlStr: '+1b', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'DO'], handlingFunction: 'rescheduleReminder', description: 'Re-schedule to next business day' }, + { label: '+2d', controlStr: '+2d', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], handlingFunction: 'rescheduleReminder', description: 'Re-schedule to 2 days later' }, + { label: '+3d', controlStr: '+3d', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], handlingFunction: 'rescheduleReminder', description: 'Re-schedule to 3 days later' }, + ] + if (sectionCode === 'DT') { + dayButtons.splice(0, 1) // remove 'today' when already in Today + } + // Outcomes finish with the reminder; edits change it but keep it + const outcomeButtons: Array = [ + { + label: 'Complete', + controlStr: 'completereminder', + description: 'Complete reminder', + handlingFunction: 'completeReminder', + icons: [{ className: 'fa-regular fa-circle-check', position: 'left' }], + sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], + }, + { + label: 'To task', + controlStr: 'converttotoday', + description: "Convert to a task in today's note (and delete the reminder)", + handlingFunction: 'convertReminderToTask', + icons: [{ className: 'fa-regular fa-circle', position: 'left' }], + sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'DT', 'TB'], + }, + { + label: 'Delete', + controlStr: 'deletereminder', + description: 'Delete reminder', + handlingFunction: 'deleteReminder', + icons: [{ className: 'fa-regular fa-trash-can', position: 'left' }], + sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], + }, + ] + const editButtons: Array = [] + if (canOpenInReminders) { + editButtons.push({ + label: 'Open in Reminders', + controlStr: 'openreminder', + description: 'Open in Apple Reminders', + handlingFunction: 'openURL', + icons: [{ className: 'fa-regular fa-arrow-up-right-from-square', position: 'left' }], + sectionCodesToRefresh: [], + }) + } -actionButtons.push( - { - label: '', - controlStr: 'deletereminder', - description: 'Delete reminder', - handlingFunction: 'deleteReminder', - icons: [{ className: 'fa-regular fa-trash-can', position: 'left' }], - sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], - }, -) + // Footer status: when it's due, or how overdue + const todayISO = getTodaysDateHyphenated() + const daysToDue = reminder.date ? daysFromToday(reminder.date, todayISO) : null + const dueStatus = daysToDue != null ? getDueStatus(null, '', null, todayISO, undefined, daysToDue) : { text: 'No due date', isUrgent: false } const showBackNavigate = canNavigateBackInIP(currentIPIndex) - - const titleParts: Array = [] - if (reminder.listname) titleParts.push(reminder.listname) - if (reminder.date) titleParts.push(reminder.date) - if (reminder.time) titleParts.push(reminder.time) - const fromLabel = titleParts.length > 0 ? titleParts.join(' · ') : 'Apple Reminders' + const ipPosition = typeof currentIPIndex === 'number' ? currentIPIndex + 1 : 0 // 1-based position of this item in IP + const showIPStatus = Boolean(interactiveProcessing) && ipPosition > 0 + const ipProgressPercent = showIPStatus && totalTasks ? Math.min(100, Math.round((ipPosition / totalTasks) * 1000) / 10) : 0 logDebug('DialogForReminderItems', `Rendering reminder "${reminder.title || ''}" section=${String(sectionCode)}`) + // Render one action button from its config (icons left/right of the label) + const renderActionButton = (button: DialogButtonProps, extraClassName: string = ''): React.Node => ( + + ) + + const inputsKey = `${reminderId}-${editorKey}` + return ( - + // CSS: shares the task dialog's .taskControlDialog styles; reminder-only bits are under .reminderControlDialog in DashboardDialog.css +
List:
- - {fromLabel} + + {reminder.listname || 'Apple Reminders'}
- {interactiveProcessing && currentIPIndex !== undefined && ( + {showIPStatus && ( {showBackNavigate && ( )} - {currentIPIndex + 1}/{totalTasks} + + {ipPosition} of {totalTasks} + )} -
+ {showIPStatus ? ( +
+ +
+ ) : null} -
-
-
Reminder:
-
+
+ {/* Title, notes and time in one editor box, with status + Update in its footer ---------------- */} +
+
{/* $FlowFixMe[incompatible-type] */} setTitleChanged(value !== baseline.title)} + // Not on iOS, where focusing brings up the keyboard and hides most of the dialog + autofocusMe={!isTouchDevice} />
- -
Notes:
-
+
{/* $FlowFixMe[incompatible-type] */} setNotesChanged(value !== baseline.notes)} autofocusMe={false} /> -
+
+ + {dueStatus?.text ?? ''} + {/* Revert / Update (and the Return hint) only appear once something has been changed */} + {hasChanges ? ( + <> + + {isDesktop ? ( + <> + ↩ save & {interactiveProcessing ? 'next' : 'close'} + + ) : null} + + + + + ) : ( + + )} +
+
-
Schedule:
-
- { - if (e.key === 'Enter') { - handleEnterPress() - } - }} - /> - {moveButtons.map((button, index) => ( - - ))} + {/* Reschedule ---------------- */} +
+
Schedule
+
+
+ {dayButtons.map((button) => ( + + ))} +
+ {reminder.date ? + + : null}
+
-
Actions:
-
- {actionButtons.map((button, index) => ( - - ))} + {/* Actions: outcomes, then edits ---------------- */} +
+
Actions
+
+
+ {outcomeButtons.map((button) => renderActionButton(button, button.controlStr === 'completereminder' ? 'primaryAction' : ''))} +
+ {editButtons.length > 0 ?
{editButtons.map((button) => renderActionButton(button))}
: null} +
+
+ + {/* Add: the header's Add dialog, on its own row ---------------- */} +
+
Add
+
+
diff --git a/jgclark.Dashboard/src/react/components/DialogForTaskItems.jsx b/jgclark.Dashboard/src/react/components/DialogForTaskItems.jsx index 0c637f818..c56a7f57d 100644 --- a/jgclark.Dashboard/src/react/components/DialogForTaskItems.jsx +++ b/jgclark.Dashboard/src/react/components/DialogForTaskItems.jsx @@ -2,21 +2,27 @@ //-------------------------------------------------------------------------- // Dashboard React component to show the Dialog for tasks // Called by TaskItem component -// Last updated 2026-10-10 for v2.5.2 by @CursorAI +// Last updated 2026-12-06 for v2.7.0 by @jgclark & @CursorAI (Add text note sends the typed text) //-------------------------------------------------------------------------- // Notes: // - onClose & detailsMessageObject are passed down from Dashboard.jsx::handleDialogClose // import React, { useEffect, useRef, useLayoutEffect, useState } from 'react' import { validateAndFlattenMessageObject } from '../../shared' +import { applyDashboardSettingsToDisplayedItemHtml, makeParaContentToLookLikeNPDisplayInReact } from '../dashboardLineToNPDisplayHTML.js' import type { MessageDataObject, TSectionCode, TSectionCodeOrLogical } from '../../types' import { useAppContext } from './AppContext.jsx' import CalendarPicker from './CalendarPicker.jsx' +import DialogMenuButton from './DialogMenuButton.jsx' import { resolveSectionCodesToRefresh } from './dialogRefreshHelpers.js' import ItemNoteLink from './ItemNoteLink.jsx' -import { buildReactSettingsAfterIPAdvance, ipItemsHaveBeenSkipped } from './interactiveProcessingHelpers.js' +import { buildReactSettingsAfterIPAdvance, ipItemsHaveBeenSkipped, withUpdatedItemContent } from './interactiveProcessingHelpers.js' +import { findLatestLineContent, getCompleteThenLabel, getDueStatus, getTopAfterDialogGrows, isSkipSwipe, mapRenderedOffsetToRaw } from './taskDialogHelpers.js' +import { canOpenAddDialog, requestOpenAddDialog } from './Header/openAddDialog' +import { playDialogEnterAnimation as playIPEnterAnimation, playDialogExitAnimation as playIPExitAnimation } from './dialogTransitions.js' import TooltipOnKeyPress from './ToolTipOnModifierPress.jsx' -import { hyphenatedDateString } from '@helpers/dateTime' +import { getTodaysDateHyphenated, hyphenatedDateString } from '@helpers/dateTime' +import { daysBeforeDueDate } from '@helpers/dueStartDates' import { clo, clof, JSP, logDebug, logInfo, logWarn } from '@helpers/dev' import EditableInput from '@helpers/react/EditableInput.jsx' import { extractModifierKeys } from '@helpers/react/reactMouseKeyboard.js' @@ -28,6 +34,7 @@ type Props = { onClose: (xWasClicked: boolean) => void, details: MessageDataObject, positionDialog: (dialogRef: { current: ?HTMLElement }) => void, // matches the React$RefObject declared below + setHiddenForAdd?: (hidden: boolean) => void, // hide this dialog (kept mounted) while Add item's Add dialog is open } type DialogButtonProps = { @@ -37,6 +44,8 @@ type DialogButtonProps = { description?: string, icons?: Array<{ className: string, position: 'left' | 'right' }>, sectionCodesToRefresh?: Array, + /** Reschedule buttons: 'day' ones are always shown; 'later' (week/month/quarter) ones go in the 'Later' menu */ + group?: 'day' | 'later', } type EditableInputHandle = { getValue: () => string } @@ -52,7 +61,75 @@ const PARAGRAPH_TYPE_CHOICES: Array = [ { value: 'text', label: 'Text' }, ] -const DialogForTaskItems = ({ details: detailsMessageObject, onClose, positionDialog }: Props): React.Node => { +// Once we've seen the visual viewport shrink for an on-screen keyboard, we can trust it to tell us when the keyboard is up. +// Until then (or on devices where it never changes, e.g. iPad with a hardware keyboard) we fall back to editor focus alone. +let viewportReportsKeyboard = false +const KEYBOARD_MIN_HEIGHT_PX = 150 + +/** + * Is the on-screen keyboard (probably) showing? Compares the visual viewport height with the tallest seen at this width. + * @param {boolean} enabled - only listen on touch devices + * @returns {boolean} + */ +function useOnScreenKeyboardVisible(enabled: boolean): boolean { + const [visible, setVisible] = useState(false) + useEffect(() => { + if (!enabled) return undefined + const vv = window.visualViewport + let lastWidth = window.innerWidth + let tallest = Math.max(window.innerHeight, vv?.height ?? 0) + const update = () => { + const height = vv ? vv.height : window.innerHeight + if (window.innerWidth !== lastWidth) { + // rotation: start again with the new orientation's height + lastWidth = window.innerWidth + tallest = height + } + tallest = Math.max(tallest, height) + const keyboardUp = tallest - height > KEYBOARD_MIN_HEIGHT_PX + if (keyboardUp) viewportReportsKeyboard = true + setVisible(keyboardUp) + } + update() + vv?.addEventListener('resize', update) + window.addEventListener('resize', update) + return () => { + vv?.removeEventListener('resize', update) + window.removeEventListener('resize', update) + } + }, [enabled]) + return visible +} + +/** + * Character offset within container's text of the point clicked, or null if the browser can't say. + * (caretRangeFromPoint is WebKit's, which NotePlan uses; caretPositionFromPoint is the standard one.) + */ +function getTextOffsetAtPoint(container: HTMLElement, x: number, y: number): ?number { + const doc: any = document + let node: ?Node = null + let offset = 0 + if (typeof doc.caretRangeFromPoint === 'function') { + const range = doc.caretRangeFromPoint(x, y) + if (range) { + node = range.startContainer + offset = range.startOffset + } + } else if (typeof doc.caretPositionFromPoint === 'function') { + const position = doc.caretPositionFromPoint(x, y) + if (position) { + node = position.offsetNode + offset = position.offset + } + } + if (!node || !container.contains(node)) return null + const before: any = (document: any).createRange() // flow-typed's Range here lacks setStart/setEnd + before.setStart(container, 0) + before.setEnd(node, offset) + return before.toString().length +} + +const DialogForTaskItems = ({ details: detailsMessageObject, onClose, positionDialog, setHiddenForAdd }: Props): React.Node => { //---------------------------------------------------------------------- // Refs //---------------------------------------------------------------------- @@ -63,7 +140,15 @@ const DialogForTaskItems = ({ details: detailsMessageObject, onClose, positionDi // Note: typed as ?HTMLElement (not ?HTMLDivElement) because flowlib types 's ref instance as HTMLElement, // and React$RefObject is invariant in its type argument. const dialogRef: React$RefObject = useRef (null) - const changeTypeMenuRef: React$RefObject = useRef (null) + // Pending 'stop editing' timer: collapse is delayed after blur so a tap on a quick-strip button lands before the layout changes + const editBlurTimerRef: { current: ?TimeoutID } = useRef(null) + // Where an IP swipe started (null when the touch began somewhere that should not swipe, e.g. the editor) + const swipeStartRef: { current: ?{ x: number, y: number, t: number } } = useRef(null) + // IP item transitions: the index we last showed, and a swipe's exit animation still holding the dialog off-screen + const prevIPIndexRef: { current: ?number } = useRef(null) + const exitAnimationRef: { current: any } = useRef(null) + // Where to put the caret (offset in the raw text) once the editor replaces the formatted text + const pendingCaretRef: { current: ?number } = useRef(null) //---------------------------------------------------------------------- // State @@ -72,18 +157,75 @@ const DialogForTaskItems = ({ details: detailsMessageObject, onClose, positionDi const [animationClass, setAnimationClass] = useState('') const [resetCalendar, setResetCalendar] = useState(false) // used to reset the calendar during IP processing if the date picker is open const [contentHasChanged, setContentHasChanged] = useState(false) // used to track if the content has changed - const [typeMenuOpen, setTypeMenuOpen] = useState(false) + const [editorFocused, setEditorFocused] = useState(false) + const [editorKey, setEditorKey] = useState(0) // bumped to remount the editor (Revert) + const { sendActionToPlugin, reactSettings, setReactSettings, dashboardSettings, pluginData } = useAppContext() + + // The item text shows formatted (as on Dashboard rows) until you choose to edit it, which swaps in the raw text editor + const [showRawText, setShowRawText] = useState(false) + // Text just sent with Update, shown until this item's data catches up (or we move to another item) + const [savedContent, setSavedContent] = useState(null) + // Add text note: prompt for text, then insert it as an indented child paragraph + const [textNotePromptOpen, setTextNotePromptOpen] = useState(false) + const [textNoteDraft, setTextNoteDraft] = useState('') + + // Each new item (e.g. the next one in Interactive Processing) starts formatted again + const itemIDForReset = detailsMessageObject?.item?.ID + + // Actions that leave the dialog open (e.g. priority up/down) change the line in the note, and the plugin sends the + // Dashboard the line's new text. Pick that up, as the plugin finds the line by its text when the next button is pressed. + const latestLineContent = findLatestLineContent(pluginData?.sections, detailsMessageObject?.item?.para) + const prevLatestLineContentRef: { current: ?string } = useRef(latestLineContent) + useEffect(() => { + const previous = prevLatestLineContentRef.current + prevLatestLineContentRef.current = latestLineContent + // Only act when the Dashboard's copy of the line changes (not when we move to another item) + if (latestLineContent == null || previous == null || latestLineContent === previous) return + if (!itemIDForReset || latestLineContent === detailsMessageObject?.item?.para?.content) return + logDebug('DialogForTaskItems', `line changed in the Dashboard data; dialog now uses {${latestLineContent}}`) + setSavedContent(null) + setReactSettings((prev) => withUpdatedItemContent(prev, itemIDForReset, latestLineContent)) + }, [latestLineContent]) + useEffect(() => { + setShowRawText(false) + setSavedContent(null) + setTextNotePromptOpen(false) + setTextNoteDraft('') + }, [itemIDForReset]) + + // Editor just swapped in for the formatted text: focus it with the caret where the user clicked. + // (Runs after EditableInput's own effects, so its text is already there.) + useEffect(() => { + const caret = pendingCaretRef.current + pendingCaretRef.current = null + if (!showRawText || caret == null) return + const editor = dialogRef.current?.querySelector('.taskEditorText .dialogItemContent') + if (!(editor instanceof HTMLElement)) return + editor.focus() + const textNode = editor.firstChild + const selection = window.getSelection() + if (!(textNode instanceof Text) || !selection) return + const range: any = (document: any).createRange() + range.setStart(textNode, Math.min(caret, (textNode.textContent ?? '').length)) + range.collapse(true) + selection.removeAllRanges() + selection.addRange(range) + }, [showRawText]) //---------------------------------------------------------------------- // Context (before validate / early return - Rules of Hooks) //---------------------------------------------------------------------- - const { sendActionToPlugin, reactSettings, setReactSettings, dashboardSettings, pluginData } = useAppContext() const { interactiveProcessing } = reactSettings ?? {} const { currentIPIndex, totalTasks } = interactiveProcessing || {} const { enableInteractiveProcessing, enableInteractiveProcessingTransitions } = dashboardSettings || {} const showAnimations = interactiveProcessing && enableInteractiveProcessing && enableInteractiveProcessingTransitions + // Touch devices: collapse to the editor + quick strip while the user is typing with the on-screen keyboard up + const isTouchDevice = pluginData?.platform === 'iOS' || pluginData?.platform === 'iPadOS' + const keyboardVisible = useOnScreenKeyboardVisible(isTouchDevice) + const isEditing = isTouchDevice && editorFocused && (keyboardVisible || !viewportReportsKeyboard) + //---------------------------------------------------------------------- // Effects (before validate / early return - Rules of Hooks) //---------------------------------------------------------------------- @@ -108,26 +250,27 @@ const DialogForTaskItems = ({ details: detailsMessageObject, onClose, positionDi } }, [showAnimations]) - // Close the type menu on outside tap or Escape. Listener is only attached while the menu is open. - useEffect(() => { - if (!typeMenuOpen) return undefined - function handlePointerDown(event: MouseEvent) { - const root = changeTypeMenuRef.current - const target = event.target - if (root && target instanceof Node && !root.contains(target)) { - setTypeMenuOpen(false) - } - } - function handleKeyDown(event: KeyboardEvent) { - if (event.key === 'Escape') setTypeMenuOpen(false) - } - document.addEventListener('pointerdown', handlePointerDown) - document.addEventListener('keydown', handleKeyDown) - return () => { - document.removeEventListener('pointerdown', handlePointerDown) - document.removeEventListener('keydown', handleKeyDown) + // Moving to another IP item keeps this dialog mounted, so the zoom above only plays on first open. + // Slide the new item in (from the right going forward, from the left going back) so the change is obvious. + useLayoutEffect(() => { + const prevIndex = prevIPIndexRef.current + prevIPIndexRef.current = typeof currentIPIndex === 'number' ? currentIPIndex : null + const dialog = dialogRef.current + if (!dialog) return + if (exitAnimationRef.current) { + exitAnimationRef.current.cancel() + exitAnimationRef.current = null } - }, [typeMenuOpen]) + dialog.style.transition = '' + dialog.style.setProperty('translate', '') + if (!showAnimations || typeof prevIndex !== 'number' || typeof currentIPIndex !== 'number' || prevIndex === currentIPIndex) return + playIPEnterAnimation(dialog, currentIPIndex > prevIndex) + }, [currentIPIndex]) + + // Clear any pending editing-collapse timer on unmount + useEffect(() => () => { + if (editBlurTimerRef.current) clearTimeout(editBlurTimerRef.current) + }, []) //---------------------------------------------------------------------- // Constants (validated message / derived UI) @@ -156,7 +299,7 @@ const DialogForTaskItems = ({ details: detailsMessageObject, onClose, positionDi logDebug('DialogForTaskItems', `thisSectionCode=${String(thisSectionCode)}`) const isDesktop = pluginData.platform === 'macOS' - const monthsToShow = (pluginData.platform === 'iOS') ? 1 : 2 + const monthsToShow = 2 // fits on phones too, with the smaller cells set in DashboardDialog.css const resched = dashboardSettings?.rescheduleNotMove || pluginData?.dashboardSettings.rescheduleNotMove || false // logDebug('DialogForTaskItems', `- rescheduleNotMove: dashboardSettings = ${String(dashboardSettings?.rescheduleNotMove)} / settings = ${String(pluginData?.dashboardSettings.rescheduleNotMove)}`) @@ -174,41 +317,61 @@ const DialogForTaskItems = ({ details: detailsMessageObject, onClose, positionDi // Set standard list of buttons to render. // ITEM_ORIG_SECTION resolves at click time to the open item's sectionCode (source section to refresh). const buttons: Array = [ - { label: 'today', controlStr: 't', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'DT'], description: 'Re-schedule to today' }, - { label: '+1d', controlStr: '+1d', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'DO'], description: 'Re-schedule to tomorrow' }, - { label: '+1b', controlStr: '+1b', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'DO'], description: 'Re-schedule to next business day' }, - { label: '+2d', controlStr: '+2d', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], description: 'Re-schedule to 2 days later' }, - { label: 'this week', controlStr: '+0w', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'W'], description: 'Re-schedule to this week' }, - { label: '+1w', controlStr: '+1w', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], description: 'Re-schedule to next week' }, - { label: '+2w', controlStr: '+2w', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], description: 'Re-schedule to 2 weeks later' }, - { label: 'this month', controlStr: '+0m', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'M'], description: 'Re-schedule to this month' }, - { label: '+1m', controlStr: '+1m', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], description: 'Re-schedule to next month' }, - { label: 'this quarter', controlStr: '+0q', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'Q'], description: 'Re-schedule to this quarter' }, + { label: 'today', group: 'day', controlStr: 't', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'DT'], description: 'Re-schedule to today' }, + { label: '+1d', group: 'day', controlStr: '+1d', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'DO'], description: 'Re-schedule to tomorrow' }, + { label: '+1b', group: 'day', controlStr: '+1b', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'DO'], description: 'Re-schedule to next business day' }, + { label: '+2d', group: 'day', controlStr: '+2d', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], description: 'Re-schedule to 2 days later' }, + { label: 'this week', group: 'later', controlStr: '+0w', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'W'], description: 'Re-schedule to this week' }, + { label: 'next week', group: 'later', controlStr: '+1w', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], description: 'Re-schedule to next week' }, + { label: 'in 2 weeks', group: 'later', controlStr: '+2w', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], description: 'Re-schedule to 2 weeks later' }, + { label: 'this month', group: 'later', controlStr: '+0m', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'M'], description: 'Re-schedule to this month' }, + { label: 'next month', group: 'later', controlStr: '+1m', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], description: 'Re-schedule to next month' }, + { label: 'this quarter', group: 'later', controlStr: '+0q', sectionCodesToRefresh: ['ITEM_ORIG_SECTION', 'Q'], description: 'Re-schedule to this quarter' }, ] // Now tweak this list if buttons slightly if we're on a weekly or monthly note etc. if (sectionCodes) { if (sectionCodes.includes('DT')) { buttons.splice(0, 1) // remove the 'today' item, as its redundant - buttons.splice(3, 0, { label: '+3d', controlStr: '+3d', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], description: 'Re-schedule to 3 days later' }) // add another one instead + buttons.splice(3, 0, { label: '+3d', group: 'day', controlStr: '+3d', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], description: 'Re-schedule to 3 days later' }) // add another one instead } if (sectionCodes.includes('W')) { buttons.splice(4, 1) // remove the 'this week' item, as its redundant } if (sectionCodes.includes('M')) { - buttons.splice(7, 1, { label: 'next month', controlStr: '+1m', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], description: 'Re-schedule to next month' }) // Replace the 'this month' item + buttons.splice(7, 1, { label: 'next month', group: 'later', controlStr: '+1m', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], description: 'Re-schedule to next month' }) // Replace the 'this month' item } if (sectionCodes.includes('Q')) { - buttons.splice(8, 1, { label: 'next quarter', controlStr: '+1q', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], description: 'Re-schedule to next quarter' }) // Replace the 'this quarter' item + buttons.splice(8, 1, { label: 'next quarter', group: 'later', controlStr: '+1q', sectionCodesToRefresh: ['ITEM_ORIG_SECTION'], description: 'Re-schedule to next quarter' }) // Replace the 'this quarter' item } } + // Day buttons are always visible; the rarer week/month/quarter ones live in the 'Later' menu + const dayButtons = buttons.filter((b) => b.group !== 'later') + const laterButtons = buttons.filter((b) => b.group === 'later') + + // 'Complete then' completes on para.dueDate, so name that date on the button. Also show a due/overdue status line. + const todayISO = getTodaysDateHyphenated() + const completeThenLabel = getCompleteThenLabel(para?.dueDate, todayISO) + const itemContent = String(para?.content ?? content ?? '') + const dueStatus = getDueStatus(para?.dueDate, itemContent, filename, todayISO, undefined, daysBeforeDueDate(itemContent)) + + // The item text as Dashboard rows show it: links, tags, priorities etc. formatted, block IDs and markdown hidden + const editorBaseContent = savedContent ?? String(content ?? '') + const itemToRender = savedContent != null && para ? { ...item, para: { ...para, content: savedContent } } : item + const renderedHtml = applyDashboardSettingsToDisplayedItemHtml( + makeParaContentToLookLikeNPDisplayInReact(itemToRender, 0, pluginData?.notePlanSettings?.timeblockMustContainString ?? '', pluginData?.reminderDisplayById), + dashboardSettings, + ) + // Fall back to the editor if there's nothing to show formatted + const showEditor = showRawText || renderedHtml === '' + // Note: Extra setup is required for certain buttons: // - Cancel button icon circle or square, and function - // - Change type is a native