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

feat: introduce @unkey/ui internal package with a new hook #2661

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
20 changes: 15 additions & 5 deletions apps/dashboard/app/(app)/ratelimits/[namespaceId]/logs/menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { toast } from "@/components/ui/toaster";
import { useCopyToClipboard } from "@unkey/ui";
import Link from "next/link";
import { parseAsArrayOf, parseAsString, useQueryState } from "nuqs";

Expand All @@ -18,7 +19,9 @@ type Props = {
};

export const Menu: React.FC<Props> = ({ namespace, identifier }) => {
const [_, setIdentifier] = useQueryState(
const [, copyToClipboard] = useCopyToClipboard();

const [, setIdentifier] = useQueryState(
"identifier",
parseAsArrayOf(parseAsString).withDefault([]).withOptions({
history: "push",
Expand All @@ -37,10 +40,17 @@ export const Menu: React.FC<Props> = ({ namespace, identifier }) => {
<DropdownMenuContent className="w-56">
<DropdownMenuItem
onClick={() => {
navigator.clipboard.writeText(identifier);
toast.success("Copied to clipboard", {
description: identifier,
});
copyToClipboard(identifier)
.then(() =>
toast.success("Identifier copied to clipboard", {
description: identifier,
}),
)
.catch((err) =>
toast.error("Failed to copy to clipboard", {
description: (err as Error).message,
}),
);
}}
>
<Copy className="w-4 h-4 mr-2" />
Expand Down
26 changes: 4 additions & 22 deletions apps/dashboard/components/dashboard/copy-button.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,24 @@
"use client";

import * as React from "react";
import type * as React from "react";

import { cn } from "@/lib/utils";
import { useCopyToClipboard } from "@unkey/ui";
import { Copy, CopyCheck } from "lucide-react";

interface CopyButtonProps extends React.HTMLAttributes<HTMLButtonElement> {
value: string;
src?: string;
}

async function copyToClipboardWithMeta(value: string, _meta?: Record<string, unknown>) {
navigator.clipboard.writeText(value);
}

export function CopyButton({ value, className, src, ...props }: CopyButtonProps) {
const [copied, setCopied] = React.useState(false);

React.useEffect(() => {
if (!copied) {
return;
}
const timer = setTimeout(() => {
setCopied(false);
}, 2000);
return () => clearTimeout(timer);
}, [copied]);
const [copied, copyToClipboard] = useCopyToClipboard(2000);

return (
<button
type="button"
className={cn("relative p-1 focus:outline-none h-6 w-6 ", className)}
onClick={() => {
copyToClipboardWithMeta(value, {
component: src,
});
setCopied(true);
}}
onClick={() => copyToClipboard(value)}
{...props}
>
<span className="sr-only">Copy</span>
Expand Down
1 change: 1 addition & 0 deletions apps/dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"@unkey/schema": "workspace:^",
"@unkey/vault": "workspace:^",
"@unkey/vercel": "workspace:^",
"@unkey/ui": "workspace:^",
"@upstash/ratelimit": "^2.0.1",
"@upstash/redis": "^1.31.3",
"@vercel/og": "^0.6.2",
Expand Down
26 changes: 3 additions & 23 deletions apps/www/components/copy-button.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,15 @@
"use client";

import { cn } from "@/lib/utils";
import { useCopyToClipboard } from "@unkey/ui";
import { Copy, CopyCheck } from "lucide-react";
import { useEffect, useState } from "react";

interface CopyButtonProps extends React.HTMLAttributes<HTMLButtonElement> {
value: string;
src?: string;
}

async function copyToClipboardWithMeta(value: string, _meta?: Record<string, unknown>) {
navigator.clipboard.writeText(value);
}

export function CopyButton({ value, className, src, children, ...props }: CopyButtonProps) {
const [copied, setCopied] = useState(false);

useEffect(() => {
if (!copied) {
return;
}
const timer = setTimeout(() => {
setCopied(false);
}, 2000);
return () => clearTimeout(timer);
}, [copied]);
const [copied, copyToClipboard] = useCopyToClipboard(2000);

return (
<button
Expand All @@ -34,12 +19,7 @@ export function CopyButton({ value, className, src, children, ...props }: CopyBu
"relative p-1 text-primary focus:outline-none flex items-center gap-2",
className,
)}
onClick={() => {
copyToClipboardWithMeta(value, {
component: src,
});
setCopied(true);
}}
onClick={() => copyToClipboard(value)}
{...props}
>
<span className="sr-only">Copy</span>
Expand Down
19 changes: 3 additions & 16 deletions apps/www/components/ui/copy-code-button.tsx
Original file line number Diff line number Diff line change
@@ -1,32 +1,19 @@
import { useEffect, useState } from "react";
import { useCopyToClipboard } from "@unkey/ui";

type Props = {
textToCopy: string;
className?: string;
};

export function CopyCodeSnippetButton(props: Props) {
const [copied, setCopied] = useState(false);

useEffect(() => {
if (!copied) {
return;
}
const timer = setTimeout(() => {
setCopied(false);
}, 2000);
return () => clearTimeout(timer);
}, [copied]);
const [copied, copyToClipboard] = useCopyToClipboard(2000);

return (
<button
type="button"
aria-label="Copy code snippet"
className={props.className}
onClick={() => {
navigator.clipboard.writeText(props.textToCopy);
setCopied(true);
}}
onClick={() => copyToClipboard(props.textToCopy)}
>
{copied ? <CheckmarkCircle /> : <CopyIcon />}
</button>
Expand Down
1 change: 1 addition & 0 deletions apps/www/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"@radix-ui/react-tabs": "^1.1.0",
"@radix-ui/react-tooltip": "^1.0.7",
"@unkey/db": "workspace:^",
"@unkey/ui": "workspace:^",
"@vercel/og": "^0.6.2",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
Expand Down
7 changes: 4 additions & 3 deletions internal/tsconfig/react-library.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
"display": "React Library",
"extends": "./base.json",
"compilerOptions": {
"jsx": "react-jsx",
"lib": ["ES2015"],
"lib": ["ES2015", "DOM"],
"module": "ESNext",
"target": "es6"
"target": "ES2022",
"jsx": "react-jsx",
"noEmit": true
}
}
10 changes: 10 additions & 0 deletions internal/ui/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<div align="center">
<h1 align="center">@unkey/ui</h1>
<h5>`@unkey/ui` is a library of React components that are used across Unkey's web applications</h5>
</div>

## Installation

```bash
pnpm i @unkey/ui
```
39 changes: 39 additions & 0 deletions internal/ui/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "@unkey/ui",
"description": "UI components for Unkey",
"version": "0.1.1",
"sideEffects": false,
"main": "./src/index.ts",
"types": "./src/index.ts",
"scripts": {
"lint": "eslint src/",
"check-types": "tsc --noEmit"
},
"peerDependencies": {
"next": "14.2.10",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@unkey/tsconfig": "workspace:^",
"@types/react": "^18.2.47",
"@types/react-dom": "^18.2.14",
"autoprefixer": "^10.4.19",
"next": "14.2.10",
"postcss": "^8.4.38",
"react": "^18.2.0",
"tailwindcss": "^3.4.3",
"typescript": "^5.5.3"
},
"dependencies": {},
"author": "Nazar Poshtarenko <[email protected]>",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

btw, not sure about this line. let me know if that’s okay or if you prefer it limited to core contributors.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and since it's an internal package, one may find this info excessive. I'm ok with refining this file to keep it clean and consistent w/ other packages

"homepage": "https://github.com/unkeyed/unkey#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/unkeyed/unkey.git"
},
"bugs": {
"url": "https://github.com/unkeyed/unkey/issues"
},
"keywords": ["unkey", "ui"]
}
9 changes: 9 additions & 0 deletions internal/ui/postcss.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// If you want to use other PostCSS plugins, see the following:
// https://tailwindcss.com/docs/using-with-preprocessors

module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
1 change: 1 addition & 0 deletions internal/ui/src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./use-copy-to-clipboard";
63 changes: 63 additions & 0 deletions internal/ui/src/hooks/use-copy-to-clipboard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { useCallback, useEffect, useRef, useState } from "react";

const DEFAULT_TIMEOUT = 3000;

export const useCopyToClipboard = (
timeout = DEFAULT_TIMEOUT,
): [boolean, (value: string | ClipboardItem) => Promise<void>] => {
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const [copied, setCopied] = useState(false);

const clearTimer = () => {
if (timer.current) {
clearTimeout(timer.current);
timer.current = null;
}
};

const writeToClipboard = async (value: string | ClipboardItem) => {
const isClipboardAvailable =
typeof navigator !== "undefined" && navigator.clipboard !== undefined;

if (!isClipboardAvailable) {
throw new Error("Clipboard API is not supported in this browser");
}

if (typeof value === "string") {
await navigator.clipboard.writeText(value);
} else if (value instanceof ClipboardItem) {
await navigator.clipboard.write([value]);
}
};

const handleTimeout = () => {
if (Number.isFinite(timeout) && timeout >= 0) {
timer.current = setTimeout(() => setCopied(false), timeout);
} else {
console.warn(`Invalid timeout value; defaulting to ${DEFAULT_TIMEOUT}ms`);
timer.current = setTimeout(() => setCopied(false), DEFAULT_TIMEOUT);
}
};

const copyToClipboard = useCallback(
async (value: string | ClipboardItem) => {
clearTimer();
try {
await writeToClipboard(value);
setCopied(true);
handleTimeout();
} catch (error) {
console.warn("Failed to copy to clipboard. ", error);
throw error; // Propagate error for higher-level handling
}
},
[timeout],
);

// Cleanup the timer when the component unmounts
useEffect(() => {
return () => clearTimer();
}, []);

return [copied, copyToClipboard];
};
1 change: 1 addition & 0 deletions internal/ui/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./hooks";
5 changes: 5 additions & 0 deletions internal/ui/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": "@unkey/tsconfig/react-library.json",
"include": ["."],
"exclude": ["dist", "build", "node_modules"]
}
3 changes: 3 additions & 0 deletions knip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ const config: KnipConfig = {
"internal/vercel": {
entry: "src/index.ts",
},
"internal/ui": {
entry: "src/index.ts",
},
"packages/*": {
entry: ["**/*.test.ts"],
},
Expand Down
11 changes: 2 additions & 9 deletions packages/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,12 @@
"publishConfig": {
"access": "public"
},
"keywords": [
"unkey",
"client",
"api"
],
"keywords": ["unkey", "client", "api"],
"bugs": {
"url": "https://github.com/unkeyed/unkey/issues"
},
"homepage": "https://github.com/unkeyed/unkey#readme",
"files": [
"./dist/**",
"README.md"
],
"files": ["./dist/**", "README.md"],
"author": "Andreas Thomas <[email protected]>",
"scripts": {
"build": "tsup"
Expand Down
Loading