refactor: remove unused feature codeinjection

This commit is contained in:
tiddlygit-test 2021-02-17 22:21:19 +08:00
parent fd580c6462
commit 6114794732
10 changed files with 2 additions and 299 deletions

View file

@ -1,123 +0,0 @@
import React from 'react';
import Button from '@material-ui/core/Button';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Switch from '@material-ui/core/Switch';
import AceEditor from 'react-ace';
import 'ace-builds/src-noconflict/mode-css';
import 'ace-builds/src-noconflict/mode-javascript';
import 'ace-builds/src-noconflict/theme-github';
import 'ace-builds/src-noconflict/theme-monokai';
import { WindowNames, WindowMeta } from '@services/windows/WindowProperties';
import connectComponent from '../../helpers/connect-component';
import { updateForm, save } from '../../state/dialog-code-injection/actions';
const styles = (theme: any) => ({
root: {
background: theme.palette.background.paper,
height: '100vh',
width: '100vw',
padding: 0,
display: 'flex',
flexDirection: 'column',
},
flexGrow: {
flex: 1,
},
actions: {
borderTop: `1px solid ${theme.palette.divider}`,
padding: theme.spacing(2),
display: 'flex',
},
actionsLeft: {
flex: 1,
},
button: {
float: 'right',
marginLeft: theme.spacing(1),
},
});
const getMode = (codeInjectionType: any) => {
if (codeInjectionType === 'css') return 'css';
if (codeInjectionType === 'js') return 'javascript';
return '';
};
interface OwnCodeInjectionProps {
allowNodeInJsCodeInjection?: boolean;
classes: any;
code: string;
onSave: (...arguments_: any[]) => any;
onUpdateForm: (...arguments_: any[]) => any;
shouldUseDarkColors: boolean;
}
// @ts-expect-error ts-migrate(2456) FIXME: Type alias 'CodeInjectionProps' circularly referen... Remove this comment to see the full error message
type CodeInjectionProps = OwnCodeInjectionProps & typeof CodeInjection.defaultProps;
// @ts-expect-error ts-migrate(7022) FIXME: 'CodeInjection' implicitly has type 'any' because ... Remove this comment to see the full error message
const CodeInjection = ({ allowNodeInJsCodeInjection, classes, code, onSave, onUpdateForm, shouldUseDarkColors }: CodeInjectionProps) => {
const { codeInjectionType } = window.meta as WindowMeta[WindowNames.codeInjection];
return (
<div className={classes.root}>
<div className={classes.flexGrow}>
<AceEditor
mode={getMode(codeInjectionType)}
theme={shouldUseDarkColors ? 'monokai' : 'github'}
height="100%"
width="100%"
name="codeEditor"
value={code}
onChange={(value) => onUpdateForm({ code: value })}
/>
</div>
<div className={classes.actions}>
<div className={classes.actionsLeft}>
{codeInjectionType === 'js' && (
<FormControlLabel
control={
<Switch checked={allowNodeInJsCodeInjection} onChange={(e) => onUpdateForm({ allowNodeInJsCodeInjection: e.target.checked })} color="primary" />
}
label="Allow access to Node.JS & Electron APIs"
/>
)}
</div>
<div className={classes.actionsRight}>
<Button color="primary" variant="contained" disableElevation className={classes.button} onClick={onSave}>
Save
</Button>
<Button variant="contained" disableElevation className={classes.button} onClick={() => window.remote.closeCurrentWindow()}>
Cancel
</Button>
</div>
</div>
</div>
);
};
CodeInjection.defaultProps = {
allowNodeInJsCodeInjection: false,
};
const mapStateToProps = (state: any) => ({
code: state.dialogCodeInjection.form.code || '',
allowNodeInJsCodeInjection: state.dialogCodeInjection.form.allowNodeInJsCodeInjection,
shouldUseDarkColors: state.general.shouldUseDarkColors,
});
const actionCreators = {
updateForm,
save,
};
export default connectComponent(CodeInjection, mapStateToProps, actionCreators, styles);

View file

@ -189,13 +189,11 @@ const getUpdaterDesc = (status: any, info: any) => {
};
interface PreferencesProps {
allowNodeInJsCodeInjection: boolean;
allowPrerelease: boolean;
askForDownloadPath: boolean;
attachToMenubar: boolean;
blockAds: boolean;
classes: any;
cssCodeInjection?: string;
customUserAgent?: string;
darkReader: boolean;
darkReaderBrightness: number;
@ -206,7 +204,6 @@ interface PreferencesProps {
hibernateUnusedWorkspacesAtLaunch: boolean;
hideMenuBar: boolean;
ignoreCertificateErrors: boolean;
jsCodeInjection?: string;
navigationBar: boolean;
openAtLogin: 'yes' | 'yes-hidden' | 'no';
pauseNotificationsBySchedule: boolean;
@ -231,13 +228,11 @@ interface PreferencesProps {
}
const Preferences = ({
allowNodeInJsCodeInjection,
allowPrerelease,
askForDownloadPath,
attachToMenubar,
blockAds,
classes,
cssCodeInjection,
customUserAgent,
darkReader,
darkReaderBrightness,
@ -248,7 +243,6 @@ const Preferences = ({
hibernateUnusedWorkspacesAtLaunch,
hideMenuBar,
ignoreCertificateErrors,
jsCodeInjection,
navigationBar,
openAtLogin,
pauseNotificationsBySchedule,
@ -1161,19 +1155,6 @@ const Preferences = ({
<ListItemText primary="Custom User Agent" secondary={customUserAgent || 'Not set'} classes={{ secondary: classes.secondaryEllipsis }} />
<ChevronRightIcon color="action" />
</ListItem>
<Divider />
<ListItem button onClick={async () => await window.service.window.open(WindowNames.codeInjection, { codeInjectionType: 'js' })}>
<ListItemText
primary="JS Code Injection"
secondary={jsCodeInjection ? `Set ${allowNodeInJsCodeInjection ? ' (with access to Node.JS & Electron APIs)' : ''}` : 'Not set'}
/>
<ChevronRightIcon color="action" />
</ListItem>
<Divider />
<ListItem button onClick={async () => await window.service.window.open(WindowNames.codeInjection, { codeInjectionType: 'css' })}>
<ListItemText primary="CSS Code Injection" secondary={cssCodeInjection ? 'Set' : 'Not set'} />
<ChevronRightIcon color="action" />
</ListItem>
</List>
</Paper>
@ -1182,7 +1163,7 @@ const Preferences = ({
</Typography>
<Paper elevation={0} className={classes.paper}>
<List dense disablePadding>
<ListItem button onClick={async async () => await window.service.native.open(await window.service.context.get('LOG_FOLDER'), true)}>
<ListItem button onClick={async () => await window.service.native.open(await window.service.context.get('LOG_FOLDER'), true)}>
<ListItemText primary={t('Preference.OpenLogFolder')} secondary={t('Preference.OpenLogFolderDetail')} />
<ChevronRightIcon color="action" />
</ListItem>
@ -1360,48 +1341,3 @@ const Preferences = ({
</div>
);
};
const mapStateToProps = (state: any) => ({
allowNodeInJsCodeInjection: state.preferences.allowNodeInJsCodeInjection,
allowPrerelease: state.preferences.allowPrerelease,
askForDownloadPath: state.preferences.askForDownloadPath,
attachToMenubar: state.preferences.attachToMenubar,
blockAds: state.preferences.blockAds,
cssCodeInjection: state.preferences.cssCodeInjection,
customUserAgent: state.preferences.customUserAgent,
darkReader: state.preferences.darkReader,
darkReaderBrightness: state.preferences.darkReaderBrightness,
darkReaderContrast: state.preferences.darkReaderContrast,
darkReaderGrayscale: state.preferences.darkReaderGrayscale,
darkReaderSepia: state.preferences.darkReaderSepia,
downloadPath: state.preferences.downloadPath,
hibernateUnusedWorkspacesAtLaunch: state.preferences.hibernateUnusedWorkspacesAtLaunch,
hideMenuBar: state.preferences.hideMenuBar,
ignoreCertificateErrors: state.preferences.ignoreCertificateErrors,
isDefaultMailClient: state.general.isDefaultMailClient,
isDefaultWebBrowser: state.general.isDefaultWebBrowser,
jsCodeInjection: state.preferences.jsCodeInjection,
navigationBar: state.preferences.navigationBar,
openAtLogin: state.systemPreferences.openAtLogin,
pauseNotificationsBySchedule: state.preferences.pauseNotificationsBySchedule,
pauseNotificationsByScheduleFrom: state.preferences.pauseNotificationsByScheduleFrom,
pauseNotificationsByScheduleTo: state.preferences.pauseNotificationsByScheduleTo,
pauseNotificationsMuteAudio: state.preferences.pauseNotificationsMuteAudio,
rememberLastPageVisited: state.preferences.rememberLastPageVisited,
shareWorkspaceBrowsingData: state.preferences.shareWorkspaceBrowsingData,
sidebar: state.preferences.sidebar,
sidebarShortcutHints: state.preferences.sidebarShortcutHints,
spellcheck: state.preferences.spellcheck,
spellcheckLanguages: state.preferences.spellcheckLanguages,
swipeToNavigate: state.preferences.swipeToNavigate,
syncDebounceInterval: state.preferences.syncDebounceInterval,
themeSource: state.preferences.themeSource,
titleBar: state.preferences.titleBar,
unreadCountBadge: state.preferences.unreadCountBadge,
updaterInfo: state.updater.info,
updaterStatus: state.updater.status,
useHardwareAcceleration: state.preferences.useHardwareAcceleration,
userName: state.preferences.userName,
});
export default connectComponent(Preferences, mapStateToProps, undefined, styles);

View file

@ -34,38 +34,6 @@ const handleLoaded = async (event: string): Promise<void> => {
void loadDarkReader();
});
await loadDarkReader();
const { jsCodeInjection, allowNodeInJsCodeInjection, cssCodeInjection } = await preference.getPreferences();
if (typeof jsCodeInjection === 'string' && jsCodeInjection.trim().length > 0) {
if (allowNodeInJsCodeInjection) {
try {
// eslint-disable-next-line no-new-func, @typescript-eslint/no-implied-eval
new Function('require', `"use strict";${jsCodeInjection}`)(require);
} catch (error) {
/* eslint-disable no-console */
console.log(error);
/* eslint-enable no-console */
}
} else {
try {
const node = document.createElement('script');
node.innerHTML = jsCodeInjection;
document.body.append(node);
} catch (error) {
/* eslint-disable no-console */
console.log(error);
/* eslint-enable no-console */
}
}
}
if (typeof cssCodeInjection === 'string' && cssCodeInjection.trim().length > 0) {
try {
const node = document.createElement('style');
node.innerHTML = cssCodeInjection;
document.body.append(node);
} catch (error) {
console.log(error); // eslint-disable-line no-console
}
}
(window as any).contextMenuBuilder = new ContextMenuBuilder();
remote.getCurrentWebContents().on('context-menu', (e, info) => {
// eslint-disable-next-line promise/catch-or-return

View file

@ -12,7 +12,6 @@ import { WindowNames, WindowMeta } from '@services/windows/WindowProperties';
import 'typeface-roboto/index.css';
import store from './state';
import { init as initDialogCodeInjection } from './state/dialog-code-injection/actions';
import { init as initDialogCustomUserAgent } from './state/dialog-custom-user-agent/actions';
import { init as initDialogEditWorkspace } from './state/dialog-edit-workspace/actions';
import { init as initDialogProxy } from './state/dialog-proxy/actions';
@ -25,7 +24,6 @@ import AppWrapper from './components/app-wrapper';
const AboutPage = React.lazy(async () => await import('./pages/About'));
const DialogAddWorkspace = React.lazy(async () => await import('./components/dialog-add-workspace'));
const DialogAuth = React.lazy(async () => await import('./components/dialog-auth'));
const DialogCodeInjection = React.lazy(async () => await import('./components/dialog-code-injection'));
const DialogCustomUserAgent = React.lazy(async () => await import('./components/dialog-custom-user-agent'));
const DialogDisplayMedia = React.lazy(async () => await import('./components/dialog-display-media'));
const DialogEditWorkspace = React.lazy(async () => await import('./components/dialog-edit-workspace'));
@ -48,8 +46,6 @@ const App = (): JSX.Element => {
case WindowNames.auth:
document.title = 'Sign In';
return <DialogAuth />;
case WindowNames.codeInjection:
return <DialogCodeInjection />;
case WindowNames.userAgent:
return <DialogCustomUserAgent />;
case WindowNames.displayMedia:
@ -95,11 +91,6 @@ async function runApp(): Promise<void> {
return false;
});
document.title = workspace.name ? `Edit Workspace ${workspace.order + 1} "${workspace.name}"` : `Edit Workspace ${workspace.order + 1}`;
} else if (window.meta.windowName === WindowNames.codeInjection) {
store.dispatch(initDialogCodeInjection());
const { codeInjectionType } = window.meta as WindowMeta[WindowNames.codeInjection];
if (!codeInjectionType) throw new Error(`codeInjectionType is undefined when startup renderer.tsx`);
document.title = `Edit ${codeInjectionType.toUpperCase()} Code Injection`;
} else if (window.meta.windowName === WindowNames.userAgent) {
store.dispatch(initDialogCustomUserAgent());
document.title = 'Edit Custom User Agent';

View file

@ -38,12 +38,10 @@ const getDefaultPauseNotificationsByScheduleTo = (): string => {
};
const defaultPreferences: IPreferences = {
allowNodeInJsCodeInjection: false,
allowPrerelease: Boolean(semver.prerelease(app.getVersion())),
askForDownloadPath: true,
attachToMenubar: false,
blockAds: false,
cssCodeInjection: '',
customUserAgent: '',
// default Dark Reader settings from its Chrome extension
darkReader: false,
@ -56,7 +54,6 @@ const defaultPreferences: IPreferences = {
hibernateUnusedWorkspacesAtLaunch: false,
hideMenuBar: false,
ignoreCertificateErrors: false,
jsCodeInjection: '',
language: 'zh_CN',
navigationBar: false,
pauseNotifications: '',

View file

@ -3,12 +3,10 @@ import { ProxyPropertyType } from '@/helpers/electron-ipc-proxy/common';
import { PreferenceChannel } from '@/constants/channels';
export interface IPreferences {
allowNodeInJsCodeInjection: boolean;
allowPrerelease: boolean;
askForDownloadPath: boolean;
attachToMenubar: boolean;
blockAds: boolean;
cssCodeInjection: string;
customUserAgent: string;
darkReader: boolean;
darkReaderBrightness: number;
@ -19,7 +17,6 @@ export interface IPreferences {
hibernateUnusedWorkspacesAtLaunch: boolean;
hideMenuBar: boolean;
ignoreCertificateErrors: boolean;
jsCodeInjection: string;
language: string;
navigationBar: boolean;
pauseNotifications: string;

View file

@ -7,7 +7,6 @@ export enum WindowNames {
preferences = 'preferences',
about = 'about',
userAgent = 'userAgent',
codeInjection = 'codeInjection',
proxy = 'proxy',
spellcheck = 'spellcheck',
auth = 'auth',
@ -57,10 +56,6 @@ export const windowDimension: Record<WindowNames, { width?: number; height?: num
width: 820,
height: 640,
},
[WindowNames.codeInjection]: {
width: 640,
height: 560,
},
[WindowNames.userAgent]: {
width: 400,
height: 180,
@ -91,15 +86,12 @@ export const windowDimension: Record<WindowNames, { width?: number; height?: num
},
};
export type CodeInjectionType = 'css' | 'js';
/**
* metadata that send to window when create them.
* Please make all property partial (?:), so wo can always assign {} as default metadata without type warning
*/
export interface WindowMeta extends Record<WindowNames, Record<string, unknown> | undefined> {
[WindowNames.displayMedia]: { displayMediaRequestedViewID?: number };
[WindowNames.codeInjection]: { codeInjectionType?: CodeInjectionType };
[WindowNames.editWorkspace]: { workspaceID?: string };
[WindowNames.openUrlWith]: { incomingUrl?: string };
[WindowNames.main]: { forceClose?: boolean };

View file

@ -6,7 +6,7 @@ import getDecorators from 'inversify-inject-decorators';
import { Menubar } from 'menubar';
import windowStateKeeper, { State as windowStateKeeperState } from 'electron-window-state';
import { IBrowserViewMetaData, WindowNames, windowDimension, WindowMeta, CodeInjectionType } from '@services/windows/WindowProperties';
import { IBrowserViewMetaData, WindowNames, windowDimension, WindowMeta } from '@services/windows/WindowProperties';
import serviceIdentifier from '@services/serviceIdentifier';
import type { IPreferenceService } from '@services/preferences/interface';

View file

@ -1,28 +0,0 @@
import { UPDATE_CODE_INJECTION_FORM, DIALOG_CODE_INJECTION_INIT } from '../../constants/actions';
import { WindowNames, WindowMeta } from '@services/windows/WindowProperties';
export const init = () => ({
type: DIALOG_CODE_INJECTION_INIT,
});
export const updateForm = (changes: any) => (dispatch: any) =>
dispatch({
type: UPDATE_CODE_INJECTION_FORM,
changes,
});
export const save = async () => async (dispatch: any, getState: any) => {
const { form } = getState().dialogCodeInjection;
const { codeInjectionType } = window.meta as WindowMeta[WindowNames.codeInjection];
void window.service.preference.set(`${codeInjectionType}CodeInjection`, form.code);
if (codeInjectionType === 'js' && typeof form.allowNodeInJsCodeInjection === 'boolean') {
void window.service.preference.set('allowNodeInJsCodeInjection', form.allowNodeInJsCodeInjection);
}
await window.service.window.requestShowRequireRestartDialog();
window.remote.closeCurrentWindow();
};

View file

@ -1,27 +0,0 @@
import { combineReducers } from 'redux';
import { UPDATE_CODE_INJECTION_FORM, DIALOG_CODE_INJECTION_INIT } from '../../constants/actions';
import { WindowNames, WindowMeta } from '@services/windows/WindowProperties';
const form = async (state = {}, action: any) => {
switch (action.type) {
case DIALOG_CODE_INJECTION_INIT: {
const { codeInjectionType } = window.meta as WindowMeta[WindowNames.codeInjection];
if (codeInjectionType === undefined) {
throw new Error(`codeInjectionType is undefined`);
}
return {
code: await window.service.preference.get(`${codeInjectionType}CodeInjection` as 'jsCodeInjection' | 'cssCodeInjection'),
// allowNodeInJsCodeInjection is only used for js injection
allowNodeInJsCodeInjection: codeInjectionType === 'js' ? await window.service.preference.get('allowNodeInJsCodeInjection') : false,
};
}
case UPDATE_CODE_INJECTION_FORM:
return { ...state, ...action.changes };
default:
return state;
}
};
export default combineReducers({ form });