Skip to content

Build your personal knowledge base with Trilium Notes

chore(web-clipper): port most files to TypeScript

Elian Doran266494ba8c54
diff --git a/apps/web-clipper/entrypoints/background/trilium_server_facade.js b/apps/web-clipper/entrypoints/background/trilium_server_facade.js
deleted file mode 100644
index b1a56a7ec4..0000000000
--- a/apps/web-clipper/entrypoints/background/trilium_server_facade.js
+++ /dev/null
@@ -1,223 +0,0 @@
-const PROTOCOL_VERSION_MAJOR = 1;
-
-export function isDevEnv() {
- const manifest = browser.runtime.getManifest();
-
- return manifest.name.endsWith('(dev)');
-}
-
-export default class TriliumServerFacade {
- constructor() {
- this.triggerSearchForTrilium();
-
- // continually scan for changes (if e.g. desktop app is started after browser)
- setInterval(() => this.triggerSearchForTrilium(), 60 * 1000);
- }
-
- async sendTriliumSearchStatusToPopup() {
- try {
- await browser.runtime.sendMessage({
- name: "trilium-search-status",
- triliumSearch: this.triliumSearch
- });
- }
- catch (e) {} // nothing might be listening
- }
- async sendTriliumSearchNoteToPopup(){
- try{
- await browser.runtime.sendMessage({
- name: "trilium-previously-visited",
- searchNote: this.triliumSearchNote
- })
-
- }
- catch (e) {} // nothing might be listening
- }
-
- setTriliumSearchNote(st){
- this.triliumSearchNote = st;
- this.sendTriliumSearchNoteToPopup();
- }
-
- setTriliumSearch(ts) {
- this.triliumSearch = ts;
-
- this.sendTriliumSearchStatusToPopup();
- }
-
- setTriliumSearchWithVersionCheck(json, resp) {
- const [major, minor] = json.protocolVersion
- .split(".")
- .map(chunk => parseInt(chunk));
-
- // minor version is intended to be used to dynamically limit features provided by extension
- // if some specific Trilium API is not supported. So far not needed.
-
- if (major !== PROTOCOL_VERSION_MAJOR) {
- this.setTriliumSearch({
- status: 'version-mismatch',
- extensionMajor: PROTOCOL_VERSION_MAJOR,
- triliumMajor: major
- });
- }
- else {
- this.setTriliumSearch(resp);
- }
- }
-
- async triggerSearchForTrilium() {
- this.setTriliumSearch({ status: 'searching' });
-
- try {
- const port = await this.getPort();
-
- console.debug('Trying port ' + port);
-
- const resp = await fetch(`http://127.0.0.1:${port}/api/clipper/handshake`);
-
- const text = await resp.text();
-
- console.log("Received response:", text);
-
- const json = JSON.parse(text);
-
- if (json.appName === 'trilium') {
- this.setTriliumSearchWithVersionCheck(json, {
- status: 'found-desktop',
- port: port,
- url: 'http://127.0.0.1:' + port
- });
-
- return;
- }
- }
- catch (error) {
- // continue
- }
-
- const {triliumServerUrl} = await browser.storage.sync.get("triliumServerUrl");
- const {authToken} = await browser.storage.sync.get("authToken");
-
- if (triliumServerUrl && authToken) {
- try {
- const resp = await fetch(triliumServerUrl + '/api/clipper/handshake', {
- headers: {
- Authorization: authToken
- }
- });
-
- const text = await resp.text();
-
- console.log("Received response:", text);
-
- const json = JSON.parse(text);
-
- if (json.appName === 'trilium') {
- this.setTriliumSearchWithVersionCheck(json, {
- status: 'found-server',
- url: triliumServerUrl,
- token: authToken
- });
-
- return;
- }
- }
- catch (e) {
- console.log("Request to the configured server instance failed with:", e);
- }
- }
-
- // if all above fails it's not found
- this.setTriliumSearch({ status: 'not-found' });
- }
-
- async triggerSearchNoteByUrl(noteUrl) {
- const resp = await this.callService('GET', 'notes-by-url/' + encodeURIComponent(noteUrl))
- let newStatus = {
- status: 'not-found',
- noteId: null
- }
- if (resp && resp.noteId) {
- newStatus.noteId = resp.noteId;
- newStatus.status = 'found';
- }
- this.setTriliumSearchNote(newStatus);
- }
- async waitForTriliumSearch() {
- return new Promise((res, rej) => {
- const checkStatus = () => {
- if (this.triliumSearch.status === "searching") {
- setTimeout(checkStatus, 500);
- }
- else if (this.triliumSearch.status === 'not-found') {
- rej(new Error("Trilium instance has not been found."));
- }
- else {
- res();
- }
- };
-
- checkStatus();
- });
- }
-
- async getPort() {
- const {triliumDesktopPort} = await browser.storage.sync.get("triliumDesktopPort");
-
- if (triliumDesktopPort) {
- return parseInt(triliumDesktopPort);
- }
- else {
- return isDevEnv() ? 37740 : 37840;
- }
- }
-
- async callService(method, path, body) {
- const fetchOptions = {
- method: method,
- headers: {
- 'Content-Type': 'application/json'
- },
- };
-
- if (body) {
- fetchOptions.body = typeof body === 'string' ? body : JSON.stringify(body);
- }
-
- try {
- await this.waitForTriliumSearch();
-
- fetchOptions.headers.Authorization = this.triliumSearch.token || "";
- fetchOptions.headers['trilium-local-now-datetime'] = this.localNowDateTime();
-
- const url = this.triliumSearch.url + "/api/clipper/" + path;
-
- console.log(`Sending ${method} request to ${url}`);
-
- const response = await fetch(url, fetchOptions);
-
- if (!response.ok) {
- throw new Error(await response.text());
- }
-
- return await response.json();
- }
- catch (e) {
- console.log("Sending request to trilium failed", e);
-
- toast('Your request failed because we could not contact Trilium instance. Please make sure Trilium is running and is accessible.');
-
- return null;
- }
- }
-
- localNowDateTime() {
- const date = new Date();
- const off = date.getTimezoneOffset();
- const absoff = Math.abs(off);
- return (new Date(date.getTime() - off * 60 * 1000).toISOString().substr(0,23).replace("T", " ") +
- (off > 0 ? '-' : '+') +
- (absoff / 60).toFixed(0).padStart(2,'0') + ':' +
- (absoff % 60).toString().padStart(2,'0'));
- }
-}
diff --git a/apps/web-clipper/entrypoints/background/trilium_server_facade.ts b/apps/web-clipper/entrypoints/background/trilium_server_facade.ts
new file mode 100644
index 0000000000..f9854437f4
--- /dev/null
+++ b/apps/web-clipper/entrypoints/background/trilium_server_facade.ts
@@ -0,0 +1,253 @@
+const PROTOCOL_VERSION_MAJOR = 1;
+
+export function isDevEnv() {
+ const manifest = browser.runtime.getManifest();
+
+ return manifest.name.endsWith('(dev)');
+}
+
+type TriliumSearchStatus = {
+ status: "searching";
+} | {
+ status: "not-found"
+} | {
+ status: "found-desktop",
+ port: number;
+ url: string;
+} | {
+ status: "found-server",
+ url: string;
+ token: string;
+} | {
+ status: "version-mismatch";
+ extensionMajor: number;
+ triliumMajor: number;
+};
+
+type TriliumSearchNoteStatus = {
+ status: "not-found",
+ noteId: null
+} | {
+ status: "found",
+ noteId: string
+};
+
+export default class TriliumServerFacade {
+ private triliumSearch?: TriliumSearchStatus;
+ private triliumSearchNote?: TriliumSearchNoteStatus;
+
+ constructor() {
+ this.triggerSearchForTrilium();
+
+ // continually scan for changes (if e.g. desktop app is started after browser)
+ setInterval(() => this.triggerSearchForTrilium(), 60 * 1000);
+ }
+
+ async sendTriliumSearchStatusToPopup() {
+ try {
+ await browser.runtime.sendMessage({
+ name: "trilium-search-status",
+ triliumSearch: this.triliumSearch
+ });
+ }
+ catch (e) {} // nothing might be listening
+ }
+ async sendTriliumSearchNoteToPopup(){
+ try{
+ await browser.runtime.sendMessage({
+ name: "trilium-previously-visited",
+ searchNote: this.triliumSearchNote
+ });
+
+ }
+ catch (e) {} // nothing might be listening
+ }
+
+ setTriliumSearchNote(st){
+ this.triliumSearchNote = st;
+ this.sendTriliumSearchNoteToPopup();
+ }
+
+ setTriliumSearch(ts: TriliumSearchStatus) {
+ this.triliumSearch = ts;
+
+ this.sendTriliumSearchStatusToPopup();
+ }
+
+ setTriliumSearchWithVersionCheck(json: { protocolVersion: string }, resp: TriliumSearchStatus) {
+ const [major, minor] = json.protocolVersion
+ .split(".")
+ .map(chunk => parseInt(chunk, 10));
+
+ // minor version is intended to be used to dynamically limit features provided by extension
+ // if some specific Trilium API is not supported. So far not needed.
+
+ if (major !== PROTOCOL_VERSION_MAJOR) {
+ this.setTriliumSearch({
+ status: 'version-mismatch',
+ extensionMajor: PROTOCOL_VERSION_MAJOR,
+ triliumMajor: major
+ });
+ }
+ else {
+ this.setTriliumSearch(resp);
+ }
+ }
+
+ async triggerSearchForTrilium() {
+ this.setTriliumSearch({ status: 'searching' });
+
+ try {
+ const port = await this.getPort();
+
+ console.debug(`Trying port ${ port}`);
+
+ const resp = await fetch(`http://127.0.0.1:${port}/api/clipper/handshake`);
+
+ const text = await resp.text();
+
+ console.log("Received response:", text);
+
+ const json = JSON.parse(text);
+
+ if (json.appName === 'trilium') {
+ this.setTriliumSearchWithVersionCheck(json, {
+ status: 'found-desktop',
+ port,
+ url: `http://127.0.0.1:${port}`
+ });
+
+ return;
+ }
+ }
+ catch (error) {
+ // continue
+ }
+
+ const {triliumServerUrl} = await browser.storage.sync.get<{ triliumServerUrl: string }>("triliumServerUrl");
+ const {authToken} = await browser.storage.sync.get<{ authToken: string }>("authToken");
+
+ if (triliumServerUrl && authToken) {
+ try {
+ const resp = await fetch(`${triliumServerUrl }/api/clipper/handshake`, {
+ headers: {
+ Authorization: authToken
+ }
+ });
+
+ const text = await resp.text();
+
+ console.log("Received response:", text);
+
+ const json = JSON.parse(text);
+
+ if (json.appName === 'trilium') {
+ this.setTriliumSearchWithVersionCheck(json, {
+ status: 'found-server',
+ url: triliumServerUrl,
+ token: authToken
+ });
+
+ return;
+ }
+ }
+ catch (e) {
+ console.log("Request to the configured server instance failed with:", e);
+ }
+ }
+
+ // if all above fails it's not found
+ this.setTriliumSearch({ status: 'not-found' });
+ }
+
+ async triggerSearchNoteByUrl(noteUrl) {
+ const resp = await this.callService('GET', `notes-by-url/${encodeURIComponent(noteUrl)}`);
+ let newStatus: TriliumSearchNoteStatus;
+ if (resp && resp.noteId) {
+ newStatus = {
+ status: 'found',
+ noteId: resp.noteId,
+ };
+ } else {
+ newStatus = {
+ status: 'not-found',
+ noteId: null
+ };
+ }
+ this.setTriliumSearchNote(newStatus);
+ }
+ async waitForTriliumSearch() {
+ return new Promise<void>((res, rej) => {
+ const checkStatus = () => {
+ if (this.triliumSearch?.status === "searching") {
+ setTimeout(checkStatus, 500);
+ } else if (this.triliumSearch?.status === 'not-found') {
+ rej(new Error("Trilium instance has not been found."));
+ } else {
+ res();
+ }
+ };
+
+ checkStatus();
+ });
+ }
+
+ async getPort() {
+ const {triliumDesktopPort} = await browser.storage.sync.get<{ triliumDesktopPort: string }>("triliumDesktopPort");
+
+ if (triliumDesktopPort) {
+ return parseInt(triliumDesktopPort, 10);
+ }
+
+ return isDevEnv() ? 37740 : 37840;
+ }
+
+ async callService(method: string, path: string, body?: string | object) {
+ await this.waitForTriliumSearch();
+ if (!this.triliumSearch || (this.triliumSearch.status !== 'found-desktop' && this.triliumSearch.status !== 'found-server')) return;
+
+ try {
+ const fetchOptions: RequestInit = {
+ method,
+ headers: {
+ Authorization: "token" in this.triliumSearch ? this.triliumSearch.token ?? "" : "",
+ 'Content-Type': 'application/json',
+ 'trilium-local-now-datetime': this.localNowDateTime()
+ },
+ };
+
+ if (body) {
+ fetchOptions.body = typeof body === 'string' ? body : JSON.stringify(body);
+ }
+
+ const url = `${this.triliumSearch.url}/api/clipper/${path}`;
+
+ console.log(`Sending ${method} request to ${url}`);
+
+ const response = await fetch(url, fetchOptions);
+
+ if (!response.ok) {
+ throw new Error(await response.text());
+ }
+
+ return await response.json();
+ }
+ catch (e) {
+ console.log("Sending request to trilium failed", e);
+
+ window.showToast('Your request failed because we could not contact Trilium instance. Please make sure Trilium is running and is accessible.');
+
+ return null;
+ }
+ }
+
+ localNowDateTime() {
+ const date = new Date();
+ const off = date.getTimezoneOffset();
+ const absoff = Math.abs(off);
+ return (`${new Date(date.getTime() - off * 60 * 1000).toISOString().substr(0,23).replace("T", " ") +
+ (off > 0 ? '-' : '+') +
+ (absoff / 60).toFixed(0).padStart(2,'0') }:${
+ (absoff % 60).toString().padStart(2,'0')}`);
+ }
+}
diff --git a/apps/web-clipper/entrypoints/content/index.js b/apps/web-clipper/entrypoints/content/index.ts
similarity index 79%
rename from apps/web-clipper/entrypoints/content/index.js
rename to apps/web-clipper/entrypoints/content/index.ts
index e5c3642479..0ee35ef0d8 100644
--- a/apps/web-clipper/entrypoints/content/index.js
+++ b/apps/web-clipper/entrypoints/content/index.ts
@@ -1,5 +1,5 @@
-import { createLink, getBaseUrl, getPageLocationOrigin, randomString } from "../../utils.js";
import Readability from "../../lib/Readability.js";
+import { createLink, getBaseUrl, getPageLocationOrigin, randomString } from "../../utils.js";
export default defineContentScript({
matches: [
@@ -19,10 +19,10 @@ export default defineContentScript({
if (url.indexOf('//') === 0) {
return location.protocol + url;
} else if (url[0] === '/') {
- return location.protocol + '//' + location.host + url;
- } else {
- return getBaseUrl() + '/' + url;
+ return `${location.protocol}//${location.host}${url}`;
}
+ return `${getBaseUrl()}/${url}`;
+
}
function pageTitle() {
@@ -47,40 +47,37 @@ export default defineContentScript({
return {
title: article.title,
body: article.content,
- }
+ };
}
function getDocumentDates() {
- var dates = {
- publishedDate: null,
- modifiedDate: null,
- };
+ let publishedDate: Date | null = null;
+ let modifiedDate: Date | null = null;
- const articlePublishedTime = document.querySelector("meta[property='article:published_time']");
- if (articlePublishedTime && articlePublishedTime.getAttribute('content')) {
- dates.publishedDate = new Date(articlePublishedTime.getAttribute('content'));
+ const articlePublishedTime = document.querySelector("meta[property='article:published_time']")?.getAttribute('content');
+ if (articlePublishedTime && articlePublishedTime) {
+ publishedDate = new Date(articlePublishedTime);
}
- const articleModifiedTime = document.querySelector("meta[property='article:modified_time']");
- if (articleModifiedTime && articleModifiedTime.getAttribute('content')) {
- dates.modifiedDate = new Date(articleModifiedTime.getAttribute('content'));
+ const articleModifiedTime = document.querySelector("meta[property='article:modified_time']")?.getAttribute('content');
+ if (articleModifiedTime && articleModifiedTime) {
+ modifiedDate = new Date(articleModifiedTime);
}
// TODO: if we didn't get dates from meta, then try to get them from JSON-LD
-
- return dates;
+ return { publishedDate, modifiedDate };
}
function getRectangleArea() {
- return new Promise((resolve, reject) => {
+ return new Promise((resolve) => {
const overlay = document.createElement('div');
overlay.style.opacity = '0.6';
overlay.style.background = 'black';
overlay.style.width = '100%';
overlay.style.height = '100%';
- overlay.style.zIndex = 99999999;
- overlay.style.top = 0;
- overlay.style.left = 0;
+ overlay.style.zIndex = "99999999";
+ overlay.style.top = "0";
+ overlay.style.left = "0";
overlay.style.position = 'fixed';
document.body.appendChild(overlay);
@@ -92,15 +89,15 @@ export default defineContentScript({
messageComp.style.position = 'fixed';
messageComp.style.opacity = '0.95';
messageComp.style.fontSize = '14px';
- messageComp.style.width = messageCompWidth + 'px';
- messageComp.style.maxWidth = messageCompWidth + 'px';
+ messageComp.style.width = `${messageCompWidth }px`;
+ messageComp.style.maxWidth = `${messageCompWidth }px`;
messageComp.style.border = '1px solid black';
messageComp.style.background = 'white';
messageComp.style.color = 'black';
messageComp.style.top = '10px';
messageComp.style.textAlign = 'center';
messageComp.style.padding = '10px';
- messageComp.style.left = Math.round(document.body.clientWidth / 2 - messageCompWidth / 2) + 'px';
+ messageComp.style.left = `${Math.round(document.body.clientWidth / 2 - messageCompWidth / 2) }px`;
messageComp.style.zIndex = overlay.style.zIndex + 1;
messageComp.textContent = 'Drag and release to capture a screenshot';
@@ -112,9 +109,9 @@ export default defineContentScript({
selection.style.border = '1px solid red';
selection.style.background = 'white';
selection.style.border = '2px solid black';
- selection.style.zIndex = overlay.style.zIndex - 1;
- selection.style.top = 0;
- selection.style.left = 0;
+ selection.style.zIndex = String(parseInt(overlay.style.zIndex, 10) - 1);
+ selection.style.top = "0";
+ selection.style.left = "0";
selection.style.position = 'fixed';
document.body.appendChild(selection);
@@ -122,17 +119,19 @@ export default defineContentScript({
messageComp.focus(); // we listen on keypresses on this element to cancel on escape
let isDragging = false;
- let draggingStartPos = null;
- let selectionArea = {};
+ let draggingStartPos: {x: number, y: number} | null = null;
+ let selectionArea: {x?: number, y?: number, width?: number, height?: number} = {};
function updateSelection() {
- selection.style.left = selectionArea.x + 'px';
- selection.style.top = selectionArea.y + 'px';
- selection.style.width = selectionArea.width + 'px';
- selection.style.height = selectionArea.height + 'px';
+ selection.style.left = `${selectionArea.x}px`;
+ selection.style.top = `${selectionArea.y}px`;
+ selection.style.width = `${selectionArea.width}px`;
+ selection.style.height = `${selectionArea.height}px`;
}
function setSelectionSizeFromMouse(event) {
+ if (!draggingStartPos) return;
+
if (event.clientX < draggingStartPos.x) {
selectionArea.x = event.clientX;
}
@@ -209,8 +208,8 @@ export default defineContentScript({
}
}
- function getImages(container) {
- const images = [];
+ function getImages(container: HTMLElement) {
+ const images: {imageId: string, src: string}[] = [];
for (const img of container.getElementsByTagName('img')) {
if (!img.src) {
@@ -226,7 +225,7 @@ export default defineContentScript({
const imageId = randomString(20);
images.push({
- imageId: imageId,
+ imageId,
src: img.src
});
@@ -237,16 +236,16 @@ export default defineContentScript({
return images;
}
- async function prepareMessageResponse(message) {
- console.info('Message: ' + message.name);
+ async function prepareMessageResponse(message: {name: string, noteId?: string, message?: string, tabIds?: string[]}) {
+ console.info(`Message: ${ message.name}`);
if (message.name === "toast") {
let messageText;
if (message.noteId) {
messageText = document.createElement('p');
- messageText.setAttribute("style", "padding: 0; margin: 0; font-size: larger;")
- messageText.appendChild(document.createTextNode(message.message + " "));
+ messageText.setAttribute("style", "padding: 0; margin: 0; font-size: larger;");
+ messageText.appendChild(document.createTextNode(`${message.message } `));
messageText.appendChild(createLink(
{name: 'openNoteInTrilium', noteId: message.noteId},
"Open in Trilium."
@@ -268,7 +267,7 @@ export default defineContentScript({
await import("../../lib/toast");
- showToast(messageText, {
+ window.showToast(messageText, {
settings: {
duration: 7000
}
@@ -278,6 +277,9 @@ export default defineContentScript({
const container = document.createElement('div');
const selection = window.getSelection();
+ if (!selection || selection.rangeCount === 0) {
+ throw new Error('No selection available to clip');
+ }
for (let i = 0; i < selection.rangeCount; i++) {
const range = selection.getRangeAt(i);
@@ -292,7 +294,7 @@ export default defineContentScript({
return {
title: pageTitle(),
content: container.innerHTML,
- images: images,
+ images,
pageUrl: getPageLocationOrigin() + location.pathname + location.search + location.hash
};
@@ -307,26 +309,26 @@ export default defineContentScript({
const images = getImages(body);
- var labels = {};
+ const labels = {};
const dates = getDocumentDates();
if (dates.publishedDate) {
labels['publishedDate'] = dates.publishedDate.toISOString().substring(0, 10);
}
if (dates.modifiedDate) {
- labels['modifiedDate'] = dates.publishedDate.toISOString().substring(0, 10);
+ labels['modifiedDate'] = dates.modifiedDate.toISOString().substring(0, 10);
}
return {
- title: title,
+ title,
content: body.innerHTML,
- images: images,
+ images,
pageUrl: getPageLocationOrigin() + location.pathname + location.search,
clipType: 'page',
- labels: labels
+ labels
};
}
else {
- throw new Error('Unknown command: ' + JSON.stringify(message));
+ throw new Error(`Unknown command: ${ JSON.stringify(message)}`);
}
}
diff --git a/apps/web-clipper/entrypoints/options/index.html b/apps/web-clipper/entrypoints/options/index.html
index 16e084ded9..4aa2969c22 100644
--- a/apps/web-clipper/entrypoints/options/index.html
+++ b/apps/web-clipper/entrypoints/options/index.html
@@ -56,7 +56,7 @@
<script type="module" src="../../lib/cash.min.js"></script>
<script type="module" src="../../lib/browser-polyfill.js"></script>
-<script type="module" src="index.js"></script>
+<script type="module" src="index.ts"></script>
</body>
diff --git a/apps/web-clipper/entrypoints/options/index.js b/apps/web-clipper/entrypoints/options/index.ts
similarity index 77%
rename from apps/web-clipper/entrypoints/options/index.js
rename to apps/web-clipper/entrypoints/options/index.ts
index 03c05822ca..da8fa1850a 100644
--- a/apps/web-clipper/entrypoints/options/index.js
+++ b/apps/web-clipper/entrypoints/options/index.ts
@@ -17,8 +17,8 @@ function showSuccess(message) {
async function saveTriliumServerSetup(e) {
e.preventDefault();
- if ($triliumServerUrl.val().trim().length === 0
- || $triliumServerPassword.val().trim().length === 0) {
+ if (($triliumServerUrl.val() as string | undefined)?.trim().length === 0
+ || ($triliumServerPassword.val() as string | undefined)?.trim().length === 0) {
showError("One or more mandatory inputs are missing. Please fill in server URL and password.");
return;
@@ -27,7 +27,7 @@ async function saveTriliumServerSetup(e) {
let resp;
try {
- resp = await fetch($triliumServerUrl.val() + '/api/login/token', {
+ resp = await fetch(`${$triliumServerUrl.val() }/api/login/token`, {
method: "POST",
headers: {
'Accept': 'application/json',
@@ -39,7 +39,8 @@ async function saveTriliumServerSetup(e) {
});
}
catch (e) {
- showError("Unknown error: " + e.message);
+ const message = e instanceof Error ? e.message : String(e);
+ showError(`Unknown error: ${message}`);
return;
}
@@ -47,7 +48,7 @@ async function saveTriliumServerSetup(e) {
showError("Incorrect credentials.");
}
else if (resp.status !== 200) {
- showError("Unrecognised response with status code " + resp.status);
+ showError(`Unrecognised response with status code ${ resp.status}`);
}
else {
const json = await resp.json();
@@ -89,8 +90,8 @@ const $triilumDesktopSetupForm = $("#trilium-desktop-setup-form");
$triilumDesktopSetupForm.on("submit", e => {
e.preventDefault();
- const port = $triliumDesktopPort.val().trim();
- const portNum = parseInt(port);
+ const port = ($triliumDesktopPort.val() as string | undefined ?? "").trim();
+ const portNum = parseInt(port, 10);
if (port && (isNaN(portNum) || portNum <= 0 || portNum >= 65536)) {
showError(`Please enter valid port number.`);
@@ -105,8 +106,8 @@ $triilumDesktopSetupForm.on("submit", e => {
});
async function restoreOptions() {
- const {triliumServerUrl} = await browser.storage.sync.get("triliumServerUrl");
- const {authToken} = await browser.storage.sync.get("authToken");
+ const {triliumServerUrl} = await browser.storage.sync.get<{ triliumServerUrl: string }>("triliumServerUrl");
+ const {authToken} = await browser.storage.sync.get<{ authToken: string }>("authToken");
$errorMessage.hide();
$successMessage.hide();
@@ -127,8 +128,7 @@ async function restoreOptions() {
$triliumServerConfiguredDiv.hide();
}
- const {triliumDesktopPort} = await browser.storage.sync.get("triliumDesktopPort");
-
+ const {triliumDesktopPort} = await browser.storage.sync.get<{ triliumDesktopPort: string }>("triliumDesktopPort");
$triliumDesktopPort.val(triliumDesktopPort);
}
diff --git a/apps/web-clipper/entrypoints/popup/index.html b/apps/web-clipper/entrypoints/popup/index.html
index 0479588e73..a1051659f3 100644
--- a/apps/web-clipper/entrypoints/popup/index.html
+++ b/apps/web-clipper/entrypoints/popup/index.html
@@ -48,7 +48,7 @@
<script type="module" src="../../lib/browser-polyfill.js"></script>
<script type="module" src="../../lib/cash.min.js"></script>
- <script type="module" src="popup.js"></script>
+ <script type="module" src="popup.ts"></script>
<script type="module" src="../../utils.js"></script>
</body>
diff --git a/apps/web-clipper/entrypoints/popup/popup.js b/apps/web-clipper/entrypoints/popup/popup.ts
similarity index 95%
rename from apps/web-clipper/entrypoints/popup/popup.js
rename to apps/web-clipper/entrypoints/popup/popup.ts
index ec5ee67f82..8f8220de1f 100644
--- a/apps/web-clipper/entrypoints/popup/popup.js
+++ b/apps/web-clipper/entrypoints/popup/popup.ts
@@ -38,9 +38,9 @@ $saveTabsButton.on("click", () => sendMessage({name: 'save-tabs'}));
const $saveLinkWithNoteWrapper = $("#save-link-with-note-wrapper");
const $textNote = $("#save-link-with-note-textarea");
-const $keepTitle = $("#keep-title-checkbox");
+const $keepTitle = $<HTMLInputElement>("#keep-title-checkbox");
-$textNote.on('keypress', function (event) {
+$textNote.on('keypress', (event) => {
if ((event.which === 10 || event.which === 13) && event.ctrlKey) {
saveLinkWithNote();
return false;
@@ -63,7 +63,7 @@ $("#cancel-button").on("click", () => {
});
async function saveLinkWithNote() {
- const textNoteVal = $textNote.val().trim();
+ const textNoteVal = ($textNote.val() as string | undefined ?? "").trim();
let title, content;
if (!textNoteVal) {
@@ -111,7 +111,7 @@ function escapeHtml(string) {
const htmlWithPars = pre.innerHTML.replace(/\n/g, "</p><p>");
- return '<p>' + htmlWithPars + '</p>';
+ return `<p>${ htmlWithPars }</p>`;
}
const $connectionStatus = $("#connection-status");
@@ -160,7 +160,7 @@ browser.runtime.onMessage.addListener(request => {
const {searchNote} = request;
if (searchNote.status === 'found'){
const a = createLink({name: 'openNoteInTrilium', noteId: searchNote.noteId},
- "Open in Trilium.")
+ "Open in Trilium.");
$alreadyVisited.text(`Already visited website!`);
$alreadyVisited[0].appendChild(a);
}else{
@@ -176,7 +176,7 @@ const $checkConnectionButton = $("#check-connection-button");
$checkConnectionButton.on("click", () => {
browser.runtime.sendMessage({
name: "trigger-trilium-search"
- })
+ });
});
$(() => browser.runtime.sendMessage({name: "send-trilium-search-status"}));
diff --git a/apps/web-clipper/types.d.ts b/apps/web-clipper/types.d.ts
new file mode 100644
index 0000000000..4d83d0f28e
--- /dev/null
+++ b/apps/web-clipper/types.d.ts
@@ -0,0 +1,7 @@
+interface Window {
+ showToast(message: string, opts?: {
+ settings?: {
+ duration: number;
+ }
+ }): void;
+}