Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/NotePlan/plugins
Browse files Browse the repository at this point in the history
  • Loading branch information
mikeerickson committed May 18, 2022
2 parents 089df79 + a2aa247 commit 0633c37
Show file tree
Hide file tree
Showing 103 changed files with 22,764 additions and 885 deletions.
48 changes: 26 additions & 22 deletions dwertheimer.DataQuerying/src/NPDataQuerying.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,21 @@ const SEARCH_OPTIONS = {
findAllMatches: true,
}

type TgetNotesForIndex = {
type: TNote['type'],
title: TNote['title'],
hashtags: TNote['hashtags'],
mentions: TNote['mentions'],
content: TNote['content'],
filename: TNote['filename'],
changedDateISO: string,
}
/**
* Get a list of notes in a form we can use for FUSE
* @param {Object} config
* @returns
*/
function getNotesForIndex(config: DataQueryingConfig) {
function getNotesForIndex(config: DataQueryingConfig): $ReadOnlyArray<TgetNotesForIndex> {
const consolidatedNotes = [...DataStore.projectNotes, ...DataStore.calendarNotes]
log(pluginJson, `getNotesForIndex: ${consolidatedNotes.length} notes before eliminating foldersToIgnore: ${config.foldersToIgnore.toString()}`)
// consolidatedNotes.prototype.changedDateISO = () => this.changedDate.toISOString()
Expand All @@ -68,24 +77,19 @@ function getNotesForIndex(config: DataQueryingConfig) {
}
// log(pluginJson, `getNotesForIndex: ${consolidatedNotes.length} notes before eliminating foldersToIgnore: ${JSON.stringify(foldersToIgnore)} `)
const cn = consolidatedNotes
.filter((note) => {
let include = true
foldersToIgnore?.forEach((skipFolder) => {
if (note.filename.includes(`${skipFolder}/`)) {
include = false
}
})
return include
.filter((note) => foldersToIgnore.every((skipFolder) => !note.filename.includes(`${skipFolder}/`)))
.map((n: TNote): TgetNotesForIndex => {
return {
type: n.type,
title: n.title,
hashtags: n.hashtags,
mentions: n.mentions,
content: n.content,
filename: n.filename,
changedDateISO: n.changedDate.toISOString(),
}
})
.map((n) => ({
type: n.type,
title: n.title,
hashtags: n.hashtags,
mentions: n.mentions,
content: n.content,
filename: n.filename,
changedDateISO: n.changedDate.toISOString(),
}))

log(pluginJson, `getNotesForIndex: FollowUp=${cn.filter((n) => n.filename == '_Inbox/FollowUp.md').length}`)
return cn
// Note: had to do the map above to get the actual NP objects to be visible in the console
Expand Down Expand Up @@ -141,7 +145,7 @@ export async function writeIndex(index: any): null | any {
* @param {Object} notesToInclude (optional) if you have the cleansed note list, pass it in, otherwise it will be created
* @returns {FuseIndex}
*/
export async function createIndex(notesToInclude = [], config: { ... }): Fuse.FuseIndex<mixed> {
export async function createIndex(notesToInclude: $ReadOnlyArray<TNote> = [], config: { ... }): Fuse.FuseIndex<mixed> {
let timeStart = new Date()
const includedNotes = notesToInclude.length ? notesToInclude : getNotesForIndex(config)
const index = fh.buildIndex(includedNotes, SEARCH_OPTIONS)
Expand Down Expand Up @@ -270,11 +274,11 @@ async function writeSearchNote(results, searchTerm, config) {
console.log(`searchUserInput: Noteplan opening/displaying search results took: ${timer(start)}`)
}

export async function search(pattern = `Cava`, config: DataQueryingConfig = getDefaultConfig(), pIndex = null, notes = null): Promise<any> {
export async function search(pattern: string = `Cava`, config: DataQueryingConfig = getDefaultConfig(), pIndex?: number, notes?: $ReadOnlyArray<TNote>): Promise<any> {
try {
// CommandBar.showLoading(true, `Searching ${DataStore.projectNotes.length} notes and attachments...`)
// await CommandBar.onAsyncThread()
let index = pIndex || null
let index = pIndex ?? null
let timeStart = new Date()
if (config.loadIndexFromDisk) {
try {
Expand All @@ -284,7 +288,7 @@ export async function search(pattern = `Cava`, config: DataQueryingConfig = getD
}
}
// const consolidatedNotes = [...DataStore.projectNotes, ...DataStore.calendarNotes].map((note) => ({ ...note, changedDate: note.changedDate.toISOString() }))
const includedNotes = notes || getNotesForIndex(config)
const includedNotes = notes ?? getNotesForIndex(config)
let results = []
if (index) {
results = fh.searchIndex(includedNotes, pattern, { options: SEARCH_OPTIONS, index })
Expand Down
2 changes: 1 addition & 1 deletion dwertheimer.DataQuerying/src/support/query-helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,4 @@ export function getSurroundingChars(value: string, start: number, end: number, c
return config.ignoreNewLines ? output.replace(/\n/gm, ' ') : output
}

export function getMatchText(indices, content) {}
// export function getMatchText(indices, content) {}
76 changes: 49 additions & 27 deletions dwertheimer.EventAutomations/src/NPTimeblocking.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ import {
import { getPresetOptions, setConfigForPreset } from './presets'
import { getTimeBlockingDefaults, validateTimeBlockConfig } from './config'
import type { IntervalMap, TimeBlockDefaults, PartialCalendarItem, EditorOrNote } from './timeblocking-flow-types'
import { checkNumber, checkObj, checkString, checkWithDefault } from '../../helpers/checkType'
import { catchError } from 'rxjs/operators'

const PLUGIN_ID = 'autoTimeBlocking'

Expand Down Expand Up @@ -133,31 +135,30 @@ export async function deleteParagraphsContainingString(destNote: TNote, timeBloc
*/
function getTodaysReferences(pNote: TNote | null = null, config): Array<TParagraph> {
const note = pNote || Editor.note
if (note) {
const backlinks = [...(note.backlinks || [])] // an array of notes which link to this note

let todayParas = []
backlinks.forEach((link, i) => {
// $FlowIgnore
const subItems = link.subItems
subItems.forEach((subItem, j) => {
subItem.title = link.content.replace('.md', '').replace('.txt', '')
todayParas.push(subItem)
})
})
// FIX CLO to work with backlinks

clo(todayParas, 'todayParas')
findTodosInNote(note, config).forEach((link, i) => {
clo(link, `findTodosInNote[${i}]`)
})
todayParas = [...todayParas, ...findTodosInNote(note, config)]
// console.log(`getTodaysReferences note.filename=${note.filename} backlinks.length=${backlinks.length} todayParas.length=${todayParas.length}`)
return todayParas
} else {
if (note == null) {
console.log(`timeblocking could not open Note`)
return []
}

const backlinks: Array<TParagraph> = [...note.backlinks] // an array of notes which link to this note

let todayParas = []
backlinks.forEach((link, i) => {
const subItems = link.children()
subItems.forEach((subItem, j) => {
subItem.title = link.content.replace('.md', '').replace('.txt', '')
todayParas.push(subItem)
})
})
// FIX CLO to work with backlinks

clo(todayParas, 'todayParas')
findTodosInNote(note).forEach((link, i) => {
clo(link, `findTodosInNote[${i}]`)
})
todayParas = [...todayParas, ...findTodosInNote(note)]
// console.log(`getTodaysReferences note.filename=${note.filename} backlinks.length=${backlinks.length} todayParas.length=${todayParas.length}`)
return todayParas
}

async function insertItemsIntoNote(note, list, config) {
Expand Down Expand Up @@ -207,7 +208,8 @@ async function getPopulatedTimeMapForToday(dateStr: string, intervalMins: number
const eventsWithStartAndEnd = getTimedEntries(eventsArray)
let eventsScheduledForToday = keepTodayPortionOnly(eventsWithStartAndEnd)
if (Editor) {
const userEnteredTimeblocks = getExistingTimeBlocksFromNoteAsEvents(Editor, config.defaultDuration)
let duration = checkWithDefault(checkNumber, 60)
const userEnteredTimeblocks = getExistingTimeBlocksFromNoteAsEvents(Editor, duration)
eventsScheduledForToday = [...userEnteredTimeblocks, ...eventsScheduledForToday]
}
const blankDayMap = getBlankDayMap(parseInt(intervalMins))
Expand All @@ -233,17 +235,37 @@ export async function deleteCalendarEventsWithTag(tag: string, dateStr: string):
}
}

function getEventsConfig(atbConfig: { [string]: mixed }) {
type TEventConfig = {
confirmEventCreation: boolean,
processedTagName: string,
calendarToWriteTo: string,
}
function getEventsConfig(atbConfig: { [string]: mixed }): TEventConfig {
const checkedConfig: {
eventEnteredOnCalTag: string,
calendarToWriteTo: string,
...
} = checkWithDefault(
checkObj({
eventEnteredOnCalTag: checkString,
calendarToWriteTo: checkString,
}),
{
eventEnteredOnCalTag: '#event_created',
calendarToWriteTo: '',
},
)

const eventsConfig = {
confirmEventCreation: false,
processedTagName: atbConfig.eventEnteredOnCalTag || '#event_created',
calendarToWriteTo: atbConfig.calendarToWriteTo || '',
processedTagName: checkedConfig.eventEnteredOnCalTag,
calendarToWriteTo: checkedConfig.calendarToWriteTo,
}

return eventsConfig
}

export async function createTimeBlocksForTodaysTasks(config: { [key: string]: any } = {}): Promise<?Array<string>> {
export async function createTimeBlocksForTodaysTasks(config: { [key: string]: mixed } = {}): Promise<?Array<string>> {
// console.log(`Starting createTimeBlocksForTodaysTasks. Time is ${new Date().toLocaleTimeString()}`)
// console.log(`config is: ${JSON.stringify(config, null, 2)}`)
const {
Expand Down
6 changes: 4 additions & 2 deletions dwertheimer.EventAutomations/src/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ export async function createNoteForCalendarItem(useQuickTemplate: boolean = true
// $FlowIgnore
const theTitle = `${selectedEvent} {{date8601()}} ${theTime || ''}`
if (selectedEvent && useQuickTemplate) {
await quickTemplateNote(theTitle)
// quickTemplateNote is not defined!
// await quickTemplateNote(theTitle)
return
}
const useTemplate = await chooseOption(
Expand All @@ -68,7 +69,8 @@ export async function createNoteForCalendarItem(useQuickTemplate: boolean = true
'Yes',
)
if (useTemplate !== 'No') {
await newNoteWithTemplate('', theTitle)
// newNoteWithTemplate is not defined!
// await newNoteWithTemplate('', theTitle)
} else {
const folder = await chooseFolder('What folder should the note be in?')
if (selEvent) {
Expand Down
6 changes: 2 additions & 4 deletions dwertheimer.EventAutomations/src/timeblocking-helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,7 @@ export function getDurationFromLine(line: string, durationMarker: string): numbe
* @param {*} paragraphsArray
* @returns
*/
export function removeDateTagsFromArray(
paragraphsArray: $ReadOnlyArray<$ReadOnly<{ ...TParagraph, title?: string }>>,
): $ReadOnlyArray<$ReadOnly<{ ...TParagraph, title?: string }>> {
export function removeDateTagsFromArray(paragraphsArray: $ReadOnlyArray<TParagraph>): Array<TParagraph> {
const newPA = paragraphsArray.map((p, i) => {
return {
...p,
Expand Down Expand Up @@ -329,7 +327,7 @@ export function matchTasksToSlots(sortedTaskList: Array<{ ...TParagraph, duratio
* @param { * } config
* @returns
*/
export function appendLinkIfNecessary(todos: Array<{ ...TParagraph, +title?: string }>, config: { [key: string]: any }): Array<{ ...TParagraph, +title?: string }> {
export function appendLinkIfNecessary(todos: Array<TParagraph>, config: { [key: string]: any }): Array<TParagraph> {
let todosWithLinks = todos
if (todos.length && config.includeLinks !== 'OFF') {
todosWithLinks = []
Expand Down
82 changes: 82 additions & 0 deletions dwertheimer.TaskAutomations/__tests__/tagTasks.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import * as tt from '../src/tagTasks'

/*
describe(section('copyTagsFromLineAbove'), () => {
it(`should render default date object`, () => {})
})
*/

// Jest codedungeon bersion
import colors from 'chalk'
const PLUGIN_NAME = `${colors.yellow('dwertheimer.TaskAutomations')}`
const section = colors.blue
describe(`${PLUGIN_NAME}`, () => {
describe(section('getTagsFromString'), () => {
it(`should not find anything if no tags`, () => {
const text = `word something nothing`
const tags = tt.getTagsFromString(text)
expect(tags).toEqual({ hashtags: [], mentions: [] })
})
it(`should find tags/mentions and return them in an object`, () => {
const text = `text1 #tag1 #tag2 text2 @mention1 @mention2 text3`
const tags = tt.getTagsFromString(text)
expect(tags).toEqual({
hashtags: ['#tag1', '#tag2'],
mentions: ['@mention1', '@mention2'],
})
})
})
describe(section('getUnduplicatedMergedTagArray'), () => {
it(`should return nothing if there are no tags`, () => {
const existingTags = []
const newTags = []
const tags = tt.getUnduplicatedMergedTagArray(existingTags, newTags)
expect(tags).toEqual(newTags)
})
it(`should return newTags if there are no oldTags`, () => {
const existingTags = []
const newTags = ['@foo']
const tags = tt.getUnduplicatedMergedTagArray(existingTags, newTags)
expect(tags).toEqual(newTags)
})
it(`should return oldTags if there are no newTags`, () => {
const existingTags = ['@foo']
const newTags = []
const tags = tt.getUnduplicatedMergedTagArray(existingTags, newTags)
expect(tags).toEqual(existingTags)
})
it(`should return merged if both have tags`, () => {
const existingTags = ['#tag1', '#tag2']
const newTags = ['#tag3', '#tag4']
const tags = tt.getUnduplicatedMergedTagArray(existingTags, newTags)
expect(tags).toEqual([...existingTags, ...newTags])
})
})
describe(section('removeTagsFromLine'), () => {
const text = `text1 #tag1 #tag2 text2 @mention1 @mention2 text3`
const toRemove = ['#tag1', '@mention2']
it(`should remove tags from text`, () => {
const revisedText = tt.removeTagsFromLine(text, toRemove)
expect(revisedText).toEqual(`text1 #tag2 text2 @mention1 text3`)
})
it(`should do nothing if no tags to remove`, () => {
const revisedText = tt.removeTagsFromLine(text, [])
expect(revisedText).toEqual(text)
})
})

describe(section('appendTagsToText'), () => {
it(`should reorder tags mentions first then hashtags`, () => {
const text = `test #bar @foo #yo`
const newTags = { hashtags: [], mentions: [] }
const ret = tt.appendTagsToText(text, newTags)
expect(ret).toEqual(`test #bar #yo @foo`)
})
it(`should add a tag if one is new`, () => {
const text = `word something nothing #bar #faz @foo`
const newTags = { hashtags: ['#far'], mentions: [] }
const ret = tt.appendTagsToText(text, newTags)
expect(ret).toEqual(`word something nothing #bar #faz #far @foo`)
})
})
})
3 changes: 3 additions & 0 deletions dwertheimer.TaskAutomations/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ See Plugin [README](https://github.com/NotePlan/plugins/blob/main/dwertheimer.Ta

# What's Changed in this Plugin?

## [1.6.2] 2022-05-17
- adding /cth and copy tags /ctm /ctt

## [1.6.1] 2022-05-09
- added /cta copy tags from line above

Expand Down
2 changes: 1 addition & 1 deletion dwertheimer.TaskAutomations/plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"plugin.name": "✅ Task Automations",
"plugin.description": "Functions for handling Tasks",
"plugin.author": "@dwertheimer",
"plugin.version": "1.6.1",
"plugin.version": "1.6.2",
"plugin.dependencies": [ ],
"plugin.script": "script.js",
"plugin.url": "https://github.com/NotePlan/plugins/blob/main/dwertheimer.TaskAutomations/readme.md",
Expand Down
2 changes: 1 addition & 1 deletion dwertheimer.TaskAutomations/src/sortTasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export async function openTasksToTop(heading: string = '## Tasks:\n', separator:
if (sweptTasks.taskArray[0].content === Editor.title) {
sweptTasks.taskArray.shift()
}
Editor.prependParagraph(heading.concat(sweptTasks.taskArray.map((m) => m.rawContent).join('\n')).concat(`\n${separator}`), 'text')
Editor.prependParagraph(heading.concat((sweptTasks.taskArray ?? []).map((m) => m.rawContent).join('\n')).concat(`\n${separator}`), 'text')
}
}

Expand Down
Loading

0 comments on commit 0633c37

Please sign in to comment.