Code optimization

This commit is contained in:
Tw93
2023-06-07 14:51:06 +08:00
parent 9221bbce10
commit ca72467fca
5 changed files with 190 additions and 203 deletions

View File

@@ -1,5 +1,5 @@
import { PakeAppOptions } from '@/types.js'; import { PakeAppOptions } from '@/types.js';
import prompts, { override } from 'prompts'; import prompts from 'prompts';
import path from 'path'; import path from 'path';
import fs from 'fs/promises'; import fs from 'fs/promises';
import fs2 from 'fs-extra'; import fs2 from 'fs-extra';
@@ -7,7 +7,6 @@ import {TauriConfig} from 'tauri/src/types';
import { npmDirectory } from '@/utils/dir.js'; import { npmDirectory } from '@/utils/dir.js';
import logger from '@/options/logger.js'; import logger from '@/options/logger.js';
import URL from 'node:url';
type DangerousRemoteDomainIpAccess = { type DangerousRemoteDomainIpAccess = {
domain: string; domain: string;
@@ -38,7 +37,8 @@ export async function promptText(message: string, initial?: string) {
} }
function setSecurityConfigWithUrl(tauriConfig: NextTauriConfig, url: string) { function setSecurityConfigWithUrl(tauriConfig: NextTauriConfig, url: string) {
const {hostname} = URL.parse(url); const myURL = new URL(url);
const hostname = myURL.hostname;
tauriConfig.tauri.security.dangerousRemoteDomainIpcAccess[0].domain = hostname; tauriConfig.tauri.security.dangerousRemoteDomainIpcAccess[0].domain = hostname;
} }

View File

@@ -46,8 +46,8 @@
"exports": "./dist/pake.js", "exports": "./dist/pake.js",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@tauri-apps/api": "^1.2.0", "@tauri-apps/api": "^1.3.0",
"@tauri-apps/cli": "^1.2.3", "@tauri-apps/cli": "^1.3.1",
"axios": "^1.1.3", "axios": "^1.1.3",
"chalk": "^5.1.2", "chalk": "^5.1.2",
"commander": "^9.4.1", "commander": "^9.4.1",

View File

@@ -8,26 +8,6 @@ pub struct DownloadFileParams {
filename: String, filename: String,
} }
#[command]
pub fn drag_window(app: AppHandle) {
app.get_window("pake").unwrap().start_dragging().unwrap();
}
#[command]
pub fn fullscreen(app: AppHandle) {
let win = app.get_window("pake").unwrap();
if win.is_fullscreen().unwrap() {
win.set_fullscreen(false).unwrap();
} else {
win.set_fullscreen(true).unwrap();
}
}
#[command]
pub fn open_browser(app: AppHandle, url: String) {
api::shell::open(&app.shell_scope(), url, None).unwrap();
}
#[command] #[command]
pub async fn download_file(app: AppHandle, params: DownloadFileParams) -> Result<(), String> { pub async fn download_file(app: AppHandle, params: DownloadFileParams) -> Result<(), String> {
let window: Window = app.get_window("pake").unwrap(); let window: Window = app.get_window("pake").unwrap();

View File

@@ -43,8 +43,7 @@ function handleShortcut(event) {
//这里参考 ChatGPT 的代码 //这里参考 ChatGPT 的代码
const uid = () => window.crypto.getRandomValues(new Uint32Array(1))[0]; const uid = () => window.crypto.getRandomValues(new Uint32Array(1))[0];
function transformCallback(callback = () => { function transformCallback(callback = () => {}, once = false) {
}, once = false) {
const identifier = uid(); const identifier = uid();
const prop = `_${identifier}`; const prop = `_${identifier}`;
Object.defineProperty(window, prop, { Object.defineProperty(window, prop, {
@@ -98,7 +97,15 @@ function externalDownLoadLink() {
return ['quickref.me'].indexOf(location.hostname) > -1; return ['quickref.me'].indexOf(location.hostname) > -1;
} }
// Directly jumping out without hostname address.
function externalTargetLink() {
return ['zbook.lol'].indexOf(location.hostname) > -1;
}
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
const tauri = window.__TAURI__;
const appWindow = tauri.window.appWindow;
const topDom = document.createElement('div'); const topDom = document.createElement('div');
topDom.id = 'pack-top-dom'; topDom.id = 'pack-top-dom';
document.body.appendChild(topDom); document.body.appendChild(topDom);
@@ -107,16 +114,18 @@ document.addEventListener('DOMContentLoaded', () => {
domEl.addEventListener('mousedown', (e) => { domEl.addEventListener('mousedown', (e) => {
e.preventDefault(); e.preventDefault();
if (e.buttons === 1 && e.detail !== 2) { if (e.buttons === 1 && e.detail !== 2) {
invoke('drag_window'); appWindow.startDragging();
} }
}); });
domEl.addEventListener('touchstart', () => { domEl.addEventListener('touchstart', () => {
invoke('drag_window'); appWindow.startDragging();
}); });
domEl.addEventListener('dblclick', () => { domEl.addEventListener('dblclick', () => {
invoke('fullscreen'); appWindow.isFullscreen().then((fullscreen) => {
appWindow.setFullscreen(!fullscreen);
});
}); });
document.addEventListener('keyup', (event) => { document.addEventListener('keyup', (event) => {
@@ -130,6 +139,7 @@ document.addEventListener('DOMContentLoaded', () => {
const detectAnchorElementClick = (e) => { const detectAnchorElementClick = (e) => {
const anchorElement = e.target.closest('a'); const anchorElement = e.target.closest('a');
console.log(">>>>>>>>>",anchorElement);
if (anchorElement && anchorElement.href) { if (anchorElement && anchorElement.href) {
const target = anchorElement.target; const target = anchorElement.target;
anchorElement.target = '_self'; anchorElement.target = '_self';
@@ -138,30 +148,35 @@ document.addEventListener('DOMContentLoaded', () => {
// Convert blob url to binary file // Convert blob url to binary file
if (absoluteUrl.includes('blob:')) { if (absoluteUrl.includes('blob:')) {
convertBlobUrlToBinary(absoluteUrl).then(binary => { convertBlobUrlToBinary(absoluteUrl).then((binary) => {
const tauri = window.__TAURI__;
tauri.fs.writeBinaryFile(anchorElement.download, binary, { tauri.fs.writeBinaryFile(anchorElement.download, binary, {
dir: tauri.fs.BaseDirectory.Download, dir: tauri.fs.BaseDirectory.Download,
}); });
}) });
return; return;
} }
// Handling external link redirection. // Handling external link redirection.
if ( if (
window.location.host !== hrefUrl.host && window.location.host !== hrefUrl.host &&
(target === '_blank' || target === '_new') (target === '_blank' || target === '_new' || externalTargetLink())
) { ) {
e.preventDefault(); e.preventDefault && e.preventDefault();
invoke('open_browser', {url: absoluteUrl}); tauri.shell.open(absoluteUrl);
return; return;
} }
let filename = anchorElement.download ? anchorElement.download : getFilenameFromUrl(absoluteUrl) let filename = anchorElement.download
? anchorElement.download
: getFilenameFromUrl(absoluteUrl);
// Process download links for Rust to handle. // Process download links for Rust to handle.
// If the download attribute is set, the download attribute is used as the file name. // If the download attribute is set, the download attribute is used as the file name.
if ((anchorElement.download || e.metaKey || e.ctrlKey || isDownloadLink(absoluteUrl)) if (
&& !externalDownLoadLink() (anchorElement.download ||
e.metaKey ||
e.ctrlKey ||
isDownloadLink(absoluteUrl)) &&
!externalDownLoadLink()
) { ) {
e.preventDefault(); e.preventDefault();
invoke('download_file', { invoke('download_file', {
@@ -175,7 +190,7 @@ document.addEventListener('DOMContentLoaded', () => {
}; };
// Prevent some special websites from executing in advance, before the click event is triggered. // Prevent some special websites from executing in advance, before the click event is triggered.
document.addEventListener('mousedown', detectAnchorElementClick); document.addEventListener('click', detectAnchorElementClick, true);
collectUrlToBlobs(); collectUrlToBlobs();
@@ -190,7 +205,7 @@ document.addEventListener('DOMContentLoaded', () => {
} else { } else {
const baseUrl = window.location.origin + window.location.pathname; const baseUrl = window.location.origin + window.location.pathname;
const hrefUrl = new URL(url, baseUrl); const hrefUrl = new URL(url, baseUrl);
invoke('open_browser', {url: hrefUrl.href}); tauri.shell.open(hrefUrl.href);
} }
// Call the original window.open function to maintain its normal functionality. // Call the original window.open function to maintain its normal functionality.
return originalWindowOpen.call(window, url, name, specs); return originalWindowOpen.call(window, url, name, specs);
@@ -223,7 +238,6 @@ function removeUrlParameters(url) {
return parsedUrl.toString(); return parsedUrl.toString();
} }
// Toggle video playback when the window is hidden. // Toggle video playback when the window is hidden.
function toggleVideoPlayback(pause) { function toggleVideoPlayback(pause) {
const videos = document.getElementsByTagName('video'); const videos = document.getElementsByTagName('video');
@@ -244,10 +258,9 @@ function collectUrlToBlobs() {
const url = backupCreateObjectURL.call(window.URL, blob); const url = backupCreateObjectURL.call(window.URL, blob);
window.blobToUrlCaches.set(url, blob); window.blobToUrlCaches.set(url, blob);
return url; return url;
} };
} }
function convertBlobUrlToBinary(blobUrl) { function convertBlobUrlToBinary(blobUrl) {
return new Promise((resolve) => { return new Promise((resolve) => {
const blob = window.blobToUrlCaches.get(blobUrl); const blob = window.blobToUrlCaches.get(blobUrl);
@@ -257,6 +270,5 @@ function convertBlobUrlToBinary(blobUrl) {
reader.onload = () => { reader.onload = () => {
resolve(reader.result); resolve(reader.result);
}; };
}) });
} }

View File

@@ -7,7 +7,7 @@ mod app;
mod util; mod util;
use app::{invoke, menu, window}; use app::{invoke, menu, window};
use invoke::{download_file, drag_window, fullscreen, open_browser}; use invoke::download_file;
use menu::{get_menu, menu_event_handle}; use menu::{get_menu, menu_event_handle};
use tauri_plugin_window_state::Builder as windowStatePlugin; use tauri_plugin_window_state::Builder as windowStatePlugin;
use util::{get_data_dir, get_pake_config}; use util::{get_data_dir, get_pake_config};
@@ -41,12 +41,7 @@ pub fn run_app() {
tauri_app tauri_app
.plugin(windowStatePlugin::default().build()) .plugin(windowStatePlugin::default().build())
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![download_file])
drag_window,
fullscreen,
open_browser,
download_file
])
.setup(|app| { .setup(|app| {
let _window = get_window(app, pake_config, data_dir); let _window = get_window(app, pake_config, data_dir);
// Prevent initial shaking // Prevent initial shaking