I am currently developing a Chrome extension similar to "OneTab" and "Better OneTab". I want you to understand the source code of the extension and help me modify it. Here is the code:
"""manifest.json
{
"manifest_version": 3,
"name": "Bookshelf",
"version": "0.9",
"description": "Store and manage your open tabs in a well-arranged bookshelf to save memory.",
"permissions": [
"tabs",
"storage",
"contextMenus"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_icon": {
"16": "icons/icon16.png",
"32": "icons/icon32.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"default_title": "Bookshelf"
},
"icons": {
"16": "icons/icon16.png",
"32": "icons/icon32.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"homepage_url": "https://your-extension-homepage.com"
}
"""
"""background.js
// Function to generate a unique ID
function generateUUID() {
return crypto.randomUUID();
}
// Open extension page when its icon is clicked
chrome.action.onClicked.addListener(() => {
chrome.tabs.create({ url: 'tabs.html' });
});
// Create context menu items when the extension is installed or updated
chrome.runtime.onInstalled.addListener(() => {
// Menu items
chrome.contextMenus.create({
id: 'savePagesOnLeft',
title: 'Save pages on the left',
contexts: ['action']
});
chrome.contextMenus.create({
id: 'savePagesOnRight',
title: 'Save pages on the right',
contexts: ['action']
});
chrome.contextMenus.create({
id: 'saveOnlyThisPage',
title: 'Save only this page',
contexts: ['action']
});
chrome.contextMenus.create({
id: 'saveAllPages',
title: 'Save all pages',
contexts: ['action']
});
// Listen for clicks on context menu items
chrome.contextMenus.onClicked.addListener((info, currentTab) => {
if (info.menuItemId === 'savePagesOnLeft') {
savePagesOnLeft(currentTab);
} else if (info.menuItemId === 'savePagesOnRight') {
savePagesOnRight(currentTab);
} else if (info.menuItemId === 'saveOnlyThisPage') {
saveOnlyThisPage(currentTab);
} else if (info.menuItemId === 'saveAllPages') {
saveAllPages(currentTab);
} else if (info.menuItemId === 'saveAllPagesExceptThis') {
saveAllPagesExceptThis(currentTab);
}
});
// Function to save pages on the left
function savePagesOnLeft(currentTab) {
chrome.tabs.query({ currentWindow: true }, (tabs) => {
savePages(tabs.filter(tab => (tab.index < currentTab.index) && (!tab.pinned) && tab.url.startsWith('http')));
});
}
// Function to save pages on the right
function savePagesOnRight(currentTab) {
chrome.tabs.query({ currentWindow: true }, (tabs) => {
savePages(tabs.filter(tab => (tab.index > currentTab.index) && (!tab.pinned) && tab.url.startsWith('http')));
});
}
// Function to save only the current page
function saveOnlyThisPage(currentTab) {
if ((!currentTab.pinned) && currentTab.url.startsWith('http')) {
savePages([currentTab]);
}
}
Assistant
// Function to save all pages
function saveAllPages(currentTab) {
chrome.tabs.query({ currentWindow: true }, (tabs) => {
savePages(tabs.filter(tab => (!tab.pinned) && tab.url.startsWith('http')));
});
}
// Function to save all pages except current
function saveAllPagesExceptThis(currentTab) {
chrome.tabs.query({ currentWindow: true }, (tabs) => {
savePages(tabs.filter(tab => (tab.id !== currentTab.id) && (!tab.pinned) && tab.url.startsWith('http')));
});
}
// Generic function to save pages
async function savePages(tabs) {
// Check if there are any pages to save
if (tabs.length === 0) {
console.log('No pages to save');
return;
}
// Map the filtered tabs to get their title and URL for the pages
const newPages = tabs.map(tab => ({
id: generateUUID(),
title: tab.title,
url: tab.url
}));
// Retrieve bookshelf saved data to determine the default book title and save it
let bookShelfData;
let selectedShelfId;
const data = await chrome.storage.local.get(['selectedShelfId', 'bookShelfData']);
if (!data.bookShelfData) {
bookShelfData = [{ id: generateUUID(), title: 'Shelf 1', books: [] }];
selectedShelfId = bookShelfData[0].id;
}
else {
bookShelfData = data.bookShelfData;
selectedShelfId = data.selectedShelfId || bookShelfData[0].id;
}
// Find the shelf
let shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
if (!shelf) {
// Create new shelf ID
let newShelfId;
do {
newShelfId = generateUUID();
} while(bookShelfData.some(shelf => shelf.id === newShelfId));
code
// Create new shelf
const newShelf = {
id: newShelfId,
title: `Shelf ${bookShelfData.length + 1}`,
books: []
}
// Save new shelf and add it at the end of the array
selectedShelfId = newShelf.id;
bookShelfData.push(newShelf);
shelf = newShelf;
}
// Create new book ID
let newBookId;
do {
newBookId = generateUUID();
} while(shelf.books.some(book => book.id === newBookId));
// Create default book title as 'Book X'
let defaultBookTitle = Book ${shelf.books.length + 1};
// Add the new book at the beginning of the array
const newBook = {
id: newBookId,
title: defaultBookTitle,
pages: newPages,
collapsed: false
};
shelf.books.unshift(newBook);
// Save the updated bookshelf data to storage
chrome.storage.local.set({ 'selectedShelfId': selectedShelfId, 'bookShelfData': bookShelfData }, () => {
console.log(${newPages.length} page(s) saved under "${defaultBookTitle}");
code
// Close the saved tabs
chrome.tabs.remove(tabs.map(tab => tab.id));
// Send a message to tabs.html to refresh the bookshelf
chrome.runtime.sendMessage({ action: 'bookShelfUpdated' });
});
}
"""
"""tabs.html
code
<!-- Main Body -->
<div id="mainBody">
<!-- Main Page -->
<div id="mainPage">
<p id="resultMessage">Loading your bookshelf...</p>
<div id="bookShelf"></div>
</div>
<!-- Settings Overlay -->
<div id="settingsOverlay" style="z-index: 101"></div>
<!-- Settings Page -->
<div id="settingsPage" style="z-index: 102">
<button id="closeSettingsButton" title="Close Settings">X</button>
<h2>Settings</h2>
<p>Customize your Bookshelf settings here.</p>
</div>
</div>
"""tabs.js
// Function to generate a unique ID
function generateUUID() {
return crypto.randomUUID();
}
// Event listener for the DOM loaded
document.addEventListener('DOMContentLoaded', async () => {
const selectedShelfTitle = document.getElementById('selectedShelfTitle');
const shelfList = document.getElementById('shelfList');
const searchBar = document.getElementById('searchBar');
const themeSelector = document.getElementById('themeSelector');
const settingsPageButton = document.getElementById('settingsPageButton');
const settingsOverlay = document.getElementById('settingsOverlay');
const settingsPage = document.getElementById('settingsPage');
const closeSettingsButton = document.getElementById('closeSettingsButton');
let selectedShelfId = "";
let bookShelfData = [];
let bookShelfDataUpdated = false;
let loadingBookShelfData = false;
let pagesToMove = [];
let bookIdOfMovingPages = '';
let isSettingsPageOpen = false;
code
// Get bookshelf saved data and display it
await LoadBookShelfDataFromStorage();
// Change the shelf title with the selected one
const selectedShelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
if (selectedShelf) {
changeSelectedShelfTitle(selectedShelf.title);
}
// Paint the DOM
displayBookShelf();
// Get saved theme
chrome.storage.local.get('themeSelected', (data) => {
if (!data.themeSelected) data.themeSelected = '';
document.body.className = data.themeSelected;
themeSelector.value = data.themeSelected; // Change select based on saved theme
});
// Create a timer that check if there are bookshelf data to save
let intervalId = setInterval(() => {
if (bookShelfDataUpdated && !loadingBookShelfData) {
// Save bookshelf data
chrome.storage.local.set({ 'selectedShelfId': selectedShelfId, 'bookShelfData': bookShelfData }, () => {
// Check for errors
if (chrome.runtime.lastError) {
console.error('Error setting storage:', chrome.runtime.lastError);
// TODO: Handle the error accordingly
}
});
bookShelfDataUpdated = false;
}
}, 2000);
// Event listener for messages from background.js
chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
if (message.action === 'bookShelfUpdated') {
// Get new bookshelf data and repaint the DOM
await LoadBookShelfDataFromStorage();
displayBookShelf();
}
});
// Handle click event for the extension name to show/hide the shelf dropdown
selectedShelfTitle.addEventListener('click', () => {
const arrowIcon = document.getElementById('arrowIcon');
shelfList.classList.toggle('close');
arrowIcon.style.transform = shelfList.classList.contains('close') ? 'rotate(0deg)' : 'rotate(180deg)';
});
// Event listener for the search bar
searchBar.addEventListener('input', () => {
let timeoutId;
// Clear the previous timer
if (timeoutId) {
clearTimeout(timeoutId);
}
// Set a new timer
timeoutId = setTimeout(() => {
// TODO: disable or enable (by settings) to move pages when filtering
// if (!settings.canMoveWhileFiltering) {
// pagesToMove = [];
// bookIdOfMovingPages = '';
// }
// Repaint the DOM
displayBookShelf();
}, 250);
});
// Event listener for the theme selector button
themeSelector.addEventListener('change', function() {
document.body.className = this.value;
chrome.storage.local.set({ 'themeSelected': this.value }); // Save theme
});
// Event listener for the settings page button
settingsPageButton.addEventListener('click', (event) => {
event.preventDefault(); // Prevent default link behavior
isSettingsPageOpen = !isSettingsPageOpen;
if (isSettingsPageOpen) {
// Open the settings page
settingsPage.classList.add('open');
settingsOverlay.classList.add('open');
} else {
// Close the settings page
settingsPage.classList.remove('open');
settingsOverlay.classList.remove('open');
}
});
// Event listener for the overlay to close the settings page when clicked
settingsOverlay.addEventListener('click', () => {
isSettingsPageOpen = false;
settingsPage.classList.remove('open');
settingsOverlay.classList.remove('open');
});
// Event listener for the close button inside the settings page
closeSettingsButton.addEventListener('click', () => {
isSettingsPageOpen = false;
settingsPage.classList.remove('open');
settingsOverlay.classList.remove('open');
});
// Close the settings page when the Escape key is pressed
document.addEventListener('keydown', (event) => {
if ((event.key === 'Escape') && isSettingsPageOpen) {
isSettingsPageOpen = false;
settingsPage.classList.remove('open');
settingsOverlay.classList.remove('open');
}
});
// Function to get bookshelf saved data from storage
async function LoadBookShelfDataFromStorage() {
loadingBookShelfData = true;
const data = await chrome.storage.local.get(['selectedShelfId', 'bookShelfData']);
if (!data.bookShelfData) {
bookShelfData = [{ id: generateUUID(), title: 'Shelf 1', books: [] }];
selectedShelfId = bookShelfData[0].id;
}
else {
bookShelfData = data.bookShelfData;
selectedShelfId = data.selectedShelfId || bookShelfData[0].id;
if (!bookShelfData.find(shelf => shelf.id === selectedShelfId)) {
selectedShelfId = bookShelfData[0].id;
saveBookShelfDataToStorage();
}
}
loadingBookShelfData = false;
}
// Function to set bookshelf data to storage
async function saveBookShelfDataToStorage() {
bookShelfDataUpdated = true; // bookshelf data has changed
}
// Get book element from ID
function getBookElementById(bookId) {
return document.querySelector(`.bookContainer[data-book-id="${bookId}"]`);
}
// Get shelf element from ID
function getShelfElementById(shelfId) {
return document.querySelector(`.shelfListItem[data-shelf-id="${shelfId}"]`);
}
// Function to change selected shelf title
function changeSelectedShelfTitle(newTitle) {
// Clone the arrow icon
const arrowIconClone = document.getElementById('arrowIcon').cloneNode(true);
// Change selected shelf title
selectedShelfTitle.innerHTML = '';
selectedShelfTitle.appendChild(arrowIconClone);
selectedShelfTitle.innerHTML += newTitle;
};
// Function to display bookshelf data on the main page
function displayBookShelf() {
const fragment = document.createDocumentFragment(); // Create fragment to minimizes the number of reflows and repaints
const currentSearchQuery = searchBar.value.trim().toLowerCase(); // Get current filtering query
const areThereAnyPagesToMove = pagesToMove.length !== 0;
// Function to create the edit shelf title button
function createEditShelfTitleButton(shelfId) {
const editShelfTitleButton = document.createElement('button');
editShelfTitleButton.title = 'Edit shelf title';
editShelfTitleButton.className = 'editShelfTitleButton';
editShelfTitleButton.dataset.mode = 'edit';
// Create SVG element
const svgElem = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgElem.setAttribute('viewBox', '0 0 48 48');
svgElem.setAttribute('width', '20px');
svgElem.setAttribute('height', '20px');
const pathElem = document.createElementNS('http://www.w3.org/2000/svg', 'path');
pathElem.setAttribute('d', 'M38.657 18.536l2.44-2.44c2.534-2.534 2.534-6.658 0-9.193-1.227-1.226-2.858-1.9-4.597-1.9s-3.371.675-4.597 1.901l-2.439 2.439L38.657 18.536zM27.343 11.464L9.274 29.533c-.385.385-.678.86-.848 1.375L5.076 41.029c-.179.538-.038 1.131.363 1.532C5.726 42.847 6.108 43 6.5 43c.158 0 .317-.025.472-.076l10.118-3.351c.517-.17.993-.463 1.378-.849l18.068-18.068L27.343 11.464z');
// Append elements in the correct order
svgElem.appendChild(pathElem);
editShelfTitleButton.appendChild(svgElem);
// Toggle between edit and save modes for the shelf title
editShelfTitleButton.addEventListener('click', () => {
// Find the shelf index
const shelf = bookShelfData.find(shelf => shelf.id === shelfId);
if (!shelf) return;
// Get HTML element
const shelfTitle = getShelfElementById(shelfId).getShelfTitle();
if (editShelfTitleButton.dataset.mode === 'edit') {
// Switch to edit mode
shelfTitle.contentEditable = true;
shelfTitle.focus();
// Move cursor to the end of the text using Range and Selection APIs
if ((typeof window.getSelection != "undefined") && (typeof document.createRange != "undefined")) {
const range = document.createRange();
range.selectNodeContents(shelfTitle);
range.collapse(false); // Collapse the range to the end
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
// Change button to 'Save'
editShelfTitleButton.title = 'Save shelf title';
editShelfTitleButton.dataset.mode = 'save';
// Handle Enter key to save
shelfTitle.onkeypress = function(e) {
if (e.key === 'Enter') {
e.preventDefault(); // Prevent newline
editShelfTitleButton.click(); // Save on Enter key
}
};
} else {
// Switch to view mode (save changes)
const newTitle = shelfTitle.textContent.trim();
if (newTitle === '') {
alert('Book title cannot be empty.');
shelfTitle.focus();
return;
}
// Update the shelf title
shelf.title = newTitle;
// Update the selected shelf title
if (shelf.id === selectedShelfId) {
changeSelectedShelfTitle(shelf.title);
}
// Save the updated shelf to storage
saveBookShelfDataToStorage();
// Disable contentEditable
shelfTitle.contentEditable = false;
// Reset the edit button
editShelfTitleButton.title = 'Edit book title';
editShelfTitleButton.dataset.mode = 'edit';
// Remove keypress handler
shelfTitle.onkeypress = null;
}
});
return editShelfTitleButton;
}
// Function to create the shelf title
function createShelfTitle(shelfId, shelfTitle) {
const shelfTitleElem = document.createElement('h2');
shelfTitleElem.textContent = shelfTitle;
shelfTitleElem.className = 'shelfTitle';
shelfTitleElem.contentEditable = false;
// Switch to this shelf
shelfTitleElem.addEventListener('click', () => {
if ((shelfTitleElem.contentEditable === 'false') && (shelfId !== selectedShelfId)) {
// Find the shelf
const shelf = bookShelfData.find(shelf => shelf.id === shelfId);
if (!shelf) return;
// Change the selected shelf title
changeSelectedShelfTitle(shelf.title);
// Change and save the selected shelf
selectedShelfId = shelfId;
saveBookShelfDataToStorage();
// Repaint the DOM
displayBookShelf();
}
});
return shelfTitleElem;
}
// Function to create the remove shelf button
function createRemoveShelfButton(shelfId) {
const removeShelfButton = document.createElement('button');
removeShelfButton.title = 'Remove this shelf';
removeShelfButton.className = 'removeShelfButton';
// Create SVG element
const svgElem = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgElem.setAttribute('viewBox', '0 0 30 30');
svgElem.setAttribute('width', '20px');
svgElem.setAttribute('height', '20px');
const pathElem = document.createElementNS('http://www.w3.org/2000/svg', 'path');
pathElem.setAttribute('d', 'M 7 4 C 6.744125 4 6.4879687 4.0974687 6.2929688 4.2929688 L 4.2929688 6.2929688 C 3.9019687 6.6839688 3.9019687 7.3170313 4.2929688 7.7070312 L 11.585938 15 L 4.2929688 22.292969 C 3.9019687 22.683969 3.9019687 23.317031 4.2929688 23.707031 L 6.2929688 25.707031 C 6.6839688 26.098031 7.3170313 26.098031 7.7070312 25.707031 L 15 18.414062 L 22.292969 25.707031 C 22.682969 26.098031 23.317031 26.098031 23.707031 25.707031 L 25.707031 23.707031 C 26.098031 23.316031 26.098031 22.682969 25.707031 22.292969 L 18.414062 15 L 25.707031 7.7070312 C 26.098031 7.3170312 26.098031 6.6829688 25.707031 6.2929688 L 23.707031 4.2929688 C 23.316031 3.9019687 22.682969 3.9019687 22.292969 4.2929688 L 15 11.585938 L 7.7070312 4.2929688 C 7.5115312 4.0974687 7.255875 4 7 4 z');
// Append elements in the correct order
svgElem.appendChild(pathElem);
removeShelfButton.appendChild(svgElem);
// Remove shelf
removeShelfButton.addEventListener('click', () => {
if (bookShelfData.length > 1) {
if (shelfId === selectedShelfId) {
alert('Please choose another shelf before removing this.');
}
else if (confirm('Are you sure you want to remove this shelf?')) {
// Remove shelf from data and save it
bookShelfData = bookShelfData.filter(shelf => shelf.id !== shelfId);
saveBookShelfDataToStorage();
// Remove shelf element
const shelfElem = getShelfElementById(shelfId);
if (shelfElem) {
shelfList.removeChild(shelfElem);
}
}
}
else if (confirm('Are you sure you want to reset this shelf?')) {
// Remove all books from this shelf
bookShelfData[0].books = [];
// Change shelf name
bookShelfData[0].title = "Shelf 1";
// Update the selected shelf title
changeSelectedShelfTitle(bookShelfData[0].title);
// Save updated shelf
saveBookShelfDataToStorage();
// Clear existing content and append the fragment to display the data
const bookShelf = document.getElementById('bookShelf');
bookShelf.innerHTML = '';
// Display the message that there are no page saved
displayResultMessage();
}
});
return removeShelfButton;
}
// Function to create the shelf list item
function createShelfListItem(shelf) {
const shelfListItem = document.createElement('li');
shelfListItem.classList.add('shelfListItem');
shelfListItem.dataset.shelfId = shelf.id;
// Create children elements
const editShelfTitleButton = createEditShelfTitleButton(shelf.id);
const shelfTitle = createShelfTitle(shelf.id, shelf.title);
const removeShelfButton = createRemoveShelfButton(shelf.id);
// Append elements to the shelf list item in the desired order
shelfListItem.appendChild(editShelfTitleButton);
shelfListItem.appendChild(shelfTitle);
shelfListItem.appendChild(removeShelfButton);
// Create functions to retrieve nested elements
shelfListItem.getShelfTitle = function() {return shelfTitle;}
return shelfListItem;
}
// Function to create the add new shelf button
function createAddNewShelfButton() {
const addNewShelfButton = document.createElement('li');
addNewShelfButton.classList.add('addNewShelfButton');
// Create SVG element
const svgElem = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgElem.setAttribute('viewBox', '0 0 48 48');
svgElem.setAttribute('width', '20px');
svgElem.setAttribute('height', '20px');
svgElem.style.marginRight = '5px';
const pathElem = document.createElementNS('http://www.w3.org/2000/svg', 'path');
pathElem.setAttribute('d', 'M 24 4 C 12.972066 4 4 12.972074 4 24 C 4 35.027926 12.972066 44 24 44 C 35.027934 44 44 35.027926 44 24 C 44 12.972074 35.027934 4 24 4 z M 24 7 C 33.406615 7 41 14.593391 41 24 C 41 33.406609 33.406615 41 24 41 C 14.593385 41 7 33.406609 7 24 C 7 14.593391 14.593385 7 24 7 z M 23.976562 13.978516 A 1.50015 1.50015 0 0 0 22.5 15.5 L 22.5 22.5 L 15.5 22.5 A 1.50015 1.50015 0 1 0 15.5 25.5 L 22.5 25.5 L 22.5 32.5 A 1.50015 1.50015 0 1 0 25.5 32.5 L 25.5 25.5 L 32.5 25.5 A 1.50015 1.50015 0 1 0 32.5 22.5 L 25.5 22.5 L 25.5 15.5 A 1.50015 1.50015 0 0 0 23.976562 13.978516 z');
// Append elements in the correct order
svgElem.appendChild(pathElem);
addNewShelfButton.appendChild(svgElem);
addNewShelfButton.innerHTML += "Add new shelf";
// Add new shelf
addNewShelfButton.addEventListener('click', () => {
// Create new shelf ID
let newShelfId;
do {
newShelfId = generateUUID();
} while(bookShelfData.some(shelf => shelf.id === newShelfId));
// Create new shelf
const newShelf = {
id: newShelfId,
title: `Shelf ${bookShelfData.length + 1}`,
books: []
}
bookShelfData.push(newShelf); // Add the new shelf at the end of the array
// Save the new shelf to storage
saveBookShelfDataToStorage();
// Insert in the list
shelfList.insertBefore(createShelfListItem(newShelf), addNewShelfButton);
});
return addNewShelfButton;
}
// Function to create the edit book title button
function createEditBookTitleButton(bookId) {
const editBookTitleButton = document.createElement('button');
editBookTitleButton.title = 'Edit book title';
editBookTitleButton.className = 'editBookTitleButton';
editBookTitleButton.dataset.mode = 'edit';
// Create SVG element
const svgElem = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgElem.setAttribute('viewBox', '0 0 48 48');
svgElem.setAttribute('width', '23px');
svgElem.setAttribute('height', '23px');
const pathElem = document.createElementNS('http://www.w3.org/2000/svg', 'path');
pathElem.setAttribute('d', 'M38.657 18.536l2.44-2.44c2.534-2.534 2.534-6.658 0-9.193-1.227-1.226-2.858-1.9-4.597-1.9s-3.371.675-4.597 1.901l-2.439 2.439L38.657 18.536zM27.343 11.464L9.274 29.533c-.385.385-.678.86-.848 1.375L5.076 41.029c-.179.538-.038 1.131.363 1.532C5.726 42.847 6.108 43 6.5 43c.158 0 .317-.025.472-.076l10.118-3.351c.517-.17.993-.463 1.378-.849l18.068-18.068L27.343 11.464z');
// Append elements in the correct order
svgElem.appendChild(pathElem);
editBookTitleButton.appendChild(svgElem);
// Toggle between edit and save modes for the book title
editBookTitleButton.addEventListener('click', () => {
// Find the shelf
const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
if (!shelf) return;
// Find the book
const book = shelf.books.find(book => book.id === bookId);
if (!book) return;
// Get HTML element
const bookTitle = getBookElementById(bookId).getBookTitle();
if (editBookTitleButton.dataset.mode === 'edit') {
// Switch to edit mode
bookTitle.contentEditable = true;
bookTitle.focus();
// Move cursor to the end of the text using Range and Selection APIs
if ((typeof window.getSelection != "undefined") && (typeof document.createRange != "undefined")) {
const range = document.createRange();
range.selectNodeContents(bookTitle);
range.collapse(false); // Collapse the range to the end
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
// Change button to 'Save'
editBookTitleButton.title = 'Save book title';
editBookTitleButton.dataset.mode = 'save';
// Handle Enter key to save
bookTitle.onkeypress = function(e) {
if (e.key === 'Enter') {
e.preventDefault(); // Prevent newline
editBookTitleButton.click(); // Save on Enter key
}
};
} else {
// Switch to view mode (save changes)
const newTitle = bookTitle.textContent.trim();
if (newTitle === '') {
alert('Book title cannot be empty.');
bookTitle.focus();
return;
}
// Update the book title
book.title = newTitle;
// Save the updated book to storage
saveBookShelfDataToStorage();
// Disable contentEditable
bookTitle.contentEditable = false;
// Reset the edit button
editBookTitleButton.title = 'Edit book title';
editBookTitleButton.dataset.mode = 'edit';
// Remove keypress handler
bookTitle.onkeypress = null;
}
});
return editBookTitleButton;
}
// Function to create the book title
function createBookTitle(bookTitle) {
const bookTitleElem = document.createElement('h2');
bookTitleElem.textContent = bookTitle;
bookTitleElem.className = 'bookTitle';
bookTitleElem.contentEditable = false;
return bookTitleElem;
}
// Function to create a pages count
function createPagesCount(bookPagesLength) {
const pagesCount = document.createElement('h2');
pagesCount.textContent = `${bookPagesLength} Page${bookPagesLength !== 1 ? 's' : ''}`;
pagesCount.className = 'pagesCount';
return pagesCount;
}
// Function to create the top part of a book header
function createBookHeaderTop(book) {
const bookHeaderTop = document.createElement('div');
bookHeaderTop.className = 'bookHeaderTop';
// Create children elements
const editBookTitleButton = createEditBookTitleButton(book.id);
const bookTitle = createBookTitle(book.title);
const pagesCount = createPagesCount(book.pages.length);
// Append elements to the top header in the desired order
bookHeaderTop.appendChild(editBookTitleButton);
bookHeaderTop.appendChild(bookTitle);
bookHeaderTop.appendChild(pagesCount);
// Create functions to retrieve nested elements
bookHeaderTop.getEditBookTitleButton = function() {return editBookTitleButton;}
bookHeaderTop.getBookTitle = function() {return bookTitle;}
bookHeaderTop.getPagesCount = function() {return pagesCount;}
return bookHeaderTop;
}
// Function to create the book checkbox
function createBookCheckbox(bookId) {
const bookCheckbox = document.createElement('input');
bookCheckbox.type = 'checkbox';
bookCheckbox.className = 'bookCheckbox';
bookCheckbox.name = 'bookCheckbox';
bookCheckbox.title = 'Select/Deselect All Pages in this Book';
// Toggle all checkboxes in a book
bookCheckbox.addEventListener('change', () => {
const pageCheckboxes = getBookElementById(bookId).getAllPageCheckbox();
pageCheckboxes.forEach((checkbox) => {
checkbox.checked = bookCheckbox.checked;
});
});
return bookCheckbox;
}
// Function to create a move selected pages button
function createMoveSelectedPagesButton(bookId) {
const moveSelectedPagesButton = document.createElement('button');
moveSelectedPagesButton.textContent = 'Move Selected Pages';
moveSelectedPagesButton.className = 'moveSelectedPagesButton';
moveSelectedPagesButton.disabled = areThereAnyPagesToMove && (bookIdOfMovingPages != bookId);
moveSelectedPagesButton.style.textDecoration = moveSelectedPagesButton.disabled ? 'line-through' : 'none';
// Add selected pages to a buffer
moveSelectedPagesButton.addEventListener('click', () => {
// Enable to move pages
if (pagesToMove.length === 0) {
// Find the shelf
const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
if (!shelf) return;
// Find the book
const book = shelf.books.find(book => book.id === bookId);
if (!book) return;
// Get HTML element
const pageCheckboxes = getBookElementById(bookId).getAllPageCheckbox();
// Assert data compatibility
if (!(pageCheckboxes.length === book.pages.length)) {
console.assert(false, `Assert error when moving selected pages in ${bookId} book`);
return;
}
// Collect the pages to move
pagesToMove = [];
pageCheckboxes.forEach((checkbox, checkboxIndex) => {
if (checkbox.checked) {
pagesToMove.push(book.pages[checkboxIndex]);
}
});
if (pagesToMove.length === 0) {
alert('Please select at least one page to move.');
return;
}
// Saves the book ID of the book where the pages to be moved were taken
bookIdOfMovingPages = bookId;
// Disable all the others moving buttons
var buttons = document.getElementsByClassName('moveSelectedPagesButton');
for (var i = 0; i < buttons.length; i++) {
if (buttons[i] !== moveSelectedPagesButton) {
buttons[i].disabled = true;
buttons[i].style.textDecoration = 'line-through';
}
}
// Remove bottom border from all the pages
var items = document.getElementsByClassName('pagesListItem');
for (var i = 0; i < items.length; i++) {
items[i].style.borderBottomWidth = '0px';
}
// Show all "Move here" buttons
var buttons = document.getElementsByClassName('moveHereButton');
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.display = 'block';
}
}
// Disable to move pages
else {
// Clear the array and the book ID
pagesToMove = [];
bookIdOfMovingPages = '';
// Enable all the others buttons
var buttons = document.getElementsByClassName('moveSelectedPagesButton');
for (var i = 0; i < buttons.length; i++) {
if (buttons[i] !== moveSelectedPagesButton) {
buttons[i].disabled = false;
buttons[i].style.textDecoration = 'none';
}
}
// Add bottom border in all the pages
var items = document.getElementsByClassName('pagesListItem');
for (var i = 0; i < items.length; i++) {
items[i].style.borderBottomWidth = '1px';
}
// Hide all "Move here" buttons
var buttons = document.getElementsByClassName('moveHereButton');
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.display = 'none';
}
}
});
return moveSelectedPagesButton;
}
// Function to create a restore selected pages button
function createRestoreSelectedPagesButton(bookId) {
const restoreSelectedPagesButton = document.createElement('button');
restoreSelectedPagesButton.textContent = 'Restore Selected Pages';
restoreSelectedPagesButton.className = 'restoreSelectedPagesButton';
// Restore selected pages from a book
restoreSelectedPagesButton.addEventListener('click', () => {
// Find the shelf
const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
if (!shelf) return;
// Find the book
const book = shelf.books.find(book => book.id === bookId);
if (!book) return;
// Get HTML elements
const pageCheckboxes = getBookElementById(bookId).getAllPageCheckbox();
// Assert data compatibility
if (!(pageCheckboxes.length === book.pages.length)) {
console.assert(false, `Assert error when restoring selected pages in ${bookId} book`);
return;
}
// Collect the pages to restore
const pagesToRestore = [];
pageCheckboxes.forEach((checkbox, checkboxIndex) => {
if (checkbox.checked) {
pagesToRestore.push(book.pages[checkboxIndex]);
}
});
if (pagesToRestore.length === 0) {
alert('Please select at least one page to restore.');
return;
}
// Confirm restoration
if (!confirm(`Are you sure you want to restore the selected page${pagesToRestore.length !== 1 ? 's' : ''}?`)) {
return;
}
// Restore the selected pages by creating new pages in the browser
pagesToRestore.forEach(page => {
chrome.tabs.create({ url: page.url });
});
});
return restoreSelectedPagesButton;
}
// Function to create a remove selected pages button
function createRemoveSelectedPagesButton(bookId) {
const removeSelectedPagesButton = document.createElement('button');
removeSelectedPagesButton.textContent = 'Remove Selected Pages';
removeSelectedPagesButton.className = 'removeSelectedPagesButton';
// Remove selected pages from a book
removeSelectedPagesButton.addEventListener('click', () => {
// Find the shelf
const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
if (!shelf) return;
// Find the book
const book = shelf.books.find(book => book.id === bookId);
if (!book) return;
// Get HTML elements
const bookContainer = getBookElementById(bookId);
const pagesList = bookContainer.getPagesList();
const pageCheckboxes = pagesList.getAllPageCheckbox();
// Assert data compatibility
if (!(pageCheckboxes.length === book.pages.length)) {
console.assert(false, `Assert error when removing selected pages in ${bookId} book`);
return;
}
// Collect the indices of pages to remove
const indicesToRemove = [];
pageCheckboxes.forEach((checkbox, checkboxIndex) => {
if (checkbox.checked) {
indicesToRemove.push(checkboxIndex);
}
});
if (indicesToRemove.length === 0) {
alert('Please select at least one page to remove.');
return;
}
// Confirm to remove the pages
if (!confirm(`Are you sure you want to remove the selected page${indicesToRemove.length !== 1 ? 's' : ''}?`)) {
return;
}
// Remove pages starting from the highest index to avoid index shifting
indicesToRemove.sort((a, b) => b - a).forEach((pageIndex) => {
pagesList.removeChild(pagesList.children[pageIndex]);
book.pages.splice(pageIndex, 1);
});
// Remove the book if no pages are left
if (book.pages.length === 0) {
removeBook(bookId);
return;
}
// Update pages count
updatePageCount(bookId);
// Save the updated bookShelfData
saveBookShelfDataToStorage();
});
return removeSelectedPagesButton;
}
// Function to create the bottom part of a book header
function createBookHeaderBottom(bookId) {
const bookHeaderBottom = document.createElement('div');
bookHeaderBottom.className = 'bookHeaderBottom';
// Create children elements
const bookCheckbox = createBookCheckbox(bookId);
const moveSelectedPagesButton = createMoveSelectedPagesButton(bookId);
const restoreSelectedPagesButton = createRestoreSelectedPagesButton(bookId);
const removeSelectedPagesButton = createRemoveSelectedPagesButton(bookId);
// Append elements to the bottom header in the desired order
bookHeaderBottom.appendChild(bookCheckbox);
bookHeaderBottom.appendChild(moveSelectedPagesButton);
bookHeaderBottom.appendChild(restoreSelectedPagesButton);
bookHeaderBottom.appendChild(removeSelectedPagesButton);
// Create functions to retrieve nested elements
bookHeaderBottom.getBookCheckbox = function() {return bookCheckbox;}
return bookHeaderBottom;
}
// Function to create a book header
function createBookHeader(book) {
const bookId = book.id;
const bookHeader = document.createElement('div');
bookHeader.className = 'bookHeader';
// Create children elements
const bookHeaderTop = createBookHeaderTop(book);
const bookHeaderBottom = createBookHeaderBottom(bookId);
// Append elements to the header in the desired order
bookHeader.appendChild(bookHeaderTop);
bookHeader.appendChild(bookHeaderBottom);
// Create functions to retrieve nested elements
bookHeader.getBookTitle = function() {return bookHeaderTop.getBookTitle();}
bookHeader.getPagesCount = function() {return bookHeaderTop.getPagesCount();}
bookHeader.getBookCheckbox = function() {return bookHeaderBottom.getBookCheckbox();}
// Add event listener
bookHeader.addEventListener('click', (event) => {
// Toggle book collapse/expand state
if ((event.target === bookHeader) || (event.target === bookHeaderTop) || (event.target === bookHeaderBottom) || (event.target === bookHeaderTop.getPagesCount())
|| ((event.target === bookHeaderTop.getBookTitle()) && (bookHeaderTop.getEditBookTitleButton().dataset.mode === 'edit'))) {
// Find the shelf
const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
if (!shelf) return;
// Find the book
const book = shelf.books.find(book => book.id === bookId);
if (!book) return;
// Get HTML elements
const pagesList = getBookElementById(bookId).getPagesList();
// Toggle the display style
if (book.collapsed) {
pagesList.style.display = 'grid';
bookHeaderBottom.style.display = 'flex';
bookHeaderTop.style.marginBottom = '5px';
} else {
pagesList.style.display = 'none';
bookHeaderBottom.style.display = 'none';
bookHeaderTop.style.marginBottom = '0';
}
book.collapsed ^= true; // toggle value
// Save the updated bookShelfData
saveBookShelfDataToStorage();
}
});
return bookHeader;
}
// Function to create the page checkbox
function createPageCheckbox(bookId) {
const pageCheckbox = document.createElement('input');
pageCheckbox.type = 'checkbox';
pageCheckbox.className = 'pageCheckbox';
pageCheckbox.name = 'pageCheckbox';
// Update the book checkbox state based on individual checkboxes
pageCheckbox.addEventListener('change', () => {
const bookContainer = getBookElementById(bookId);
const bookCheckbox = bookContainer.getBookCheckbox();
const pageCheckboxes = bookContainer.getAllPageCheckbox();
const allChecked = Array.from(pageCheckboxes).every(checkbox => checkbox.checked);
const anyChecked = Array.from(pageCheckboxes).some(checkbox => checkbox.checked);
bookCheckbox.checked = allChecked;
bookCheckbox.indeterminate = !allChecked && anyChecked;
});
return pageCheckbox;
}
// Function to create the page link
function createPageLink(page) {
const pageLink = document.createElement('a');
pageLink.className = 'pageLink';
pageLink.href = page.url;
pageLink.textContent = page.title;
pageLink.target = '_blank';
return pageLink;
}
// Function to create the remove page button
function createRemovePageButton(bookId, pageId) {
const removePageButton = document.createElement('button');
removePageButton.textContent = 'X';
removePageButton.title = 'Remove this page';
removePageButton.className = 'removePageButton';
removePageButton.addEventListener('click', () => {
// Find the shelf
const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
if (!shelf) return;
// Find the book
const book = shelf.books.find(book => book.id === bookId);
if (!book) return;
// Find the page index
const pageIndex = book.pages.findIndex(page => page.id === pageId);
if (pageIndex === -1) return;
// Get HTML element
const pagesList = getBookElementById(bookId).getPagesList();
// Assert data compatibility
if (!(pagesList.getAllPagesListItem().length === book.pages.length)) {
console.assert(false, `Assert error when removing ${pageId} page in ${bookId} book`);
return;
}
// Confirm to remove the pages
if (!confirm('Are you sure you want to remove this page?')) {
return;
}
// Remove page
pagesList.removeChild(pagesList.children[pageIndex]);
book.pages.splice(pageIndex, 1);
// Remove the book if no pages are left
if (book.pages.length === 0) {
removeBook(bookId);
return;
}
// Update pages count
updatePageCount(bookId);
// Save the updated bookShelfData
saveBookShelfDataToStorage();
});
return removePageButton;
}
// Function to create a container for the page info and controls
function createPageContainer(page, bookId, pageId) {
const pageContainer = document.createElement('div');
pageContainer.className = 'pageContainer';
pageContainer.dataset.pageId = pageId;
// Create children elements
const pageCheckbox = createPageCheckbox(bookId);
const pageLink = createPageLink(page);
const removePageButton = createRemovePageButton(bookId, pageId);
// Append elements to the container in the desired order
pageContainer.appendChild(pageCheckbox);
pageContainer.appendChild(pageLink);
pageContainer.appendChild(removePageButton);
// Create functions to retrieve nested elements
pageContainer.getPageCheckbox = function() {return pageCheckbox;}
return pageContainer;
}
// Function to create the "Move here" button
function createMoveHereButton(bookId, pageId) {
const moveHereButton = document.createElement('button');
moveHereButton.textContent = 'Move here';
moveHereButton.className = 'moveHereButton';
moveHereButton.style.display = areThereAnyPagesToMove ? 'block' : 'none';
// Move buffered pages inside a book
moveHereButton.addEventListener('click', () => {
if (pagesToMove.length === 0) return;
// Find the shelf
const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
if (!shelf) return;
// Find the book
let book = shelf.books.find(book => book.id === bookId);
if (!book) return;
// Find the page index
let pageIndex = book.pages.findIndex(page => page.id === pageId);
if (pageIndex < 0) pageIndex = book.pages.length;
// Check if the pages we are moving have the same ID as those in the book
let bookIds;
let pageToAdd = JSON.parse(JSON.stringify(pagesToMove)); // Make a deep copy (NOTE: can be slow)
do {
// Get book pages IDs
bookIds = new Set(book.pages.map(page => page.id));
// Check for duplicated IDs
pageToAdd.forEach(page => {
if (bookIds.has(page.id)) {
page.id = generateUUID(); // generate new ID
}
});
} while(pageToAdd.some(page => bookIds.has(page.id)));
// Add pages
book.pages.splice(pageIndex, 0, ...pageToAdd);
// Remove pages from previous book
book = shelf.books.find(book => book.id === bookIdOfMovingPages);
if (book) {
bookIds = new Set(pagesToMove.map(page => page.id));
book.pages = book.pages.filter(page => !bookIds.has(page.id));
if (book.pages.length === 0) {
// Remove the book because no pages are left
removeBook(bookIdOfMovingPages);
}
else {
// Update pages count
updatePageCount(bookIdOfMovingPages);
}
}
// Update pages count
updatePageCount(bookId);
// Clear the array and the book ID
pagesToMove = [];
bookIdOfMovingPages = '';
// Save the updated bookShelfData
saveBookShelfDataToStorage();
// Repaint the DOM
displayBookShelf();
});
return moveHereButton;
}
// Function to create a page list item
function createPagesListItem(page, bookId, pageId) {
const pagesListItem = document.createElement('li');
pagesListItem.className = 'pagesListItem';
pagesListItem.style.display = page.title.toLowerCase().includes(currentSearchQuery) ? 'grid' : 'none';
// Create children elements
const moveHereButton = createMoveHereButton(bookId, pageId);
const pageContainer = createPageContainer(page, bookId, pageId);
// Append elements to the item in the desired order
pagesListItem.appendChild(moveHereButton);
pagesListItem.appendChild(pageContainer);
// Create functions to retrieve nested elements
pagesListItem.getPageCheckbox = function() {return pageContainer.getPageCheckbox();}
return pagesListItem;
}
// Function to create a pages list
function createPagesList(book) {
const pagesList = document.createElement('ul');
pagesList.className = 'pagesList';
pagesList.style.display = book.collapsed ? 'none' : 'grid';
// Append elements to the pages list in the desired order
book.pages.forEach((page) => {
pagesList.appendChild(createPagesListItem(page, book.id, page.id));
});
// Create functions to retrieve nested elements
pagesList.getAllPagesListItem = function() {return [...pagesList.children];}
pagesList.getAllPageCheckbox = function() {
const allPageCheckbox = [];
pagesList.getAllPagesListItem().forEach(item => {
allPageCheckbox.push(item.getPageCheckbox());
});
return allPageCheckbox;
};
return pagesList;
}
// Function to create a container for the book info and controls
function createBookContainer(book) {
const bookContainer = document.createElement('div');
bookContainer.className = 'bookContainer';
bookContainer.dataset.bookId = book.id;
// Create children elements
const bookHeader = createBookHeader(book);
const pagesList = createPagesList(book);
const moveHereButton = createMoveHereButton(book.id, '');
// Append elements to the container in the desired order
bookContainer.appendChild(bookHeader);
bookContainer.appendChild(pagesList);
bookContainer.appendChild(moveHereButton);
// Create functions to retrieve nested elements
bookContainer.getBookTitle = function() {return bookHeader.getBookTitle();}
bookContainer.getPagesCount = function() {return bookHeader.getPagesCount();}
bookContainer.getBookCheckbox = function() {return bookHeader.getBookCheckbox();}
bookContainer.getPagesList = function() {return pagesList;}
bookContainer.getAllPageCheckbox = function() {return pagesList.getAllPageCheckbox();}
bookContainer.getAllPagesListItem = function() {return pagesList.getAllPagesListItem();}
// Show or hide the book based on whether any pages are visible
bookContainer.style.display = Object.values(bookContainer.getAllPagesListItem()).some(item => item.style.display === 'grid') ? 'grid': 'none';
return bookContainer;
}
// Create the elements based on the data
shelfList.innerHTML = '';
bookShelfData.forEach((shelf) => {
shelfList.appendChild(createShelfListItem(shelf));
if (shelf.id === selectedShelfId) {
shelf.books.forEach((book) => {
fragment.appendChild(createBookContainer(book));
});
}
});
shelfList.appendChild(createAddNewShelfButton());
// Clear existing content and append the fragment to display the data
const bookShelf = document.getElementById('bookShelf');
bookShelf.innerHTML = '';
bookShelf.appendChild(fragment);
// Display a message if no pages match
displayResultMessage();
}
// Function to update pages count
function updatePageCount(bookId) {
// Find the shelf
const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
if (!shelf) return;
// Find the book
const book = shelf.books.find(book => book.id === bookId);
if (!book) return;
// Get HTML elements
const pagesCount = getBookElementById(bookId).getPagesCount();
// Change text
pagesCount.textContent = `${book.pages.length} Page${book.pages.length !== 1 ? 's' : ''}`;
}
// Function to remove an entire page book
function removeBook(bookId) {
// Find the shelf
const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
if (!shelf) return;
// Find the book index
const bookIndex = shelf.books.findIndex(book => book.id === bookId);
if (bookIndex < 0) return;
// Get HTML element
const bookContainer = getBookElementById(bookId);
if (!bookContainer) return;
// Remove the book
bookContainer.parentElement.removeChild(bookContainer);
shelf.books.splice(bookIndex, 1);
// Display a message if there are no pages
displayResultMessage();
// Save the updated bookShelfData
saveBookShelfDataToStorage();
}
// Display a message if there are no pages visible in the page
function displayResultMessage() {
// Find the shelf
const shelf = bookShelfData.find(shelf => shelf.id === selectedShelfId);
// Get HTML elements
const resultMessage = document.getElementById('resultMessage');
const bookContainers = document.getElementsByClassName('bookContainer');
// Check if any book is visible
const anyBooksVisible = Object.values(bookContainers).some(book => book.style.display === 'grid');
// Check if the data is correct
if (!shelf) {
resultMessage.style.display = 'block';
resultMessage.textContent = 'Error when loading the shelf. Try to reload the extension.';
}
// Check if there are books to visualize
else if (shelf.books.length === 0) {
resultMessage.style.display = 'block';
resultMessage.textContent = 'No pages saved. Try adding some.';
}
// Check if any book is visible
else if (!anyBooksVisible) {
resultMessage.style.display = 'block';
resultMessage.textContent = 'No pages match your search.';
}
else {
resultMessage.style.display = 'none';
resultMessage.textContent = '';
}
}
Thank you for sharing the comprehensive source code for your Chrome extension, "Bookshelf". I'll provide a detailed overview of how each component functions, followed by some general suggestions and considerations for possible modifications or improvements. If you have specific changes in mind, feel free to let me know, and I can assist you accordingly.
Overview of the Extension Components
1. Manifest (manifest.json)
Manifest Version: 3
Name: Bookshelf
Version: 0.9
Description: A tool to store and manage open tabs in an organized "bookshelf" to save memory.
Permissions:
tabs: To interact with browser tabs.
storage: To store and retrieve user data.
contextMenus: To create custom context menu items.
Background Service Worker:background.js handles background tasks.
Action: Defines the extension's icon and title, which appears in the Chrome toolbar.
Icons: Various sizes for different display contexts.
Homepage URL: Placeholder link for the extension's homepage.
2. Background Script (background.js)
UUID Generation: Uses crypto.randomUUID() to generate unique identifiers for shelves, books, and pages.
Action Click Listener: Opens tabs.html when the extension icon is clicked.
Context Menu Creation: On installation or update, creates several context menu items under the extension's action context:
Save pages on the left
Save pages on the right
Save only this page
Save all pages
Save all pages except this
Context Menu Click Handling: Depending on which menu item is clicked, it invokes the corresponding function to save tabs based on their position relative to the current tab.
Tab Saving Logic:
Filtering Tabs: Excludes pinned tabs and ensures only HTTP/HTTPS URLs are saved.
Bookshelf Structure: Organizes saved tabs into "shelves" and "books." Each shelf can contain multiple books, and each book consists of multiple pages (tabs).
Storage Management: Uses chrome.storage.local to persistently store the bookshelf data and the selected shelf.
3. Popup Page (tabs.html)
Header:
Shelf Title: Displays the currently selected shelf with a dropdown icon.
Search Bar: Allows users to search through saved pages.
Theme Selector: Dropdown to switch between different UI themes.
Settings Button: Opens the settings overlay.
Main Body:
Result Message: Shows messages like "Loading your bookshelf..." or "No pages saved."
Bookshelf Display: Renders the shelves, books, and pages.
Settings Overlay:
Overlay Background: Semi-transparent background to focus on the settings panel.
Settings Panel: Contains settings options (currently a placeholder).
4. Popup Script (tabs.js)
Initialization:
Loads bookshelf data from storage and displays it.
Sets up event listeners for UI interactions like editing shelf/book titles, adding/removing shelves, searching, theme switching, and handling settings.
UI Rendering:
Dynamically creates and manages HTML elements for shelves, books, and pages based on the stored data.
Provides functionalities to move, restore, and remove pages within books.
Event Handling:
Shelf Management: Add new shelves, edit shelf titles, remove shelves.
Book Management: Edit book titles, collapse/expand books, manage pages within books.
Page Management: Move selected pages, restore them as browser tabs, remove pages.
Search Functionality: Filters visible pages based on the search query.
Theme Management: Applies selected themes and persists the choice.
Settings Handling: Toggles the visibility of the settings overlay.
5. Stylesheet (tabs.css)
Theming: Supports multiple themes (Light Theme 1, Light Theme 2, Dark Theme 1, Dark Theme 2, Dark Theme 3) with corresponding CSS variables for colors.
Layout and Design:
Header: Fixed positioning with a clean layout for navigation and controls.
Bookshelf Display: Responsive grid layout for shelves and books.
Buttons and Controls: Styled buttons with hover effects, editable titles with indicators, and checkboxes for page selection.
Responsive Design: Ensures the UI adapts well to different screen sizes and states.
General Suggestions and Considerations
Based on the provided code, here are some suggestions and potential areas for modification or enhancement:
1. Enhancing User Experience
Drag and Drop Functionality:
Description: Allow users to reorder shelves, books, and pages using drag-and-drop interactions.
Benefit: Improves intuitiveness and ease of organization.
Bulk Actions:
Description: Enable bulk operations like moving multiple shelves or books at once.
Benefit: Simplifies managing large numbers of tabs.
Keyboard Shortcuts:
Description: Implement keyboard shortcuts for common actions (e.g., saving tabs, switching shelves).
Benefit: Provides power users with quicker access to functionalities.
2. Performance Optimization
Lazy Loading:
Description: Only render shelves, books, or pages when they are in view or selected.
Benefit: Reduces initial load time and improves performance, especially with large datasets.
Debouncing and Throttling:
Description: Optimize event listeners, especially for the search functionality, to prevent excessive rerenders.
Benefit: Enhances responsiveness and reduces unnecessary computations.
3. Data Management and Persistence
Synchronization:
Description: Use chrome.storage.sync instead of (or in addition to) chrome.storage.local for syncing data across devices.
Benefit: Allows users to access their bookshelf from multiple devices.
Data Backup and Restore:
Description: Provide options to export and import bookshelf data.
Benefit: Ensures users can back up their data and restore it if needed.
4. Security Enhancements
Content Security Policy (CSP):
Description: Ensure that the CSP in manifest.json restricts inline scripts and styles to prevent XSS attacks.
Benefit: Enhances the security of the extension.
Input Validation:
Description: Sanitize and validate user inputs, especially when editing titles, to prevent malicious data insertion.
Benefit: Protects against potential security vulnerabilities.
5. Accessibility Improvements
ARIA Labels and Roles:
Description: Add ARIA attributes to UI elements to make the extension more accessible to users utilizing screen readers.
Benefit: Enhances usability for users with disabilities.
Color Contrast:
Description: Ensure that all themes, especially dark themes, have sufficient color contrast for readability.
Benefit: Improves accessibility and readability.
6. Feature Enhancements
Tagging and Categorization:
Description: Allow users to tag or categorize books and pages for more flexible organization.
Benefit: Provides additional layers of organization beyond shelves and books.
Search Filtering Options:
Description: Offer advanced search filters (e.g., by date saved, domain, custom tags).
Benefit: Helps users quickly locate specific pages within their bookshelf.
Integration with Other Extensions or Services:
Description: Integrate with note-taking apps or productivity tools to enhance functionality.
Benefit: Adds value and versatility to the extension.
7. User Interface Refinements
Responsive Design:
Description: Ensure the UI scales well across different window sizes and resolutions.
Benefit: Provides a consistent experience on various devices.
Animations and Transitions:
Description: Add smooth animations for expanding/collapsing shelves, books, and pages.
Benefit: Makes interactions feel more natural and engaging.
Theme Customization:
Description: Allow users to create and customize their own themes beyond the predefined options.
Benefit: Offers personalization and caters to diverse user preferences.
8. Error Handling and Notifications
User Notifications:
Description: Inform users of successful saves, errors, or important actions through toast notifications or modals.
Benefit: Keeps users informed about the extension's operations and any issues that arise.
Robust Error Handling:
Description: Implement comprehensive error handling throughout the scripts to gracefully manage unexpected scenarios.
Benefit: Prevents the extension from crashing and enhances reliability.
Potential Modifications Based on Current Functionality
Given that "Bookshelf" functions similarly to "OneTab" by saving and managing browser tabs, here are some specific modifications you might consider:
1. Duplicate Tab Handling
Feature: Automatically detect and handle duplicate tabs to prevent redundancy within the bookshelf.
Implementation: Before saving tabs, check if a tab with the same URL already exists in the bookshelf. Offer options to skip, replace, or merge duplicates.
2. Import Existing OneTab/Better OneTab Data
Feature: Allow users to import their existing data from "OneTab" or "Better OneTab" for a seamless transition.
Implementation: Provide an import feature in the settings where users can paste JSON data exported from the other extensions.
3. Integration with Tab Groups
Feature: Sync or integrate with Chrome's native tab groups for enhanced organization.
Implementation: Map tab groups to bookshelf shelves or books, allowing synchronization between native groups and the bookshelf.
4. Enhanced Search and Filtering
Feature: Improve the search functionality to include filters like domain, recently added, or custom tags.
Implementation: Modify the search bar to offer advanced filtering options and update the displayBookShelf function to handle these filters.
5. Exporting Bookshelf Data
Feature: Allow users to export their bookshelf data as a JSON file for backup or sharing purposes.
Implementation: Add an export button in the settings that serializes bookShelfData and prompts the user to download it.
6. Managing Book Capacity
Feature: Set limits on the number of books or pages within a shelf to prevent clutter.
Implementation: Implement checks when adding new books or pages and notify users when limits are reached.
7. Customizable Shelf and Book Names
Feature: Allow users to custom name their shelves and books beyond the default "Shelf X" and "Book Y" titles.
Implementation: Enhance the title editing functionality to support more options and validations.
8. Theming Enhancements
Feature: Introduce more themes, including high-contrast and user-defined themes.
Implementation: Expand the tabs.css with additional themes and provide a user interface for theme creation and customization.
9. Mobile Support
Feature: Adapt the extension's interface for better usability on tablet devices.
Implementation: Implement responsive design tweaks in tabs.css to enhance touch interactions and layout on smaller screens.
10. Analytics and Usage Stats
Feature: Track usage statistics to understand how users interact with their bookshelf.
Implementation: Collect anonymized data on actions like saving, restoring, and removing pages, and present insights in the settings.
Next Steps
To provide more targeted assistance, please let me know:
Specific Modifications:
What particular features or changes are you looking to implement?
Are there any issues or bugs you've encountered that need addressing?
Enhancements or New Features:
Any new functionalities you wish to add beyond the current scope?
UI/UX improvements you have in mind?
Optimization Goals:
Are you aiming to improve performance, security, accessibility, etc.?
User Feedback or Requests:
Have you received any feedback from users that you'd like to incorporate?
Feel free to provide details on the modifications you have in mind, and I can assist you with code snippets, explanations, or strategies to implement them effectively.