Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/202307 code smells 31 #1201

Merged
merged 8 commits into from
Jul 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion starsky/build/helpers/SonarQube.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ public static bool SonarBegin(bool noUnitTest, bool noSonar, string branchName,
/* .Append($"/d:sonar.verbose=true ") */
.Append($"/d:sonar.host.url={url} ")
.Append($"/k:{key} ")
.Append($"/n:\"Starsky\" ")
.Append($"/n:Starsky ")
.Append($"/d:sonar.token={sonarToken} ")
.Append($"/o:" + organisation +" ")
.Append($"/d:sonar.typescript.tsconfigPath={tsconfig} ")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public SizeFileHashIsTheSameHelper(IStorage subPathStorage)
/// <returns>Last Edited is the bool (null is should check further in process), FileHash Same bool (null is not checked) , database item</returns>
internal async Task<Tuple<bool?,bool?,FileIndexItem>> SizeFileHashIsTheSame(List<FileIndexItem> dbItems, string subPath)
{
var dbItem = dbItems.FirstOrDefault(p => p.FilePath == subPath);
var dbItem = dbItems.Find(p => p.FilePath == subPath);
if ( dbItem == null )
{
return new Tuple<bool?, bool?, FileIndexItem>(false, false, null);
Expand Down
2 changes: 1 addition & 1 deletion starsky/starsky.foundation.sync/Helpers/SyncIgnoreCheck.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public SyncIgnoreCheck(AppSettings appSettings, IConsole console)

public bool Filter(string subPath)
{
var isSynced = _appSettings.SyncIgnore.Any(subPath.StartsWith);
var isSynced = _appSettings.SyncIgnore.Exists(subPath.StartsWith);
if ( isSynced && _appSettings.IsVerbose()) _console.WriteLine($"sync ignored for: {subPath}");
return isSynced;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export interface IDropAreaProps {
* @param event DragEvent which should contain files
*/
const containsFiles = (event: DragEvent) => {
if (event.dataTransfer && event.dataTransfer.types) {
if (event?.dataTransfer?.types) {
for (const type of event.dataTransfer.types) {
if (type === "Files") {
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,7 @@ const PanAndZoomImage = ({ src, id, ...props }: IPanAndZoomImage) => {

const imageReference = containerRef.current?.querySelector("img");
const isLoaded =
imageReference &&
imageReference.complete &&
imageReference.naturalHeight !== 0;
imageReference?.complete && imageReference?.naturalHeight !== 0;
props.setIsLoading(isLoaded === false);

// use Memo gives issues elsewhere
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ const ArchiveSidebarLabelEditSearchReplace: React.FunctionComponent = () => {

const replaceFieldName = "replace" + Capitalize(fieldName);
const replaceAnyValue = (update as any)[replaceFieldName];
const replaceValue: string = replaceAnyValue ? replaceAnyValue : "";
const replaceValue: string = replaceAnyValue ?? "";

bodyParams.set("replace", replaceValue);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,23 +223,22 @@ const MenuInlineSearch: React.FunctionComponent<IMenuSearchBarProps> = memo(
);
})
: null}
{suggest &&
suggest.map((item, index) =>
index <= 8 ? (
<li
key={item}
data-key={item}
className="menu-item menu-item--results"
{suggest?.map((item, index) =>
index <= 8 ? (
<li
key={item}
data-key={item}
className="menu-item menu-item--results"
>
<button
onClick={() => navigate(item)}
className="search-icon"
>
<button
onClick={() => navigate(item)}
className="search-icon"
>
{item}
</button>
</li>
) : null
)}
{item}
</button>
</li>
) : null
)}
</ul>
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const SearchPagination: React.FunctionComponent<IRelativeLink> = memo(
);
}

function next(): JSX.Element {
function next(): React.JSX.Element {
if (!urlObject || !lastPageNumber) return <></>;
urlObject.p = urlObject.p ? urlObject.p : 0;
const nextObject = { ...urlObject };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ const DetailViewMp4: React.FunctionComponent = memo(() => {

// Check if media is found
useEffect(() => {
if (!state || !state.fileIndexItem || !state.fileIndexItem.status) return;
if (!state?.fileIndexItem?.status) return;
if (state.fileIndexItem.status === IExifStatus.NotFoundSourceMissing) {
setIsError(MessageVideoNotFound);
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ const MenuDetailView: React.FunctionComponent<MenuDetailViewProps> = ({
const [isModalMoveFile, setModalMoveFile] = React.useState(false);
const [isModalPublishOpen, setModalPublishOpen] = useState(false);

const goToParentFolderJSX: JSX.Element | null = isSearchQuery ? (
const goToParentFolderJSX: React.JSX.Element | null = isSearchQuery ? (
<li
className="menu-option"
data-test="go-to-parent-folder"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ export function addDefaultClickSetMarker(
}

function latLongRound(latitudeLong: number | undefined) {
return !!latitudeLong ? Math.round(latitudeLong * 1000000) / 1000000 : 0;
return latitudeLong ? Math.round(latitudeLong * 1000000) / 1000000 : 0;
}

function updateMap(
Expand Down Expand Up @@ -308,7 +308,7 @@ const ModalGeo: React.FunctionComponent<IModalMoveFileProps> = ({
: MessageViewLocation;
}

function updateButton(): JSX.Element {
function updateButton(): React.JSX.Element {
return isLocationUpdated ? (
<button
onClick={async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ const ModalMoveFile: React.FunctionComponent<IModalMoveFileProps> = (props) => {
/**
* Fallback if there is no result or when mounting with no context
*/
if (!usesFileList || !usesFileList.archive) {
if (!usesFileList?.archive) {
usesFileList = {
archive: newIArchive(),
pageType: PageType.Loading
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,8 @@ export const PreferencesAppSettings: React.FunctionComponent<any> = (_) => {
useEffect(() => {
function permissions(): boolean {
if (
!permissionsData ||
!permissionsData.data ||
!permissionsData.data.includes ||
permissionsData.statusCode !== 200
!permissionsData?.data?.includes ||
permissionsData?.statusCode !== 200
) {
return false;
}
Expand Down
2 changes: 1 addition & 1 deletion starsky/starsky/clientapp/src/containers/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ const Login: React.FC<ILoginProps> = () => {
"Email=" + userEmail + "&Password=" + userPassword
);
setLoading(false);
if (!response || !response.data) {
if (!response?.data) {
setError(MessageConnection);
} else if (response.statusCode === 423) {
setError(MessageLockedOut);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ function DetailViewWrapper(detailViewProp: IDetailView) {

// Gets the content of the props and inject into the state
useEffect(() => {
if (!detailViewProp || !detailViewProp.fileIndexItem) return;
if (!detailViewProp?.fileIndexItem) return;
dispatch({ type: "reset", payload: detailViewProp });
// should run only at start or change page
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { useSocketsEventName } from "./use-sockets.const";
import WebSocketService from "./websocket-service";

export function isKeepAliveMessage(item: any) {
if (!item || !item.type) return false;
if (!item?.type) return false;
return item.type === "Welcome" || item.type === "Heartbeat";
}

Expand Down
11 changes: 5 additions & 6 deletions starsky/starsky/clientapp/src/hooks/use-filelist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { useEffect, useState } from "react";
import { IArchive, newIArchive } from "../interfaces/IArchive";
import {
IDetailView,
newDetailView,
PageType
PageType,
newDetailView
} from "../interfaces/IDetailView";
import { CastToInterface } from "../shared/cast-to-interface";
import { FileListCache } from "../shared/filelist-cache";
Expand Down Expand Up @@ -114,10 +114,9 @@ const useFileList = (
setParent(new URLPath().getParent(locationSearch));

if (
!responseObject ||
!responseObject.pageType ||
responseObject.pageType === PageType.NotFound ||
responseObject.pageType === PageType.ApplicationException
!responseObject?.pageType ||
responseObject?.pageType === PageType.NotFound ||
responseObject?.pageType === PageType.ApplicationException
)
return;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ export const getCurrentTouches = (
preventDefault: originalEvent.preventDefault,
stopPropagation: originalEvent.stopPropagation,
...pointer,
deltaX: prevTouch && prevTouch.x ? pointer.x - prevTouch.x : 0,
deltaY: prevTouch && prevTouch.y ? pointer.y - prevTouch.y : 0,
deltaX: prevTouch?.x ? pointer.x - prevTouch.x : 0,
deltaY: prevTouch?.y ? pointer.y - prevTouch.y : 0,
delta: prevTouch ? getDistance(pointer, prevTouch) : 0,
distance: firstTouch ? getDistance(pointer, firstTouch) : 0,
angleDeg: prevTouch ? getAngleDeg(pointer, prevTouch) : 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import {
useRef,
useState
} from "react";
import { ICurrentTouches } from "./ICurrentTouches.types";
import { IHandlers } from "./IHandlers.types";
import { callHandler } from "./call-handler";
import { debounce } from "./debounce";
import { getCurrentTouches } from "./get-current-touches";
import { ICurrentTouches } from "./ICurrentTouches.types";
import { IHandlers } from "./IHandlers.types";
import { Pointer } from "./pointer";

/**
Expand Down Expand Up @@ -125,7 +125,7 @@ const executeTouchEnd = (
touches: ICurrentTouches,
gesture: string
) => {
if (touches && touches.pointers) {
if (touches?.pointers) {
if (touches.pointers.length === 2) {
callHandler("onPinchEnd", currentTouches, handlers);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ function useHotKeys(
useEffect(() => {
const handler = function (event: KeyboardEvent) {
if (new Keyboard().isInForm(event)) return;
if (!predefined || !predefined.key) {
if (!predefined?.key) {
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ function useKeyboardEvent(
) {
useEffect(() => {
const handler = function (event: KeyboardEvent) {
if (regex && event.key.match(regex)) {
if (regex?.exec(event.key)) {
callback(event);
}
};
Expand Down
16 changes: 15 additions & 1 deletion starsky/starsky/clientapp/src/shared/browser-detect.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,23 @@ describe("browser-detect", () => {
jest.spyOn(navigator, "userAgent", "get").mockImplementationOnce(() => {
return "Safari";
});
jest.spyOn(navigator, "platform", "get").mockImplementationOnce(() => {
jest.spyOn(navigator, "userAgent", "get").mockImplementationOnce(() => {
return "iPhone";
});
expect(new BrowserDetect().IsIOS()).toBeTruthy();
});

it("Fake IsIOS iPad", () => {
(document.documentElement.style as any)["WebkitAppearance"] = true;
document.ontouchend = jest.fn();

Object.defineProperty(navigator, "maxTouchPoints", {
value: 2
});
jest.spyOn(navigator, "userAgent", "get").mockImplementationOnce(() => {
return "Safari";
});

expect(new BrowserDetect().IsIOS()).toBeTruthy();
});
});
6 changes: 3 additions & 3 deletions starsky/starsky/clientapp/src/shared/browser-detect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ export class BrowserDetect {
const isWebKit =
"WebkitAppearance" in document.documentElement.style &&
navigator.userAgent.indexOf("Safari") !== -1;
const isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
const isIPadOS =
navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1;
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);

const isIPadOS = "ontouchend" in document && navigator.maxTouchPoints > 1;
return isWebKit && (isIOS || isIPadOS);
}
public IsLegacy = (): boolean => {
Expand Down
2 changes: 1 addition & 1 deletion starsky/starsky/clientapp/src/shared/clipboard-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export class ClipboardHelper {
let result = {};
try {
const resultString = sessionStorage.getItem(this.clipBoardName);
result = JSON.parse(resultString ? resultString : "");
result = JSON.parse(resultString ?? "");
} catch (error) {
return null;
}
Expand Down
5 changes: 2 additions & 3 deletions starsky/starsky/clientapp/src/shared/fetch-post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@ const FetchPost = async (
headers: object = {}
): Promise<IConnectionDefault> => {
function getCookie(name: string): string {
const match = document.cookie.match(
new RegExp("(^| )" + name + "=([^;]+)")
);
const regex = new RegExp("(^| )" + name + "=([^;]+)");
const match = regex.exec(document.cookie);
if (match) return match[2];
return "X-XSRF-TOKEN";
}
Expand Down
22 changes: 14 additions & 8 deletions starsky/starsky/clientapp/src/shared/file-extensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ export class FileExtensions {
public MatchExtension(from: string, to: string): boolean | null {
const extensionRegex = /\.[0-9a-z]+$/;

const fromExtMatchArray = from.match(extensionRegex);
const fromExtMatchArray = extensionRegex.exec(from);
if (!fromExtMatchArray) return null;

const toExtMatchArray = to.match(extensionRegex);
const toExtMatchArray = extensionRegex.exec(to);
if (!toExtMatchArray) return false;

return toExtMatchArray[0] === fromExtMatchArray[0];
}

Expand All @@ -20,10 +21,9 @@ export class FileExtensions {
* @param filename
*/
public IsValidFileName(filename: string): boolean {
// before 02/23 /^[a-zA-Z0-9_](?:[a-zA-Z0-9 ._-]*[a-zA-Z0-9])?\.[a-zA-Z0-9_-]+$/;
const extensionRegex =
/^\w(?:[a-zA-Z0-9 ._-]*[a-zA-Z0-9])?\.[a-zA-Z0-9_-]+$/;
const fromExtMatchArray = filename.match(extensionRegex);
const fromExtMatchArray = extensionRegex.exec(filename);
return !!fromExtMatchArray;
}

Expand All @@ -33,7 +33,7 @@ export class FileExtensions {
*/
public IsValidDirectoryName(directoryName: string): boolean {
const extensionRegex = /^[$a-zA-Z0-9_\s-]{2,}$/;
const fromDirMatchArray = directoryName.match(extensionRegex);
const fromDirMatchArray = extensionRegex.exec(directoryName);
return !!fromDirMatchArray;
}

Expand All @@ -44,15 +44,18 @@ export class FileExtensions {
*/
public GetParentPath(filePath: string) {
if (!filePath) return "/";

const parentRegex = /.+(?=\/[^/]+$)/;

// remove slash from end
// Remove slash from end
if (filePath.length >= 2 && filePath.endsWith("/")) {
filePath = filePath.slice(0, -1);
}

const parentMatchArray = filePath.match(parentRegex);
const parentMatchArray = parentRegex.exec(filePath);

if (!parentMatchArray) return "/";

return parentMatchArray[0];
}

Expand Down Expand Up @@ -81,7 +84,10 @@ export class FileExtensions {
*/
public GetFileExtensionWithoutDot(fileNameWithDot: string) {
if (fileNameWithDot.indexOf(".") === -1) return "";
const fileNameMatchArray = fileNameWithDot.match(/[^.][a-zA-Z0-9]{1,4}$/);

const extensionRegex = /[^.][a-zA-Z0-9]{1,4}$/;
const fileNameMatchArray = extensionRegex.exec(fileNameWithDot);

if (!fileNameMatchArray) return "";
return fileNameMatchArray[0].toLowerCase();
}
Expand Down
Loading
Loading