Skip to content

Commit

Permalink
refactor: reconstruct option management (#659)
Browse files Browse the repository at this point in the history
* refactor option management

* lint: run prettier

* refactor: use features-loader as a webpack loader

* chore: remove unused import

* docs: update website url

* chore: remove unused `getBrowserType`

* fix: fix settings cannot be saved

* fix: cannot load undefined settings

* fix: locale not updates immediately when choose a different language

* refactor: a more cohesive options-storage

* refactor: change the consumption way of options storage in views

* fix: wrong import path

* fix: carefully deal with a featureId and featureName

* fix: different orders between two react renders output error in console

* chore: a simple popup page with a button directed to Options page

* fix: oss-gpt doen't show whether enabled or not

* refactor: use default options as the default state of the `options` state in views

---------

Co-authored-by: Lam Tang <tangyenan@gmail.com>
  • Loading branch information
wxharry and tyn1998 authored May 17, 2023
1 parent 9bfbddc commit 4acd096
Show file tree
Hide file tree
Showing 23 changed files with 1,064 additions and 1,137 deletions.
3 changes: 1 addition & 2 deletions src/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,4 @@ export const OSS_XLAB_ENDPOINT = 'https://oss.x-lab.info';
export const HYPERTRONS_CRX_NEW_ISSUE =
'https://github.com/hypertrons/hypertrons-crx/issues/new/choose';

export const HYPERTRONS_CRX_WEBSITE =
'https://hypertrons.github.io/hypertrons-crx-website/';
export const HYPERTRONS_CRX_WEBSITE = 'https://crx.hypertrons.io';
23 changes: 16 additions & 7 deletions src/feature-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import isRestorationVisit from './helpers/is-restoration-visit';
import shouldFeatureRun, {
ShouldRunConditions,
} from './helpers/should-feature-run';
import optionsStorage from './options-storage';

type FeatureInit = () => Promisable<void>;
type FeatureRestore = Function;
Expand Down Expand Up @@ -60,7 +61,7 @@ const log = {
};

// eslint-disable-next-line no-async-promise-executor -- Rule assumes we don't want to leave it pending
const globalReady = new Promise<void>(async (resolve) => {
const globalReady = new Promise<object>(async (resolve) => {
await waitFor(() => document.body);

if (pageDetect.is500() || pageDetect.isPasswordConfirmation()) {
Expand All @@ -81,11 +82,13 @@ const globalReady = new Promise<void>(async (resolve) => {

document.documentElement.classList.add('hypercrx');

resolve();
const options = await optionsStorage.getAll();

resolve(options);
});

const setupPageLoad = async (
id: FeatureID,
id: FeatureId,
config: InternalRunConfig
): Promise<void> => {
const { asLongAs, include, exclude, init } = config;
Expand All @@ -108,23 +111,29 @@ const setupPageLoad = async (

// url can be in forms of: "foo/bar/feature-name.tsx" or "foo/bar/feature-name/index.tsx".
// This function extracts "feature-name" in url and prefixes it with "hypercrx-".
const getFeatureID = (url: string): FeatureID => {
const getFeatureID = (url: string): FeatureId => {
const prefix = 'hypercrx-';
const pathComponents = url.split('/');
let name = pathComponents.pop()!.split('.')[0];
if (name === 'index') {
name = pathComponents.pop()!;
}
return `${prefix}${name}` as FeatureID;
return `${prefix}${name}` as FeatureId;
};

/** Register a new feature */
const add = async (
id: FeatureID,
id: FeatureId,
...loaders: FeatureLoader[]
): Promise<void> => {
/* Feature filtering and running */
await globalReady;
const options = await globalReady;

// If the feature is disabled, skip it
if (!options[id as keyof typeof options]) {
log.info('↩️', 'Skipping', id);
return;
}

for (const loader of loaders) {
// Input defaults and validation
Expand Down
8 changes: 7 additions & 1 deletion src/global.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
type ThemeType = 'light' | 'dark';

type FeatureID = string & { feature: true };
type FeatureName = string;
type FeatureId = `hypercrx-${FeatureName}`;

// It should be just for README.md, but 🤷‍♂️
declare module '*.md' {
export const importedFeatures: FeatureName[];
}
26 changes: 26 additions & 0 deletions src/options-storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { importedFeatures } from '../README.md';

export type HypercrxOptions = typeof defaults;

export const defaults = Object.assign(
{
locale: 'en',
},
Object.fromEntries(
importedFeatures.map((name) => [`hypercrx-${name}` as FeatureId, true])
)
);

class OptionsStorage {
public async getAll(): Promise<HypercrxOptions> {
return (await chrome.storage.sync.get(defaults)) as HypercrxOptions;
}

public async set(options: Partial<HypercrxOptions>): Promise<void> {
await chrome.storage.sync.set(options);
}
}

const optionsStorage = new OptionsStorage();

export default optionsStorage;
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import React, { useState, useEffect } from 'react';

import { getGithubTheme, getMessageByLocale } from '../../../../utils/utils';
import { generateDataByMonth } from '../../../../utils/data';
import Settings, { loadSettings } from '../../../../utils/settings';
import optionsStorage, {
HypercrxOptions,
defaults,
} from '../../../../options-storage';
import Bars from '../../../../components/Bars/index';

const githubTheme = getGithubTheme();
Expand All @@ -20,15 +23,15 @@ interface Props {
}

const View = ({ activity, openrank }: Props): JSX.Element | null => {
const [settings, setSettings] = useState(new Settings());
const [options, setOptions] = useState<HypercrxOptions>(defaults);

useEffect(() => {
(async () => {
setSettings(await loadSettings());
(async function () {
setOptions(await optionsStorage.getAll());
})();
}, []);

if (!settings || !activity || !openrank) return null;
if (!activity || !openrank) return null;

let barsData: any = generateBarsData(activity, openrank);

Expand All @@ -37,27 +40,27 @@ const View = ({ activity, openrank }: Props): JSX.Element | null => {
<h2 className="h4 mb-3">
{getMessageByLocale(
'component_developerActORTrend_title',
settings.locale
options.locale
)}
</h2>
<Bars
theme={githubTheme as 'light' | 'dark'}
height={350}
legend1={getMessageByLocale(
'component_developerActORTrend_legend1',
settings.locale
options.locale
)}
legend2={getMessageByLocale(
'component_developerActORTrend_legend2',
settings.locale
options.locale
)}
yName1={getMessageByLocale(
'component_developerActORTrend_yName1',
settings.locale
options.locale
)}
yName2={getMessageByLocale(
'component_developerActORTrend_yName2',
settings.locale
options.locale
)}
data1={barsData.data1}
data2={barsData.data2}
Expand Down
47 changes: 25 additions & 22 deletions src/pages/ContentScripts/features/developer-networks/view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import ReactModal from 'react-modal';

import Graph from '../../../../components/Graph';
import { getMessageByLocale } from '../../../../utils/utils';
import Settings, { loadSettings } from '../../../../utils/settings';
import optionsStorage, {
HypercrxOptions,
defaults,
} from '../../../../options-storage';
import { iconDeveloperNetwork, iconRepoNetwork } from './icon-svg-path';
import './react-modal.scss';

Expand All @@ -24,13 +27,13 @@ const View = ({
developerNetwork,
repoNetwork,
}: Props): JSX.Element => {
const [settings, setSettings] = useState(new Settings());
const [options, setOptions] = useState<HypercrxOptions>(defaults);
const [showDeveloperNetwork, setShowDeveloperNetwork] = useState(false);
const [showRepoNetwork, setShowRepoNetwork] = useState(false);

useEffect(() => {
(async () => {
setSettings(await loadSettings());
(async function () {
setOptions(await optionsStorage.getAll());
})();
}, []);

Expand Down Expand Up @@ -62,10 +65,10 @@ const View = ({
<span
title={`${getMessageByLocale(
'global_clickToshow',
settings.locale
options.locale
)} ${getMessageByLocale(
'component_developerCollaborationNetwork_title',
settings.locale
options.locale
)}`}
className="Label"
style={{
Expand All @@ -75,7 +78,7 @@ const View = ({
>
{getMessageByLocale(
'component_developerCollaborationNetwork_title',
settings.locale
options.locale
)}
</span>
</button>
Expand Down Expand Up @@ -104,10 +107,10 @@ const View = ({
<span
title={`${getMessageByLocale(
'global_clickToshow',
settings.locale
options.locale
)} ${getMessageByLocale(
'component_mostParticipatedProjects_title',
settings.locale
options.locale
)}`}
className="Label"
style={{
Expand All @@ -117,7 +120,7 @@ const View = ({
>
{getMessageByLocale(
'component_mostParticipatedProjects_title',
settings.locale
options.locale
)}
</span>
</button>
Expand All @@ -138,12 +141,12 @@ const View = ({
<span>
{getMessageByLocale(
'component_developerCollaborationNetwork_title',
settings.locale
options.locale
)}
</span>
<div className="hypertrons-crx-title-extra developer-tab">
{getMessageByLocale('global_period', settings.locale)}:{' '}
{REPO_PERIOD} {getMessageByLocale('global_day', settings.locale)}
{getMessageByLocale('global_period', options.locale)}:{' '}
{REPO_PERIOD} {getMessageByLocale('global_day', options.locale)}
</div>
</div>
<div className="d-flex flex-wrap justify-content-lg-between align-items-center">
Expand All @@ -161,20 +164,20 @@ const View = ({
<p>
{getMessageByLocale(
'component_developerCollaborationNetwork_description',
settings.locale
options.locale
)}
</p>
<ul style={{ margin: '0px 0 10px 15px' }}>
<li>
{getMessageByLocale(
'component_developerCollaborationNetwork_description_node',
settings.locale
options.locale
)}
</li>
<li>
{getMessageByLocale(
'component_developerCollaborationNetwork_description_edge',
settings.locale
options.locale
)}
</li>
</ul>
Expand All @@ -198,13 +201,13 @@ const View = ({
<span>
{getMessageByLocale(
'component_mostParticipatedProjects_title',
settings.locale
options.locale
)}
</span>
<div className="hypertrons-crx-title-extra">
{getMessageByLocale('global_period', settings.locale)}:{' '}
{getMessageByLocale('global_period', options.locale)}:{' '}
{DEVELOPER_PERIOD}{' '}
{getMessageByLocale('global_day', settings.locale)}
{getMessageByLocale('global_day', options.locale)}
</div>
</div>
<div className="d-flex flex-wrap justify-content-lg-between align-items-center">
Expand All @@ -218,20 +221,20 @@ const View = ({
<p>
{getMessageByLocale(
'component_mostParticipatedProjects_description',
settings.locale
options.locale
)}
</p>
<ul style={{ margin: '0px 0 10px 15px' }}>
<li>
{getMessageByLocale(
'component_mostParticipatedProjects_description_node',
settings.locale
options.locale
)}
</li>
<li>
{getMessageByLocale(
'component_mostParticipatedProjects_description_edge',
settings.locale
options.locale
)}
</li>
</ul>
Expand Down
Loading

0 comments on commit 4acd096

Please sign in to comment.