diff --git a/README.md b/README.md index f77e7e6..0b97b27 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ Thank you for being a part of this movement to revolutionize our approach to kno ## Manual installation -1. Download the latest release 🔗 **Plugin Download:** [Obsidian Gamification Plugin](https://github.com/saertna/obsidian-gamified-pkm/releases/tag/0.0.83) +1. Download the latest release 🔗 **Plugin Download:** [Obsidian Gamification Plugin](https://github.com/saertna/obsidian-gamified-pkm/releases/tag/0.0.84) 2. Extract the obsidian-gamified-pkm folder from the zip to your vault's plugins folder: ``/.obsidian/plugins/ - Note: On some machines the .obsidian folder may be hidden. On MacOS you should be able to press Command+Shift+Dot to show the folder in Finder. - Note: the files `main.js` and `manifest.json` are the files which you need in this folder. diff --git a/manifest.json b/manifest.json index 63356c2..3d95af2 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "gamified-pkm", "name": "Gamificate your PKM", - "version": "0.0.83", + "version": "0.0.84", "minAppVersion": "0.15.0", "description": "Enhance your Personal Knowledge Management with gamification elements. Boost motivation and achieve growth as you engage with your PKM.", "author": "Andreas Trebing", diff --git a/obsidian-gamified-pkm/obsidian-gamified-pkm.zip b/obsidian-gamified-pkm/obsidian-gamified-pkm.zip index 69ea861..4813935 100644 Binary files a/obsidian-gamified-pkm/obsidian-gamified-pkm.zip and b/obsidian-gamified-pkm/obsidian-gamified-pkm.zip differ diff --git a/package.json b/package.json index c062667..42e4735 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "obsidian-gamified-pkm", - "version": "0.0.83", + "version": "0.0.84", "description": "Enhance your Personal Knowledge Management with gamification elements. Boost motivation and achieve growth as you engage with your PKM.", "main": "main.js", "scripts": { diff --git a/src/ModalBooster.ts b/src/ModalBooster.ts index 10acfa4..d443803 100644 --- a/src/ModalBooster.ts +++ b/src/ModalBooster.ts @@ -15,25 +15,22 @@ export class ModalBooster extends Modal { onOpen() { const { contentEl } = this; contentEl.setText(this.displayText); + const multiSelectModal = new MultiSelectModal(this.app, [], 'Craft Booster Item', this.gamificationInstance); // Create the modal instance - // Add a button to open the multi-select modal const button = document.createElement('button'); button.innerText = 'Open Crafting Table'; + button.classList.add('modal-button'); button.onclick = () => { - multiSelectModal.setUseBooster(false); // Set the flag for crafting table + multiSelectModal.setUseBooster(false); multiSelectModal.open(); }; - - multiSelectModal.readBoostersStock(); - multiSelectModal.readIngrementStock(); - - const button2 = document.createElement('button'); button2.innerText = 'Open Booster Board'; + button2.classList.add('modal-button'); button2.onclick = () => { multiSelectModal.setUseBooster(true); multiSelectModal.open(); @@ -41,6 +38,7 @@ export class ModalBooster extends Modal { contentEl.appendChild(button); contentEl.appendChild(button2); + } onClose() { diff --git a/src/MultiSelectModal.ts b/src/MultiSelectModal.ts index 50b107c..6a6ee25 100644 --- a/src/MultiSelectModal.ts +++ b/src/MultiSelectModal.ts @@ -4,7 +4,8 @@ import { elements, boosterRecipes, listOfUseableBoostersToBeShown, - listOfUseableIngredientsToBeShown + listOfUseableIngredientsToBeShown, + debugLogs } from './constants'; import { ModalInformationbox } from 'ModalInformationbox'; import gamification, { isMinutesPassed, hoursUntilMinutesPassed} from 'main'; @@ -33,7 +34,7 @@ export class MultiSelectModal extends Modal { const { contentEl } = this; contentEl.empty(); - //this.readBoostersStock(); + this.readBoostersStock(); // take care only to run several times through when boosters are used if (this.useBooster) { boosterRecipes.forEach(item => { @@ -59,10 +60,9 @@ export class MultiSelectModal extends Modal { } private boosterAvailableForUse(item: string) { - //console.debug(`boosterAvailableForUse: ${item}`) + if(debugLogs) console.debug(`boosterAvailableForUse: ${item}`) let found = false; listOfUseableBoostersToBeShown.forEach(element => { - //console.debug(`${item} == ${element} ??`) if (item == element) { if (!found) { found = true; @@ -90,7 +90,7 @@ export class MultiSelectModal extends Modal { } updateIncrementStock(increment: string, stock: number) { - console.debug(`increment "${increment}" new value ${stock}`); + if(debugLogs) console.debug(`increment "${increment}" new value ${stock}`); this.remainingStock[increment] = stock; this.gamificationInstance.setSettingNumber(this.getIngerementVarNameFromName(increment) || '', stock); } @@ -116,7 +116,7 @@ export class MultiSelectModal extends Modal { this.gamificationInstance.setSettingNumber('boosterUseCount',boosterOverallUse + 1) } else { // Handle the case where boosterLastUsedDate is not a valid string. - console.debug(`decrementBooster: "boosterUseCount" could not got read.`) + if(debugLogs) console.debug(`decrementBooster: "boosterUseCount" could not got read.`) } const boosterUse = this.gamificationInstance.getSettingNumber(this.getBoosterUseFromName(booster)) if (typeof boosterUse === 'number' && boosterUse !== null) { @@ -124,7 +124,7 @@ export class MultiSelectModal extends Modal { this.gamificationInstance.setSettingNumber(this.getBoosterUseFromName(booster),boosterUse + 1) } else { // Handle the case where boosterLastUsedDate is not a valid string. - console.debug(`decrementBooster: "${this.getBoosterUseFromName(booster)}" could not got read.`) + if(debugLogs) console.debug(`decrementBooster: "${this.getBoosterUseFromName(booster)}" could not got read.`) } this.updateQuantityDisplay(booster); } @@ -235,6 +235,7 @@ export class MultiSelectModal extends Modal { container.className = 'modal-checkbox-container'; //const stock = this.remainingStock[labelText] || 0; + if(debugLogs) console.log(`createBoosterList: labelText: ${labelText}`) const stock = this.boosters[labelText]; const label = container.createEl('div', { cls: `${labelText.replace(' ', '-')}` }); @@ -243,7 +244,8 @@ export class MultiSelectModal extends Modal { const momentDate = this.gamificationInstance.getSettingString(this.getBoosterDateFromName(labelText)); if (isMinutesPassed(window.moment(momentDate as string, 'YYYY-MM-DD HH:mm:ss'), this.getBoosterCooldownFromName(labelText)) == false) { - console.debug(`Booster ${labelText} is still in cooldown for ${window.moment(momentDate as string, 'YYYY-MM-DD HH:mm:ss'), this.getBoosterCooldownFromName(labelText) / 60} hours`); + if(debugLogs) console.debug(`Booster ${labelText} is still in cooldown for ${window.moment(momentDate as string, 'YYYY-MM-DD HH:mm:ss'), this.getBoosterCooldownFromName(labelText) / 60} hours`); + if(debugLogs) console.log(`createBoosterList: Stock amount ${stock}`) label.createEl('div', { text: `${labelText} : (${stock})` }); useButton.innerText = `cooldown ${hoursUntilMinutesPassed(window.moment(momentDate as string, 'YYYY-MM-DD HH:mm:ss'), this.getBoosterCooldownFromName(labelText))} hours`; @@ -279,7 +281,7 @@ export class MultiSelectModal extends Modal { incrementItem(item: string) { const stock = this.remainingStock[item]; - //console.debug(`incrementItem: stock = ${stock}`); + if(debugLogs) console.debug(`incrementItem: stock = ${stock}`); if (stock > 0) { this.selectedItems.push(item); this.remainingStock[item]--; @@ -308,9 +310,9 @@ export class MultiSelectModal extends Modal { private useBoosterItem(labelText: string) { - console.debug(`use Booster ${labelText}`); + if(debugLogs) console.debug(`use Booster ${labelText}`); if(labelText=='Fortune Infusion'){ - //console.debug(`acquireIngredients();`) + if(debugLogs) console.debug(`acquireIngredients();`) this.gamificationInstance.acquireIngredients(1,1,10) } else if (labelText=='Temporal Tweaker'){ @@ -383,10 +385,10 @@ export class MultiSelectModal extends Modal { private checkIngredientsAvailability(incredients: { name: string; incredients: string[]; }) { for (const ingredient of incredients.incredients) { const [quantity, shortName] = ingredient.split('x'); - //console.debug(`quantity: ${quantity}\tshortName: ${shortName}`) + if(debugLogs) console.debug(`quantity: ${quantity}\tshortName: ${shortName}`) const requiredQuantity = parseInt(quantity); const availableStock = this.remainingStock[this.getIngerementNameFromShortName(shortName) || 0]; - //console.debug(`requiredQuantity: ${requiredQuantity}\tavailableStock: ́${availableStock}`) + if(debugLogs) console.debug(`requiredQuantity: ${requiredQuantity}\tavailableStock: ́${availableStock}`) if (requiredQuantity > availableStock) { return false; // Not enough stock for this ingredient } @@ -405,7 +407,7 @@ export class MultiSelectModal extends Modal { totalAvailableIngredients += this.remainingStock[this.getIngerementFromName(increment).name] || 0; }); - console.debug(`total amount of ingrediments: ${totalAvailableIngredients}`) + if(debugLogs) console.debug(`total amount of ingrediments: ${totalAvailableIngredients}`) // If at least 1000 ingredients are available if (totalAvailableIngredients >= 1000) { // Burn ingredients proportionally @@ -414,7 +416,7 @@ export class MultiSelectModal extends Modal { if (this.remainingStock[this.getIngerementFromName(increment).name]) { const proportionalAmount = Math.ceil((this.remainingStock[this.getIngerementFromName(increment).name] / totalAvailableIngredients) * 1000); //const rest = this.remainingStock[this.getIngerementFromName(increment).name] - proportionalAmount; - //console.debug(`${this.getIngerementFromName(increment).shortName} ${this.remainingStock[this.getIngerementFromName(increment).name]} shall be ${this.remainingStock[this.getIngerementFromName(increment).name] - rest} = ${this.remainingStock[this.getIngerementFromName(increment).name]} - ${rest}`) + //if(debugLogs) console.debug(`${this.getIngerementFromName(increment).shortName} ${this.remainingStock[this.getIngerementFromName(increment).name]} shall be ${this.remainingStock[this.getIngerementFromName(increment).name] - rest} = ${this.remainingStock[this.getIngerementFromName(increment).name]} - ${rest}`) //this.remainingStock[this.getIngerementFromName(increment).name] = this.remainingStock[this.getIngerementFromName(increment).name] - proportionalAmount; //this.updateIncrementStock(this.getIngerementFromName(increment).varName, this.remainingStock[this.getIngerementFromName(increment).name]) this.updateIncrementStock(this.getIngerementFromName(increment).name, this.remainingStock[this.getIngerementFromName(increment).name] - proportionalAmount) @@ -476,23 +478,23 @@ export class MultiSelectModal extends Modal { if(this.check1000IngredientsAvailableAndBurn()){ this.updateBoosterStock(selectedItems.name, 1); this.gamificationInstance.setSettingNumber(this.getBoosterVarNameFromName(selectedItems.name), this.boosters[selectedItems.name]); - console.debug(`craft booster ${selectedItems.name}`); + if(debugLogs) console.debug(`craft booster ${selectedItems.name}`); } else { - console.debug(`not enough ingredients for booster ${selectedItems.name} in stock`); + if(debugLogs) console.debug(`not enough ingredients for booster ${selectedItems.name} in stock`); new ModalInformationbox(this.app, `Not enough ingrediments available for '${selectedItems.name}'. Craft more Notes to collect new ingrediments.`).open(); } } else if(selectedItems.name == 'Fortune Infusion'){ } else { if (this.checkIngredientsAvailability(selectedItems)) { - console.debug(`craft booster ${selectedItems.name}`); + if(debugLogs) console.debug(`craft booster ${selectedItems.name}`); this.updateBoosterStock(selectedItems.name, 1); this.gamificationInstance.setSettingNumber(this.getBoosterVarNameFromName(selectedItems.name), this.boosters[selectedItems.name]); this.useIngrediments(selectedItems); //this.updateQuantityDisplay(selectedItems.name) this.updateStockInformation(); } else { - console.debug(`not enough ingredients for booster ${selectedItems.name} in stock`); + if(debugLogs) console.debug(`not enough ingredients for booster ${selectedItems.name} in stock`); new ModalInformationbox(this.app, `Not enough ingrediments available for '${selectedItems.name}'. Craft more Notes to collect new ingrediments.`).open(); } } diff --git a/src/badges.ts b/src/badges.ts index 910a0c5..11901f4 100644 --- a/src/badges.ts +++ b/src/badges.ts @@ -79,7 +79,7 @@ export function getBadgeForLevel(level: number, inform: boolean): Badge { // Example usage: // const currentLevel = 42; // Replace this with the actual player's level // const badge = getBadgeForLevel(currentLevel); - // console.debug(`Congratulations! You've reached Level ${currentLevel}. You've earned the "${badge.name}" badge. ${badge.description}`); + // if(debugLogs) console.debug(`Congratulations! You've reached Level ${currentLevel}. You've earned the "${badge.name}" badge. ${badge.description}`); diff --git a/src/constants.ts b/src/constants.ts index e39622e..d8ff687 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -7,6 +7,7 @@ export const streakboosterIncreaseDaily: number = 0.1; export const streakboosterIncreaseWeekly: number = 1; export const CryptoJS = require("crypto-js"); export const secretKey = "2ZU^12y#QmNB5$yEin5^"; +export const debugLogs = false; export const avatarInitContent = `# Avatar | | | diff --git a/src/creatmodchartcalculation.ts b/src/creatmodchartcalculation.ts index c09d388..f951b7a 100644 --- a/src/creatmodchartcalculation.ts +++ b/src/creatmodchartcalculation.ts @@ -1,4 +1,5 @@ import {TFile} from 'obsidian'; +import { debugLogs } from './constants'; export function findEarliestCreatedFile(files: TFile[]): TFile { let earliestCreatedFile: TFile = files[0]; @@ -82,7 +83,7 @@ export function createChartFormat(y_axis: string, countsStringMod: string, chart export async function replaceChartContent (avatarPageName: string, newContent: string) { const existingFile = this.app.vault.getAbstractFileByPath(`${avatarPageName}.md`); if (existingFile == null) { - console.debug(`File ${avatarPageName}.md does not exist`); + if(debugLogs) console.debug(`File ${avatarPageName}.md does not exist`); return; } const file = existingFile as TFile; diff --git a/src/main.ts b/src/main.ts index 822803c..b2f5a12 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,19 +1,21 @@ -import {App, MarkdownView, Notice, Plugin, TFile, Vault} from 'obsidian'; -import {defaultSettings, ISettings, GamificationPluginSettings} from './settings'; +import {App, MarkdownView, Notice, Plugin, TFile} from 'obsidian'; +import {defaultSettings, GamificationPluginSettings, ISettings} from './settings'; import format from 'date-fns/format'; import { avatarInitContent, - pointsMajurity, - pointsNoteMajurity, + boosterRecipes, + chanceToEarnIngredient, + debugLogs, + elements, + listOfUseableIngredientsToBeShown, pointsForDailyChallenge, pointsForWeeklyChallenge, - elements, - boosterRecipes, + pointsMajurity, + pointsNoteMajurity, streakboosterDecrease, streakboosterIncreaseDaily, - streakboosterIncreaseWeekly, - chanceToEarnIngredient, - listOfUseableIngredientsToBeShown} from './constants' + streakboosterIncreaseWeekly +} from './constants' import { count_inlinks, countCharactersInActiveFile, @@ -32,12 +34,16 @@ import { import {Badge, checkIfReceiveABadge, getBadgeForInitLevel, getBadgeForLevel} from './badges' import {getLevelForPoints, statusPointsForLevel} from './levels' import type {Moment} from 'moment'; -import { getRandomMessageWeeklyChallenge, getRandomMessageTwoNoteChallenge , getRandomMessagePoints } from './randomNotificationText' -import { ModalInformationbox } from 'ModalInformationbox'; -import { ModalBooster } from 'ModalBooster'; -import { encryptValue, encryptString, decryptString, encryptNumber, decryptNumber, encryptBoolean, decryptBoolean } from 'encryption'; - -let pointsToReceived: number = 0; +import { + getRandomMessagePoints, + getRandomMessageTwoNoteChallenge, + getRandomMessageWeeklyChallenge +} from './randomNotificationText' +import {ModalInformationbox} from 'ModalInformationbox'; +import {ModalBooster} from 'ModalBooster'; +import {decryptBoolean, decryptNumber, decryptString, encryptBoolean, encryptNumber, encryptString} from 'encryption'; + +let pointsToReceived = 0; export default class gamification extends Plugin { //public settings: GamificationPluginSettings; private timerInterval: number; @@ -49,51 +55,41 @@ export default class gamification extends Plugin { getSettingString(key: string) { const decryptedValue = this.settings[key] !== undefined ? this.settings[key].toString() : '' - //console.debug(`String: decrypted ${key} is ${decryptString(decryptedValue)}`) + //if(debugLogs) console.debug(`String: decrypted ${key} is ${decryptString(decryptedValue)}`) return decryptString(decryptedValue); } getSettingNumber(key: string) { const decryptedValue = this.settings[key] !== undefined ? this.settings[key].toString() : '' - //console.debug(`Number: decrypted ${key} is ${decryptNumber(decryptedValue)}`) + //if(debugLogs) console.debug(`Number: decrypted ${key} is ${decryptNumber(decryptedValue)}`) return decryptNumber(decryptedValue); } getSettingBoolean(key: string) { const decryptedValue = this.settings[key] !== undefined ? this.settings[key].toString() : '' - //console.debug(`Boolean: decrypted ${key} is ${decryptBoolean(decryptedValue)}`) + //if(debugLogs) console.debug(`Boolean: decrypted ${key} is ${decryptBoolean(decryptedValue)}`) return decryptBoolean(decryptedValue); } setSettingString(key: string, value: string) { // Set a specific setting - const valueEncrypted = encryptString(value) - this.settings[key] = valueEncrypted; - //console.debug(`String: new value for ${key} is ${valueEncrypted}`) - //this.settings[key] = value; - this.saveSettings(); + this.settings[key] = encryptString(value); + this.saveSettings(); } setSettingNumber(key: string, value: number) { // Set a specific setting - //console.debug(`new value for ${key} is ${value}`) - const valueEncrypted = encryptNumber(value) - //console.debug(`new value for ${key} is ${value} ⇒ ${valueEncrypted}`) - this.settings[key] = valueEncrypted; - //console.debug(`Number: new value for ${key} is ${valueEncrypted}`) + this.settings[key] = encryptNumber(value); this.saveSettings(); } setSettingBoolean(key: string, value: boolean) { // Set a specific setting - //console.debug(`new value for ${key} is ${value}`) - const valueEncrypted = encryptBoolean(value) - this.settings[key] = valueEncrypted; - //console.debug(`Boolean: new value for ${key} is ${valueEncrypted}`) - this.saveSettings(); + this.settings[key] = encryptBoolean(value); + this.saveSettings(); } @@ -104,7 +100,6 @@ export default class gamification extends Plugin { console.log('obsidian-pkm-gamification loaded!'); //this.settings = defaultSettings; - this.addSettingTab(new GamificationPluginSettings(this.app, this)); @@ -149,11 +144,11 @@ export default class gamification extends Plugin { const badgeDict = parseBadgeCSV(csvString); // Access badge information - //console.debug(badgeDict["Brainiac Trailblazer"]); + //if(debugLogs) console.debug(badgeDict["Brainiac Trailblazer"]); for (const badgeName in badgeDict) { if (badgeDict.hasOwnProperty(badgeName)) { const badgeInfo = badgeDict[badgeName]; - console.debug(`Badge: ${badgeName}, Date: ${badgeInfo.date}, Level: ${badgeInfo.level}`); + if(debugLogs) console.debug(`Badge: ${badgeName}, Date: ${badgeInfo.date}, Level: ${badgeInfo.level}`); } }*/ //this.openAvatarFile(); @@ -201,7 +196,7 @@ export default class gamification extends Plugin { id: 'create-avatar-page', name: 'Create profile page', callback: async () => { - const { vault } = this.app; + //const { vault } = this.app; await createAvatarFile(this.app, this.getSettingString('avatarPageName')) //const chartString = await this.createChart(vault) //await replaceChartContent(this.getSettingString('avatarPageName'), chartString) @@ -277,14 +272,14 @@ export default class gamification extends Plugin { this.setSettingString('gamificationStartDate', format(new Date(), 'yyyy-MM-dd')); await this.saveSettings(); - const {vault} = this.app; + //const {vault} = this.app; await createAvatarFile(this.app, this.getSettingString('avatarPageName')) //const chartString = await this.createChart(vault) //await replaceChartContent(this.getSettingString('avatarPageName'), chartString) await this.openAvatarFile() const fileCountMap: TFile[] | null = await getFileMap(this.app, this.getSettingString('tagsExclude'), this.getSettingString('folderExclude')); if (fileCountMap !== null) { - console.debug(`fileCountMap loaded. Number of files: ${fileCountMap.length}`); + if(debugLogs) console.debug(`fileCountMap loaded. Number of files: ${fileCountMap.length}`); let pointsReceived = 0; // to have one message at the end how many points received @@ -296,7 +291,7 @@ export default class gamification extends Plugin { console.warn(`File ${file.path} is currently open. Skipping.`); continue; } - //console.debug(`fileName.basename: ${fileName.basename}`) + //if(debugLogs) console.debug(`fileName.basename: ${fileName.basename}`) const fileLength = countCharactersInActiveFile(fileContents, fileName.basename); const rateFileLength = rateNoteLength(fileLength); const { @@ -312,7 +307,7 @@ export default class gamification extends Plugin { const noteMajurity = rateLevelOfMaturity(rateFileLength, fileNameRate, inlinkClass, rateOut, rateProgressiveSum); - console.debug(`Processing file ${fileName.basename} in path ${fileName.path}`); + if(debugLogs) console.debug(`Processing file ${fileName.basename} in path ${fileName.path}`); try { await this.app.fileManager.processFrontMatter(file, (frontmatter) => { @@ -388,7 +383,7 @@ export default class gamification extends Plugin { } if (pointsReceived > 0) { new Notice(`${pointsReceived} Points received`,this.getSettingNumber('timeShowNotice') * 1000) - console.debug(`${pointsReceived} Points received`) + if(debugLogs) console.debug(`${pointsReceived} Points received`) } @@ -397,7 +392,7 @@ export default class gamification extends Plugin { // Code that you want to execute after the delay const initBadge: Badge = getBadgeForInitLevel(this.getSettingNumber('statusLevel')); new Notice(`You've earned the "${initBadge.name}" badge. ${initBadge.description}`,this.getSettingNumber('timeShowNotice') * 1000 * 1.2) - console.debug(`You earned ${initBadge.name} - ${initBadge.description}`) + if(debugLogs) console.debug(`You earned ${initBadge.name} - ${initBadge.description}`) await this.giveInitBadgeInProfile(this.getSettingString('avatarPageName'), initBadge); await this.removeBadgesWhenInitLevelHigher(this.getSettingString('avatarPageName'), this.getSettingNumber('statusLevel')) await this.boosterForInit() @@ -482,7 +477,7 @@ export default class gamification extends Plugin { if (frontmatter) { let pointsReceived = 0; // to have one message at the end how many points received if (rateDirectionForStatusPoints(frontmatter['note-maturity'], noteMajurity) >= 1){ - console.debug(`note-maturity >=1`) + if(debugLogs) console.debug(`note-maturity >=1`) //pointsReceived += pointsNoteMajurity*rateDirectionForStatusPoints(frontmatter['note-maturity'], noteMajurity) const newLevel = this.giveStatusPoints(pointsNoteMajurity * rateDirectionForStatusPoints("frontmatter['note-maturity']", noteMajurity),'fromNoteMajurity') pointsReceived += pointsToReceived; @@ -559,11 +554,11 @@ export default class gamification extends Plugin { pointsReceived += pointsToReceived; this.decisionIfBadge(newLevel) } - //console.debug(`pointsReceived: ${pointsReceived}`) + //if(debugLogs) console.debug(`pointsReceived: ${pointsReceived}`) if (pointsReceived > 0){ const messagePoints = getRandomMessagePoints(pointsReceived); new Notice(messagePoints,this.getSettingNumber('timeShowNotice') * 1000) - console.debug(messagePoints) + if(debugLogs) console.debug(messagePoints) } this.writeFrontmatter(frontmatter, fileNameRate, rateFileLength, inlinkClass, rateOut, rateProgressiveSum, noteMajurity); @@ -577,7 +572,7 @@ export default class gamification extends Plugin { } } new Notice('note majurity updated!'); - console.debug('note majurity updated!') + if(debugLogs) console.debug('note majurity updated!') await this.updateStatusBar(this.statusbarGamification) } else { console.error('file was not found to calculate majurities. Make sure one is active.') @@ -595,18 +590,18 @@ export default class gamification extends Plugin { this.setSettingNumber('dailyNoteCreationTask', 0); this.setSettingString('dailyNoteCreationDate', window.moment().format('DD.MM.YYYY')) await this.saveSettings(); - console.debug(`daily Challenge reseted`) + if(debugLogs) console.debug(`daily Challenge reseted`) reset = true; } if(!isOneDayBefore(window.moment(this.getSettingString('weeklyNoteCreationDate'), 'DD.MM.YYYY')) && !isSameDay(window.moment(this.getSettingString('weeklyNoteCreationDate'), 'DD.MM.YYYY'))){ const daysPassed = window.moment().diff(window.moment(this.getSettingString('weeklyNoteCreationDate'), 'DD.MM.YYYY'), 'days') - 1; //today is still a chance. this.setSettingNumber('weeklyNoteCreationTask', 0); this.setSettingString('weeklyNoteCreationDate', window.moment().subtract(1, 'day').format('DD.MM.YYYY')) - this.decreaseStreakbooster(daysPassed) - console.debug(`${daysPassed} days passed`) + await this.decreaseStreakbooster(daysPassed) + if(debugLogs) console.debug(`${daysPassed} days passed`) await this.saveSettings(); await this.updateStatusBar(this.statusbarGamification) - console.debug(`weekly Challenge reseted`) + if(debugLogs) console.debug(`weekly Challenge reseted`) reset = true; } if(isOneDayBefore(window.moment(this.getSettingString('weeklyNoteCreationDate'), 'DD.MM.YYYY')) && this.getSettingNumber('weeklyNoteCreationTask') == 7){ @@ -622,39 +617,39 @@ export default class gamification extends Plugin { // deativate boosters if (this.getSettingBoolean('boosterFactorPerpetualProgress') == true && isMinutesPassed(window.moment(this.getSettingString('boosterDatePerpetualProgress'), 'YYYY-MM-DD HH:mm:ss'),getBoosterRunTimeFromVarName('perpetualProgress'))){ this.setSettingBoolean('boosterFactorPerpetualProgress',false); - console.debug('"Perpetual Progress" has ended.') + if(debugLogs) console.debug('"Perpetual Progress" has ended.') } if (this.getSettingBoolean('boosterFactorStrategicSynapses') == true && isMinutesPassed(window.moment(this.getSettingString('boosterDateStrategicSynapses'), 'YYYY-MM-DD HH:mm:ss'),getBoosterRunTimeFromVarName('strategicSynapses'))){ this.setSettingBoolean('boosterFactorStrategicSynapses',false); - console.debug('"Strategic Synapses" has ended.') + if(debugLogs) console.debug('"Strategic Synapses" has ended.') } if (this.getSettingBoolean('boosterFactorLinkersLode') == true && isMinutesPassed(window.moment(this.getSettingString('boosterDateLinkersLode'), 'YYYY-MM-DD HH:mm:ss'),getBoosterRunTimeFromVarName('linkersLode'))){ this.setSettingBoolean('boosterFactorLinkersLode',false); - console.debug('"Linkers Lode" has ended.') + if(debugLogs) console.debug('"Linkers Lode" has ended.') } if (this.getSettingBoolean('boosterFactorRecursiveReflection') == true && isMinutesPassed(window.moment(this.getSettingString('boosterDateRecursiveReflection'), 'YYYY-MM-DD HH:mm:ss'),getBoosterRunTimeFromVarName('recursiveReflection'))){ this.setSettingBoolean('boosterFactorRecursiveReflection',false); - console.debug('"Recursive Reflection" has ended.') + if(debugLogs) console.debug('"Recursive Reflection" has ended.') } if (this.getSettingBoolean('boosterFactorSynapticSurge') == true && isMinutesPassed(window.moment(this.getSettingString('boosterDateSynapticSurge'), 'YYYY-MM-DD HH:mm:ss'),getBoosterRunTimeFromVarName('synapticSurge'))){ this.setSettingBoolean('boosterFactorSynapticSurge',false); - console.debug('"Synaptic Surge" has ended.') + if(debugLogs) console.debug('"Synaptic Surge" has ended.') } if (this.getSettingBoolean('boosterFactorTitleTitan') == true && isMinutesPassed(window.moment(this.getSettingString('boosterDateTitleTitan'), 'YYYY-MM-DD HH:mm:ss'),getBoosterRunTimeFromVarName('titleTitan'))){ this.setSettingBoolean('boosterFactorTitleTitan',false); - console.debug('"Title Titan" has ended.') + if(debugLogs) console.debug('"Title Titan" has ended.') } if (this.getSettingBoolean('boosterFactorPrecisionPrism') == true && isMinutesPassed(window.moment(this.getSettingString('boosterDatePrecisionPrism'), 'YYYY-MM-DD HH:mm:ss'),getBoosterRunTimeFromVarName('precisionPrism'))){ this.setSettingBoolean('boosterFactorPrecisionPrism',false); - console.debug('"Precision Prism" has ended.') + if(debugLogs) console.debug('"Precision Prism" has ended.') } if (this.getSettingBoolean('boosterFactorHyperlinkHarmony') == true && isMinutesPassed(window.moment(this.getSettingString('boosterDateHyperlinkHarmony'), 'YYYY-MM-DD HH:mm:ss'),getBoosterRunTimeFromVarName('hyperlinkHarmony'))){ this.setSettingBoolean('boosterFactorHyperlinkHarmony',false); - console.debug('"Hyperlink Harmony" has ended.') + if(debugLogs) console.debug('"Hyperlink Harmony" has ended.') } if (this.getSettingBoolean('boosterFactorEphemeralEuphoria') == true && isMinutesPassed(window.moment(this.getSettingString('boosterDateEphemeralEuphoria'), 'YYYY-MM-DD HH:mm:ss'),getBoosterRunTimeFromVarName('ephemeralEuphoria'))){ this.setSettingBoolean('boosterFactorEphemeralEuphoria',false); - console.debug('"Ephemeral Euphoria" has ended.') + if(debugLogs) console.debug('"Ephemeral Euphoria" has ended.') } } @@ -670,19 +665,19 @@ export default class gamification extends Plugin { if(newDailyNoteCreationTask == 1){ // update Avatar Page await this.updateAvatarPage(this.getSettingString('avatarPageName')); - console.debug(`${newDailyNoteCreationTask}/2 Notes created today.`) + if(debugLogs) console.debug(`${newDailyNoteCreationTask}/2 Notes created today.`) } else if (newDailyNoteCreationTask == 2) { - this.increaseStreakbooster(streakboosterIncreaseDaily) + await this.increaseStreakbooster(streakboosterIncreaseDaily) await this.saveSettings(); await this.updateStatusBar(this.statusbarGamification) await this.giveStatusPoints(pointsForDailyChallenge,'formIncreaseDailyCreatedNoteCount') const message = getRandomMessageTwoNoteChallenge(pointsForDailyChallenge * (this.getSettingNumber('badgeBoosterFactor') + this.getSettingNumber('streakbooster'))); - console.debug(`daily Challenge reached! ${newDailyNoteCreationTask}/2 created.`) + if(debugLogs) console.debug(`daily Challenge reached! ${newDailyNoteCreationTask}/2 created.`) new Notice(message,this.getSettingNumber('timeShowNotice') * 1000) - console.debug(message) + if(debugLogs) console.debug(message) } else { // nothing else to do here - console.debug(`${newDailyNoteCreationTask}/2 Notes created today.`) + if(debugLogs) console.debug(`${newDailyNoteCreationTask}/2 Notes created today.`) } } } @@ -693,7 +688,7 @@ export default class gamification extends Plugin { await this.checkForWeeklyNoteChallengeBelow7(); } else if (isSameDay(window.moment(this.getSettingString('weeklyNoteCreationDate'), 'DD.MM.YYYY'))){ // do nothing - console.debug(`daily note creation was rated already today.`) + if(debugLogs) console.debug(`daily note creation was rated already today.`) } else { this.setSettingString('weeklyNoteCreationDate', window.moment().format('DD.MM.YYYY')) this.setSettingNumber('weeklyNoteCreationTask', 1); @@ -719,19 +714,19 @@ export default class gamification extends Plugin { if (newWeeklyNoteCreationTask <= 6) { // update Avatar Page await this.updateAvatarPage(this.getSettingString('avatarPageName')); - console.debug(`${newWeeklyNoteCreationTask}/7 Notes created in a chain.`) + if(debugLogs) console.debug(`${newWeeklyNoteCreationTask}/7 Notes created in a chain.`) } else if (newWeeklyNoteCreationTask == 7) { - this.increaseStreakbooster(streakboosterIncreaseWeekly); + await this.increaseStreakbooster(streakboosterIncreaseWeekly); await this.saveSettings(); await this.updateStatusBar(this.statusbarGamification) await this.giveStatusPoints(pointsForWeeklyChallenge, 'fromCheckForWeeklyNoteChallengeEvaluation') - console.debug(`Weekly Challenge reached! ${newWeeklyNoteCreationTask}/7 created in a chain.`) + if(debugLogs) console.debug(`Weekly Challenge reached! ${newWeeklyNoteCreationTask}/7 created in a chain.`) const message = getRandomMessageWeeklyChallenge(pointsForWeeklyChallenge * (this.getSettingNumber('badgeBoosterFactor') + this.getSettingNumber('streakbooster'))); new Notice(message,this.getSettingNumber('timeShowNotice') * 1000) - console.debug(message) + if(debugLogs) console.debug(message) } else { // nothing else to do here - console.debug(`${newWeeklyNoteCreationTask}/7 Notes created in a chain.`) + if(debugLogs) console.debug(`${newWeeklyNoteCreationTask}/7 Notes created in a chain.`) } } @@ -773,7 +768,7 @@ export default class gamification extends Plugin { async loadSettings() { this.settings = Object.assign({}, defaultSettings, await this.loadData()); - console.debug('loadSettings()') + if(debugLogs) console.debug('loadSettings()') } @@ -784,7 +779,7 @@ export default class gamification extends Plugin { async giveStatusPoints(pointsToAdd: number, caller: string): Promise{ let boosterFactor = 1; - let streakbooster = this.getSettingNumber('streakbooster'); + const streakbooster = this.getSettingNumber('streakbooster'); let boosterFactorPerpetualProgress = 0; let boosterFactorStrategicSynapses = 0; let boosterFactorLinkersLode = 0; @@ -846,13 +841,13 @@ export default class gamification extends Plugin { if(newBoosterFakfor > 80){ newBoosterFakfor = 80; } - console.debug(`newBoosterFakfor: ${newBoosterFakfor}`) - //console.debug(`old value streakbooster: ${this.getSettingNumber('streakbooster')}`) + if(debugLogs) console.debug(`newBoosterFakfor: ${newBoosterFakfor}`) + //if(debugLogs) console.debug(`old value streakbooster: ${this.getSettingNumber('streakbooster')}`) this.setSettingNumber('streakbooster', newBoosterFakfor); this.setSettingBoolean('streakboosterDate', true); - //console.debug(`new value streakbooster: ${this.getSettingNumber('streakbooster')}`) + //if(debugLogs) console.debug(`new value streakbooster: ${this.getSettingNumber('streakbooster')}`) //await this.saveData(this.settings) - //console.debug(`streakbooster: ${this.getSettingNumber('streakbooster')}`) + //if(debugLogs) console.debug(`streakbooster: ${this.getSettingNumber('streakbooster')}`) } @@ -872,7 +867,7 @@ export default class gamification extends Plugin { try { const existingFile = this.app.vault.getAbstractFileByPath(`${avatarPageName}.md`); if (existingFile == null) { - console.debug(`File ${avatarPageName}.md does not exist`); + if(debugLogs) console.debug(`File ${avatarPageName}.md does not exist`); return false; } const file = existingFile as TFile; @@ -973,7 +968,7 @@ export default class gamification extends Plugin { async giveBadgeInProfile(avatarPageName: string, badge: Badge){ const existingFile = this.app.vault.getAbstractFileByPath(`${avatarPageName}.md`); if (existingFile == null) { - console.debug(`File ${avatarPageName}.md does not exist`); + if(debugLogs) console.debug(`File ${avatarPageName}.md does not exist`); return; } const file = existingFile as TFile; @@ -1011,7 +1006,7 @@ export default class gamification extends Plugin { const newLines = [...lines.slice(0, start), badgeString, ...lines.slice(end)]; const newLines2 = [...newLines.slice(0, start2), ...newLines.slice(end2)] await this.app.vault.modify(file, newLines2.join("\n")); - //console.debug(`badgeString: ${badgeString}`) + //if(debugLogs) console.debug(`badgeString: ${badgeString}`) } } @@ -1019,7 +1014,7 @@ export default class gamification extends Plugin { async giveInitBadgeInProfile(avatarPageName: string, badge: Badge){ const existingFile = this.app.vault.getAbstractFileByPath(`${avatarPageName}.md`); if (existingFile == null) { - console.debug(`File ${avatarPageName}.md does not exist`); + if(debugLogs) console.debug(`File ${avatarPageName}.md does not exist`); return; } const file = existingFile as TFile; @@ -1045,7 +1040,7 @@ export default class gamification extends Plugin { const badgeString = "**" + badge.name + "**\n> " + badge.description + " - *" + window.moment().format('D.M.YY') + "*\n" const newLines = [...lines.slice(0, start), badgeString, ...lines.slice(end)]; await this.app.vault.modify(file, newLines.join("\n")); - console.debug(`badgeString: ${badgeString}`) + if(debugLogs) console.debug(`badgeString: ${badgeString}`) } } @@ -1053,7 +1048,7 @@ export default class gamification extends Plugin { async removeBadgesWhenInitLevelHigher(avatarPageName: string, level: number){ const existingFile = this.app.vault.getAbstractFileByPath(`${avatarPageName}.md`); if (existingFile == null) { - console.debug(`File ${avatarPageName}.md does not exist`); + if(debugLogs) console.debug(`File ${avatarPageName}.md does not exist`); return; } const file = existingFile as TFile; @@ -1133,7 +1128,7 @@ export default class gamification extends Plugin { let charStringModified = "" for (const [value] of fileDateMonthMapMod) { - //console.debug(`key: ${key}, value: ${value}`); + //if(debugLogs) console.debug(`key: ${key}, value: ${value}`); charStringModified = charStringModified + value + ", " } charStringModified = charStringModified.slice(0,charStringModified.length-2) @@ -1147,7 +1142,7 @@ export default class gamification extends Plugin { if(result){ const badge : Badge = getBadgeForLevel(this.getSettingNumber('statusLevel'), false) new Notice(`You've earned the "${badge.name}" badge. ${badge.description}`,this.getSettingNumber('timeShowNotice') * 1000 * 1.2) - console.debug(`You've earned the "${badge.name}" badge. ${badge.description}`) + if(debugLogs) console.debug(`You've earned the "${badge.name}" badge. ${badge.description}`) this.giveBadgeInProfile(this.getSettingString('avatarPageName'), badge) this.setSettingBoolean('badgeBoosterState', false); this.setSettingNumber('badgeBoosterFactor', 1); @@ -1168,7 +1163,7 @@ export default class gamification extends Plugin { console.warn(`File ${fileName} not found.`); continue; } - console.debug(`Processing file ${fileName}`); + if(debugLogs) console.debug(`Processing file ${fileName}`); try { await this.app.fileManager.processFrontMatter(file, (frontmatter) => { delete frontmatter['title-class'] @@ -1180,14 +1175,14 @@ export default class gamification extends Plugin { }); } catch (e) { if (e?.name === 'YAMLParseError') { - const errorMessage = `Update majuritys failed Malformed frontamtter ${e.message}`; + const errorMessage = `Update majuritys failed Malformed frontmatter ${e.message}`; new Notice(errorMessage, this.getSettingNumber('timeShowNotice') * 1000); console.error(errorMessage); } } } } else { - console.debug(`No files in vault found to remove frontmatter keys from`) + if(debugLogs) console.debug(`No files in vault found to remove frontmatter keys from`) } } @@ -1222,14 +1217,14 @@ export default class gamification extends Plugin { const nextBadgeAt = await this.whichLevelNextBadge(this.getSettingNumber('statusLevel')) if (nextBadgeAt != null){ const statusPointsToReach = statusPointsForLevel(nextBadgeAt) - //console.debug(`statusPointsToReach for next Badge: ${statusPointsToReach}`) + //if(debugLogs) console.debug(`statusPointsToReach for next Badge: ${statusPointsToReach}`) // 50 Notes from Level 1 to 5 to get the first badge. // 300 Points in average for a Note. const boosterFactor = Math.round((statusPointsToReach - this.getSettingNumber('statusPoints'))/50/300); this.setSettingNumber('badgeBoosterFactor', boosterFactor) this.setSettingBoolean('badgeBoosterState', true) //await this.saveData(this.settings) - //console.debug(`boosterFaktor: ${boosterFactor}`) + //if(debugLogs) console.debug(`boosterFaktor: ${boosterFactor}`) return boosterFactor } else { return 0 @@ -1248,39 +1243,39 @@ export default class gamification extends Plugin { const sourcePath = this.app.workspace.getActiveFile()?.path || ''; await this.app.workspace.openLinkText(existingFile.path, sourcePath); } else { - console.debug("File not found or unable to open."); + if(debugLogs) console.debug("File not found or unable to open."); } } getRandomInt(min: number, max: number) { return Math.floor(Math.random() * (max - min + 1)) + min; - } + } async acquireIngredients(chance:number, min:number, max:number) { - let earnedIngredientToShow = []; + const earnedIngredientToShow = []; if (Math.random() < chance) { const randomAmount = this.getRandomInt(min,max); for (let i=1;i<=randomAmount;i++){ const randomIngredientIndex = this.getRandomInt(0, listOfUseableIngredientsToBeShown.length-1); const earnedIngredient = elements[randomIngredientIndex]; - let elementCount = this.getSettingNumber(earnedIngredient.varName); + const elementCount = this.getSettingNumber(earnedIngredient.varName); earnedIngredientToShow.push(earnedIngredient.name); // Perform a null check if (elementCount !== null && typeof elementCount === 'number') { this.setSettingNumber(earnedIngredient.varName, elementCount + 1); - this.saveSettings(); + await this.saveSettings(); } else { console.error(`Invalid element count for ${earnedIngredient.varName}`); } } - console.debug(`You earned: ${concatenateStrings(earnedIngredientToShow)}`); + if(debugLogs) console.debug(`You earned: ${concatenateStrings(earnedIngredientToShow)}`); new Notice(`You earned ${concatenateStrings(earnedIngredientToShow)}`,this.getSettingNumber('timeShowNotice') * 1000) } else { new Notice(`This time you didn't earn an ingredient.`,this.getSettingNumber('timeShowNotice') * 1000) - console.debug('You did not earn an ingredient this time.'); + if(debugLogs) console.debug('You did not earn an ingredient this time.'); } } @@ -1378,7 +1373,7 @@ async function createAvatarFile(app: App, fileName: string) { const existingFile = this.app.vault.getAbstractFileByPath(`${fileName}.md`); if (existingFile instanceof TFile) { - console.debug(`File ${fileName}.md already exists`); + if(debugLogs) console.debug(`File ${fileName}.md already exists`); return; } // Create the file in the root of the vault diff --git a/src/majuritycalculation.ts b/src/majuritycalculation.ts index 0c807a6..4b37172 100644 --- a/src/majuritycalculation.ts +++ b/src/majuritycalculation.ts @@ -10,7 +10,7 @@ export function rateProgressiveSummarization(charCountTotal: number, layer2count var majurity = 0; if (charCountTotal < 3000) { majurity = 0; - //console.debug(`Note is not long enough to get into calculation for majurity. The total character count is ${charCountTotal}`); + //if(debugLogs) console.debug(`Note is not long enough to get into calculation for majurity. The total character count is ${charCountTotal}`); } else { if (percentLayer2 == 0) { layer2majurity = 0; @@ -54,9 +54,9 @@ export function rateProgressiveSummarization(charCountTotal: number, layer2count } - //console.debug(`layer2majurity: ${layer2majurity} \tlayer3majurity: ${layer3majurity} \tmajurity: ${majurity}`); - //console.debug(`percentLayer2: ${percentLayer2} \tpercentLayer3: ${percentLayer3} \tmajurity: ${majurity}`); - //console.debug(`charCountTotal: ${charCountTotal}`); + //if(debugLogs) console.debug(`layer2majurity: ${layer2majurity} \tlayer3majurity: ${layer3majurity} \tmajurity: ${majurity}`); + //if(debugLogs) console.debug(`percentLayer2: ${percentLayer2} \tpercentLayer3: ${percentLayer3} \tmajurity: ${majurity}`); + //if(debugLogs) console.debug(`charCountTotal: ${charCountTotal}`); return majurity; } @@ -64,38 +64,38 @@ export function rateProgressiveSummarization(charCountTotal: number, layer2count export function countLayer2AndLayer3Characters(content: string, filename: string, layer2: string, layer3: string): { charCount: number; highlightedCount: number; boldCount: number } { const filenameWithoutExtension = filename; //.slice(0, -filename.length); - // console.debug(`filenameWithoutExtension: ${filenameWithoutExtension}`); + // if(debugLogs) console.debug(`filenameWithoutExtension: ${filenameWithoutExtension}`); // Remove markdown formatting symbols const strippedContent = content.replace(/[*_~`]/g, ""); - // console.debug(`filenameWithoutExtension: ${filenameWithoutExtension}`); + // if(debugLogs) console.debug(`filenameWithoutExtension: ${filenameWithoutExtension}`); // Remove markdown headings that match the filename const headingRegex = /^(#+)\s(.*)$/gm; const contentWithoutHeadings = strippedContent.replace(headingRegex, (match, p1, p2) => { - // console.debug(`p2: ${p2}`); + // if(debugLogs) console.debug(`p2: ${p2}`); if (p2 === filenameWithoutExtension) { return ""; } return match; }); - // console.debug(`contentWithoutHeadings: ${contentWithoutHeadings}`); + // if(debugLogs) console.debug(`contentWithoutHeadings: ${contentWithoutHeadings}`); // Remove metadata blocks from count const metadataRegex = /^---[\s\S]*?---/gm; const contentWithoutMetadata = contentWithoutHeadings.replace(metadataRegex, ""); - // console.debug(`contentWithoutMetadata: ${contentWithoutMetadata}`); + // if(debugLogs) console.debug(`contentWithoutMetadata: ${contentWithoutMetadata}`); // Remove #tags from count const tagRegex = /#[^\s]+/g; const contentWithoutTags = contentWithoutMetadata.replace(tagRegex, ""); - // console.debug(`contentWithoutTags: ${contentWithoutTags}`); + // if(debugLogs) console.debug(`contentWithoutTags: ${contentWithoutTags}`); // Remove links and Wikipedia-links from count const linkRegex = /\[.*?\]\(.*?\)|\[\[.*?\]\]/g; const contentWithoutLinks = contentWithoutTags.replace(linkRegex, ""); - // console.debug(`contentWithoutLinks: ${contentWithoutLinks}`); + // if(debugLogs) console.debug(`contentWithoutLinks: ${contentWithoutLinks}`); // Remove blank newlines const filteredContent: string = contentWithoutLinks @@ -103,11 +103,11 @@ export function countLayer2AndLayer3Characters(content: string, filename: string .filter(line => line.trim() !== '') // Filter out lines that are empty or contain only whitespace .filter(line => line.trim() !== '---') // remove --- on single lines .join('\n'); // Join the remaining lines back into a string, separated by newlines - // console.debug(`filteredContent: ${filteredContent}`); + // if(debugLogs) console.debug(`filteredContent: ${filteredContent}`); // Count the remaining characters const charCount = filteredContent.length; - // console.debug(`charCount: ${charCount}`); + // if(debugLogs) console.debug(`charCount: ${charCount}`); // calculate Layer 2 & 3 Length @@ -156,7 +156,7 @@ export function countLayer2AndLayer3Characters(content: string, filename: string export function rateLevelOfMaturity(noteLength: number, lengthOfTitle: number, Inlinks: number, outgoingLinks: number, progressiveSumMajurity: number): number { - // console.debug(`noteLength: ${noteLength}\tlengthOfTitle: ${lengthOfTitle}\tInlinks: ${Inlinks}\toutgoingLinks: ${outgoingLinks}`) + // if(debugLogs) console.debug(`noteLength: ${noteLength}\tlengthOfTitle: ${lengthOfTitle}\tInlinks: ${Inlinks}\toutgoingLinks: ${outgoingLinks}`) // decide if noteLength-majurity or progressiveSum-majurity shall be used var lengthMajurity = 0; @@ -168,7 +168,7 @@ export function rateLevelOfMaturity(noteLength: number, lengthOfTitle: number, I const totalWeight : number = lengthMajurity + lengthOfTitle + Inlinks + outgoingLinks; const averageWeight = totalWeight / 5; - // console.debug(`totalWeight: ${totalWeight}\taverageWeight: ${averageWeight}`) + // if(debugLogs) console.debug(`totalWeight: ${totalWeight}\taverageWeight: ${averageWeight}`) if (averageWeight < 0.5) { return 0; } else if (averageWeight <= 1) { @@ -188,7 +188,7 @@ export function rateLevelOfMaturity(noteLength: number, lengthOfTitle: number, I export function rateOutlinks(outlinks: number): number { - // console.debug(`outlinks: ${outlinks}`) + // if(debugLogs) console.debug(`outlinks: ${outlinks}`) if (outlinks < 2) { return 0; } else if (outlinks < 3) { @@ -209,7 +209,7 @@ export function rateOutlinks(outlinks: number): number { export function rateInlinks(numInlinks: number): number { //var prozentInlinks = numInlinks * 100 / numAllFiles; - //console.debug(`numInlinks: ${numInlinks}\tnumAllFiles: ${numAllFiles}\tprozentInlinks: ${prozentInlinks}`) + //if(debugLogs) console.debug(`numInlinks: ${numInlinks}\tnumAllFiles: ${numAllFiles}\tprozentInlinks: ${prozentInlinks}`) /*if (prozentInlinks < 0.005 || prozentInlinks > 0.1) { return 0; } else */ if (numInlinks == 0) { @@ -301,38 +301,38 @@ export function getNumberOfOutlinks(activeFile: TFile): number { export function countCharactersInActiveFile(content: string, filename: string): number { const filenameWithoutExtension = filename; //.slice(0, -filename.length); - // console.debug(`filenameWithoutExtension: ${filenameWithoutExtension}`); + // if(debugLogs) console.debug(`filenameWithoutExtension: ${filenameWithoutExtension}`); // Remove markdown formatting symbols const strippedContent = content.replace(/[*_~`]/g, ""); - // console.debug(`filenameWithoutExtension: ${filenameWithoutExtension}`); + // if(debugLogs) console.debug(`filenameWithoutExtension: ${filenameWithoutExtension}`); // Remove markdown headings that match the filename const headingRegex = /^(#+)\s(.*)$/gm; const contentWithoutHeadings = strippedContent.replace(headingRegex, (match, p1, p2) => { - // console.debug(`p2: ${p2}`); + // if(debugLogs) console.debug(`p2: ${p2}`); if (p2 === filenameWithoutExtension) { return ""; } return match; }); - // console.debug(`contentWithoutHeadings: ${contentWithoutHeadings}`); + // if(debugLogs) console.debug(`contentWithoutHeadings: ${contentWithoutHeadings}`); // Remove metadata blocks from count const metadataRegex = /^---[\s\S]*?---/gm; const contentWithoutMetadata = contentWithoutHeadings.replace(metadataRegex, ""); - // console.debug(`contentWithoutMetadata: ${contentWithoutMetadata}`); + // if(debugLogs) console.debug(`contentWithoutMetadata: ${contentWithoutMetadata}`); // Remove #tags from count const tagRegex = /#[^\s]+/g; const contentWithoutTags = contentWithoutMetadata.replace(tagRegex, ""); - // console.debug(`contentWithoutTags: ${contentWithoutTags}`); + // if(debugLogs) console.debug(`contentWithoutTags: ${contentWithoutTags}`); // Remove links and Wikipedia-links from count const linkRegex = /\[.*?\]\(.*?\)|\[\[.*?\]\]/g; const contentWithoutLinks = contentWithoutTags.replace(linkRegex, ""); - // console.debug(`contentWithoutLinks: ${contentWithoutLinks}`); + // if(debugLogs) console.debug(`contentWithoutLinks: ${contentWithoutLinks}`); // Remove blank newlines const filteredContent: string = contentWithoutLinks @@ -340,11 +340,11 @@ export function countCharactersInActiveFile(content: string, filename: string): .filter(line => line.trim() !== '') // Filter out lines that are empty or contain only whitespace .filter(line => line.trim() !== '---') // remove --- on single lines .join('\n'); // Join the remaining lines back into a string, separated by newlines - // console.debug(`filteredContent: ${filteredContent}`); + // if(debugLogs) console.debug(`filteredContent: ${filteredContent}`); // Count the remaining characters const charCount = filteredContent.length; - // console.debug(`charCount: ${charCount}`); + // if(debugLogs) console.debug(`charCount: ${charCount}`); return charCount; } @@ -473,7 +473,7 @@ export const getFileMap = async (app: App, excludeTag: string, excludeFolder: st } else { excludedSubstrings = excludeTag.split(', '); } - //console.debug(`excludedSubstrings: ${excludedSubstrings}`) + //if(debugLogs) console.debug(`excludedSubstrings: ${excludedSubstrings}`) // folders to ignore .md-files in let excludedFolders : string[] = [] if (excludeFolder == undefined) { @@ -482,16 +482,16 @@ export const getFileMap = async (app: App, excludeTag: string, excludeFolder: st excludedFolders = excludeFolder.split(', '); } excludedFolders.push('.obsidian', '.trash'); // hardcode the basic folders - //console.debug(`excludedFolders: ${excludedFolders}`) + //if(debugLogs) console.debug(`excludedFolders: ${excludedFolders}`) let fileArray: TFile[] = []; const files = await vault.getMarkdownFiles(); for (const file of files) { const fileContents = await app.vault.read(file); - //console.debug(`file.path: ${file.path}`) + //if(debugLogs) console.debug(`file.path: ${file.path}`) if ((!excludedSubstrings.some(substring => fileContents.includes(substring)) || excludeTag.length === 0) && !excludedFolders.some(folder => file.path.includes(folder))) { - //console.debug(`file ${file} get's added.`) + //if(debugLogs) console.debug(`file ${file} get's added.`) fileArray.push(file) } } diff --git a/src/settings.ts b/src/settings.ts index 9ad03cf..2d67116 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -2,6 +2,7 @@ import { App, PluginSettingTab, Setting } from 'obsidian'; import gamification from './main'; import type {MomentInput} from 'moment'; import { encryptValue, encryptString, decryptString, encryptNumber, decryptNumber, encryptBoolean, decryptBoolean } from 'encryption'; +import { debugLogs } from './constants'; export const defaultSettings: Partial = { enableInitCommand: "U2FsdGVkX1+7lWe/h95uqzgl27JBGW2iki7sBwk44YQ=", @@ -299,7 +300,7 @@ export class GamificationPluginSettings extends PluginSettingTab { //const { containerEl } = this; //containerEl.empty(); - console.debug('settings called') + if(debugLogs) console.debug('settings called') new Setting(containerEl) .setName('#tags to ignore') .setDesc('Enter tags without # and separate with ", ".\nInclude nested tags.') @@ -321,7 +322,7 @@ export class GamificationPluginSettings extends PluginSettingTab { //.setValue(this.plugin.settings.folderExclude) .setValue(decryptString(this.plugin.settings.folderExclude)) .onChange(async (value) => { - // console.debug('folder to exclude: ' + value); + // if(debugLogs) console.debug('folder to exclude: ' + value); this.plugin.settings.folderExclude = encryptString(value); await this.plugin.saveSettings(); })); @@ -334,7 +335,7 @@ export class GamificationPluginSettings extends PluginSettingTab { //.setValue(this.plugin.settings.avatarPageName) .setValue(decryptString(this.plugin.settings.avatarPageName)) .onChange(async (value) => { - // console.debug('folder to exclude: ' + value); + // if(debugLogs) console.debug('folder to exclude: ' + value); this.plugin.settings.avatarPageName = encryptString(value); await this.plugin.saveSettings(); })); @@ -383,7 +384,7 @@ export class GamificationPluginSettings extends PluginSettingTab { .setPlaceholder('Layer 2 is usually **') .setValue(decryptString(this.plugin.settings.progressiveSumLayer2)) .onChange(async (value) => { - // console.debug('folder to exclude: ' + value); + // if(debugLogs) console.debug('folder to exclude: ' + value); this.plugin.settings.progressiveSumLayer2 = encryptString(value); await this.plugin.saveSettings(); })) @@ -391,7 +392,7 @@ export class GamificationPluginSettings extends PluginSettingTab { .setPlaceholder('Layer 3 is usually ==') .setValue(decryptString(this.plugin.settings.progressiveSumLayer3)) .onChange(async (value) => { - // console.debug('folder to exclude: ' + value); + // if(debugLogs) console.debug('folder to exclude: ' + value); this.plugin.settings.progressiveSumLayer3 = encryptString(value); await this.plugin.saveSettings(); })); diff --git a/styles.css b/styles.css index ae0d9b8..9ea962c 100644 --- a/styles.css +++ b/styles.css @@ -34,11 +34,15 @@ } .modal-checkbox-container { - margin-bottom: 10px; display: flex; align-items: center; + gap: 10px; } .modal-checkbox-container input[type="checkbox"] { margin-right: 5px; +} + +.modal-button { + margin-right: 10px; } \ No newline at end of file