Files
gitmost/apps/client/src/lib/utils.tsx
claude code agent 227 9e1d057878 fix(qa): resolve QA-pass issues #122–#134
Batch of fixes from the automated QA pass on develop. Each was reproduced and
then verified fixed live (browser/curl); logic-bearing fixes have unit tests.

Functional bugs:
- #122 collab-token was capped by the anonymous public-share-AI throttler (5/min);
  skip all non-AUTH named throttlers on this auth-guarded, client-cached route.
- #123 editor onAuthenticationFailed threw `jwtDecode(undefined)` and never
  reconnected; read the token via a ref, guard the decode (incl. missing exp),
  and refetch+reconnect on any auth failure.
- #124 a slash command containing a space ("/Heading 1") inserted literal text;
  enable allowSpaces and close the menu when the query matches no items.
- #125 space slug auto-gen produced uppercase initials for multi-word names;
  computeSpaceSlug now yields a lowercase alphanumeric slug.
- #126 AI chat window position/size now persisted (atomWithStorage) across reload;
  also fixes a latent ResizeObserver-attach bug on first open.
- #127 workspace name update accepted URLs; add @NoUrls (parity with setup).
- #132 icon-columns 4/5 passed calc() into SVG width/height attrs (console spam);
  size via style. share-for-page query returns null instead of undefined.
- #134 "Reindex now" counter looked stuck: reindex runs async; the client now
  polls coverage (bounded) so the counter climbs live; misleading server comment
  reworded.

UX / consistency:
- #128 add success toasts to favorite/label/avatar/member-(de)activate.
- #129 "1 result found" pluralization; hide the single-option Type filter.
- #130 replace raw Zod strings with friendly messages (name/password/group).
- #131 unify "Untitled" casing in tree/breadcrumb/tab; stop force-uppercasing
  space-name chips; fix confirm-dialog labels (Cancel / Remove), invite
  placeholder typo, Export/Move-to-space labels.
- #133 disable profile Save when clean; toast on unsupported avatar image;
  style the invalid-invitation page with a CTA; hide Share for read-only users;
  align the dictation "not configured" message; "Go to login page" typo.

Tests: computeSpaceSlug, workspace-name NoUrls DTO, share-query null
normalization, slash getSuggestionItems empty-close.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 20:47:40 +03:00

137 lines
3.9 KiB
TypeScript

import { validate as isValidUUID } from "uuid";
import { IconFileDescription } from "@tabler/icons-react";
import { ReactNode } from "react";
import { TFunction } from "i18next";
export function formatMemberCount(memberCount: number, t: TFunction): string {
if (memberCount === 1) {
return `1 ${t("member")}`;
} else {
return `${memberCount} ${t("members")}`;
}
}
export function extractPageSlugId(slug: string): string {
if (!slug) {
return undefined;
}
if (isValidUUID(slug)) {
return slug;
}
const parts = slug.split("-");
return parts.length > 1 ? parts[parts.length - 1] : slug;
}
export const computeSpaceSlug = (name: string) => {
// Slug is validated as alphanumeric-only (@IsAlphanumeric / ^[a-zA-Z0-9]+$),
// so lowercase the name and strip every non-alphanumeric character (spaces,
// punctuation, unicode). No hyphens or uppercase initials.
return name.toLowerCase().replace(/[^a-z0-9]/g, "");
};
export const formatBytes = (bytes: number): string => {
if (bytes === 0) return "0.0 KB";
const unitSize = 1024;
const units = ["KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const kilobytes = bytes / unitSize;
const unitIndex = Math.floor(Math.log(kilobytes) / Math.log(unitSize));
const adjustedUnitIndex = Math.max(unitIndex, 0);
const adjustedSize = kilobytes / Math.pow(unitSize, adjustedUnitIndex);
// Use one decimal for KB and no decimals for MB or higher
const precision = adjustedUnitIndex === 0 ? 1 : 0;
return `${adjustedSize.toFixed(precision)} ${units[adjustedUnitIndex]}`;
};
export async function svgStringToFile(
svgString: string,
fileName: string,
): Promise<File> {
const blob = new Blob([svgString], { type: "image/svg+xml" });
return new File([blob], fileName, { type: "image/svg+xml" });
}
// Convert a string holding Base64 encoded UTF-8 data into a proper UTF-8 encoded string
// as a replacement for `atob`.
// based on: https://developer.mozilla.org/en-US/docs/Glossary/Base64
function decodeBase64(base64: string): string {
// convert string to bytes
const bytes = Uint8Array.from(atob(base64), (m) => m.codePointAt(0));
// properly decode bytes to UTF-8 encoded string
return new TextDecoder().decode(bytes);
}
export function decodeBase64ToSvgString(base64Data: string): string {
const base64Prefix = "data:image/svg+xml;base64,";
if (base64Data.startsWith(base64Prefix)) {
base64Data = base64Data.replace(base64Prefix, "");
}
return decodeBase64(base64Data);
}
export function capitalizeFirstChar(string: string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
export function getPageIcon(icon: string, size = 18): string | ReactNode {
return (
icon || (
<IconFileDescription
size={size}
color="var(--mantine-color-gray-6)"
aria-hidden="true"
/>
)
);
}
export const normalizeUrl = (url: string): string => {
if (!url) return url;
if (url.startsWith("/") || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)) return url;
return `https://${url}`;
};
const _isApple = /mac|iphone|ipad|ipod/i.test(navigator.platform ?? "");
/// Cmd key on Apple devices, Ctrl key everywhere else
export function platformModifierKey(event: KeyboardEvent): boolean {
return _isApple ? event.metaKey : event.ctrlKey;
}
export const platformModifierLabel = _isApple ? "⌘" : "Ctrl";
export function castToBoolean(value: unknown): boolean {
if (value == null) {
return false;
}
if (typeof value === "boolean") {
return value;
}
if (typeof value === "number") {
return value !== 0;
}
if (typeof value === "string") {
const trimmed = value.trim().toLowerCase();
const trueValues = ["true", "1"];
const falseValues = ["false", "0"];
if (trueValues.includes(trimmed)) {
return true;
}
if (falseValues.includes(trimmed)) {
return false;
}
return Boolean(trimmed);
}
return Boolean(value);
}