adjustment: migrated to InfisicalSecretInput component

This commit is contained in:
Sheen Capadngan
2024-04-22 22:22:48 +08:00
parent f9957e111c
commit 0899fdb7d5
7 changed files with 555 additions and 17 deletions

View File

@@ -0,0 +1,324 @@
/* eslint-disable react/no-danger */
import React, { forwardRef, TextareaHTMLAttributes, useRef, useState } from "react";
import { twMerge } from "tailwind-merge";
import {
REGEX_SECRET_REFERENCE_FIND,
REGEX_SECRET_REFERENCE_INVALID
} from "@app/helpers/secret-reference";
import { useToggle } from "@app/hooks";
import SecretReferenceSelect from "./SecretReferenceSelect";
const replaceContentWithDot = (str: string) => {
let finalStr = "";
for (let i = 0; i < str.length; i += 1) {
const char = str.at(i);
finalStr += char === "\n" ? "\n" : "*";
}
return finalStr;
};
const syntaxHighlight = (content?: string | null, isVisible?: boolean) => {
if (content === "") return "EMPTY";
if (!content) return "EMPTY";
if (!isVisible) return replaceContentWithDot(content);
let skipNext = false;
const formattedContent = content.split(REGEX_SECRET_REFERENCE_FIND).flatMap((el, i) => {
const isInterpolationSyntax = el.startsWith("${") && el.endsWith("}");
if (isInterpolationSyntax) {
skipNext = true;
return (
<span className="ph-no-capture text-yellow" key={`secret-value-${i + 1}`}>
&#36;&#123;
<span
className={twMerge(
"ph-no-capture text-yellow-200/80",
REGEX_SECRET_REFERENCE_INVALID.test(el.slice(2, -1)) &&
"underline decoration-red decoration-wavy"
)}
>
{el.slice(2, -1)}
</span>
&#125;
</span>
);
}
if (skipNext) {
skipNext = false;
return [];
}
return el;
});
// akhilmhdh: Dont remove this br. I am still clueless how this works but weirdly enough
// when break is added a line break works properly
return formattedContent.concat(<br />);
};
type Props = TextareaHTMLAttributes<HTMLTextAreaElement> & {
value?: string | null;
isVisible?: boolean;
isReadOnly?: boolean;
isDisabled?: boolean;
containerClassName?: string;
environment?: string;
secretPath?: string;
};
const commonClassName = "font-mono text-sm caret-white border-none outline-none w-full break-all";
export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
(
{
value: propValue,
isVisible,
containerClassName,
onBlur,
isDisabled,
isReadOnly,
onFocus,
secretPath: propSecretPath,
environment: propEnvironment,
onChange,
...props
},
ref
) => {
const childRef = useRef<HTMLTextAreaElement>(null);
const [isSecretFocused, setIsSecretFocused] = useToggle();
const [value, setValue] = useState<string>(propValue || "");
const [showReferencePopup, setShowReferencePopup] = useState<boolean>(false);
const [referenceKey, setReferenceKey] = useState<string>();
const [lastCaretPos, setLastCaretPos] = useState<number>(0);
function isCaretInsideReference(str: string, start: number) {
const matches = [...str.matchAll(REGEX_SECRET_REFERENCE_FIND)];
for (let i = 0; i < matches.length; i += 1) {
const match = matches[i];
if (
typeof match?.index !== "undefined" &&
match.index <= start &&
start < match.index + match[0].length
) {
return match;
}
}
return null;
}
function setCaretPos(caretPos: number) {
if (childRef?.current) {
childRef.current.focus();
setTimeout(() => {
if (!childRef?.current) return;
childRef.current.selectionStart = caretPos;
childRef.current.selectionEnd = caretPos;
}, 200);
}
}
function referencePopup(text: string, pos: number) {
const match = isCaretInsideReference(text, pos);
if (match && typeof match.index !== "undefined") {
setLastCaretPos(pos);
setReferenceKey(match?.[2]);
}
setShowReferencePopup(!!match);
}
function handleReferencePopup(element: HTMLTextAreaElement) {
const { selectionStart, selectionEnd, value: text } = element;
if (selectionStart !== selectionEnd || selectionStart === 0) {
return;
}
referencePopup(text, selectionStart);
}
function handleKeyUp(event: React.KeyboardEvent<HTMLTextAreaElement>) {
if (event.key === "Escape") {
setShowReferencePopup(false);
return;
}
if (event.key === "{") {
// auto close the bracket
const currCaretPos = event.currentTarget.selectionEnd;
const isPrevDollar = value[currCaretPos - 2] === "$";
if (!isPrevDollar) return;
const newValue = `${value.slice(0, currCaretPos)}}${value.slice(currCaretPos)}`;
setValue(newValue);
// TODO: there should be a better way to do
onChange?.({ target: { value: newValue } } as any);
setCaretPos(currCaretPos);
if (event.currentTarget) {
setTimeout(() => {
referencePopup(newValue, currCaretPos);
}, 200);
return;
}
}
if (!(event.key.startsWith("Arrow") || event.key === "Backspace" || event.key === "Delete")) {
handleReferencePopup(event.currentTarget);
}
}
function handleKeyDown(event: React.KeyboardEvent<HTMLTextAreaElement>) {
if (
!(
event.key.startsWith("Arrow") ||
["Backspace", "Delete", "."].includes(event.key) ||
(event.metaKey && event.key.toLowerCase() === "a")
)
) {
const match = isCaretInsideReference(value, event.currentTarget.selectionEnd);
if (match) event.preventDefault();
}
}
function handleMouseClick(event: React.MouseEvent<HTMLTextAreaElement, MouseEvent>) {
handleReferencePopup(event.currentTarget);
}
async function handleReferenceSelect({
name,
type,
slug
}: {
name: string;
type: "folder" | "secret" | "environment";
slug?: string;
}) {
setShowReferencePopup(false);
// forward ref for parent component
if (typeof ref === "function") {
ref(childRef.current);
} else if (ref && "current" in ref) {
const refCopy = ref;
refCopy.current = childRef.current;
}
let newValue = value || "";
const match = isCaretInsideReference(newValue, lastCaretPos);
const referenceStartIndex = match?.index || 0;
const referenceEndIndex = referenceStartIndex + (match?.[0]?.length || 0);
const [start, oldReference, end] = [
value.slice(0, referenceStartIndex),
value.slice(referenceStartIndex, referenceEndIndex),
value.slice(referenceEndIndex)
];
let oldReferenceStr = oldReference.slice(2, -1);
let currentPath = type === "environment" ? slug! : name;
currentPath = currentPath.replace(/\./g, "\\.");
let replaceReference = "";
let offset = 3;
switch (type) {
case "folder":
replaceReference = `${oldReferenceStr}${currentPath}.`;
offset -= 1;
break;
case "secret": {
if (oldReferenceStr.indexOf(".") === -1) oldReferenceStr = "";
replaceReference = `${oldReferenceStr}${currentPath}`;
break;
}
case "environment":
replaceReference = `${currentPath}.`;
offset -= 1;
break;
default:
}
replaceReference = replaceReference.replace(/[//]/g, "");
newValue = `${start}$\{${replaceReference}}${end}`;
setValue(newValue);
// TODO: there should be a better way to do
onChange?.({ target: { value: newValue } } as any);
setShowReferencePopup(type !== "secret");
setTimeout(() => {
setIsSecretFocused.on();
if (type !== "secret") setReferenceKey(replaceReference);
const caretPos = start.length + replaceReference.length + offset;
setCaretPos(caretPos);
}, 100);
}
function handleChange(event: React.ChangeEvent<HTMLTextAreaElement>) {
setValue(event.target.value);
if (typeof onChange === "function") onChange(event);
}
function handleReferenceOpenChange(currOpen: boolean) {
if (!currOpen) setShowReferencePopup(false);
}
return (
<div
className={twMerge(
"flex w-full flex-col overflow-auto rounded-md no-scrollbar",
containerClassName
)}
>
<div style={{ maxHeight: `${21 * 7}px` }}>
<div className="relative overflow-hidden">
<pre aria-hidden className="m-0 ">
<code className={`inline-block w-full ${commonClassName}`}>
<span style={{ whiteSpace: "break-spaces" }}>
{syntaxHighlight(value, isVisible || isSecretFocused)}
</span>
</code>
</pre>
<textarea
style={{ whiteSpace: "break-spaces" }}
aria-label="secret value"
ref={childRef}
className={twMerge(
"absolute inset-0 block h-full resize-none overflow-hidden bg-transparent text-transparent no-scrollbar focus:border-0",
commonClassName
)}
onFocus={() => setIsSecretFocused.on()}
onKeyUp={handleKeyUp}
onKeyDown={handleKeyDown}
onClick={handleMouseClick}
onChange={handleChange}
disabled={isDisabled}
spellCheck={false}
onBlur={(evt) => {
onBlur?.(evt);
if (!showReferencePopup) setIsSecretFocused.off();
}}
{...props}
value={value}
readOnly={isReadOnly}
/>
</div>
</div>
<SecretReferenceSelect
reference={referenceKey}
secretPath={propSecretPath}
environment={propEnvironment}
open={showReferencePopup}
handleOpenChange={(isOpen) => handleReferenceOpenChange(isOpen)}
onSelect={(refValue) => handleReferenceSelect(refValue)}
onEscapeKeyDown={() => {
setTimeout(() => {
setCaretPos(lastCaretPos);
}, 200);
}}
/>
</div>
);
}
);
InfisicalSecretInput.displayName = "SecretInput";

View File

@@ -0,0 +1,211 @@
import React, { useEffect, useState } from "react";
import {
faCaretDown,
faCaretUp,
faChevronRight,
faFolder,
faKey,
faRecycle
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as SelectPrimitive from "@radix-ui/react-select";
import { twMerge } from "tailwind-merge";
import { useWorkspace } from "@app/context";
import { useGetUserWsKey } from "@app/hooks/api";
import { useGetFoldersByEnv } from "@app/hooks/api/secretFolders/queries";
import { useGetProjectSecrets } from "@app/hooks/api/secrets/queries";
type ReferenceType = "environment" | "folder" | "secret";
type Props = {
open: boolean;
reference?: string;
secretPath?: string;
environment?: string;
handleOpenChange: (params: boolean) => void;
onEscapeKeyDown: () => void;
onSelect: (params: { type: ReferenceType; name: string; slug?: string }) => void;
};
type ReferenceItem = {
name: string;
type: "folder" | "secret";
slug?: string;
};
export default function SecretReferenceSelect({
open,
secretPath: propSecretPath,
environment: propEnvironment,
handleOpenChange,
reference,
onSelect,
onEscapeKeyDown
}: Props) {
const { currentWorkspace } = useWorkspace();
const [listReference, setListReference] = useState<ReferenceItem[]>([]);
const [secretPath, setSecretPath] = useState<string>(propSecretPath || "/");
const [environment, setEnvironment] = useState<string | undefined>(propEnvironment);
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
});
useEffect(() => {
let currentEnvironment = propEnvironment;
let currentSecretPath = propSecretPath || "/";
if (!reference) {
setSecretPath(currentSecretPath);
setEnvironment(currentEnvironment!);
return;
}
const isNested = reference.includes(".");
if (isNested) {
const [envSlug, ...folderPaths] = reference.split(".");
const isValidEnvSlug = currentWorkspace?.environments.find((e) => e.slug === envSlug);
currentEnvironment = isValidEnvSlug ? envSlug : undefined;
currentSecretPath = `/${folderPaths?.join("/")}` || "/";
}
setSecretPath(currentSecretPath);
setEnvironment(currentEnvironment);
}, [reference]);
useEffect(() => {
const currentListReference: ReferenceItem[] = [];
const isNested = reference?.includes(".");
if (!environment) {
setListReference(currentListReference);
return;
}
if (isNested) {
folders?.forEach((folder) => {
currentListReference.unshift({ name: folder, type: "folder" });
});
}
secrets?.forEach((secret) => {
currentListReference.unshift({ name: secret.key, type: "secret" });
});
setListReference(currentListReference);
}, [secrets, environment, reference]);
return (
<SelectPrimitive.Root
open={open}
onOpenChange={handleOpenChange}
onValueChange={(str) => onSelect(JSON.parse(str))}
>
<SelectPrimitive.Trigger>
<SelectPrimitive.Value>
<div />
</SelectPrimitive.Value>
</SelectPrimitive.Trigger>
<SelectPrimitive.Portal>
<SelectPrimitive.Content
className={twMerge(
"relative top-3 z-[100] ml-4 overflow-hidden rounded-md border border-mineshaft-600 bg-mineshaft-900 font-inter text-bunker-100 shadow-md"
)}
position="popper"
side="left"
onEscapeKeyDown={onEscapeKeyDown}
style={{
width: "300px",
maxHeight: "var(--radix-select-content-available-height)"
}}
>
<SelectPrimitive.ScrollUpButton>
<div className="flex items-center justify-center">
<FontAwesomeIcon icon={faCaretUp} size="sm" />
</div>
</SelectPrimitive.ScrollUpButton>
<SelectPrimitive.Viewport className="max-w-60 h-full w-full flex-col items-center justify-center rounded-md p-1 py-4 text-white">
<SelectPrimitive.Group>
{listReference.map((e, i) => {
return (
<SelectPrimitive.Item
className="flex items-center justify-between border-b border-mineshaft-600 px-2 text-left last:border-b-0"
key={`secret-reference-secret-${i + 1}`}
value={JSON.stringify(e)}
asChild
>
<SelectPrimitive.ItemText asChild>
<div className="text-md relative mb-0.5 flex w-full cursor-pointer select-none items-center justify-between rounded-md px-2 outline-none transition-all hover:bg-mineshaft-500 data-[highlighted]:bg-mineshaft-500">
<div className="flex gap-2">
<div className="flex items-center text-yellow-700">
<FontAwesomeIcon icon={e.type === "secret" ? faKey : faFolder} />
</div>
<div className="text-md w-48 truncate text-left">{e.name}</div>
</div>
{e.type === "folder" && (
<div className="flex items-center text-bunker-200">
<FontAwesomeIcon icon={faChevronRight} />
</div>
)}
</div>
</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
);
})}
{listReference.length !== 0 && (
<SelectPrimitive.Separator className="m-1 h-[1px] mb-2 bg-mineshaft-400" />
)}
</SelectPrimitive.Group>
<SelectPrimitive.Group>
<SelectPrimitive.Label className="flex w-full justify-center gap-2 pt-1 text-sm text-bunker-300">
All Secrets
</SelectPrimitive.Label>
{currentWorkspace?.environments.map((env, i) => (
<SelectPrimitive.Item
className="flex items-center justify-between border-b border-mineshaft-600 px-2 text-left last:border-b-0"
key={`secret-reference-env-${i + 1}`}
value={JSON.stringify({ ...env, type: "environment" })}
asChild
>
<SelectPrimitive.ItemText asChild>
<div className="text-md relative mb-0.5 flex w-full cursor-pointer select-none items-center justify-between rounded-md px-2 outline-none transition-all hover:bg-mineshaft-500 data-[highlighted]:bg-mineshaft-500">
<div className="flex gap-2">
<div className="flex items-center text-yellow-700">
<FontAwesomeIcon icon={faRecycle} />
</div>
<div className="text-md w-48 truncate text-left">{env.name}</div>
</div>
<div className="flex items-center text-bunker-200">
<FontAwesomeIcon icon={faChevronRight} />
</div>
</div>
</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))}
</SelectPrimitive.Group>
</SelectPrimitive.Viewport>
<SelectPrimitive.ScrollDownButton>
<div className="flex items-center justify-center">
<FontAwesomeIcon icon={faCaretDown} size="sm" />
</div>
</SelectPrimitive.ScrollDownButton>
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
</SelectPrimitive.Root>
);
}

View File

@@ -3,7 +3,8 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
import { Button, FormControl, Input, Modal, ModalContent, SecretInput } from "@app/components/v2";
import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput/InfisicalSecretInput";
import { useCreateSecretV3 } from "@app/hooks/api";
import { UserWsKeyPair } from "@app/hooks/api/types";
@@ -103,7 +104,7 @@ export const CreateSecretForm = ({
isError={Boolean(errors?.value)}
errorText={errors?.value?.message}
>
<SecretInput
<InfisicalSecretInput
{...field}
environment={environment}
secretPath={secretPath}

View File

@@ -172,12 +172,7 @@ export const SecretImportItem = ({
{key}
</td>
<td className="h-10" style={{ padding: "0.25rem 1rem" }}>
<SecretInput
value={value}
isReadOnly
environment={overriden?.env}
secretPath={overriden?.secretPath}
/>
<SecretInput value={value} isReadOnly />
</td>
<td className="h-10" style={{ padding: "0.25rem 1rem" }}>
<EnvFolderIcon env={overriden?.env} secretPath={overriden?.secretPath} />

View File

@@ -27,12 +27,12 @@ import {
FormControl,
IconButton,
Input,
SecretInput,
Switch,
Tag,
TextArea,
Tooltip
} from "@app/components/v2";
import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput/InfisicalSecretInput";
import { ProjectPermissionActions, ProjectPermissionSub, useProjectPermission } from "@app/context";
import { useToggle } from "@app/hooks";
import { useGetSecretVersion } from "@app/hooks/api";
@@ -204,7 +204,7 @@ export const SecretDetailSidebar = ({
control={control}
render={({ field }) => (
<FormControl label="Value">
<SecretInput
<InfisicalSecretInput
isReadOnly={isReadOnly}
environment={environment}
secretPath={secretPath}
@@ -242,7 +242,7 @@ export const SecretDetailSidebar = ({
control={control}
render={({ field }) => (
<FormControl label="Value Override">
<SecretInput
<InfisicalSecretInput
isReadOnly={isReadOnly}
environment={environment}
secretPath={secretPath}

View File

@@ -14,7 +14,6 @@ import {
Popover,
PopoverContent,
PopoverTrigger,
SecretInput,
Spinner,
TextArea,
Tooltip
@@ -49,6 +48,7 @@ import { memo, useEffect } from "react";
import { Controller, useFieldArray, useForm } from "react-hook-form";
import { twMerge } from "tailwind-merge";
import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput/InfisicalSecretInput";
import { CreateReminderForm } from "./CreateReminderForm";
import { formSchema, SecretActionType, TFormSchema } from "./SecretListView.utils";
@@ -263,7 +263,7 @@ export const SecretItem = memo(
key="value-overriden"
control={control}
render={({ field }) => (
<SecretInput
<InfisicalSecretInput
key="value-overriden"
isVisible={isVisible}
isReadOnly={isReadOnly}
@@ -280,7 +280,7 @@ export const SecretItem = memo(
key="secret-value"
control={control}
render={({ field }) => (
<SecretInput
<InfisicalSecretInput
isReadOnly={isReadOnly}
key="secret-value"
isVisible={isVisible}

View File

@@ -5,7 +5,8 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
import { ProjectPermissionCan } from "@app/components/permissions";
import { IconButton, SecretInput, Tooltip } from "@app/components/v2";
import { IconButton, Tooltip } from "@app/components/v2";
import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput/InfisicalSecretInput";
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
import { useToggle } from "@app/hooks";
@@ -87,13 +88,19 @@ export const SecretEditRow = ({
};
return (
<div className="group flex w-full cursor-text space-x-2 items-center">
<div className="group flex w-full cursor-text items-center space-x-2">
<div className="flex-grow border-r border-r-mineshaft-600 pr-2 pl-1">
<Controller
control={control}
name="value"
render={({ field }) => (
<SecretInput {...field} value={field.value as string} isVisible={isVisible} secretPath={secretPath} environment={environment} />
<InfisicalSecretInput
{...field}
value={field.value as string}
isVisible={isVisible}
secretPath={secretPath}
environment={environment}
/>
)}
/>
</div>