Add type definitions based on JSDoc types

This commit is contained in:
nachtjasmin 2023-07-28 23:33:23 +02:00
parent 65d808b59b
commit bc1a6a72f5
No known key found for this signature in database
7 changed files with 39 additions and 26 deletions

View file

@ -10,7 +10,7 @@ const cacheMaxAge = 24 * 60 * 60 * 1000; // time after which cached pronouns sho
* @param {string} account The account ID
* @param {string} pronouns The pronouns to cache.
*/
export async function cachePronouns(account, pronouns) {
export async function cachePronouns(account: string, pronouns: string) {
let cache = {};
try {
cache = await storage.local.get();
@ -38,7 +38,7 @@ export async function cachePronouns(account, pronouns) {
* @param {string} accountName
* @returns {Promise<string>} Account's cached pronouns, or null if not saved or stale
*/
export async function getPronouns(accountName) {
export async function getPronouns(accountName: string): Promise<string> {
const fallback = { pronounsCache: {} };
let cacheResult;
try {

View file

@ -3,7 +3,7 @@
* @param {Node} node
* @return {Node[]} Array containing the root node and all its descendants
*/
export function findAllDescendants(node) {
export function findAllDescendants(node: Node): Node[] {
return [node, ...node.childNodes, ...[...node.childNodes].flatMap((n) => findAllDescendants(n))];
}
@ -14,7 +14,7 @@ export function findAllDescendants(node) {
* @param {string[]} cl The class(es) to check for.
* @returns Whether the classList contains the class.
*/
export function hasClasses(element, ...cl) {
export function hasClasses(element: HTMLElement, ...cl: string[]) {
const classList = element.classList;
if (!classList || !cl) return false;
@ -35,7 +35,7 @@ export function hasClasses(element, ...cl) {
* @param {(el: Element) => void} callback
* @copyright CC-BY-SA 4.0 wOxxoM https://stackoverflow.com/a/71488320
*/
export function waitForElement(node, selector, callback) {
export function waitForElement(node: Element, selector: string, callback: (el: Element) => void) {
let el = node.querySelector(selector);
if (el) {
callback(el);
@ -60,7 +60,11 @@ export function waitForElement(node, selector, callback) {
* @param {(el: Element) => void} callback
* @copyright CC-BY-SA 4.0 wOxxoM https://stackoverflow.com/a/71488320
*/
export function waitForElementRemoved(node, selector, callback) {
export function waitForElementRemoved(
node: Element,
selector: string,
callback: (el: Element) => void,
) {
let el = node.querySelector(selector);
if (!el) {
callback(el);
@ -81,7 +85,7 @@ export function waitForElementRemoved(node, selector, callback) {
* @param {HTMLElement} insertion Element to insert
* @param {HTMLElement} target Element, which insertion is placed after
*/
export function insertAfter(insertion, target) {
export function insertAfter(insertion: HTMLElement, target: HTMLElement) {
//docs: https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore#example_2
target.parentElement.insertBefore(insertion, target.nextSibling);
}

View file

@ -14,7 +14,11 @@ let conversationsCache;
* @param {string} type Type of data-id
* @returns {string} The pronouns if we have any, otherwise "null".
*/
export async function fetchPronouns(dataID, accountName, type) {
export async function fetchPronouns(
dataID: string | undefined,
accountName: string,
type: string,
): Promise<string> {
// log(`searching for ${account_name}`);
const cacheResult = await getPronouns(accountName);
debug(cacheResult);
@ -65,7 +69,7 @@ export async function fetchPronouns(dataID, accountName, type) {
* @param {string} statusID ID of status being requested.
* @returns {Promise<object>} Contents of the status in json form.
*/
async function fetchStatus(statusID) {
async function fetchStatus(statusID: string): Promise<object> {
const accessToken = await getActiveAccessToken();
//fetch status from home server with access token
const response = await fetch(
@ -90,7 +94,7 @@ async function fetchStatus(statusID) {
* @param {string} notificationID ID of notification being requested.
* @returns {Promise<object>} Contents of notification in json form.
*/
async function fetchNotification(notificationID) {
async function fetchNotification(notificationID: string): Promise<object> {
const accessToken = await getActiveAccessToken();
const response = await fetch(
@ -111,7 +115,7 @@ async function fetchNotification(notificationID) {
* @param {string} accountID ID of account being requested.
* @returns {Promise<object>} Contents of account in json form.
*/
async function fetchAccount(accountID) {
async function fetchAccount(accountID: string): Promise<object> {
const accessToken = await getActiveAccessToken();
const response = await fetch(
@ -134,7 +138,7 @@ async function fetchAccount(accountID) {
*
* DOCS: https://docs.joinmastodon.org/methods/conversations/#response
*/
async function fetchConversations() {
async function fetchConversations(): Promise<Array<any>> {
if (conversationsCache) return conversationsCache;
//the api wants status IDs, not conversation IDs
//as a result we can only get pronouns for the first 40 conversations max
@ -158,7 +162,7 @@ async function fetchConversations() {
* Fetches the current access token for the user.
* @returns {Promise<string>} The accessToken for the current user if we are logged in.
*/
async function getActiveAccessToken() {
async function getActiveAccessToken(): Promise<string> {
// Fortunately, Mastodon provides the initial state in a <script> element at the beginning of the page.
// Besides a lot of other information, it contains the access token for the current user.
const initialStateEl = document.getElementById("initial-state");

View file

@ -3,26 +3,26 @@
import { isLogging } from "./settings";
/** @param {any[]} args */
export function error(...args) {
export function error(...args: any[]) {
if (isLogging()) console.error(...args);
}
/** @param {any[]} args */
export function warn(...args) {
export function warn(...args: any[]) {
if (isLogging()) console.warn(...args);
}
/** @param {any[]} args */
export function log(...args) {
export function log(...args: any[]) {
if (isLogging()) console.log(...args);
}
/** @param {any[]} args */
export function info(...args) {
export function info(...args: any[]) {
if (isLogging()) console.info(...args);
}
/** @param {any[]} args */
export function debug(...args) {
export function debug(...args: any[]) {
if (isLogging()) console.debug(...args);
}

View file

@ -17,7 +17,7 @@ const knownPronounUrls = [
* @param {any} status
* @returns {Promise<string|null>} Author pronouns if found. Otherwise returns null.
*/
export async function extractFromStatus(status) {
export async function extractFromStatus(status: any): Promise<string | null> {
// get account from status and pull out fields
const account = status.account;
const { fields, note } = account;
@ -42,7 +42,7 @@ export async function extractFromStatus(status) {
* @param {{name: string, value: string}} field The field value
* @returns {Promise<string|null>} The pronouns or null.
*/
async function extractFromField(field) {
async function extractFromField(field: { name: string; value: string }): Promise<string | null> {
let pronounsRaw;
for (const matcher of fieldMatchers) {
if (field.name.match(matcher)) {
@ -82,7 +82,7 @@ async function extractFromField(field) {
* @param {string} username The username of the person, without the leading "@".
* @returns {Promise<string|null>} The pronouns that have set the "yes" or "meh" opinion.
*/
async function queryUserFromPronounsPage(username) {
async function queryUserFromPronounsPage(username: string): Promise<string | null> {
// Example page: https://en.pronouns.page/api/profile/get/andrea?version=2
const resp = await fetch(`https://en.pronouns.page/api/profile/get/${username}?version=2`);
if (resp.status >= 400) {
@ -120,7 +120,7 @@ async function queryUserFromPronounsPage(username) {
* @param {string} val
* @returns {Promise<string>}
*/
async function normalizePronounPagePronouns(val) {
async function normalizePronounPagePronouns(val: string): Promise<string> {
const match = val.match(/pronouns\.page\/(.+)/);
if (match) val = match[1];
@ -156,7 +156,7 @@ async function normalizePronounPagePronouns(val) {
* @param {string} str The input string.
* @returns {string|null} The sanitized string.
*/
function sanitizePronouns(str) {
function sanitizePronouns(str: string): string | null {
if (!str) return null;
// Remove all custom emojis with the :shortcode: format.
@ -285,7 +285,7 @@ const knownPronouns = [
* @param {string} bio The bio
* @returns {string|null} The result or null
*/
function extractFromBio(bio) {
function extractFromBio(bio: string): string | null {
const exactMatches = bio.matchAll(/(\w+) ?\/ ?(\w+)/gi);
for (const [match, subjective, objective] of exactMatches) {
if (

View file

@ -24,8 +24,14 @@ export function normaliseAccountName(name) {
* @param {string|null} url URL to an account on their own instance
* @returns {string} username (not normalised)
*/
<<<<<<< HEAD
export function accountNameFromURL(url) {
if (!url) return null;
||||||| parent of 7061ebc (Add type definitions based on JSDoc types)
export function accountNameFromURL(url) {
=======
export function accountNameFromURL(url: string): string {
>>>>>>> 7061ebc (Add type definitions based on JSDoc types)
const splitURL = url.split("/");
const username = [splitURL.pop(), splitURL.pop()].join("@");
@ -37,7 +43,7 @@ export function accountNameFromURL(url) {
* Checks which type an element is and adds the according protoots-type attribute
* @param {HTMLElement} ActionElement
*/
export function addTypeAttribute(ActionElement) {
export function addTypeAttribute(ActionElement: HTMLElement) {
if (hasClasses(ActionElement, "status") && !hasClasses(ActionElement, "notification__message")) {
ActionElement.setAttribute("protoots-type", "status");
} else if (hasClasses(ActionElement, "detailed-status")) {

View file

@ -1,4 +1,3 @@
// @ts-nocheck
import { storage } from "webextension-polyfill";
import { error } from "../libs/logging";