Skip to content

Commit

Permalink
Merge pull request #63 from rohanb10/repeat
Browse files Browse the repository at this point in the history
Merge Repeated Snoozes into the main branch
  • Loading branch information
rohanb10 authored Oct 17, 2021
2 parents 195345e + 9e4b230 commit d8de537
Show file tree
Hide file tree
Showing 11 changed files with 107 additions and 107 deletions.
5 changes: 3 additions & 2 deletions build.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ def minifyFilesInDirectory(directory, ext, url):
for root, dirs, files in os.walk(directory):
for name in files:
chars = len(ext)
if name.endswith('.min' + ext):
if ext == '.js' or name.endswith('.min' + ext):
# if name.endswith(ext):
shutil.copyfile(os.path.join(root, name), FOLDER + '/' + directory + '/' + name)
elif name.endswith(ext):
print('\n⧖ Minifying ' + '\x1b[1;32;33m' + name + '\x1b[0m ...', end='')
Expand All @@ -67,7 +68,7 @@ def replaceInHTMLFiles(original, replacement):
file.write(data)
file.close()

minifyFilesInDirectory('scripts', '.js', 'https://javascript-minifier.com/raw')
minifyFilesInDirectory('scripts', '.js', 'https://www.toptal.com/developers/javascript-minifier/raw')
minifyFilesInDirectory('styles', '.css', 'https://cssminifier.com/raw')

#
Expand Down
3 changes: 2 additions & 1 deletion html/nap-room.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
</div>
<div tabindex="0" data-hover="Settings" class="settings"><img src="../icons/settings.png"></div>
<div class="changelog-overlay">
<div id="changelog"><!-- <div id="changelog" class="disabled"> -->
<div id="changelog">
<!-- <div id="changelog" class="disabled"> -->
<div class="changelog-container">
<h2 class="center">Snoozz has been updated <span id="v"></span>&nbsp;🎉</h2>
<p>This version is a huge update that brings in one of the most requested features.</p>
Expand Down
1 change: 1 addition & 0 deletions html/rise-and-shine.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
<div class="tab-list"></div>
</div>

<script type="text/javascript" src="../scripts/gradient.min.js"></script>
<script type="text/javascript" src="../scripts/dayjs.min.js"></script>
<script type="text/javascript" src="../scripts/common.js"></script>
<script type="text/javascript" src="../scripts/rise.js"></script>
Expand Down
2 changes: 1 addition & 1 deletion html/settings.html
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ <h4>Custom Keyboard Shortcuts</h4>
<div tabindex="0" class="btn"><div></div></div>
<div class="mini firefox-info">
<strong>Instructions</strong>
<div>Firefox shortcuts can only be configured on a different page, outside of this extension. To configure your custom shortcuts:</div>
<div>Firefox shortcuts can only be <a target="_blank" href="https://support.mozilla.org/en-US/kb/manage-extension-shortcuts-firefox">configured</a> on a different page, outside of this extension. To configure your custom shortcuts:</div>
<ol>
<li>Open the Firefox Add-Ons page in a new tab: <u><code>about:addons</code></u> (Click URL to copy).</li>
<li>Click on the <a tabindex="0" target="_blank" href="https://bug1303384.bmoattachments.org/attachment.cgi?id=9051647">gear icon</a> in the top right and select <strong>Manage Extension Shortcuts</strong>.</li>
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "Snoozz - Snooze Tabs & Windows for later",
"short_name": "Snoozz",
"description": "Declutter your browser by snoozing tabs and windows until you actually need them.",
"version": "2.4.4.3",
"version": "2.5.0",

"icons": {
"128": "icons/ext-icon-128.png",
Expand Down
12 changes: 7 additions & 5 deletions scripts/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,10 @@ async function wakeUpTask(cachedTabs) {

var debounce;
async function setNextAlarm(tabs) {
var next = sleeping(tabs).filter(t => t.wakeUpTime && !t.paused).reduce((t1,t2) => t1.wakeUpTime < t2.wakeUpTime ? t1 : t2);
if (next && next.wakeUpTime <= dayjs().valueOf()) {
var next = sleeping(tabs).filter(t => t.wakeUpTime && !t.paused);
next = next.length ? next.reduce((t1,t2) => t1.wakeUpTime < t2.wakeUpTime ? t1 : t2) : undefined;
if (!next) return;
if (next.wakeUpTime <= dayjs().valueOf()) {
clearTimeout(debounce)
debounce = setTimeout(_ => wakeMeUp(tabs), 3000)
} else {
Expand Down Expand Up @@ -198,8 +200,8 @@ function sendToLogs([which, p1]) {

async function init() {
var allTabs = await getSnoozedTabs();
if (allTabs && allTabs.length && allTabs.some(t => t.startUp && !t.opened)) {
allTabs.filter(t => t.startUp && !t.opened).forEach(t => t.wakeUpTime = dayjs().subtract(10, 's').valueOf());
if (allTabs && allTabs.length && allTabs.some(t => (t.startUp || (t.repeat && t.repeat.type === 'startup')) && !t.opened)) {
allTabs.filter(t => (t.startUp || (t.repeat && t.repeat.type === 'startup')) && !t.opened).forEach(t => t.wakeUpTime = dayjs().subtract(10, 's').valueOf());
await saveTabs(allTabs);
}
await wakeUpTask();
Expand All @@ -210,7 +212,7 @@ chrome.runtime.onInstalled.addListener(async details => {
setUpExtension();
if (chrome.runtime.setUninstallURL) chrome.runtime.setUninstallURL('https://tally.so/r/mO5GYw');
if (details && details.reason && details.reason == 'update' && details.previousVersion && details.previousVersion != chrome.runtime.getManifest().version) {
if (chrome.runtime.getManifest().version.search(/^\d\.\d\.\d$/) !== 0) return; // skip if minor version
if (chrome.runtime.getManifest().version.search(/^\d{1,3}(\.\d{1,3}){1,2}$/) !== 0) return; // skip if minor version
await new Promise(r => chrome.storage.local.set({'updated': true}, r));
if (chrome.notifications) createNotification(null, 'Snoozz has been updated', 'icons/logo.svg', 'Click here to see what\'s new.', true);
}
Expand Down
97 changes: 34 additions & 63 deletions scripts/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,23 +197,37 @@ async function openWindow(t, automatic = false) {
return;
}

async function dupeSnoozedTab(tabId, snoozeTime) {
async function editSnoozed(tabId, snoozeTime, duplicating) {
var t = await getSnoozedTabs(tabId);
['startUp', 'opened', 'deleted', 'repeat', 'paused'].forEach(prop => delete t[prop]);
t.wakeUpTime = snoozeTime === 'startup' ? dayjs().add(20, 'y').valueOf() : dayjs(snoozeTime).valueOf(),
t.timeCreated = dayjs().valueOf();
t.id = getRandomId();
t.id = duplicating ? getRandomId() : t.id;
if (snoozeTime === 'startup') t.startUp = true;
await saveTab(t);
return {duped: true}
return duplicating ? {duped: true} : {edited: true}
}

async function editSnoozeTime(tabId, snoozeTime) {
async function editRecurringSnoozed(tabId, data, duplicating) {
var t = await getSnoozedTabs(tabId);
['startUp', 'opened', 'deleted', 'paused'].forEach(prop => delete t[prop]);
t.wakeUpTime = await calculateNextSnoozeTime(data);
t.timeCreated = dayjs().valueOf();
if (data.repeat === 'startup') t.startUp = true;
t.repeat = data;
t.id = duplicating ? getRandomId() : t.id;
await saveTab(t);
return duplicating ? {duped: true} : {edited: true}
}

async function editSnoozeRecurring(tabId, data, ) {
var t = await getSnoozedTabs(tabId);
['startUp', 'opened', 'deleted', 'repeat', 'paused'].forEach(prop => delete t[prop]);
t.wakeUpTime = snoozeTime === 'startup' ? dayjs().add(20, 'y').valueOf() : dayjs(snoozeTime).valueOf(),
if (data.repeat === 'startup') t.startUp = true;
t.wakeUpTime = await calculateNextSnoozeTime(data);
t.modifiedTime = dayjs().valueOf();
if (snoozeTime === 'startup') t.startUp = true;
t.repeat = data;
t.paused = false;
await saveTab(t);
return {edited: true}
}
Expand All @@ -224,7 +238,7 @@ async function snoozeTab(snoozeTime, overrideTab) {
if (!activeTab || !activeTab.url) return {};
var sleepyTab = {
id: getRandomId(),
title: activeTab.title ?? getBetterUrl(activeTab.url),
title: activeTab.title || getBetterUrl(activeTab.url),
url: activeTab.url,
...activeTab.pinned ? {pinned: true} : {},
wakeUpTime: snoozeTime === 'startup' ? dayjs().add(20, 'y').valueOf() : dayjs(snoozeTime).valueOf(),
Expand Down Expand Up @@ -290,14 +304,14 @@ async function snoozeRecurring(target, data) {
if (data.repeat === 'startup') sleepyObj.startUp = true;

sleepyObj.wakeUpTime = await calculateNextSnoozeTime(data);
console.log(dayjs(sleepyObj.wakeUpTime).format('DD/MM/YY HH:mm'));
// console.log(dayjs(sleepyObj.wakeUpTime).format('DD/MM/YY HH:mm'));

if (validTabs.length === 0) return {};
if (validTabs.length === 1 || target === 'tab') {
var activeTab = validTabs && validTabs.length ? validTabs[0] : await getTabsInWindow(true);
if (!activeTab || !activeTab.url) return {};
Object.assign(sleepyObj, {
title: activeTab.title ?? getBetterUrl(activeTab.url),
title: activeTab.title || getBetterUrl(activeTab.url),
url: activeTab.url,
...activeTab.pinned ? {pinned: true} : {},
});
Expand Down Expand Up @@ -325,7 +339,7 @@ async function getTimeWithModifier(choice) {
var options = await getOptions(['morning', 'evening', 'popup']);
var modifier = options.popup ? options.popup[choice] : '';
options = upgradeSettings(options);
var m = options[modifier] ?? [dayjs().hour(), dayjs().minute()];
var m = options[modifier] || [dayjs().hour(), dayjs().minute()];
return dayjs(c.time).add(m[0], 'h').add(m[1], 'm');
}

Expand Down Expand Up @@ -357,7 +371,7 @@ async function getChoices(which) {
},
'today-morning': {
label: 'This Morning',
repeatLabel: '-',
repeatLabel: '',
time: NOW.startOf('d').add(config.morning[0], 'h').add(config.morning[1], 'm'),
timeString: 'Today',
repeatTime: '',
Expand All @@ -368,7 +382,7 @@ async function getChoices(which) {
},
'today-evening': {
label: `Today ${getEveningLabel(config.evening[0])}`,
repeatLabel: `Everyday`,
repeatLabel: `Everyday, Now`,
time: NOW.startOf('d').add(config.evening[0], 'h').add(config.evening[1], 'm'),
timeString: 'Today',
repeatTime: NOW.format(getHourFormat(true)),
Expand Down Expand Up @@ -445,9 +459,10 @@ async function getChoices(which) {
}

async function calculateNextSnoozeTime(data) {
console.log(data);
var NOW = dayjs(), TYPE = data.type, [HOUR, MINUTE] = data.time;
if (TYPE === 'hourly') {
if (TYPE === 'startup') {
return NOW.add(20, 'y');
} else if (TYPE === 'hourly') {
var isNextHour = NOW.minute() >= MINUTE ? 1 : 0;
return NOW.startOf('h').add(isNextHour, 'h').minute(MINUTE).valueOf();
} else if (TYPE === 'daily') {
Expand Down Expand Up @@ -476,51 +491,6 @@ async function calculateNextSnoozeTime(data) {
return false;
}

// async function calculateNextSnoozeTime(repeat, start, data) {
// var NOW = dayjs(), start = dayjs(start);
// if (repeat === 'custom' && data) {
// var days = [];
// if (data.weekly) {
// var thisWeek = data.weekly, nextWeek = data.weekly.map(day => day + 7);
// days = nextWeek.concat(thisWeek).map(day => dayjs().startOf('w').add(day, 'd').add(start.hour(), 'h').add(start.minute(), 'm'));
// } else if (data.monthly) {
// var thisMonth = data.monthly.filter(d => d <= dayjs().daysInMonth()).map(d => dayjs().startOf('M').date(d).add(start.hour(), 'h').add(start.minute(), 'm'));
// var nextMonth = data.monthly.filter(d => d <= dayjs().add(1, 'M').daysInMonth()).map(d => dayjs().startOf('M').add(1, 'M').date(d).add(start.hour(), 'h').add(start.minute(), 'm'));
// days = nextMonth.concat(thisMonth);
// }
// return days.filter(d => d > NOW).pop();
// } else if (repeat === 'startup') {
// return NOW.add(20, 'y');
// } else if (repeat === 'hourly') {
// var isThisHour = NOW.minute() < start.minute();
// return NOW.startOf('h').add(isThisHour ? 0 : 1, 'h').minute(start.minute());
// } else if (repeat === 'daily') {
// return dayjs().startOf('d').add(1, 'd').hour(NOW.hour()).minute(NOW.minute());
// } else if (repeat === 'daily_morning') {
// var morning = await getOptions('morning');
// var isToday = NOW.hour() < morning[0] || (NOW.hour() === morning[0] && NOW.minute() < morning[1]);
// return NOW.startOf('d').add(isToday ? 0 : 1, 'd').hour(morning[0]).minute(morning[1]);
// } else if (repeat === 'daily_evening') {
// var evening = await getOptions('evening');
// var isToday = NOW.hour() < evening[0] || (NOW.hour() === evening[0] && NOW.minute() < evening[1]);
// return NOW.startOf('d').add(isToday ? 0 : 1, 'd').hour(evening[0]).minute(evening[1]);
// } else if (repeat === 'weekends') {
// var isThisWeek = NOW.day() < 6 || (NOW.day() === 6 && (NOW.hour() < start.hour() || (NOW.hour() === start.hour() && NOW.minute() < start.minute())));
// return NOW.startOf('w').add(isThisWeek ? 0 : 1, 'w').day(6).hour(start.hour()).minute(start.minute());
// } else if (repeat === 'mondays') {
// var isThisWeek = NOW.day() < 1 || (NOW.day() === 1 && (NOW.hour() < start.hour() || (NOW.hour() === start.hour() && NOW.minute() < start.minute())));
// return NOW.startOf('w').add(isThisWeek ? 0 : 1, 'w').day(1).hour(start.hour()).minute(start.minute());
// } else if (repeat === 'weekly') {
// var isThisWeek = NOW.day() < start.day() || (NOW.day() === start.day() && (NOW.hour() < start.hour() || (NOW.hour() === start.hour() && NOW.minute() < start.minute())));
// return NOW.startOf('w').add(isThisWeek ? 0 : 1, 'w').day(start.day()).hour(start.hour()).minute(start.minute());
// } else if (repeat === 'monthly') {
// var isThisMonth = NOW.date() < start.date() || (NOW.date() === start.date() && (NOW.hour() < start.hour() ||( NOW.hour() === start.hour() && NOW.minute() < start.minute()))) ? 0 : 1;
// var isMonthValid = start.date() <= NOW.daysInMonth(isThisMonth, 'M') ? 0 : 1;
// return NOW.startOf('M').add(isThisMonth + isMonthValid, 'M').date(start.date()).hour(start.hour()).minute(start.minute());
// }
// return false;
// }

/* END ASYNC FUNCTIONS */

// var getFaviconUrl = url => `https://icons.duckduckgo.com/ip3/${getHostname(url)}.ico`
Expand Down Expand Up @@ -557,10 +527,10 @@ var sleeping = tabs => tabs.filter(t => !t.opened);
var today = tabs => tabs.filter(t => t.wakeUpTime && dayjs(t.wakeUpTime).dayOfYear() === dayjs().dayOfYear() && dayjs(t.wakeUpTime).year() === dayjs().year())

var isDefault = tabs => tabs.title && ['nap room | snoozz', 'settings | snoozz', 'rise and shine | snoozz', 'New Tab', 'Start Page'].includes(tabs.title);
// var isDefault = tabs => false;

var isValid = tabs => tabs.url && ['http', 'https', 'ftp', 'chrome-extension', 'web-extension', 'moz-extension', 'extension'].includes(tabs.url.substring(0, tabs.url.indexOf(':')));
// var isValid = tabs => true;

var isSameYear = (a, b) => dayjs(a).year() === dayjs(b).year();

var capitalize = s => s.charAt(0).toUpperCase() + s.slice(1);

Expand Down Expand Up @@ -592,12 +562,13 @@ var clipboard = text => {
}

var formatSnoozedUntil = t => {
if (t.startUp) return `Next ${capitalize(getBrowser())} Launch`;
if (t.startUp || (t.repeat && t.repeat.type === 'startup')) return `Next ${capitalize(getBrowser())} Launch`;
var ts = t.wakeUpTime;
var date = dayjs(ts);
if (date.dayOfYear() === dayjs().dayOfYear()) return (date.hour() > 17 ? 'Tonight' : 'Today') + date.format(` [@] ${getHourFormat(date.minute() !== 0)}`);
if (date.dayOfYear() === dayjs().add(1,'d').dayOfYear()) return 'Tomorrow' + date.format(` [@] ${getHourFormat(date.minute() !== 0)}`);
if (date.week() === dayjs().week()) return date.format(`dddd [@] ${getHourFormat(date.minute() !== 0)}`);
if (date.year() !== dayjs().year()) return date.format(`ddd, MMM D, YYYY`);
return date.format(`ddd, MMM D [@] ${getHourFormat(date.minute() !== 0)}`);
}

Expand Down Expand Up @@ -650,7 +621,7 @@ var bgLog = (logs, colors, timestampColor = 'grey') => {
colors.unshift(timestampColor);
colors = colors.flatMap((v,i,a)=>i !== a.length ? [v, ''] : v).map(c => {
var colors = {green:'limegreen', red:'crimson', blue:'dodgerblue', yellow:'gold', pink:'violet', grey:'slategrey', white: 'navajowhite'}
return 'color:' + (colors[c] ?? 'unset')
return 'color:' + (colors[c] || 'unset')
})
console.log(timestamp + logs, ...colors)
}
Expand Down
20 changes: 12 additions & 8 deletions scripts/nap_room.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,10 @@ function search(t, query) {
if (t.startUp && !t.opened && ('start starting launch launching next time open opening').indexOf(query) > -1) return true;
if (!t.opened && ('snoozed sleeping asleep napping snoozzed snoozing snoozzing').indexOf(query) > -1) return true;
if (t.opened && ('manually deleted removed woke awake history').indexOf(query) > -1) return true;
if (t.tabs && t.tabs.length) {
if (t.tabs.map(tt => tt.url.toLowerCase()).some(url => url.indexOf(query) > -1)) return true;
if (t.tabs.map(tt => tt.title.toLowerCase()).some(title => title.indexOf(query) > -1)) return true;
}
// categories
if (matchQuery(query, getTimeGroup(t, 'wakeUpTime', true).map(tg => tg.replace(/_/g, ' ')))) return true;
if (matchQuery(query, getTimeGroup(t, 'timeCreated', true).map(tg => tg.replace(/_/g, ' ')))) return true;
Expand Down Expand Up @@ -253,7 +257,7 @@ function buildTabActions(t, tabDiv) {
editMenuItem = wrapInDiv({className: 'overflow-menu-item edit', innerText: 'Edit Snooze Time', tabIndex: 0});
editMenuItem.onclick = _ => openPopupModal(t.id, 'edit', tabDiv.querySelector('img.icon').getAttribute('src') === '../icons/unknown.png');
dupeMenuItem = wrapInDiv({className: 'overflow-menu-item duplicate', innerText: 'Duplicate & Change Time', tabIndex: 0});
dupeMenuItem.onclick = _ => openPopupModal(t.id, 'dupe', tabDiv.querySelector('img.icon').getAttribute('src') === '../icons/unknown.png');
dupeMenuItem.onclick = _ => openPopupModal(t.id, 'clone', tabDiv.querySelector('img.icon').getAttribute('src') === '../icons/unknown.png');
if (t.repeat) {
if (!t.paused) {
pauseMenuItem = wrapInDiv({className: 'overflow-menu-item pause', innerText: 'Pause Wakeups', tabIndex: 0});
Expand Down Expand Up @@ -338,13 +342,13 @@ function getTimeGroup(tab, timeType = 'wakeUpTime', searchQuery = false) {
var group = [];
if (!tab.opened && !tab[timeType]) return group;
var now = dayjs(), time = searchQuery && tab.opened ? dayjs(tab.opened) : dayjs(tab[timeType]);
if (time.week() === now.subtract(1, 'week').week()) group.push('last_week');
if (time.dayOfYear() === now.subtract(1, 'd').dayOfYear()) group.push('yesterday');
if (time.dayOfYear() === now.dayOfYear() && time.year() == now.year()) group.push('today');
if (time.dayOfYear() === now.add(1, 'd').dayOfYear()) group.push('tomorrow');
if (time.week() === now.week()) group.push('this_week');
if (time.week() === now.add(1, 'week').week()) group.push('next_week');
if (time.valueOf() > now.add(1, 'week').valueOf()) group.push('later');
if (time.week() === now.subtract(1, 'week').week() && isSameYear(now, time)) group.push('last_week');
if (time.dayOfYear() === now.subtract(1, 'd').dayOfYear() && isSameYear(now, time)) group.push('yesterday');
if (time.dayOfYear() === now.dayOfYear() && time.year() == now.year() && isSameYear(now, time)) group.push('today');
if (time.dayOfYear() === now.add(1, 'd').dayOfYear() && isSameYear(now, time)) group.push('tomorrow');
if (time.week() === now.week() && isSameYear(now, time)) group.push('this_week');
if (time.week() === now.add(1, 'week').week() && isSameYear(now, time)) group.push('next_week');
if (time.valueOf() > now.add(1, 'week').valueOf()) group.push('later');
return searchQuery ? group : group[0];
}

Expand Down
Loading

0 comments on commit d8de537

Please sign in to comment.