Merge pull request #1818 from akhilmhdh/fix/patches-v2

Improvised secret input component and fontawesome performance improvment
This commit is contained in:
Maidul Islam
2024-05-13 13:42:30 -04:00
committed by GitHub
10 changed files with 454 additions and 352 deletions
@@ -120,7 +120,7 @@ export default function NavHeader({
passHref passHref
legacyBehavior legacyBehavior
href={{ href={{
pathname: "/project/[id]/secrets/v2/[env]", pathname: "/project/[id]/secrets/[env]",
query: { id: router.query.id, env: router.query.env } query: { id: router.query.id, env: router.query.env }
}} }}
> >
@@ -0,0 +1,19 @@
import { forwardRef, HTMLAttributes } from "react";
type Props = {
symbolName: string;
} & HTMLAttributes<HTMLDivElement>;
export const FontAwesomeSymbol = forwardRef<HTMLDivElement, Props>(
({ symbolName, ...props }, ref) => {
return (
<div ref={ref} {...props}>
<svg className="w-inherit h-inherit">
<use href={`#${symbolName}`} />
</svg>
</div>
);
}
);
FontAwesomeSymbol.displayName = "FontAwesomeSymbol";
@@ -0,0 +1 @@
export { FontAwesomeSymbol } from "./FontAwesomeSymbol";
@@ -1,17 +1,42 @@
import { TextareaHTMLAttributes, useEffect, useRef, useState } from "react"; import { forwardRef, TextareaHTMLAttributes, useCallback, useMemo, useRef, useState } from "react";
import { faCircle, faFolder, faKey } from "@fortawesome/free-solid-svg-icons"; import { faCircle, faFolder, faKey } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as Popover from "@radix-ui/react-popover"; import * as Popover from "@radix-ui/react-popover";
import { twMerge } from "tailwind-merge";
import { useWorkspace } from "@app/context"; import { useWorkspace } from "@app/context";
import { useDebounce } from "@app/hooks"; import { useDebounce, useToggle } from "@app/hooks";
import { useGetFoldersByEnv, useGetProjectSecrets, useGetUserWsKey } from "@app/hooks/api"; import { useGetProjectFolders, useGetProjectSecrets, useGetUserWsKey } from "@app/hooks/api";
import { SecretInput } from "../SecretInput"; import { SecretInput } from "../SecretInput";
const REGEX_UNCLOSED_SECRET_REFERENCE = /\${(?![^{}]*\})/g; const getIndexOfUnclosedRefToTheLeft = (value: string, pos: number) => {
const REGEX_OPEN_SECRET_REFERENCE = /\${/g; // take substring up to pos in order to consider edits for closed references
for (let i = pos; i >= 1; i -= 1) {
if (value[i] === "}") return -1;
if (value[i - 1] === "$" && value[i] === "{") {
return i;
}
}
return -1;
};
const getIndexOfUnclosedRefToTheRight = (value: string, pos: number) => {
// use it with above to identify an open ${
for (let i = pos; i < value.length; i += 1) {
if (value[i] === "}") return i - 1;
}
return -1;
};
const getClosingSymbol = (isSelectedSecret: boolean, isClosed: boolean) => {
if (!isClosed) {
return isSelectedSecret ? "}" : ".";
}
if (!isSelectedSecret) return ".";
return "";
};
const mod = (n: number, m: number) => ((n % m) + m) % m;
export enum ReferenceType { export enum ReferenceType {
ENVIRONMENT = "environment", ENVIRONMENT = "environment",
@@ -19,8 +44,9 @@ export enum ReferenceType {
SECRET = "secret" SECRET = "secret"
} }
type Props = TextareaHTMLAttributes<HTMLTextAreaElement> & { type Props = Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, "onChange" | "value"> & {
value?: string | null; value?: string;
onChange: (val: string) => void;
isImport?: boolean; isImport?: boolean;
isVisible?: boolean; isVisible?: boolean;
isReadOnly?: boolean; isReadOnly?: boolean;
@@ -31,339 +57,298 @@ type Props = TextareaHTMLAttributes<HTMLTextAreaElement> & {
}; };
type ReferenceItem = { type ReferenceItem = {
name: string; label: string;
type: ReferenceType; type: ReferenceType;
slug?: string; slug: string;
}; };
export const InfisicalSecretInput = ({ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
value: propValue, (
containerClassName, {
secretPath: propSecretPath, value = "",
environment: propEnvironment, onChange,
onChange, containerClassName,
...props secretPath: propSecretPath,
}: Props) => { environment: propEnvironment,
const [inputValue, setInputValue] = useState(propValue ?? ""); ...props
const [isSuggestionsOpen, setIsSuggestionsOpen] = useState(false); },
const [currentCursorPosition, setCurrentCursorPosition] = useState(0); ref
const [currentReference, setCurrentReference] = useState<string>(""); ) => {
const [secretPath, setSecretPath] = useState<string>(propSecretPath || "/"); const { currentWorkspace } = useWorkspace();
const [environment, setEnvironment] = useState<string | undefined>(propEnvironment); const workspaceId = currentWorkspace?.id || "";
const { currentWorkspace } = useWorkspace(); const { data: decryptFileKey } = useGetUserWsKey(workspaceId);
const workspaceId = currentWorkspace?.id || "";
const { data: decryptFileKey } = useGetUserWsKey(workspaceId);
const { data: secrets } = useGetProjectSecrets({
decryptFileKey: decryptFileKey!,
environment: environment || currentWorkspace?.environments?.[0].slug!,
secretPath,
workspaceId
});
const { folderNames: folders } = useGetFoldersByEnv({
path: secretPath,
environments: [environment || currentWorkspace?.environments?.[0].slug!],
projectId: workspaceId
});
const debouncedCurrentReference = useDebounce(currentReference, 100); const debouncedValue = useDebounce(value, 500);
const [listReference, setListReference] = useState<ReferenceItem[]>([]); const [highlightedIndex, setHighlightedIndex] = useState(-1);
const [highlightedIndex, setHighlightedIndex] = useState(-1);
const inputRef = useRef<HTMLTextAreaElement>(null);
const isPopupOpen = isSuggestionsOpen && listReference.length > 0 && currentReference.length > 0;
useEffect(() => { const inputRef = useRef<HTMLTextAreaElement>(null);
setInputValue(propValue ?? ""); const popoverContentRef = useRef<HTMLDivElement>(null);
}, [propValue]); const [isFocused, setIsFocused] = useToggle(false);
const currentCursorPosition = inputRef.current?.selectionStart || 0;
useEffect(() => { const suggestionSource = useMemo(() => {
let currentEnvironment = propEnvironment; const left = getIndexOfUnclosedRefToTheLeft(debouncedValue, currentCursorPosition - 1);
let currentSecretPath = propSecretPath || "/"; if (left === -1) return { left, value: "", predicate: "", isDeep: false };
if (!currentReference) { const suggestionSourceValue = debouncedValue.slice(left + 1, currentCursorPosition);
setSecretPath(currentSecretPath); let suggestionSourceEnv: string | undefined = propEnvironment;
setEnvironment(currentEnvironment); let suggestionSourceSecretPath: string | undefined = propSecretPath || "/";
return;
}
const isNested = currentReference.includes("."); // means its like <environment>.<folder1>.<...more folder>.secret
const isDeep = suggestionSourceValue.includes(".");
let predicate = suggestionSourceValue;
if (isDeep) {
const [envSlug, ...folderPaths] = suggestionSourceValue.split(".");
const isValidEnvSlug = currentWorkspace?.environments.find((e) => e.slug === envSlug);
suggestionSourceEnv = isValidEnvSlug ? envSlug : undefined;
suggestionSourceSecretPath = `/${folderPaths.slice(0, -1)?.join("/")}`;
predicate = folderPaths[folderPaths.length - 1];
}
if (isNested) { return {
const [envSlug, ...folderPaths] = currentReference.split("."); left: left + 1,
const isValidEnvSlug = currentWorkspace?.environments.find((e) => e.slug === envSlug); // the full value inside a ${<value>}
currentEnvironment = isValidEnvSlug ? envSlug : undefined; value: suggestionSourceValue,
// the final part after staging.dev.<folder1>.<predicate>
predicate,
isOpen: left !== -1,
isDeep,
environment: suggestionSourceEnv,
secretPath: suggestionSourceSecretPath
};
}, [debouncedValue]);
// should be based on the last valid section (with .) const isPopupOpen = Boolean(suggestionSource.isOpen) && isFocused;
folderPaths.pop(); const { data: secrets } = useGetProjectSecrets({
currentSecretPath = `/${folderPaths?.join("/")}`; decryptFileKey: decryptFileKey!,
} environment: suggestionSource.environment || "",
secretPath: suggestionSource.secretPath || "",
setSecretPath(currentSecretPath); workspaceId,
setEnvironment(currentEnvironment); options: {
}, [debouncedCurrentReference]); enabled: isPopupOpen
}
useEffect(() => {
const currentListReference: ReferenceItem[] = [];
const isNested = currentReference?.includes(".");
if (!currentReference) {
setListReference(currentListReference);
return;
}
if (!environment) {
currentWorkspace?.environments.forEach((env) => {
currentListReference.unshift({
name: env.slug,
type: ReferenceType.ENVIRONMENT
});
});
} else if (isNested) {
folders?.forEach((folder) => {
currentListReference.unshift({ name: folder, type: ReferenceType.FOLDER });
});
} else if (environment) {
currentWorkspace?.environments.forEach((env) => {
currentListReference.unshift({
name: env.slug,
type: ReferenceType.ENVIRONMENT
});
});
}
secrets?.forEach((secret) => {
currentListReference.unshift({ name: secret.key, type: ReferenceType.SECRET });
}); });
const { data: folders } = useGetProjectFolders({
// Get fragment inside currentReference environment: suggestionSource.environment || "",
const searchFragment = isNested ? currentReference.split(".").pop() || "" : currentReference; path: suggestionSource.secretPath || "",
const filteredListRef = currentListReference projectId: workspaceId,
.filter((suggestionEntry) => options: {
suggestionEntry.name.toUpperCase().startsWith(searchFragment.toUpperCase()) enabled: isPopupOpen
)
.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
setListReference(filteredListRef);
}, [secrets, environment, debouncedCurrentReference]);
const getIndexOfUnclosedRefToTheLeft = (pos: number) => {
// take substring up to pos in order to consider edits for closed references
const unclosedReferenceIndexMatches = [
...inputValue.substring(0, pos).matchAll(REGEX_UNCLOSED_SECRET_REFERENCE)
].map((match) => match.index);
// find unclosed reference index less than the current cursor position
let indexIter = -1;
unclosedReferenceIndexMatches.forEach((index) => {
if (index !== undefined && index > indexIter && index < pos) {
indexIter = index;
} }
}); });
return indexIter; const suggestions = useMemo(() => {
}; if (!isPopupOpen) return [];
// reset highlight whenever recomputation happens
setHighlightedIndex(-1);
const suggestionsArr: ReferenceItem[] = [];
const predicate = suggestionSource.predicate.toLowerCase();
const getIndexOfUnclosedRefToTheRight = (pos: number) => { if (!suggestionSource.isDeep) {
const unclosedReferenceIndexMatches = [...inputValue.matchAll(REGEX_OPEN_SECRET_REFERENCE)].map( // At first level only environments and secrets
(match) => match.index (currentWorkspace?.environments || []).forEach(({ name, slug }) => {
); if (name.toLowerCase().startsWith(predicate))
suggestionsArr.push({
// find the next unclosed reference index to the right of the current cursor position label: name,
// this is so that we know the limitation for slicing references slug,
let indexIter = Infinity; type: ReferenceType.ENVIRONMENT
unclosedReferenceIndexMatches.forEach((index) => { });
if (index !== undefined && index > pos && index < indexIter) { });
indexIter = index; } else {
// one deeper levels its based on an environment folders and secrets
(folders || []).forEach(({ name }) => {
if (name.toLowerCase().startsWith(predicate))
suggestionsArr.push({
label: name,
slug: name,
type: ReferenceType.FOLDER
});
});
} }
}); (secrets || []).forEach(({ key }) => {
if (key.toLowerCase().startsWith(predicate))
suggestionsArr.push({
label: key,
slug: key,
type: ReferenceType.SECRET
});
});
return suggestionsArr;
}, [secrets, folders, currentWorkspace?.environments, isPopupOpen, suggestionSource.value]);
return indexIter; const handleSuggestionSelect = (selectIndex?: number) => {
}; const selectedSuggestion =
suggestions[typeof selectIndex !== "undefined" ? selectIndex : highlightedIndex];
if (!selectedSuggestion) {
return;
}
const handleKeyUp = (e: React.KeyboardEvent<HTMLTextAreaElement>) => { const rightBracketIndex = getIndexOfUnclosedRefToTheRight(value, suggestionSource.left);
// open suggestions if current position is to the right of an unclosed secret reference const isEnclosed = rightBracketIndex !== -1;
const indexIter = getIndexOfUnclosedRefToTheLeft(currentCursorPosition); // <lhsValue>${}<rhsvalue>
if (indexIter === -1) { const lhsValue = value.slice(0, suggestionSource.left);
return; const rhsValue = value.slice(
} rightBracketIndex !== -1 ? rightBracketIndex + 1 : currentCursorPosition
);
setIsSuggestionsOpen(true); // mid will be computed value inside the interpolation
const mid = suggestionSource.isDeep
if (e.key !== "Enter") { ? `${suggestionSource.value.slice(0, -suggestionSource.predicate.length || undefined)}${selectedSuggestion.slug
// current reference is then going to be based on the text from the closest ${ to the right }`
// until the current cursor position : selectedSuggestion.slug;
const openReferenceValue = inputValue.slice(indexIter + 2, currentCursorPosition); // whether we should append . or closing bracket on selecting suggestion
setCurrentReference(openReferenceValue); const closingSymbol = getClosingSymbol(
} selectedSuggestion.type === ReferenceType.SECRET,
}; isEnclosed
const handleSuggestionSelect = (selectedIndex?: number) => {
const selectedSuggestion = listReference[selectedIndex ?? highlightedIndex];
if (!selectedSuggestion) {
return;
}
const leftIndexIter = getIndexOfUnclosedRefToTheLeft(currentCursorPosition);
const rightIndexLimit = getIndexOfUnclosedRefToTheRight(currentCursorPosition);
if (leftIndexIter === -1) {
return;
}
let newValue = "";
const currentOpenRef = inputValue.slice(leftIndexIter + 2, currentCursorPosition);
if (currentOpenRef.includes(".")) {
// append suggestion after last DOT (.)
const lastDotIndex = currentReference.lastIndexOf(".");
const existingPath = currentReference.slice(0, lastDotIndex);
const refEndAfterAppending = Math.min(
leftIndexIter +
3 +
existingPath.length +
selectedSuggestion.name.length +
Number(selectedSuggestion.type !== ReferenceType.SECRET),
rightIndexLimit - 1
); );
newValue = `${inputValue.slice(0, leftIndexIter + 2)}${existingPath}.${ const newValue = `${lhsValue}${mid}${closingSymbol}${rhsValue}`;
selectedSuggestion.name onChange?.(newValue);
}${selectedSuggestion.type !== ReferenceType.SECRET ? "." : "}"}${inputValue.slice( // this delay is for cursor adjustment
refEndAfterAppending // cannot do this without a delay because what happens in onChange gets propogated after the cursor change
)}`; // Thus the cursor goes last to avoid that we put a slight delay on cursor change to make it happen later
const openReferenceValue = newValue.slice(leftIndexIter + 2, refEndAfterAppending); const delay = setTimeout(() => {
setCurrentReference(openReferenceValue); clearTimeout(delay);
if (inputRef.current)
inputRef.current.selectionEnd =
lhsValue.length +
mid.length +
closingSymbol.length +
(isEnclosed && selectedSuggestion.type === ReferenceType.SECRET ? 1 : 0); // if secret is selected the cursor should move after the closing bracket -> }
}, 10);
setHighlightedIndex(-1); // reset highlight
};
// add 1 in order to prevent referenceOpen from being triggered by handleKeyUp const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
setCurrentCursorPosition(refEndAfterAppending + 1); // key operation should trigger only when popup is open
} else { if (isPopupOpen) {
// append selectedSuggestion at position after unclosed ${ if (e.key === "ArrowDown" || (e.key === "Tab" && !e.shiftKey)) {
const refEndAfterAppending = Math.min( setHighlightedIndex((prevIndex) => {
selectedSuggestion.name.length + const pos = mod(prevIndex + 1, suggestions.length);
leftIndexIter + popoverContentRef.current?.children?.[pos]?.scrollIntoView({
2 + block: "nearest",
Number(selectedSuggestion.type !== ReferenceType.SECRET), behavior: "smooth"
rightIndexLimit - 1 });
); return pos;
});
} else if (e.key === "ArrowUp" || (e.key === "Tab" && e.shiftKey)) {
setHighlightedIndex((prevIndex) => {
const pos = mod(prevIndex - 1, suggestions.length);
popoverContentRef.current?.children?.[pos]?.scrollIntoView({
block: "nearest",
behavior: "smooth"
});
return pos;
});
} else if (e.key === "Enter" && highlightedIndex >= 0) {
e.preventDefault();
handleSuggestionSelect();
}
if (["ArrowDown", "ArrowUp", "Tab"].includes(e.key)) {
e.preventDefault();
}
}
};
newValue = `${inputValue.slice(0, leftIndexIter + 2)}${selectedSuggestion.name}${ const handlePopUpOpen = () => {
selectedSuggestion.type !== ReferenceType.SECRET ? "." : "}" setHighlightedIndex(-1);
}${inputValue.slice(refEndAfterAppending)}`; };
const openReferenceValue = newValue.slice(leftIndexIter + 2, refEndAfterAppending); // to handle multiple ref for single component
setCurrentReference(openReferenceValue); const handleRef = useCallback((el: HTMLTextAreaElement) => {
setCurrentCursorPosition(refEndAfterAppending); // @ts-expect-error this is for multiple ref single component
} inputRef.current = el;
if (ref) {
if (typeof ref === "function") {
ref(el);
} else {
// eslint-disable-next-line
ref.current = el;
}
}
}, []);
onChange?.({ target: { value: newValue } } as any); return (
setInputValue(newValue); <Popover.Root open={isPopupOpen} onOpenChange={handlePopUpOpen}>
setHighlightedIndex(-1); <Popover.Trigger asChild>
setIsSuggestionsOpen(false); <SecretInput
}; {...props}
ref={handleRef}
onKeyDown={handleKeyDown}
value={value}
onFocus={() => setIsFocused.on()}
onBlur={(evt) => {
// should not on blur when its mouse down selecting a item from suggestion
if (!(evt.relatedTarget?.getAttribute("aria-label") === "suggestion-item"))
setIsFocused.off();
}}
onChange={(e) => onChange?.(e.target.value)}
containerClassName={containerClassName}
/>
</Popover.Trigger>
<Popover.Content
align="start"
onOpenAutoFocus={(e) => e.preventDefault()}
className="relative top-2 z-[100] max-h-64 overflow-auto rounded-md border border-mineshaft-600 bg-mineshaft-900 font-inter text-bunker-100 shadow-md"
style={{
width: "var(--radix-popover-trigger-width)"
}}
>
<div
className="max-w-60 h-full w-full flex-col items-center justify-center rounded-md text-white"
ref={popoverContentRef}
>
{suggestions.map((item, i) => {
let entryIcon;
if (item.type === ReferenceType.SECRET) {
entryIcon = faKey;
} else if (item.type === ReferenceType.ENVIRONMENT) {
entryIcon = faCircle;
} else {
entryIcon = faFolder;
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => { return (
const mod = (n: number, m: number) => ((n % m) + m) % m;
if (e.key === "ArrowDown") {
setHighlightedIndex((prevIndex) => mod(prevIndex + 1, listReference.length));
} else if (e.key === "ArrowUp") {
setHighlightedIndex((prevIndex) => mod(prevIndex - 1, listReference.length));
} else if (e.key === "Enter" && highlightedIndex >= 0) {
handleSuggestionSelect();
}
if (["ArrowDown", "ArrowUp", "Enter"].includes(e.key) && isPopupOpen) {
e.preventDefault();
}
};
const setIsOpen = (isOpen: boolean) => {
setHighlightedIndex(-1);
if (isSuggestionsOpen) {
setIsSuggestionsOpen(isOpen);
}
};
const handleSecretChange = (e: any) => {
// propagate event to react-hook-form onChange
if (onChange) {
onChange(e);
}
setCurrentCursorPosition(inputRef.current?.selectionStart || 0);
setInputValue(e.target.value);
};
return (
<Popover.Root open={isPopupOpen} onOpenChange={setIsOpen}>
<Popover.Trigger asChild>
<SecretInput
{...props}
ref={inputRef}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
value={inputValue}
onChange={handleSecretChange}
containerClassName={containerClassName}
/>
</Popover.Trigger>
<Popover.Content
align="start"
onOpenAutoFocus={(e) => e.preventDefault()}
className={twMerge(
"relative top-2 z-[100] overflow-hidden rounded-md border border-mineshaft-600 bg-mineshaft-900 font-inter text-bunker-100 shadow-md"
)}
style={{
width: "var(--radix-popover-trigger-width)",
maxHeight: "var(--radix-select-content-available-height)"
}}
>
<div className="max-w-60 h-full w-full flex-col items-center justify-center rounded-md text-white">
{listReference.map((item, i) => {
let entryIcon;
if (item.type === ReferenceType.SECRET) {
entryIcon = faKey;
} else if (item.type === ReferenceType.ENVIRONMENT) {
entryIcon = faCircle;
} else {
entryIcon = faFolder;
}
return (
<div
tabIndex={0}
role="button"
onMouseDown={(e) => {
e.preventDefault();
setHighlightedIndex(i);
handleSuggestionSelect(i);
}}
style={{ pointerEvents: "auto" }}
className="flex items-center justify-between border-mineshaft-600 text-left"
key={`secret-reference-secret-${i + 1}`}
>
<div <div
className={`${ tabIndex={0}
highlightedIndex === i ? "bg-gray-600" : "" role="button"
} text-md relative mb-0.5 flex w-full cursor-pointer select-none items-center justify-between rounded-md px-2 py-2 outline-none transition-all hover:bg-mineshaft-500 data-[highlighted]:bg-mineshaft-500`} onKeyDown={(e) => {
if (e.key === "Enter") handleSuggestionSelect(i);
}}
aria-label="suggestion-item"
onClick={(e) => {
inputRef.current?.focus();
e.preventDefault();
e.stopPropagation();
handleSuggestionSelect(i);
}}
onMouseEnter={() => setHighlightedIndex(i)}
style={{ pointerEvents: "auto" }}
className="flex items-center justify-between border-mineshaft-600 text-left"
key={`secret-reference-secret-${i + 1}`}
> >
<div className="flex w-full gap-2"> <div
<div className="flex items-center text-yellow-700"> className={`${highlightedIndex === i ? "bg-gray-600" : ""
<FontAwesomeIcon } text-md relative mb-0.5 flex w-full cursor-pointer select-none items-center justify-between rounded-md px-2 py-2 outline-none transition-all hover:bg-mineshaft-500 data-[highlighted]:bg-mineshaft-500`}
icon={entryIcon} >
size={item.type === ReferenceType.ENVIRONMENT ? "xs" : "1x"} <div className="flex w-full gap-2">
/> <div className="flex items-center text-yellow-700">
<FontAwesomeIcon
icon={entryIcon}
size={item.type === ReferenceType.ENVIRONMENT ? "xs" : "1x"}
/>
</div>
<div className="text-md w-10/12 truncate text-left">{item.label}</div>
</div> </div>
<div className="text-md w-10/12 truncate text-left">{item.name}</div>
</div> </div>
</div> </div>
</div> );
); })}
})} </div>
</div> </Popover.Content>
</Popover.Content> </Popover.Root>
</Popover.Root> );
); }
}; );
InfisicalSecretInput.displayName = "InfisicalSecretInput"; InfisicalSecretInput.displayName = "InfisicalSecretInput";
@@ -41,7 +41,7 @@ const syntaxHighlight = (content?: string | null, isVisible?: boolean, isImport?
// akhilmhdh: Dont remove this br. I am still clueless how this works but weirdly enough // akhilmhdh: Dont remove this br. I am still clueless how this works but weirdly enough
// when break is added a line break works properly // when break is added a line break works properly
return formattedContent.concat(<br />); return formattedContent.concat(<br key={`secret-value-${formattedContent.length + 1}`} />);
}; };
type Props = TextareaHTMLAttributes<HTMLTextAreaElement> & { type Props = TextareaHTMLAttributes<HTMLTextAreaElement> & {
@@ -90,7 +90,10 @@ export const SecretInput = forwardRef<HTMLTextAreaElement, Props>(
aria-label="secret value" aria-label="secret value"
ref={ref} ref={ref}
className={`absolute inset-0 block h-full resize-none overflow-hidden bg-transparent text-transparent no-scrollbar focus:border-0 ${commonClassName}`} className={`absolute inset-0 block h-full resize-none overflow-hidden bg-transparent text-transparent no-scrollbar focus:border-0 ${commonClassName}`}
onFocus={() => setIsSecretFocused.on()} onFocus={(evt) => {
onFocus?.(evt);
setIsSecretFocused.on();
}}
disabled={isDisabled} disabled={isDisabled}
spellCheck={false} spellCheck={false}
onBlur={(evt) => { onBlur={(evt) => {
+1
View File
@@ -10,6 +10,7 @@ export * from "./Drawer";
export * from "./Dropdown"; export * from "./Dropdown";
export * from "./EmailServiceSetupModal"; export * from "./EmailServiceSetupModal";
export * from "./EmptyState"; export * from "./EmptyState";
export * from "./FontAwesomeSymbol";
export * from "./FormControl"; export * from "./FormControl";
export * from "./HoverCardv2"; export * from "./HoverCardv2";
export * from "./IconButton"; export * from "./IconButton";
+8
View File
@@ -45,6 +45,14 @@ html {
width: 1%; width: 1%;
white-space: nowrap; white-space: nowrap;
} }
.w-inherit {
width: inherit;
}
.h-inherit {
height: inherit;
}
} }
@layer components { @layer components {
@@ -8,6 +8,7 @@ import {
DropdownMenuItem, DropdownMenuItem,
DropdownMenuLabel, DropdownMenuLabel,
DropdownMenuTrigger, DropdownMenuTrigger,
FontAwesomeSymbol,
FormControl, FormControl,
IconButton, IconButton,
Input, Input,
@@ -19,6 +20,7 @@ import {
TextArea, TextArea,
Tooltip Tooltip
} from "@app/components/v2"; } from "@app/components/v2";
import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
import { import {
ProjectPermissionActions, ProjectPermissionActions,
ProjectPermissionSub, ProjectPermissionSub,
@@ -29,20 +31,6 @@ import { useToggle } from "@app/hooks";
import { DecryptedSecret } from "@app/hooks/api/secrets/types"; import { DecryptedSecret } from "@app/hooks/api/secrets/types";
import { WsTag } from "@app/hooks/api/types"; import { WsTag } from "@app/hooks/api/types";
import { subject } from "@casl/ability"; import { subject } from "@casl/ability";
import { faCheckCircle } from "@fortawesome/free-regular-svg-icons";
import {
faCheck,
faClock,
faClose,
faCodeBranch,
faComment,
faCopy,
faEllipsis,
faKey,
faTag,
faTags
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { AnimatePresence, motion } from "framer-motion"; import { AnimatePresence, motion } from "framer-motion";
import { memo, useEffect } from "react"; import { memo, useEffect } from "react";
@@ -50,7 +38,12 @@ import { Controller, useFieldArray, useForm } from "react-hook-form";
import { twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge";
import { CreateReminderForm } from "./CreateReminderForm"; import { CreateReminderForm } from "./CreateReminderForm";
import { formSchema, SecretActionType, TFormSchema } from "./SecretListView.utils"; import {
FontAwesomeSpriteName,
formSchema,
SecretActionType,
TFormSchema
} from "./SecretListView.utils";
type Props = { type Props = {
secret: DecryptedSecret; secret: DecryptedSecret;
@@ -206,7 +199,6 @@ export const SecretItem = memo(
} }
}} }}
/> />
<form onSubmit={handleSubmit(handleFormSubmit)}> <form onSubmit={handleSubmit(handleFormSubmit)}>
<div <div
className={twMerge( className={twMerge(
@@ -227,9 +219,12 @@ export const SecretItem = memo(
onCheckedChange={() => onToggleSecretSelect(secret.id)} onCheckedChange={() => onToggleSecretSelect(secret.id)}
className={twMerge("ml-3 hidden group-hover:flex", isSelected && "flex")} className={twMerge("ml-3 hidden group-hover:flex", isSelected && "flex")}
/> />
<FontAwesomeIcon <FontAwesomeSymbol
icon={faKey} className={twMerge(
className={twMerge("ml-3 block group-hover:hidden", isSelected && "hidden")} "ml-3 block h-3.5 w-3.5 group-hover:hidden",
isSelected && "hidden"
)}
symbolName={FontAwesomeSpriteName.SecretKey}
/> />
</div> </div>
<div className="flex h-11 w-80 flex-shrink-0 items-center px-4 py-2"> <div className="flex h-11 w-80 flex-shrink-0 items-center px-4 py-2">
@@ -278,10 +273,12 @@ export const SecretItem = memo(
key="secret-value" key="secret-value"
control={control} control={control}
render={({ field }) => ( render={({ field }) => (
<SecretInput <InfisicalSecretInput
isReadOnly={isReadOnly} isReadOnly={isReadOnly}
key="secret-value" key="secret-value"
isVisible={isVisible} isVisible={isVisible}
environment={environment}
secretPath={secretPath}
{...field} {...field}
containerClassName="py-1.5 rounded-md transition-all group-hover:mr-2" containerClassName="py-1.5 rounded-md transition-all group-hover:mr-2"
/> />
@@ -297,7 +294,14 @@ export const SecretItem = memo(
className="w-0 overflow-hidden p-0 group-hover:mr-2 group-hover:w-5" className="w-0 overflow-hidden p-0 group-hover:mr-2 group-hover:w-5"
onClick={copyTokenToClipboard} onClick={copyTokenToClipboard}
> >
<FontAwesomeIcon icon={isSecValueCopied ? faCheck : faCopy} /> <FontAwesomeSymbol
className="h-3.5 w-3"
symbolName={
isSecValueCopied
? FontAwesomeSpriteName.Check
: FontAwesomeSpriteName.ClipboardCopy
}
/>
</IconButton> </IconButton>
</Tooltip> </Tooltip>
<DropdownMenu> <DropdownMenu>
@@ -318,7 +322,10 @@ export const SecretItem = memo(
isDisabled={!isAllowed} isDisabled={!isAllowed}
> >
<Tooltip content="Tags"> <Tooltip content="Tags">
<FontAwesomeIcon icon={faTags} /> <FontAwesomeSymbol
className="h-3.5 w-3.5"
symbolName={FontAwesomeSpriteName.Tags}
/>
</Tooltip> </Tooltip>
</IconButton> </IconButton>
</DropdownMenuTrigger> </DropdownMenuTrigger>
@@ -334,7 +341,14 @@ export const SecretItem = memo(
<DropdownMenuItem <DropdownMenuItem
onClick={() => handleTagSelect(tag)} onClick={() => handleTagSelect(tag)}
key={`${secret.id}-${tagId}`} key={`${secret.id}-${tagId}`}
icon={isTagSelected && <FontAwesomeIcon icon={faCheckCircle} />} icon={
isTagSelected && (
<FontAwesomeSymbol
symbolName={FontAwesomeSpriteName.CheckedCircle}
className="h-3 w-3"
/>
)
}
iconPos="right" iconPos="right"
> >
<div className="flex items-center"> <div className="flex items-center">
@@ -353,7 +367,12 @@ export const SecretItem = memo(
className="w-full" className="w-full"
colorSchema="primary" colorSchema="primary"
variant="outline_bg" variant="outline_bg"
leftIcon={<FontAwesomeIcon icon={faTag} />} leftIcon={
<FontAwesomeSymbol
symbolName={FontAwesomeSpriteName.Tags}
className="h-3 w-3"
/>
}
onClick={onCreateTag} onClick={onCreateTag}
> >
Create a tag Create a tag
@@ -379,7 +398,10 @@ export const SecretItem = memo(
isOverriden && "w-5 text-primary" isOverriden && "w-5 text-primary"
)} )}
> >
<FontAwesomeIcon icon={faCodeBranch} /> <FontAwesomeSymbol
symbolName={FontAwesomeSpriteName.Override}
className="h-3.5 w-3.5"
/>
</IconButton> </IconButton>
)} )}
</ProjectPermissionCan> </ProjectPermissionCan>
@@ -393,6 +415,7 @@ export const SecretItem = memo(
variant="plain" variant="plain"
size="md" size="md"
ariaLabel="add-reminder" ariaLabel="add-reminder"
onClick={() => setCreateReminderFormOpen.on()}
> >
<Tooltip <Tooltip
content={ content={
@@ -404,9 +427,9 @@ export const SecretItem = memo(
: "Reminder" : "Reminder"
} }
> >
<FontAwesomeIcon <FontAwesomeSymbol
onClick={() => setCreateReminderFormOpen.on()} className="h-3.5 w-3.5"
icon={faClock} symbolName={FontAwesomeSpriteName.Clock}
/> />
</Tooltip> </Tooltip>
</IconButton> </IconButton>
@@ -430,7 +453,10 @@ export const SecretItem = memo(
isDisabled={!isAllowed} isDisabled={!isAllowed}
> >
<Tooltip content="Comment"> <Tooltip content="Comment">
<FontAwesomeIcon icon={faComment} /> <FontAwesomeSymbol
className="h-3.5 w-3.5"
symbolName={FontAwesomeSpriteName.Comment}
/>
</Tooltip> </Tooltip>
</IconButton> </IconButton>
</PopoverTrigger> </PopoverTrigger>
@@ -466,10 +492,13 @@ export const SecretItem = memo(
ariaLabel="more" ariaLabel="more"
variant="plain" variant="plain"
size="md" size="md"
className="p-0 opacity-0 group-hover:opacity-100" className="p-0 opacity-0 group-hover:opacity-100 h-5 w-4"
onClick={() => onDetailViewSecret(secret)} onClick={() => onDetailViewSecret(secret)}
> >
<FontAwesomeIcon icon={faEllipsis} size="lg" /> <FontAwesomeSymbol
symbolName={FontAwesomeSpriteName.More}
className="h-5 w-4"
/>
</IconButton> </IconButton>
</Tooltip> </Tooltip>
<ProjectPermissionCan <ProjectPermissionCan
@@ -488,7 +517,10 @@ export const SecretItem = memo(
onClick={() => onDeleteSecret(secret)} onClick={() => onDeleteSecret(secret)}
isDisabled={!isAllowed} isDisabled={!isAllowed}
> >
<FontAwesomeIcon icon={faClose} size="lg" /> <FontAwesomeSymbol
symbolName={FontAwesomeSpriteName.Close}
className="h-5 w-4"
/>
</IconButton> </IconButton>
)} )}
</ProjectPermissionCan> </ProjectPermissionCan>
@@ -516,10 +548,12 @@ export const SecretItem = memo(
{isSubmitting ? ( {isSubmitting ? (
<Spinner className="m-0 h-4 w-4 p-0" /> <Spinner className="m-0 h-4 w-4 p-0" />
) : ( ) : (
<FontAwesomeIcon <FontAwesomeSymbol
icon={faCheck} symbolName={FontAwesomeSpriteName.Check}
size="lg" className={twMerge(
className={twMerge("text-primary", errors.key && "text-mineshaft-300")} "h-4 w-4 text-primary",
errors.key && "text-mineshaft-300"
)}
/> />
)} )}
</IconButton> </IconButton>
@@ -536,7 +570,10 @@ export const SecretItem = memo(
onClick={() => reset()} onClick={() => reset()}
isDisabled={isSubmitting} isDisabled={isSubmitting}
> >
<FontAwesomeIcon icon={faClose} size="lg" /> <FontAwesomeSymbol
symbolName={FontAwesomeSpriteName.Close}
className="h-4 w-4 text-primary"
/>
</IconButton> </IconButton>
</Tooltip> </Tooltip>
</motion.div> </motion.div>
@@ -1,4 +1,5 @@
import { useCallback } from "react"; import { useCallback } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import { twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge";
@@ -17,6 +18,7 @@ import { useSelectedSecretActions, useSelectedSecrets } from "../../SecretMainPa
import { Filter, GroupBy, SortDir } from "../../SecretMainPage.types"; import { Filter, GroupBy, SortDir } from "../../SecretMainPage.types";
import { SecretDetailSidebar } from "./SecretDetaiSidebar"; import { SecretDetailSidebar } from "./SecretDetaiSidebar";
import { SecretItem } from "./SecretItem"; import { SecretItem } from "./SecretItem";
import { FontAwesomeSpriteSymbols } from "./SecretListView.utils";
type Props = { type Props = {
secrets?: DecryptedSecret[]; secrets?: DecryptedSecret[];
@@ -89,7 +91,6 @@ export const SecretListView = ({
isVisible, isVisible,
isProtectedBranch = false isProtectedBranch = false
}: Props) => { }: Props) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { popUp, handlePopUpToggle, handlePopUpOpen, handlePopUpClose } = usePopUp([ const { popUp, handlePopUpToggle, handlePopUpOpen, handlePopUpClose } = usePopUp([
"deleteSecret", "deleteSecret",
@@ -341,6 +342,13 @@ export const SecretListView = ({
> >
{namespace} {namespace}
</div> </div>
{FontAwesomeSpriteSymbols.map(({ icon, symbol }) => (
<FontAwesomeIcon
icon={icon}
symbol={symbol}
key={`font-awesome-svg-spritie-${symbol}`}
/>
))}
{filteredSecrets.map((secret) => ( {filteredSecrets.map((secret) => (
<SecretItem <SecretItem
environment={environment} environment={environment}
@@ -1,4 +1,16 @@
/* eslint-disable no-nested-ternary */ /* eslint-disable no-nested-ternary */
import { faCheckCircle } from "@fortawesome/free-regular-svg-icons";
import {
faCheck,
faClock,
faClose,
faCodeBranch,
faComment,
faCopy,
faEllipsis,
faKey,
faTags
} from "@fortawesome/free-solid-svg-icons";
import { z } from "zod"; import { z } from "zod";
export enum SecretActionType { export enum SecretActionType {
@@ -41,3 +53,31 @@ export const formSchema = z.object({
}); });
export type TFormSchema = z.infer<typeof formSchema>; export type TFormSchema = z.infer<typeof formSchema>;
export enum FontAwesomeSpriteName {
SecretKey = "secret-key",
Check = "check",
ClipboardCopy = "clipboard-copy",
Tags = "secret-tags",
Clock = "reminder-clock",
Comment = "comment",
More = "more",
Override = "secret-override",
Close = "close",
CheckedCircle = "check-circle"
}
// this is an optimization technique
// https://docs.fontawesome.com/web/add-icons/svg-symbols
export const FontAwesomeSpriteSymbols = [
{ icon: faKey, symbol: FontAwesomeSpriteName.SecretKey },
{ icon: faCheck, symbol: FontAwesomeSpriteName.Check },
{ icon: faCopy, symbol: FontAwesomeSpriteName.ClipboardCopy },
{ icon: faTags, symbol: FontAwesomeSpriteName.Tags },
{ icon: faClock, symbol: FontAwesomeSpriteName.Clock },
{ icon: faComment, symbol: FontAwesomeSpriteName.Comment },
{ icon: faEllipsis, symbol: FontAwesomeSpriteName.More },
{ icon: faCodeBranch, symbol: FontAwesomeSpriteName.Override },
{ icon: faClose, symbol: FontAwesomeSpriteName.Close },
{ icon: faCheckCircle, symbol: FontAwesomeSpriteName.CheckedCircle }
];