Refactor code to use the new 'id' function

This commit is contained in:
2025-08-26 00:16:38 +03:00
Unverified
parent 909a13eae1
commit 6efb21ff20
12 changed files with 83 additions and 74 deletions
+13 -12
View File
@@ -10,14 +10,15 @@ import type { ErrorResponse, LoginResponse, LoginRequest, RegisterRequest } from
import { API_BASE_URL } from "../core/config"; import { API_BASE_URL } from "../core/config";
import { loadChat, showLogin, showRegister } from "../navigation"; import { loadChat, showLogin, showRegister } from "../navigation";
import { setUser } from "./api"; import { setUser } from "./api";
import { id } from "../utils/utils";
/** /**
* Clears all alert messages from authentication forms * Clears all alert messages from authentication forms
* @private * @private
*/ */
export function clearAlerts(): void { export function clearAlerts(): void {
document.getElementById('login-alerts')!.innerHTML = ''; id('login-alerts').innerHTML = '';
document.getElementById('register-alerts')!.innerHTML = ''; id('register-alerts').innerHTML = '';
} }
/** /**
@@ -27,7 +28,7 @@ export function clearAlerts(): void {
* @param {'success' | 'danger'} type - Type of alert (success or danger) * @param {'success' | 'danger'} type - Type of alert (success or danger)
*/ */
export function showAlert(containerId: string, message: string, type: "success" | "danger" = 'danger'): void { export function showAlert(containerId: string, message: string, type: "success" | "danger" = 'danger'): void {
const container = document.getElementById(containerId)!; const container = id(containerId);
const alertDiv = document.createElement('div'); const alertDiv = document.createElement('div');
alertDiv.className = `alert alert-${type}`; alertDiv.className = `alert alert-${type}`;
alertDiv.textContent = message; alertDiv.textContent = message;
@@ -41,8 +42,8 @@ export function showAlert(containerId: string, message: string, type: "success"
async function handleLogin(e: Event): Promise<void> { async function handleLogin(e: Event): Promise<void> {
e.preventDefault(); e.preventDefault();
const usernameElement = document.getElementById('login-username') as HTMLInputElement; const usernameElement = id<HTMLInputElement>('login-username');
const passwordElement = document.getElementById('login-password') as HTMLInputElement; const passwordElement = id<HTMLInputElement>('login-password');
const username = usernameElement.value.trim(); const username = usernameElement.value.trim();
const password = passwordElement.value.trim(); const password = passwordElement.value.trim();
@@ -89,9 +90,9 @@ async function handleLogin(e: Event): Promise<void> {
async function handleRegister(e: Event): Promise<void> { async function handleRegister(e: Event): Promise<void> {
e.preventDefault(); e.preventDefault();
const usernameElement = document.getElementById('register-username') as HTMLInputElement; const usernameElement = id<HTMLInputElement>('register-username');
const passwordElement = document.getElementById('register-password') as HTMLInputElement; const passwordElement = id<HTMLInputElement>('register-password');
const confirmPasswordElement = document.getElementById('register-confirm-password') as HTMLInputElement; const confirmPasswordElement = id<HTMLInputElement>('register-confirm-password');
const username = usernameElement.value.trim(); const username = usernameElement.value.trim();
const password = passwordElement.value.trim(); const password = passwordElement.value.trim();
@@ -152,11 +153,11 @@ async function handleRegister(e: Event): Promise<void> {
* @private * @private
*/ */
function init(): void { function init(): void {
document.getElementById('login-form-element')!.addEventListener('submit', handleLogin); id('login-form-element').addEventListener('submit', handleLogin);
document.getElementById('register-form-element')!.addEventListener('submit', handleRegister); id('register-form-element').addEventListener('submit', handleRegister);
document.getElementById("login-link")!.addEventListener("click", showLogin); id("login-link").addEventListener("click", showLogin);
document.getElementById("register-link")!.addEventListener("click", showRegister); id("register-link").addEventListener("click", showRegister);
} }
init(); init();
+4 -4
View File
@@ -8,15 +8,15 @@
import { websocket } from "../websocket"; import { websocket } from "../websocket";
import type { Message, WebSocketMessage } from "../core/types"; import type { Message, WebSocketMessage } from "../core/types";
import { showSuccess, showError } from "../utils/notification"; import { showSuccess, showError } from "../utils/notification";
import { delay } from "../utils/utils"; import { delay, id } from "../utils/utils";
import type { Dialog } from "mdui/components/dialog"; import type { Dialog } from "mdui/components/dialog";
import type { TextField } from "mdui/components/text-field"; import type { TextField } from "mdui/components/text-field";
import { currentUser, authToken } from "../auth/api"; import { currentUser, authToken } from "../auth/api";
let menu = document.getElementById("message-context-menu")!; let menu = id("message-context-menu")!;
let editDialog = document.getElementById("edit-message-dialog") as Dialog; let editDialog = id<Dialog>("edit-message-dialog");
let replyDialog = document.getElementById("reply-message-dialog") as Dialog; let replyDialog = id<Dialog>("reply-message-dialog");
let currentMessage: Message | null = null; let currentMessage: Message | null = null;
function init() { function init() {
+2 -3
View File
@@ -9,14 +9,13 @@ import { getAuthHeaders, currentUser } from "../auth/api";
import { API_BASE_URL } from "../core/config"; import { API_BASE_URL } from "../core/config";
import type { UserProfile } from "../core/types"; import type { UserProfile } from "../core/types";
import { showError, showSuccess } from "../utils/notification"; import { showError, showSuccess } from "../utils/notification";
import { formatTime } from "../utils/utils"; import { formatTime, id } from "../utils/utils";
import defaultAvatar from "../resources/images/default-avatar.png"; import defaultAvatar from "../resources/images/default-avatar.png";
import type { Tabs } from "mdui/components/tabs";
import type { Dialog } from "mdui/components/dialog"; import type { Dialog } from "mdui/components/dialog";
import type { TextField } from "mdui/components/text-field"; import type { TextField } from "mdui/components/text-field";
let dialog = document.getElementById("user-profile-dialog") as Dialog; let dialog = id<Dialog>("user-profile-dialog");
let currentProfile: UserProfile | null = null; let currentProfile: UserProfile | null = null;
let isOwnProfile: boolean = false; let isOwnProfile: boolean = false;
+2 -1
View File
@@ -6,8 +6,9 @@
*/ */
import { showLogin } from "../navigation"; import { showLogin } from "../navigation";
import { id } from "../utils/utils";
import { PRODUCT_NAME } from "./config"; import { PRODUCT_NAME } from "./config";
showLogin(); showLogin();
document.getElementById("productname")!.textContent = PRODUCT_NAME; id("productname").textContent = PRODUCT_NAME;
document.title = PRODUCT_NAME; document.title = PRODUCT_NAME;
+2 -1
View File
@@ -7,11 +7,12 @@
import "../../electron.d.ts"; import "../../electron.d.ts";
import { PRODUCT_NAME } from "../core/config.ts"; import { PRODUCT_NAME } from "../core/config.ts";
import { id } from "../utils/utils.ts";
if (window.electronInterface !== undefined) { if (window.electronInterface !== undefined) {
console.log("Running in Electron"); console.log("Running in Electron");
document.documentElement.classList.add("electron", `platform-${window.electronInterface.platform}`); document.documentElement.classList.add("electron", `platform-${window.electronInterface.platform}`);
document.getElementById("window-title")!.textContent = PRODUCT_NAME; id("window-title").textContent = PRODUCT_NAME;
} else { } else {
console.log("Running in normal browser"); console.log("Running in normal browser");
} }
+18 -12
View File
@@ -1,37 +1,43 @@
import { clearAlerts } from "./auth/auth"; import { clearAlerts } from "./auth/auth";
import { loadMessages } from "./chat/chat"; import { loadMessages } from "./chat/chat";
import { id } from "./utils/utils";
const loginForm = id("login-form");
const registerForm = id("register-form");
const chatInterface = id("chat-interface");
const titleBar = id("electron-title-bar");
/** /**
* Shows the login form and hides other interfaces. * Shows the login form and hides other interfaces.
*/ */
export function showLogin(): void { export function showLogin(): void {
document.getElementById('login-form')!.style.display = 'flex'; loginForm.style.display = 'flex';
document.getElementById('register-form')!.style.display = 'none'; registerForm.style.display = 'none';
document.getElementById('chat-interface')!.style.display = 'none'; chatInterface.style.display = 'none';
clearAlerts(); clearAlerts();
document.getElementById("electron-title-bar")!.classList.add("color-surface"); titleBar.classList.add("color-surface");
} }
/** /**
* Shows the registration form and hides other interfaces. * Shows the registration form and hides other interfaces.
*/ */
export function showRegister(): void { export function showRegister(): void {
document.getElementById('login-form')!.style.display = 'none'; loginForm.style.display = 'none';
document.getElementById('register-form')!.style.display = 'flex'; registerForm.style.display = 'flex';
document.getElementById('chat-interface')!.style.display = 'none'; chatInterface.style.display = 'none';
clearAlerts(); clearAlerts();
document.getElementById("electron-title-bar")!.classList.add("color-surface"); titleBar.classList.add("color-surface");
} }
/** /**
* Shows the chat interface and hides authentication forms. * Shows the chat interface and hides authentication forms.
*/ */
export function showChat(): void { export function showChat(): void {
document.getElementById('login-form')!.style.display = 'none'; loginForm.style.display = 'none';
document.getElementById('register-form')!.style.display = 'none'; registerForm.style.display = 'none';
document.getElementById('chat-interface')!.style.display = 'block'; chatInterface.style.display = 'block';
loadMessages(); loadMessages();
document.getElementById("electron-title-bar")!.classList.remove("color-surface"); titleBar.classList.remove("color-surface");
} }
/** /**
+10 -9
View File
@@ -5,18 +5,19 @@
* @version 1.0.0 * @version 1.0.0
*/ */
import type { Dialog } from "mdui/components/dialog"; import { Dialog } from "mdui/components/dialog";
import { loadProfilePicture } from "./profile/upload"; import { loadProfilePicture } from "./profile/upload";
import { id } from "../utils/utils";
// сварачивание и разворачивание чата // сварачивание и разворачивание чата
const chatCollapseBtn = document.getElementById('hide-chat')!; const chatCollapseBtn = id('hide-chat')!;
const chat1 = document.getElementById('chat-list-chat-1')!; const chat1 = id('chat-list-chat-1')!;
const chat2 = document.getElementById('chat-list-chat-2')!; const chat2 = id('chat-list-chat-2')!;
const chatInner = document.getElementById('chat-inner')!; const chatInner = id('chat-inner')!;
const chatName = document.getElementById('chat-name')!; const chatName = id('chat-name')!;
const profileButton = document.getElementById('profile-open')!; const profileButton = id('profile-open')!;
const dialog = document.getElementById("profile-dialog") as Dialog; const dialog = id<Dialog>("profile-dialog");
const dialogClose = document.getElementById("profile-dialog-close")!; const dialogClose = id("profile-dialog-close")!;
/** /**
* Sets up chat collapse functionality * Sets up chat collapse functionality
+9 -14
View File
@@ -8,11 +8,12 @@
import { updateProfile } from './api'; import { updateProfile } from './api';
import { loadProfile } from './api'; import { loadProfile } from './api';
import { showSuccess, showError } from '../../utils/notification'; import { showSuccess, showError } from '../../utils/notification';
import type { TextField } from 'mdui/components/text-field'; import { TextField } from 'mdui/components/text-field';
import { id } from '../../utils/utils';
let profileForm = document.getElementById('profile-form')!; let profileForm = id('profile-form')!;
let nicknameField = document.getElementById('username-field') as unknown as TextField; let nicknameField = id<TextField>('username-field');
let descriptionField = document.getElementById('description-field') as unknown as TextField; let descriptionField = id<TextField>('description-field');
/** /**
* Initialization state flag * Initialization state flag
@@ -107,16 +108,10 @@ async function handleFormSubmission(e: Event): Promise<void> {
* @private * @private
*/ */
function setupFormHandler(): void { function setupFormHandler(): void {
if (isInitialized) return; if (!isInitialized) {
profileForm.addEventListener('submit', handleFormSubmission);
// Get DOM elements isInitialized = true;
profileForm = document.getElementById('profile-form')!; }
nicknameField = document.getElementById('username-field') as TextField;
descriptionField = document.getElementById('description-field') as TextField;
profileForm.addEventListener('submit', handleFormSubmission);
isInitialized = true;
} }
/** /**
+3 -2
View File
@@ -9,10 +9,11 @@ import type { Dialog } from "mdui/components/dialog";
import { loadProfileData } from './editor'; import { loadProfileData } from './editor';
import { loadProfilePicture, initializeProfileUpload } from "./upload"; import { loadProfilePicture, initializeProfileUpload } from "./upload";
import { initializeProfileEditor } from './editor'; import { initializeProfileEditor } from './editor';
import { id } from "../../utils/utils";
// Handle profile form submission // Handle profile form submission
const form = document.getElementById("profile-form")!; const form = id("profile-form")!;
const dialog = document.getElementById("profile-dialog") as Dialog; const dialog = id<Dialog>("profile-dialog");
form.addEventListener("submit", async (e) => { form.addEventListener("submit", async (e) => {
e.preventDefault(); e.preventDefault();
+11 -12
View File
@@ -10,26 +10,25 @@ import { ImageCropper } from './imageCropper';
import { uploadProfilePicture } from './api'; import { uploadProfilePicture } from './api';
import { loadProfile } from './api'; import { loadProfile } from './api';
import { showSuccess, showError } from '../../utils/notification'; import { showSuccess, showError } from '../../utils/notification';
import { id } from "../../utils/utils";
/** /**
* Global image cropper instance * Global image cropper instance
* @type {ImageCropper | null}
*/ */
let cropper: ImageCropper | null = null; let cropper: ImageCropper | null = null;
/** /**
* Initialization state flag * Initialization state flag
* @type {boolean}
*/ */
let isInitialized = false; let isInitialized = false;
let cropperDialog = document.getElementById('cropper-dialog') as Dialog; let cropperDialog = id<Dialog>('cropper-dialog');
let fileInput = document.getElementById('pfp-file-input') as HTMLInputElement; let fileInput = id<HTMLInputElement>('pfp-file-input');
let uploadBtn = document.getElementById('upload-pfp-btn')!; let uploadBtn = id('upload-pfp-btn');
let cropSaveBtn = document.getElementById('crop-save')!; let cropSaveBtn = id('crop-save');
let cropCancelBtn = document.getElementById('crop-cancel')!; let cropCancelBtn = id('crop-cancel');
let cropperCloseBtn = document.getElementById('cropper-close')!; let cropperCloseBtn = id('cropper-close');
let cropperArea = document.getElementById('cropper-area')!; let cropperArea = id('cropper-area');
/** /**
* Opens the image cropper with the selected file * Opens the image cropper with the selected file
@@ -81,7 +80,7 @@ async function saveCroppedImage(): Promise<void> {
if (result) { if (result) {
// Update profile picture display // Update profile picture display
const profilePicture = document.getElementById('profile-picture') as HTMLImageElement; const profilePicture = id<HTMLInputElement>('profile-picture');
profilePicture.src = `${result.profile_picture_url}?t=${Date.now()}`; // Cache bust profilePicture.src = `${result.profile_picture_url}?t=${Date.now()}`; // Cache bust
// Close cropper // Close cropper
@@ -136,8 +135,8 @@ export async function loadProfilePicture(): Promise<void> {
if (userData?.profile_picture) { if (userData?.profile_picture) {
const url = `${userData.profile_picture}?t=${Date.now()}`; const url = `${userData.profile_picture}?t=${Date.now()}`;
const profilePicture = document.getElementById('profile-picture') as HTMLImageElement; const profilePicture = id<HTMLImageElement>('profile-picture');
const profilePicture2 = document.getElementById("preview1") as HTMLImageElement; const profilePicture2 = id<HTMLImageElement>("preview1");
profilePicture.src = url; profilePicture.src = url;
profilePicture2.src = url; profilePicture2.src = url;
} }
+5 -4
View File
@@ -6,10 +6,11 @@
*/ */
import type { Dialog } from "mdui/components/dialog"; import type { Dialog } from "mdui/components/dialog";
import { id } from "../utils/utils";
const dialog = document.getElementById('settings-dialog') as Dialog; const dialog = id<Dialog>('settings-dialog');
const openButton = document.getElementById('settings-open')!; const openButton = id('settings-open')!;
const closeButton = document.getElementById('settings-close')!; const closeButton = id('settings-close')!;
// Settings panel management // Settings panel management
const settingsList = document.querySelector('#settings-menu mdui-list')!; const settingsList = document.querySelector('#settings-menu mdui-list')!;
@@ -48,7 +49,7 @@ function handleListItemClick(item: Element): void {
const panelId = panelMapping[itemText as keyof typeof panelMapping]; const panelId = panelMapping[itemText as keyof typeof panelMapping];
if (panelId) { if (panelId) {
const targetPanel = document.getElementById(panelId); const targetPanel = id(panelId);
if (targetPanel) { if (targetPanel) {
targetPanel.classList.add('active'); targetPanel.classList.add('active');
} }
+4
View File
@@ -31,3 +31,7 @@ export function formatTime(dateString: string): string {
export function delay(ms: number): Promise<void> { export function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms)); return new Promise(resolve => setTimeout(resolve, ms));
} }
export function id<T extends Element = HTMLElement>(id: string): T {
return document.getElementById(id) as unknown as T
}