ramda#isNil TypeScript Examples
The following examples show how to use
ramda#isNil.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx From back-home-safe with GNU General Public License v3.0 | 6 votes |
CameraSetting = () => {
const { t } = useTranslation("camera_setting");
const { preferredCameraId, setPreferredCameraId, cameraList } = useCamera();
return (
<PageWrapper>
<Header backPath="/" name={t("name")} />
<FormWrapper>
<StyledFormControl>
<InputLabel id="cameraId">{t("form.camera_choice.label")}</InputLabel>
<Select
labelId="cameraId"
id="demo-simple-select"
value={preferredCameraId}
onChange={(e) => {
setPreferredCameraId((e.target.value as string) || "AUTO");
}}
>
<MenuItem value="AUTO">{t("form.camera_choice.auto")}</MenuItem>
{cameraList.map(({ deviceId, label }) => (
<MenuItem value={deviceId} key="deviceId">
{isNil(label) || isEmpty(label) ? deviceId : label}
</MenuItem>
))}
</Select>
<FormHelperText>{t("form.camera_choice.explain")}</FormHelperText>
</StyledFormControl>
</FormWrapper>
<VideoContainer>
<MediaStream suppressError />
</VideoContainer>
</PageWrapper>
);
}
Example #2
Source File: index.ts From reskript with MIT License | 6 votes |
runBuild = (configuration: Configuration[]): Promise<Stats> => {
const executor = (resolve: (value: Stats) => void) => webpack(
configuration as Configuration, // https://github.com/Microsoft/TypeScript/issues/14107
(err?: Error, stats?: Stats) => {
if (err) {
logger.error(err.toString());
process.exit(22);
}
if (!stats) {
logger.error('Unknown error: webpack does not return its build stats');
process.exit(22);
}
const toJsonOptions = {all: false, errors: true, warnings: true, assets: true};
// webpack的`toJson`的定义是错的
const {errors, warnings} = stats.toJson(toJsonOptions);
for (const error of reject(isNil, errors ?? [])) {
printWebpackResult('error', error as unknown as WebpackResult);
}
for (const warning of reject(isNil, warnings ?? [])) {
printWebpackResult('warn', warning as unknown as WebpackResult);
}
if (stats.hasErrors()) {
process.exit(22);
}
resolve(stats);
}
);
return new Promise(executor);
}
Example #3
Source File: case.ts From reskript with MIT License | 6 votes |
parseMarkdownToCases = async (markdown: string): Promise<PlayCase[]> => {
if (!markdown) {
return [];
}
const nodes = splitToCaseNodes(markdown);
const cases = await pMap(nodes, parseToCase);
return reject(isNil, cases);
}
Example #4
Source File: fieldManager.ts From react-js-tutorial with MIT License | 6 votes |
getDiagonals = (gameField: GameFieldType, bottomToTop = true) => {
const Ylength = gameField.length;
const Xlength = gameField[0].length;
const maxLength = Math.max(Xlength, Ylength);
const result: string[][] = [];
for (let k = 0; k <= 2 * maxLength; k++) {
for (let y = 0; y <= Ylength - 1; y++) {
const x = k - (bottomToTop ? Ylength - y : y);
if (x >= 0 && x < Xlength && gameField[y][x]) {
if (!result[k]) {
result[k] = [];
}
result[k].push(gameField[y][x]);
}
}
}
return filter(complement(isNil), result);
}
Example #5
Source File: setup-station.page.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
public ngOnInit(): void {
this.form = this.formBuilder.group({
settings: this.formBuilder.group({
configurationType: ['azura', Validators.required],
streamUrl: ['', Validators.required],
streamType: ['', Validators.required],
azuraCastApiKey: ['', Validators.required],
azuraCastBaseUrl: ['', Validators.required],
azuraCastStationId: ['', Validators.required],
matchingService: ['spotify'],
spotifyClientId: [''],
spotifyClientSecret: [''],
}),
});
this.form.valueChanges.pipe(
takeUntil(this.componentDestroyed$)
).subscribe(() => this.streamConnectionSuccessful = false);
this.sessionQuery.select()
.pipe(
filter((tenant) => !isNil(tenant)),
distinctUntilChanged()
)
.subscribe(({ tenant }) => {
this.tenantUuid = tenant.uuid;
this.fetch(tenant.uuid);
});
}
Example #6
Source File: ConfirmPage.tsx From back-home-safe with GNU General Public License v3.0 | 5 votes |
ConfirmPage = ({
travelRecord,
readOnly = false,
confirmPageIcon,
autoLeave = true,
setAutoLeave,
autoLeaveHour = 4,
handleChangeAutoLeaveHour,
handleLeave,
}: Props) => {
const { t } = useTranslation("confirm");
const { language } = useI18n();
const date = useMemo(() => dayjs(travelRecord.inTime), [travelRecord]);
const place = useMemo(
() => getVenueName(travelRecord, language),
[travelRecord, language]
);
const venueType = propOr(locationType.PLACE, "type", travelRecord);
return (
<>
<PageWrapper>
<Header>
{confirmPageIcon && <Logo src={confirmPageIcon} />}
{readOnly ? (
<Cross src={cross} />
) : (
<Link to="/">
<Cross src={cross} />
</Link>
)}
</Header>
<MessageWrapper>
{venueType === locationType.TAXI ? (
<>
<Msg>{t("message.you_have_entered_taxi")}</Msg>
<License>{t("message.res_mark")}:</License>
</>
) : (
<Msg>{t("message.you_have_entered_venue")}</Msg>
)}
<PlaceWrapper>
<Place value={place || ""} readOnly />
</PlaceWrapper>
<Time>{date.format("YYYY-MM-DD HH:mm")}</Time>
</MessageWrapper>
<TickWrapper>
<TickWrapperInner>
<Tick src={tick} />
</TickWrapperInner>
</TickWrapper>
<ActionGroup>
<ConfirmButton shadowed onClick={handleLeave}>
{venueType === locationType.TAXI
? t("button.get_off")
: t("button.leave")}
</ConfirmButton>
<LeaveMessage>{t("message.remember_to_leave")}</LeaveMessage>
<AutoLeave>
<CheckBoxWrapper>
<CheckBox
checked={autoLeave}
onChange={setAutoLeave}
readOnly={isNil(setAutoLeave)}
/>
{t("form.auto_leave_after_x_hour", { hour: autoLeaveHour })}
</CheckBoxWrapper>
<Change onClick={handleChangeAutoLeaveHour}>
{t("global:button.change")}
</Change>
</AutoLeave>
</ActionGroup>
</PageWrapper>
</>
);
}
Example #7
Source File: duplicatePackages.ts From reskript with MIT License | 5 votes |
extractUniqueModules = (compilations: StatsCompilation[]): string[] => {
const modules = compilations.flatMap(c => c.modules);
const names = modules.map(m => m?.nameForCondition);
return uniq(reject(isNil, names));
}
Example #8
Source File: htmlImportable.ts From reskript with MIT License | 5 votes |
extractScriptEntries = (compilations: StatsCompilation[]): string[] => {
const entries = compilations.flatMap(c => Object.values(c.entrypoints ?? {}));
// 这里的`assets`是有顺序的(大概),被别人依赖的在前面(大概),真正的入口是最后一个(大概)
return uniq(reject(isNil, entries.map(v => last(v.assets ?? [])?.name)));
}
Example #9
Source File: config.ts From reskript with MIT License | 5 votes |
createWebpackConfig = async (target: string, cmd: PlayCommandLineArgs, buildContext: BuildContext) => {
const hostType = await resolveDevHost(cmd.host);
const extra = await createWebpackDevServerPartial(buildContext, hostType);
const baseConfig = await createBaseWebpackConfig(buildContext, {extras: [extra]});
const enableConcurrentMode = cmd.concurrentMode ?? buildContext.projectSettings.play.defaultEnableConcurrentMode;
const playEntryPath = resolveEntryPath(enableConcurrentMode);
const componentTypeName = resolveComponentName(target);
const entryLoaders = [
await loaders.babel(buildContext),
{
loader: await resolve('loader-of-loader'),
options: {
resolveLoader: async () => {
return {
loader: path.join(currentDirectory, 'loader.js'),
type: 'module',
options: {
componentTypeName,
cwd: buildContext.cwd,
componentModulePath: path.resolve(buildContext.cwd, target),
globalSetupModulePath: cmd.setup
? path.resolve(cmd.cwd, cmd.setup)
: buildContext.projectSettings.play.defaultGlobalSetup,
},
};
},
},
},
];
const config: webpack.Configuration = {
...baseConfig,
entry: {
index: playEntryPath,
},
module: {
rules: [
{
test: playEntryPath,
use: reject(isNil, entryLoaders),
},
...(baseConfig.module?.rules ?? []),
],
},
resolve: {
...baseConfig.resolve,
fallback: {
...baseConfig.resolve?.fallback,
// React要从`17.0.3`开始才会有`exports`配置,这之前的版本在ESM下是必须加`.js`后续的。
// 利用这个`resolve.fallback`,可以在找不到`react/jsx-runtime`时跳到`react/jsx-runtime.js`上去,兼容旧版本。
'react/jsx-runtime': 'react/jsx-runtime.js',
},
},
};
return config;
}
Example #10
Source File: overrides.ts From the-fake-backend with ISC License | 5 votes |
isNotEmpty = complement(either(isNil, isEmpty))
Example #11
Source File: App.tsx From back-home-safe with GNU General Public License v3.0 | 4 votes |
App = () => {
useMigration();
const [finishedTutorial, setFinishedTutorial] = useLocalStorage(
"finished_tutorial",
false
);
const [confirmPageIcon, setConfirmPageIcon] = useLocalStorage<string | null>(
"confirmPageIcon",
null
);
const { lockStore, unlocked, isEncrypted } = useData();
const { pathname } = useLocation();
const browserHistory = useHistory();
const handleBlur = useCallback(() => {
if (pathname !== "/qrReader" && pathname !== "/cameraSetting") lockStore();
}, [lockStore, pathname]);
useEffect(() => {
window.addEventListener("blur", handleBlur);
return () => {
window.removeEventListener("blur", handleBlur);
};
}, [handleBlur]);
const pageMap = useMemo<
{ route: RouteProps; component: React.ReactNode; privateRoute: boolean }[]
>(
() => [
{
privateRoute: false,
route: { exact: true, path: "/tutorial" },
component: <Tutorial setFinishedTutorial={setFinishedTutorial} />,
},
{
privateRoute: false,
route: { exact: true, path: "/login" },
component: <Login />,
},
{
privateRoute: true,
route: {
exact: true,
path: "/",
},
component: <MainScreen />,
},
{
privateRoute: true,
route: {
exact: true,
path: "/confirm/:id",
},
component: <Confirm confirmPageIcon={confirmPageIcon} />,
},
{
privateRoute: true,
route: {
exact: true,
path: "/qrGenerator",
},
component: <QRGenerator />,
},
{
privateRoute: true,
route: {
exact: true,
path: "/disclaimer",
},
component: <Disclaimer />,
},
{
privateRoute: true,
route: {
exact: true,
path: "/qrReader",
},
component: <QRReader />,
},
{
privateRoute: true,
route: {
exact: true,
path: "/cameraSetting",
},
component: <CameraSetting />,
},
{
privateRoute: true,
route: {
exact: true,
path: "/confirmPageSetting",
},
component: (
<ConfirmPageSetting
confirmPageIcon={confirmPageIcon}
setConfirmPageIcon={setConfirmPageIcon}
/>
),
},
{
privateRoute: true,
route: {
exact: true,
path: "/vaccinationQRReader",
},
component: <VaccinationQRReader />,
},
],
[confirmPageIcon, setConfirmPageIcon, setFinishedTutorial]
);
// transition group cannot use switch component, thus need manual redirect handling
// ref: https://reactcommunity.org/react-transition-group/with-react-router
useEffect(() => {
if (!unlocked && pathname !== "/login") {
browserHistory.replace("/login");
}
if (unlocked && pathname === "/login") {
browserHistory.replace("/");
}
}, [isEncrypted, unlocked, browserHistory, pathname]);
useEffect(() => {
if (!finishedTutorial && pathname !== "/tutorial") {
browserHistory.replace("/tutorial");
}
if (finishedTutorial && pathname === "/tutorial") {
browserHistory.replace("/");
}
}, [finishedTutorial, browserHistory, pathname]);
useEffect(() => {
const hasMatch = any(({ route }) => {
if (!route.path) return false;
return !isNil(matchPath(pathname, route));
}, pageMap);
if (!hasMatch) {
browserHistory.replace("/");
}
}, [browserHistory, pathname, pageMap]);
return (
<>
<GlobalStyle />
{pageMap.map(({ route, component, privateRoute }) =>
privateRoute && !unlocked ? (
<React.Fragment key={String(route.path)} />
) : (
<Route {...route} key={String(route.path)}>
{({ match }) => (
<CSSTransition
in={match != null}
timeout={300}
classNames="page"
unmountOnExit
>
<div className="page">
<Suspense fallback={<PageLoading />}>{component}</Suspense>
</div>
</CSSTransition>
)}
</Route>
)
)}
</>
);
}
Example #12
Source File: index.tsx From back-home-safe with GNU General Public License v3.0 | 4 votes |
Confirm = ({ confirmPageIcon }: Props) => {
const browserHistory = useHistory();
const { id } = useParams<{ id: string }>();
const { state } = useLocation<TravelRecord>();
const { updateTravelRecord, getTravelRecord } = useTravelRecord();
const [isAutoLeaveModalOpen, setIsAutoLeaveModalOpen] = useState(false);
const [isLeaveModalOpen, setIsLeaveModalOpen] = useState(false);
const travelRecord = useMemo(
() => (state ? state : getTravelRecord(id)),
[state, getTravelRecord, id]
);
useEffect(() => {
if (!travelRecord) browserHistory.replace("/");
}, [travelRecord, browserHistory]);
const [autoLeave, setAutoLeave] = useState(
travelRecord ? !isNil(travelRecord.outTime) : true
);
const [autoLeaveHour, setAutoLeaveHour] = useState(
travelRecord && travelRecord.outTime
? dayjs(travelRecord.outTime).diff(travelRecord.inTime, "hour")
: 4
);
const inTime = useMemo(
() => (travelRecord ? travelRecord.inTime : dayjs().toISOString()),
[travelRecord]
);
const handleSetAutoLeaveHour = (value: number) => {
setAutoLeaveHour(value);
setIsAutoLeaveModalOpen(false);
};
const handleLeavePage = () => {
setIsAutoLeaveModalOpen(false);
setIsLeaveModalOpen(false);
browserHistory.push("/");
};
const handleLeave = (date: Dayjs) => {
updateTravelRecord(id, {
outTime: date.startOf("minute").toISOString(),
});
handleLeavePage();
};
useEffect(() => {
const toDate = dayjs(inTime).add(autoLeaveHour, "hour");
updateTravelRecord(id, {
outTime: autoLeave ? toDate.toISOString() : undefined,
});
}, [autoLeave, autoLeaveHour, updateTravelRecord, id, inTime]);
return travelRecord ? (
<>
<ConfirmPage
travelRecord={travelRecord}
confirmPageIcon={confirmPageIcon}
autoLeave={autoLeave}
setAutoLeave={setAutoLeave}
autoLeaveHour={autoLeaveHour}
handleChangeAutoLeaveHour={() => {
setIsAutoLeaveModalOpen(true);
}}
handleLeave={() => {
setIsLeaveModalOpen(true);
}}
/>
<AutoLeaveModal
isModalOpen={isAutoLeaveModalOpen}
onCancel={() => {
setIsAutoLeaveModalOpen(false);
}}
onConfirm={handleSetAutoLeaveHour}
selectedAutoLeaveHour={autoLeaveHour}
date={dayjs(inTime)}
/>
<LeaveModal
id={id}
visible={isLeaveModalOpen}
onDiscard={() => {
setIsLeaveModalOpen(false);
}}
onFinish={handleLeave}
/>
</>
) : (
<></>
);
}
Example #13
Source File: useEncryptedStore.ts From back-home-safe with GNU General Public License v3.0 | 4 votes |
useEncryptedStore = <T extends T[] | Object>({
key,
defaultValue: fallbackValue,
passthroughOnly = false,
}: {
key: string;
defaultValue: T;
passthroughOnly?: boolean;
}) => {
const [incognito, setIncognito] = useLocalStorage("incognito", false);
const [defaultValue] = useState<T>(fallbackValue);
const [password, setPassword] = useState<string | null>(null);
const [savedValue, setSavedValue, removeSavedValue] = useLocalStorage<string>(
key,
passthroughOnly
? undefined
: password
? encryptValue(JSON.stringify(defaultValue), password)
: JSON.stringify(defaultValue)
);
const isEncrypted = useMemo(() => {
try {
if (!savedValue) return false;
JSON.parse(savedValue);
} catch (e) {
return true;
}
return false;
}, [savedValue]);
const [decryptedValue, setDecryptedValue] = useState<T>(
!isEncrypted && savedValue ? JSON.parse(savedValue) : defaultValue
);
const [unlocked, setUnlocked] = useState(!isEncrypted);
useDeepCompareEffect(() => {
if (!unlocked || incognito || passthroughOnly) return;
if (isEncrypted && !password) return;
const value = JSON.stringify(decryptedValue);
console.log(value);
setSavedValue(password ? encryptValue(value, password) : value);
}, [decryptedValue]);
const initPassword = useCallback(
(newPassword: string) => {
if (isEncrypted || passthroughOnly) return;
const data = encryptValue(
savedValue || JSON.stringify(defaultValue),
newPassword
);
setSavedValue(data);
setPassword(newPassword);
},
[passthroughOnly, savedValue, setSavedValue, defaultValue, isEncrypted]
);
const unlockStore = useCallback(
(password: string) => {
if (!isEncrypted) return true;
try {
const decryptedValue = decryptValue(
savedValue || JSON.stringify(defaultValue),
password
);
setDecryptedValue(JSON.parse(decryptedValue));
setPassword(password);
setUnlocked(true);
return true;
} catch (e) {
return false;
}
},
[defaultValue, savedValue, isEncrypted]
);
const lockStore = useCallback(() => {
if (!isEncrypted) return;
setUnlocked(false);
setPassword(null);
setDecryptedValue(defaultValue);
}, [isEncrypted, defaultValue]);
return {
isEncrypted,
unlockStore,
lockStore,
value: decryptedValue,
setValue: setDecryptedValue,
initPassword,
unlocked,
incognito,
setIncognito,
password,
destroy: removeSavedValue,
hasData: !isNil(savedValue),
};
}