Migrate to npm-workspaces monorepo (#294)

* spec update

* update md files

* add plan: monorepo

* feat: add empty apps and packages directories

* Add shared tsconfig.base.json

* feat add workspaces

* feat: move hudozka-writer into apps/

* feat: move migrate-to-pocketbase into apps/

* feat: split package.json for apps/hudozka workspace

* feat: extend tsconfig.base.json in apps/hudozka

* add dockerfile path

* feat: verify Phase 3 monorepo migration of Next app

* feat: scaffold @hudozka/utils package

* feat: add utils barrel export

* feat: extract utilities into hudozka-utils package

* feat: extract hooks into hudozka-hooks package

* Extract Box/Button/Panel/Title/Overlay into @hudozka/ui

* Scope Next ESLint rules to apps/hudozka in root flat config

* Update README and CLAUDE.md for monorepo layout

* disable image optimisation
This commit is contained in:
tmshv authored and GitHub committed 2026-04-25 01:33:06 +03:00
1 parent 0665fa7ae7
commit f874b58dd9
258 files changed
+3793 -214

No files matched your search

View File
Whitespace-only changes.
+15
View File
@@ -0,0 +1,15 @@
{
"name": "@hudozka/hooks",
"private": true,
"version": "0.0.0",
"type": "module",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"test": "vitest run"
},
"peerDependencies": {
"react": ">=19"
}
}
+5
View File
@@ -0,0 +1,5 @@
export * from "./useToggle"
export * from "./useLockBodyScroll"
export * from "./useMediaQuery"
export * from "./useMobile"
export * from "./useReducedMotion"
@@ -0,0 +1,40 @@
import { renderHook } from "@testing-library/react"
import { describe, it, expect, beforeEach } from "vitest"
import { useLockBodyScroll } from "./useLockBodyScroll"
describe("useLockBodyScroll", () => {
beforeEach(() => {
document.body.style.overflow = ""
})
it("sets overflow hidden when locked", () => {
renderHook(() => useLockBodyScroll(true))
expect(document.body.style.overflow).toBe("hidden")
})
it("does not change overflow when unlocked", () => {
document.body.style.overflow = "auto"
renderHook(() => useLockBodyScroll(false))
expect(document.body.style.overflow).toBe("auto")
})
it("restores original overflow on unmount", () => {
document.body.style.overflow = "scroll"
const { unmount } = renderHook(() => useLockBodyScroll(true))
expect(document.body.style.overflow).toBe("hidden")
unmount()
expect(document.body.style.overflow).toBe("scroll")
})
it("responds to lock/unlock transitions", () => {
const { rerender } = renderHook(
({ locked }) => useLockBodyScroll(locked),
{ initialProps: { locked: false } },
)
expect(document.body.style.overflow).toBe("")
rerender({ locked: true })
expect(document.body.style.overflow).toBe("hidden")
rerender({ locked: false })
expect(document.body.style.overflow).toBe("")
})
})
+16
View File
@@ -0,0 +1,16 @@
import { useEffect } from "react"
export function useLockBodyScroll(locked: boolean): void {
useEffect(() => {
if (!locked) {
return
}
const original = document.body.style.overflow
document.body.style.overflow = "hidden"
return () => {
document.body.style.overflow = original
}
}, [locked])
}
+57
View File
@@ -0,0 +1,57 @@
import { renderHook, act } from "@testing-library/react"
import { describe, it, expect, beforeEach, vi } from "vitest"
import { useMediaQuery } from "./useMediaQuery"
describe("useMediaQuery", () => {
let listeners: Map<string, Set<() => void>>
let matches: Map<string, boolean>
beforeEach(() => {
listeners = new Map()
matches = new Map()
vi.stubGlobal("matchMedia", (query: string) => ({
matches: matches.get(query) ?? false,
addEventListener: (_: string, cb: () => void) => {
if (!listeners.has(query)) {
listeners.set(query, new Set())
}
listeners.get(query)!.add(cb)
},
removeEventListener: (_: string, cb: () => void) => {
listeners.get(query)?.delete(cb)
},
}))
})
it("returns current match state", () => {
matches.set("(min-width: 800px)", true)
const { result } = renderHook(() => useMediaQuery("(min-width: 800px)"))
expect(result.current).toBe(true)
})
it("returns false when query does not match", () => {
const { result } = renderHook(() => useMediaQuery("(min-width: 800px)"))
expect(result.current).toBe(false)
})
it("updates on change events", () => {
const query = "(min-width: 800px)"
const { result } = renderHook(() => useMediaQuery(query))
expect(result.current).toBe(false)
act(() => {
matches.set(query, true)
listeners.get(query)?.forEach((cb) => cb())
})
expect(result.current).toBe(true)
})
it("cleans up listener on unmount", () => {
const query = "(min-width: 800px)"
const { unmount } = renderHook(() => useMediaQuery(query))
expect(listeners.get(query)?.size).toBe(1)
unmount()
expect(listeners.get(query)?.size).toBe(0)
})
})
+13
View File
@@ -0,0 +1,13 @@
import { useSyncExternalStore } from "react"
export function useMediaQuery(query: string, defaultValue = false): boolean {
return useSyncExternalStore(
(callback) => {
const mql = window.matchMedia(query)
mql.addEventListener("change", callback)
return () => mql.removeEventListener("change", callback)
},
() => window.matchMedia(query).matches,
() => defaultValue,
)
}
+5
View File
@@ -0,0 +1,5 @@
import { useMediaQuery } from "./useMediaQuery"
export function useMobile(): boolean {
return useMediaQuery("(max-width: 31.25em)", false)
}
+5
View File
@@ -0,0 +1,5 @@
import { useMediaQuery } from "./useMediaQuery"
export function useReducedMotion(): boolean {
return useMediaQuery("(prefers-reduced-motion: reduce)")
}
+37
View File
@@ -0,0 +1,37 @@
import { renderHook, act } from "@testing-library/react"
import { describe, it, expect } from "vitest"
import { useToggle } from "./useToggle"
describe("useToggle", () => {
it("returns initial value", () => {
const { result } = renderHook(() => useToggle(false))
expect(result.current[0]).toBe(false)
})
it("toggles value", () => {
const { result } = renderHook(() => useToggle(false))
act(() => result.current[1]())
expect(result.current[0]).toBe(true)
act(() => result.current[1]())
expect(result.current[0]).toBe(false)
})
it("sets explicit true", () => {
const { result } = renderHook(() => useToggle(false))
act(() => result.current[1](true))
expect(result.current[0]).toBe(true)
})
it("sets explicit false", () => {
const { result } = renderHook(() => useToggle(true))
act(() => result.current[1](false))
expect(result.current[0]).toBe(false)
})
it("has a stable dispatch reference", () => {
const { result, rerender } = renderHook(() => useToggle(false))
const first = result.current[1]
rerender()
expect(result.current[1]).toBe(first)
})
})
+9
View File
@@ -0,0 +1,9 @@
import { useCallback, useState } from "react"
export function useToggle(initialValue: boolean): [boolean, (nextValue?: boolean) => void] {
const [state, setState] = useState(initialValue)
const toggle = useCallback((next?: boolean) => {
setState(prev => typeof next === "boolean" ? next : !prev)
}, [])
return [state, toggle]
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.base.json",
"include": ["src/**/*"]
}
+9
View File
@@ -0,0 +1,9 @@
import { defineConfig } from "vitest/config"
export default defineConfig({
test: {
include: ["src/**/*.test.{ts,tsx}"],
environment: "happy-dom",
setupFiles: ["./vitest.setup.ts"],
},
})
+1
View File
@@ -0,0 +1 @@
import "@testing-library/jest-dom/vitest"
+19
View File
@@ -0,0 +1,19 @@
{
"name": "@hudozka/text",
"private": true,
"version": "0.0.0",
"type": "module",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"test": "vitest run"
},
"dependencies": {
"markdown-it": "^14.1.0",
"typograf": "^7.6.0"
},
"devDependencies": {
"@types/markdown-it": "^14.1.0"
}
}
+1
View File
@@ -0,0 +1 @@
export * from "./text"
+24
View File
@@ -0,0 +1,24 @@
import { describe, it, expect } from "vitest"
import { markdownToHtml, typograf } from "./text"
describe("markdownToHtml", () => {
it("should convert markdown paragraph to HTML", () => {
expect(markdownToHtml("hello")).toBe("<p>hello</p>\n")
})
it("should convert bold text", () => {
expect(markdownToHtml("**bold**")).toBe("<p><strong>bold</strong></p>\n")
})
it("should pass through raw HTML", () => {
expect(markdownToHtml("<div>test</div>")).toBe("<div>test</div>")
})
})
describe("typograf", () => {
it("should apply Russian typographic rules", () => {
const result = typograf("Привет - мир")
expect(result).toContain("Привет")
expect(result).toContain("мир")
})
})
+19
View File
@@ -0,0 +1,19 @@
import MarkdownIt from "markdown-it"
import Typograf from "typograf"
const tp = new Typograf({ locale: ["ru"] })
const md = new MarkdownIt({
html: true,
})
export type MarkdownProps = {
data: string
}
export function markdownToHtml(data: string): string {
return md.render(data)
}
export function typograf(data: string): string {
return tp.execute(data)
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.base.json",
"include": ["src/**/*"]
}
+20
View File
@@ -0,0 +1,20 @@
{
"name": "@hudozka/ui",
"private": true,
"version": "0.0.0",
"type": "module",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"test": "vitest run"
},
"dependencies": {
"classnames": "^2.5.0",
"@hudozka/hooks": "*"
},
"peerDependencies": {
"react": ">=19",
"react-dom": ">=19"
}
}
+44
View File
@@ -0,0 +1,44 @@
import { render, screen } from "@testing-library/react"
import { describe, it, expect } from "vitest"
import { Box } from "."
describe("Box", () => {
it("renders children", () => {
render(<Box>hello</Box>)
expect(screen.getByText("hello")).toBeInTheDocument()
})
it("defaults to a div tag", () => {
render(<Box>content</Box>)
expect(screen.getByText("content").tagName).toBe("DIV")
})
it("renders as a custom tag via the as prop", () => {
render(<Box as="section">section content</Box>)
expect(screen.getByText("section content").tagName).toBe("SECTION")
})
it("applies vertical class", () => {
const { container } = render(<Box vertical>v</Box>)
const el = container.firstElementChild!
expect(el.className).toMatch(/vertical/)
})
it("applies center class", () => {
const { container } = render(<Box center>c</Box>)
const el = container.firstElementChild!
expect(el.className).toMatch(/center/)
})
it("applies wrap class", () => {
const { container } = render(<Box wrap>w</Box>)
const el = container.firstElementChild!
expect(el.className).toMatch(/wrap/)
})
it("passes gap to inline style", () => {
const { container } = render(<Box gap={8}>g</Box>)
const el = container.firstElementChild!
expect(el).toHaveStyle({ gap: "8px" })
})
})
+23
View File
@@ -0,0 +1,23 @@
.box {
display: flex;
justify-content: flex-start;
flex-wrap: nowrap;
flex-direction: row;
}
.box.align {
align-items: center;
}
.box.wrap {
flex-wrap: wrap;
}
.box.center {
align-items: center;
justify-content: center;
}
.box.vertical {
flex-direction: column;
}
+40
View File
@@ -0,0 +1,40 @@
import s from "./box.module.css"
import classnames from "classnames/bind"
import { createElement } from "react"
const cx = classnames.bind(s)
export type BoxProps = {
as?: keyof HTMLElementTagNameMap
children?: React.ReactNode
className?: string
style?: React.CSSProperties
wrap?: boolean
align?: boolean
vertical?: boolean
center?: boolean
gap?: number | string
}
export const Box: React.FC<BoxProps> = ({
as = "div",
wrap = false,
vertical = false,
center = false,
align = true,
style,
gap,
className,
...props
}) => {
const newProps = {
className: cx(className, s.box, { vertical, align, center, wrap }),
style: {
...style,
gap,
},
}
return createElement(as, newProps, props.children)
}
+40
View File
@@ -0,0 +1,40 @@
import { render, screen, fireEvent } from "@testing-library/react"
import { describe, it, expect, vi } from "vitest"
import { Button } from "."
describe("Button", () => {
it("renders children in a button element", () => {
render(<Button>Click me</Button>)
const button = screen.getByRole("button", { name: "Click me" })
expect(button).toBeInTheDocument()
expect(button.tagName).toBe("BUTTON")
})
it("renders as a link when href is provided", () => {
render(<Button href="/about">About</Button>)
const link = screen.getByRole("link", { name: "About" })
expect(link).toBeInTheDocument()
expect(link).toHaveAttribute("href", "/about")
})
it("calls onClick with value when clicked", () => {
const onClick = vi.fn()
render(<Button value="test-value" onClick={onClick}>Click</Button>)
fireEvent.click(screen.getByRole("button", { name: "Click" }))
expect(onClick).toHaveBeenCalledOnce()
expect(onClick).toHaveBeenCalledWith("test-value", expect.anything())
})
it("calls onClick with undefined when no value is provided", () => {
const onClick = vi.fn()
render(<Button onClick={onClick}>Press</Button>)
fireEvent.click(screen.getByRole("button", { name: "Press" }))
expect(onClick).toHaveBeenCalledOnce()
expect(onClick).toHaveBeenCalledWith(undefined, expect.anything())
})
it("applies disabled class when disabled is true", () => {
const { container } = render(<Button disabled>Disabled</Button>)
expect(container.firstElementChild!.className).toMatch(/disabled/)
})
})
+60
View File
@@ -0,0 +1,60 @@
.button {
display: inline-flex;
align-items: center;
font-size: var(--font-size-default);
text-align: center;
border-radius: var(--size-s);
border: 1px solid var(--color-shadow);
color: var(--color-text);
background-color: var(--color-back);
box-shadow: none;
transition: box-shadow 200ms ease-in, background-color 200ms ease-in;
outline: none;
cursor: pointer;
}
.button:hover {
border-color: rgba(0, 0, 0, 0);
box-shadow: var(--shadow);
}
/* MODIFICATORS */
.disabled {
pointer-events: none;
color: var(--color-text-second);
}
/* SIZE */
.sizeDefault {
padding: var(--size-s) var(--size-m);
}
.sizeSmall {
padding: var(--size-xs) var(--size-s);
font-size: var(--font-size-second);
}
/* THEME */
.themeGhost {
border-color: rgba(0, 0, 0, 0);
}
.themeIcon {
border-color: rgba(0, 0, 0, 0);
padding: var(--size-xs) var(--size-xs);
}
/* DARK THEME */
@media (prefers-color-scheme: dark) {
.button:hover {
background-color: var(--color-back-active);
}
}
+57
View File
@@ -0,0 +1,57 @@
import s from "./button.module.css"
import Link from "next/link"
import cx from "classnames"
import { useCallback } from "react"
import type { MouseEvent, MouseEventHandler } from "react"
const sizeClass = {
default: s.sizeDefault,
small: s.sizeSmall,
}
const themeClass = {
default: "",
icon: s.themeIcon,
ghost: s.themeGhost,
}
export type ButtonProps = {
children?: React.ReactNode
value?: string
style?: React.CSSProperties
href?: string
theme?: "default" | "ghost" | "icon"
size?: "default" | "small"
disabled?: boolean
onClick?: (value: string | undefined, event: MouseEvent) => void
}
export const Button: React.FC<ButtonProps> = ({ size = "default", theme = "default", disabled = false, ...props }) => {
const className = cx(s.button, sizeClass[size], themeClass[theme], {
[s.disabled]: disabled,
})
const onClick = useCallback<MouseEventHandler<HTMLButtonElement>>(event => {
if (typeof props.onClick === "function") {
props.onClick(props.value, event)
}
}, [props])
if (props.href) {
return (
<Link href={props.href} className={className} style={props.style}>
{props.children}
</Link>
)
}
return (
<button
className={className}
style={props.style}
onClick={onClick}
>
{props.children}
</button>
)
}
+65
View File
@@ -0,0 +1,65 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
export type TransitionProps = {
children?: React.ReactNode
duration: number
extraStyle?: React.CSSProperties
show: boolean
}
export function Transition(props: TransitionProps) {
const [mounted, setMounted] = useState(props.show)
const [opacity, setOpacity] = useState(0)
const timerRef = useRef<ReturnType<typeof setTimeout>>(null)
const onTransitionEnd = useCallback(() => {
if (opacity === 0) {
setMounted(false)
}
}, [opacity])
const transition = useMemo(
() => `all ${props.duration}ms`,
[props.duration],
)
if (props.show && !mounted) {
setMounted(true)
}
if (!props.show && opacity !== 0) {
setOpacity(0)
}
useEffect(() => {
if (!props.show) {
return
}
timerRef.current = setTimeout(() => {
setOpacity(1)
}, 16)
return () => {
if (timerRef.current) {
clearTimeout(timerRef.current)
}
}
}, [props.show])
if (!mounted) {
return null
}
return (
<div
style={{
...props.extraStyle,
opacity,
transition,
}}
onTransitionEnd={onTransitionEnd}
>
{props.children}
</div>
)
}
+38
View File
@@ -0,0 +1,38 @@
import s from "./styles.module.css"
import { Transition } from "./Transition"
import { useLockBodyScroll, useReducedMotion } from "@hudozka/hooks"
export type OverlayProps = {
children?: React.ReactNode
show: boolean
onClickOverlay: () => void
style?: React.CSSProperties
duration: number
}
export const Overlay: React.FC<OverlayProps> = props => {
const motionDisabled = useReducedMotion()
const duration = motionDisabled ? 0 : props.duration
useLockBodyScroll(props.show)
return (
<Transition
duration={duration}
show={props.show}
>
<div
onClick={(event) => {
if (event.target === event.currentTarget) {
props.onClickOverlay()
}
}}
className={s.overlay}
style={props.style}
>
{props.children}
</div>
</Transition>
)
}
+11
View File
@@ -0,0 +1,11 @@
.overlay {
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
overflow-y: auto;
z-index: 1000000;
background-color: var(--color-back-main);
}
+29
View File
@@ -0,0 +1,29 @@
import { render } from "@testing-library/react"
import { describe, it, expect } from "vitest"
import { Panel } from "."
describe("Panel", () => {
it("renders children", () => {
const { container } = render(<Panel>hello</Panel>)
expect(container).toHaveTextContent("hello")
})
it("applies the default variant class", () => {
const { container } = render(<Panel>content</Panel>)
const el = container.firstElementChild!
expect(el.className).toMatch(/default/)
})
it("applies the ghost variant class when ghost is true", () => {
const { container } = render(<Panel ghost>content</Panel>)
const el = container.firstElementChild!
expect(el.className).toMatch(/ghost/)
expect(el.className).not.toMatch(/default/)
})
it("forwards a custom className", () => {
const { container } = render(<Panel className="custom">content</Panel>)
const el = container.firstElementChild!
expect(el.className).toContain("custom")
})
})
+25
View File
@@ -0,0 +1,25 @@
import s from "./panel.module.css"
import { Box } from "../Box"
export type PanelProps = {
children?: React.ReactNode
style?: React.CSSProperties
className?: string
ghost?: boolean
}
export function Panel({
style,
className,
children,
ghost = false,
}: PanelProps) {
const variant = ghost ? s.ghost : s.default
return (
<Box vertical align={false} className={`${s.panel} ${variant}${className ? ` ${className}` : ""}`} style={style}>
{children}
</Box>
)
}
+12
View File
@@ -0,0 +1,12 @@
.panel {
border-radius: var(--radius);
}
.default {
padding: var(--size-m);
background-color: white;
}
.ghost {
background-color: none;
}
+12
View File
@@ -0,0 +1,12 @@
import { createElement } from "react"
export type TitleProps = {
level?: 1 | 2 | 3 | 4 | 5 | 6
children?: React.ReactNode
className?: string
style?: React.CSSProperties
}
export const Title: React.FC<TitleProps> = ({ level = 1, children, ...props }) => {
return createElement(`h${level}`, props, children)
}
+5
View File
@@ -0,0 +1,5 @@
export * from "./Box"
export * from "./Button"
export * from "./Panel"
export * from "./Title"
export * from "./Overlay"
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.base.json",
"include": ["src/**/*"]
}
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from "vitest/config"
export default defineConfig({
test: {
include: ["src/**/*.test.{ts,tsx}"],
environment: "happy-dom",
setupFiles: ["./vitest.setup.tsx"],
css: true,
},
})
+1
View File
@@ -0,0 +1 @@
import "@testing-library/jest-dom/vitest"
+15
View File
@@ -0,0 +1,15 @@
{
"name": "@hudozka/utils",
"private": true,
"version": "0.0.0",
"type": "module",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"date-fns": "^4.0.0"
}
}
+37
View File
@@ -0,0 +1,37 @@
import { describe, it, expect } from "vitest"
import { insertBetween, tail } from "./array"
describe("insertBetween", () => {
it("should return empty array for empty input", () => {
expect(insertBetween([], () => ",")).toEqual([])
})
it("should return single item without separator", () => {
expect(insertBetween(["a"], () => ",")).toEqual(["a"])
})
it("should insert separators between items", () => {
expect(insertBetween(["a", "b", "c"], () => ",")).toEqual([
"a", ",", "b", ",", "c",
])
})
it("should pass index to separator function", () => {
const result = insertBetween(["a", "b", "c"], (i) => i)
expect(result).toEqual(["a", 0, "b", 1, "c"])
})
})
describe("tail", () => {
it("should return empty array for empty input", () => {
expect(tail([])).toEqual([])
})
it("should return empty array for single item", () => {
expect(tail(["a"])).toEqual([])
})
it("should return all items except first", () => {
expect(tail([1, 2, 3])).toEqual([2, 3])
})
})
+19
View File
@@ -0,0 +1,19 @@
export type InsertBetweenFunction<T> = (i: number) => T
export function insertBetween<T, I = T>(items: T[], fn: InsertBetweenFunction<I>): Array<T | I> {
return items.reduce<Array<T | I>>((acc, x, i) => {
acc.push(x)
if (i < items.length - 1) {
acc.push(fn(i))
}
return acc
}, [])
}
export function tail<T>(items: T[]): T[] {
const [_, ...rest] = items
return rest
}
+14
View File
@@ -0,0 +1,14 @@
import { describe, it, expect } from "vitest"
import { dateFormat } from "./date"
describe("dateFormat", () => {
it("should format a Date object in Russian locale", () => {
const result = dateFormat(new Date(2024, 0, 15))
expect(result).toBe("15 января 2024")
})
it("should format a date string in Russian locale", () => {
const result = dateFormat("2024-06-01T00:00:00.000Z")
expect(result).toBe("1 июня 2024")
})
})
+15
View File
@@ -0,0 +1,15 @@
import { format } from "date-fns/format"
import { ru } from "date-fns/locale"
/**
*
* Date -> D MMMM yyyy
*
* @param date
*/
export const dateFormat = (date: string | Date) => {
const value = typeof date === "string" ? new Date(date) : date
return format(value, "d MMMM yyyy", {
locale: ru,
})
}
+51
View File
@@ -0,0 +1,51 @@
import { describe, it, expect } from "vitest"
import { ext, size } from "./file"
describe("ext", () => {
it("should return ПДФ for application/pdf", () => {
expect(ext("application/pdf")).toBe("ПДФ")
})
it("should return ЖПГ for image/jpeg", () => {
expect(ext("image/jpeg")).toBe("ЖПГ")
})
it("should return ПНГ for image/png", () => {
expect(ext("image/png")).toBe("ПНГ")
})
it("should return raw MIME type for unknown types", () => {
expect(ext("text/plain")).toBe("text/plain")
})
})
describe("size", () => {
it("should return empty string for NaN", () => {
expect(size(NaN)).toBe("")
})
it("should return empty string for non-finite values", () => {
expect(size(Infinity)).toBe("")
expect(size(-Infinity)).toBe("")
})
it("should format bytes", () => {
expect(size(500)).toBe("500.0 байт")
})
it("should format kilobytes", () => {
expect(size(1024)).toBe("1.0 КБ")
})
it("should format megabytes", () => {
expect(size(1024 * 1024)).toBe("1.0 МБ")
})
it("should format gigabytes", () => {
expect(size(1024 * 1024 * 1024)).toBe("1.0 ГБ")
})
it("should respect precision parameter", () => {
expect(size(1536, 2)).toBe("1.50 КБ")
})
})
+24
View File
@@ -0,0 +1,24 @@
const units = ["байт", "КБ", "МБ", "ГБ", "ТБ", "ПБ"]
const mime = new Map([
["application/pdf", "ПДФ"],
["image/jpeg", "ЖПГ"],
["image/png", "ПНГ"],
])
export function ext(mimeType: string): string {
if (mime.has(mimeType)) {
return mime.get(mimeType)!
}
return mimeType
}
export function size(bytes: number, precision = 1): string {
if (Number.isNaN(bytes) || !Number.isFinite(bytes)) return ""
const number = Math.floor(Math.log(bytes) / Math.log(1024))
const size = (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision)
return `${size} ${units[number]}`
}
+25
View File
@@ -0,0 +1,25 @@
import { describe, it, expect } from "vitest"
import { getResizedUrl } from "./image"
describe("getResizedUrl", () => {
it("should construct resize URL with default n", () => {
const result = getResizedUrl("example.com/img.jpg", {
width: 800,
height: 600,
})
expect(result).toBe(
"https://images.weserv.nl/?url=example.com/img.jpg&w=800&h=600&n=1",
)
})
it("should use custom n parameter", () => {
const result = getResizedUrl("example.com/img.jpg", {
width: 400,
height: 300,
n: -1,
})
expect(result).toBe(
"https://images.weserv.nl/?url=example.com/img.jpg&w=400&h=300&n=-1",
)
})
})
+11
View File
@@ -0,0 +1,11 @@
export type ResizeOptions = {
width: number
height: number
n?: number
}
export function getResizedUrl(src: string, options: ResizeOptions): string {
const n = options.n ?? 1
return `https://images.weserv.nl/?url=${src}&w=${options.width}&h=${options.height}&n=${n}`
}
+7
View File
@@ -0,0 +1,7 @@
export * from "./array"
export * from "./string"
export * from "./url"
export * from "./math"
export * from "./image"
export * from "./file"
export * from "./date"
+30
View File
@@ -0,0 +1,30 @@
import { describe, it, expect } from "vitest"
import { clamp } from "./math"
describe("clamp", () => {
it("should return value when within range", () => {
expect(clamp(5, 0, 10)).toBe(5)
})
it("should return min when value is below range", () => {
expect(clamp(-1, 0, 10)).toBe(0)
})
it("should return max when value is above range", () => {
expect(clamp(15, 0, 10)).toBe(10)
})
it("should return min when value equals min", () => {
expect(clamp(0, 0, 10)).toBe(0)
})
it("should return max when value equals max", () => {
expect(clamp(10, 0, 10)).toBe(10)
})
it("should work with negative ranges", () => {
expect(clamp(-5, -10, -1)).toBe(-5)
expect(clamp(-15, -10, -1)).toBe(-10)
expect(clamp(0, -10, -1)).toBe(-1)
})
})
+9
View File
@@ -0,0 +1,9 @@
export function clamp(val: number, min: number, max: number): number {
if (val < min) {
return min
}
if (val > max) {
return max
}
return val
}
+20
View File
@@ -0,0 +1,20 @@
import { describe, it, expect } from "vitest"
import { titleCase } from "./string"
describe("titleCase", () => {
it("should capitalize first letter of lowercase string", () => {
expect(titleCase("hello")).toBe("Hello")
})
it("should keep already capitalized string", () => {
expect(titleCase("Hello")).toBe("Hello")
})
it("should handle empty string", () => {
expect(titleCase("")).toBe("")
})
it("should capitalize single character", () => {
expect(titleCase("a")).toBe("A")
})
})
+3
View File
@@ -0,0 +1,3 @@
export function titleCase(str: string) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
+18
View File
@@ -0,0 +1,18 @@
import { describe, it, expect } from "vitest"
import { queryList } from "./url"
describe("queryList", () => {
it("should return empty string for empty values", () => {
expect(queryList("tag", [])).toBe("")
})
it("should return single key=value pair", () => {
expect(queryList("tag", ["art"])).toBe("tag=art")
})
it("should join multiple values with &", () => {
expect(queryList("tag", ["art", "music", "photo"])).toBe(
"tag=art&tag=music&tag=photo",
)
})
})
+9
View File
@@ -0,0 +1,9 @@
export function queryList(key: string, values: string[]): string {
if (values.length === 0) {
return ""
}
return values
.map(value => `${key}=${value}`)
.join("&")
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.base.json",
"include": ["src/**/*"]
}
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig } from "vitest/config"
export default defineConfig({
test: {
include: ["src/**/*.test.ts"],
},
})