Skip to content

Commit

Permalink
Merge pull request #187 from vict0rsch/remove-custom-title
Browse files Browse the repository at this point in the history
  • Loading branch information
vict0rsch authored Nov 20, 2023
2 parents 14bbc8f + b87f9ad commit dae103b
Show file tree
Hide file tree
Showing 9 changed files with 18 additions and 227 deletions.
4 changes: 2 additions & 2 deletions manifest.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"name": "Paper Memory",
"version": "0.5.13",
"version": "0.6.0",
"manifest_version": 2,
"description": "Automatically record papers and their codes from Arxiv, OpenReview & more! Organize your library with tags, links and quick notes.",
"homepage_url": "https://github.com/vict0rsch/PaperMemory",
"homepage_url": "https://papermemory.org",
"icons": {
"192": "icons/favicon-192x192.png"
},
Expand Down
1 change: 0 additions & 1 deletion src/content_scripts/content_script.js
Original file line number Diff line number Diff line change
Expand Up @@ -570,7 +570,6 @@ const huggingfacePapers = (paper, url) => {

const arxiv = async (checks) => {
const { checkMd, checkBib, checkDownload, checkStore } = checks;
global.state.titleFunction = (await getTitleFunction()).titleFunction;

const url = window.location.href;
const isArxivAbs = url.includes("https://arxiv.org/abs/");
Expand Down
42 changes: 0 additions & 42 deletions src/options/options.html
Original file line number Diff line number Diff line change
Expand Up @@ -215,48 +215,6 @@ <h2 id="select-sources">Select Sources</h2>

<hr>

<div class="section">
<h2 id="custom-title-function">Custom title function</h2>
<p>Provide a Javascript function code to produce a "title" from a <code>paper</code> object. This function
<em>must</em> return a <code>string</code> which will be used to 1/ Change the webpage titles 2/ Name
the pdf files you download with Paper Memory. The <code>.pdf</code> extension will be added
automatically, you need not include it in the returned string.
</p>
<p>Note that not all characters are usable for file names <a
href="https://superuser.com/questions/358855/what-characters-are-safe-in-cross-platform-file-names-for-linux-windows-and-os">depending
on your os</a>.</p>
<p>In order for PaperMemory to know one of its items has been downloaded, it will match downloaded pdf file
names to in-memory paper titles. If you remove the title from the downloaded file names, PaperMemory
will
not be able to do this anymore and may miss stored papers.</p>
<p>For illustration, an example from your memory is displayed after the code input.</p>
<div class="row">

<div class="col-6">
<textarea id="custom-title-textarea" style="font-family: 'Fira Code'; font-size: 0.8rem;"
class="w-100 mb-2" rows="7"></textarea>
<div class="flex-center-evenly mb-3">
<button id="custom-title-save">Save function</button>
<button id="custom-title-default">Back to default</button>
</div>
<div id="custom-title-feedback"></div>
</div>
<div class="col-6">
Example paper :
<code id="custom-title-example"></code><span id="another-paper">(try another)</span>
<br />
<br />
<span>Available keys:</span>
<span id="paper-available-keys"></span>
</div>
<div class="col-12 mt-3">Result: <br /><code id="custom-title-result"></code></div>

</div>

</div>

<hr>

<div class="section">
<h2 id="data-management">Data Management</h2>

Expand Down
80 changes: 0 additions & 80 deletions src/options/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -571,85 +571,6 @@ const setupPreprintMatching = async () => {
});
};

// -----------------------------------
// ----- Custom title function -----
// -----------------------------------

const handleCustomPDFFunctionSave = async () => {
const userCode = val("custom-title-textarea").trim();
const { titleFunction, code, errorMessage } = await getTitleFunction(userCode);
const examplePaper = await getExamplePaper(0);
setHTML("custom-title-example", examplePaper.title);
if (errorMessage) {
const errorFeedback = /*html*/ `<span style="color: red">${errorMessage}</span>`;
setHTML("custom-title-feedback", errorFeedback);
} else {
findEl("custom-title-result").innerText = titleFunction(examplePaper);
// save function string
chrome.storage.local.set({ titleFunctionCode: code });
// no error so far: all good!
const savedFeedback = /*html*/ `<span style="color: green">Saved!</span>`;
setHTML("custom-title-feedback", savedFeedback);
setTimeout(() => {
setHTML("custom-title-feedback", "");
}, 1000);
}
};

const handleDefaultPDFFunctionClick = async () => {
const code = global.defaultTitleFunctionCode;
const titleFunction = eval(code);
chrome.storage.local.set({ titleFunctionCode: code });
val("custom-title-textarea", code);

const examplePaper = await getExamplePaper(0);
setHTML("custom-title-example", examplePaper.title);
findEl("custom-title-result").innerText = titleFunction(examplePaper);

const savedFeedback = /*html*/ `<span style="color: var(--green)"
>Saved!</span
>`;
setHTML("custom-title-feedback", savedFeedback);
setTimeout(() => {
setHTML("custom-title-feedback", "");
}, 1000);
};

const handleTryAnotherPaper = async () => {
const examplePaper = await getExamplePaper();
const { titleFunction } = await getTitleFunction();
setHTML("custom-title-example", examplePaper.title);
findEl("custom-title-result").innerText = titleFunction(examplePaper);
};

/**
* Retrieve the custom pdf function, updates the associated textarea and adds and
* event listener for when the latter changes.
*/
const setupTitleFunction = async () => {
// attempt to use the user's custom function
const { titleFunction, code } = await getTitleFunction();

// update the user's textarea
val("custom-title-textarea", code);
const examplePaper = await getExamplePaper(0);
findEl("custom-title-example").innerText = examplePaper.title;
findEl("custom-title-result").innerText = titleFunction(examplePaper);
setHTML(
"paper-available-keys",
Object.keys(examplePaper)
.map((k) => `<code>${k}</code>`)
.join(", ")
);
// listen to saving click
addListener("custom-title-save", "click", handleCustomPDFFunctionSave);
// listen to the event resetting the pdf title function
// to the built-in default
addListener("custom-title-default", "click", handleDefaultPDFFunctionClick);
// listen to the 'try another' paper button
addListener("another-paper", "click", handleTryAnotherPaper);
};

// -----------------------------
// ----- Data Management -----
// -----------------------------
Expand Down Expand Up @@ -1371,7 +1292,6 @@ const setupModals = () => {
setupImportPapers();
setUpKeyboardListeners();
setupSourcesSelection();
setupTitleFunction();
setupDataManagement();
setupSync();
setupModals();
Expand Down
1 change: 1 addition & 0 deletions src/popup/js/popup.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ const setStandardPopupClicks = () => {
showPopupModal("keyboard");
});
shouldWarn("pdf-title", (displayWarning) => {
// keep as demo ; remove when another shouldWarn is added
if (displayWarning) {
showId("warning-button");
addListener("warning-button", "click", async () => {
Expand Down
17 changes: 9 additions & 8 deletions src/shared/js/utils/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,18 @@ global.state = {
sortedPapers: [], // [papers]
sortKey: "",
titleHashToIds: {}, // (miniHash(title) -> [ids])
titleFunction: null, // function(paper) => string
urlHashToId: {}, // (miniHash(url) => id)
};

global.state.titleFunction = (paper) => {
const title = paper.title.replaceAll("\n", "");
const id = paper.id;
let name = `${title} - ${id}`;
name = name.replaceAll(":", " ").replace(/\\s\\s+/g, " ");
return name;
};

global.descendingSortKeys = [
"addDate",
"count",
Expand Down Expand Up @@ -253,13 +262,6 @@ global.consolHeaderStyle =
*/
global.fuzzyTitleMatchMinDist = 4;

global.defaultTitleFunctionCode = `
(paper) => {\n
const title = paper.title.replaceAll("\\n", '');\n
const id = paper.id;\n
let name = \`\${title} - \${id}\`;\n
name = name.replaceAll(":", " ").replace(/\\s\\s+/g, " ");\n
return name\n};`;
global.storeReadme = `
/!\\ Warning: This folder has been created automatically by your PaperMemory browser extension.\n
/!\\ It has to stay in your downloads for PaperMemory to be able to access your papers.\n
Expand Down Expand Up @@ -422,7 +424,6 @@ if (typeof module !== "undefined" && module.exports != null) {
overridePMLRConfs: global.overridePMLRConfs,
overrideDBLPVenues: global.overrideDBLPVenues,
fuzzyTitleMatchMinDist: global.fuzzyTitleMatchMinDist,
defaultTitleFunctionCode: global.defaultTitleFunctionCode,
storeReadme: global.storeReadme,
englishStopWords: global.englishStopWords,
journalAbbreviations: global.journalAbbreviations,
Expand Down
9 changes: 0 additions & 9 deletions src/shared/js/utils/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -811,15 +811,6 @@ const silentPromiseTimeout = (prom, time = 5000) => {
};

const shouldWarn = async (warningName, callback = () => {}) => {
if (warningName === "pdf-title") {
const code = await getStorage("titleFunctionCode");
if (code && code !== global.defaultTitleFunctionCode) {
const warnings = (await getStorage("userWarnings")) ?? {};
if (!warnings[warningName]) {
return callback(true);
}
}
}
return callback(false);
};

Expand Down
75 changes: 1 addition & 74 deletions src/shared/js/utils/state.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,6 @@ const initState = async ({ papers, isContentScript, print = true } = {}) => {
print && log("Time to parse data version (s): " + duration(times));
times.unshift(Date.now());

global.state.titleFunction = (await getTitleFunction()).titleFunction;
print && log("Time to make title function (s): " + duration(times));
times.unshift(Date.now());

weeklyBackup();
print && log("Time to backup papers (weekly) (s): " + duration(times));
times.unshift(Date.now());
Expand Down Expand Up @@ -187,65 +183,6 @@ const getExamplePaper = async (idx) => {
return paper;
};

/**
* Tries to parse the text input by the user to define the function that takes
* a paper in order to create the custom page title / pdf filename.
* If there is an error, it uses the built-in function from global.defaultTitleFunctionCode.
* @param {string} code The string describing the code function.
* @returns {function} Either the user's function if it runs without errors, or the built-in
* formatting function
*/
const getTitleFunction = async (code = null) => {
let titleFunction;
if (!code) {
// no code provided: load it from storage
code = await getStorage("titleFunctionCode");
}
if (typeof code === "undefined") {
// no code provided and no code in storage: use the built-in function code
code = global.defaultTitleFunctionCode;
}

let errorMessage;

try {
// eval the code into a function
titleFunction = eval(code);
} catch (error) {
// there was an error evaluating the code: use the built-in function
errorMessage = `Error parsing the title function: ${error}`;
log("Error parsing the title function. Function string then error:");
log(code);
log(error);
titleFunction = eval(global.defaultTitleFunctionCode);
code = global.defaultTitleFunctionCode;
}

try {
// test the loaded title function on a paper
const examplePaper = await getExamplePaper(0);
const result = titleFunction(examplePaper);
// assert the result is a string
if (typeof result !== "string") {
throw new Error(`Result ${result} is not a string`);
}
} catch (error) {
// there was an error running the title function: use the built-in function
errorMessage = `Error executing the title function: ${error}`;
log("Error testing the user's title function. Function string then error:");
log(code);
log(error);
titleFunction = eval(global.defaultTitleFunctionCode);
code = global.defaultTitleFunctionCode;
}

return {
titleFunction: titleFunction, // the function to use
code: code.trim(), // the code to store in storage
errorMessage: errorMessage, // potential error message
};
};

/**
* Uses the state-loaded title function to get the title of a paper.
*
Expand All @@ -263,16 +200,7 @@ const stateTitleFunction = (paperOrId) => {
return "Unknown ID";
}
}
let name;
try {
// try using the state-loaded title function
name = global.state.titleFunction(paper);
} catch (error) {
// there was an error: use the built-in function
log("Error in stateTitleFunction:", error);
name = eval(global.defaultTitleFunctionCode)(paper);
}
// make sure there's no new line and no double spaces in the title
const name = global.state.titleFunction(paper);
return name.replaceAll("\n", " ").replace(/\s\s+/g, " ");
};

Expand Down Expand Up @@ -368,7 +296,6 @@ if (typeof module !== "undefined" && module.exports != null) {
dummyModule.exports = {
initState,
getExamplePaper,
getTitleFunction,
stateTitleFunction,
updateDuplicatedUrls,
addPaperToTitleHashToId,
Expand Down
Loading

0 comments on commit dae103b

Please sign in to comment.