init project

This commit is contained in:
Timi
2026-10-21 11:24:31 +08:00
parent 8a368f5d1e
commit 947ae4cac2
20 changed files with 935 additions and 2 deletions
+10
View File
@@ -0,0 +1,10 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Ignored default folder with query files
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/timi-ts.iml" filepath="$PROJECT_DIR$/.idea/timi-ts.iml" />
</modules>
</component>
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
+2
View File
@@ -0,0 +1,2 @@
/cache
/project.local.yml
+169
View File
@@ -0,0 +1,169 @@
# the name by which the project can be referenced within Serena/when chatting with the LLM.
project_name: "timi-ts"
# list of language servers to start when using the LSP backend; choose from:
# ada al angular ansible bash
# bsl clojure cpp cpp_ccls crystal
# csharp csharp_omnisharp cue dart deno
# elixir elm erlang fortran fsharp
# gdscript gleam go groovy haskell
# haxe hlsl html java json
# julia kotlin latex lean4 lua
# luau markdown matlab msl nextflow
# nix ocaml pascal perl php
# php_phpactor php_phpantom powershell python python_basedpyright
# python_jedi python_pyrefly python_ty qml r
# rego ruby ruby_solargraph rust scala
# scss solidity svelte swift systemverilog
# terraform toml typescript typescript_vts vue
# wolfram yaml zig
# (This list may be outdated; generated with scripts/print_language_list.py;
# For the current list, see values of the LanguageServerId enum here:
# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py)
# For some languages, there are several alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.)
# Note:
# - For C, use cpp
# - For JavaScript, use typescript
# - For Angular projects, use angular (subsumes typescript+html; requires `npm install` in the project root)
# - For Svelte projects, use svelte (subsumes typescript/javascript for .svelte projects; requires npm)
# - For Deno projects, use deno (serves the same .ts/.js files as typescript; requires the deno CLI on PATH)
# - For SCSS / Sass / plain CSS, use scss (some-sass-language-server handles all three)
# - For Free Pascal/Lazarus, use pascal
# Special requirements:
# Some language servers require additional setup/installations.
# See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers
# When using multiple language servers, the first language server that supports a given file will be used for that file.
# The first language server is the default language and the respective language server will be used as a fallback.
# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
language_servers:
- typescript
# the encoding used by text files in the project
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
encoding: "utf-8"
# optional shell command to run before the language backend (LSP or JetBrains) is initialised.
# the command runs in the project root directory and is only executed if the project is trusted
# (see trusted_project_path_patterns in the global configuration).
# serena waits for the command to exit: a non-zero exit code is logged as an error but does not
# abort activation. a per-project timeout (activation_command_timeout, default 180s) is the safety
# backstop for non-terminating commands; on expiry the process is killed and activation continues.
# example: activation_command: "npx nx run-many -t build"
activation_command:
# maximum time in seconds to wait for activation_command to complete before killing it (default 180s).
# must be a positive number.
activation_command_timeout: 180.0
# line ending convention to use when writing source files.
# Possible values: unset (use global setting), "lf", "crlf", or "native" (platform default)
# This does not affect Serena's own files (e.g. memories and configuration files), which always use native line endings.
line_ending:
# The language backend to use for this project.
# If not set, the global setting from serena_config.yml is used.
# Valid values: LSP, JetBrains
# Note: the backend is fixed at startup. If a project with a different backend
# is activated post-init, an error will be returned.
language_backend:
# whether to use project's .gitignore files to ignore files
ignore_all_files_in_gitignore: true
# advanced configuration option allowing to configure language server-specific options.
# Maps the language key to the options.
# The settings are considered only if the project is trusted (see global configuration to define trusted projects).
# See https://oraios.github.io/serena/02-usage/050_configuration.html#language-server-specific-settings
ls_specific_settings: {}
# list of workspace folder paths (LSP backend only).
# These folders will be used to build up Serena's symbol index.
# Paths must be within the project root and should thus be relative to the project root.
# Furthermore, the paths should not be filtered by ignore settings.
# Default setting: The entire project root folder (".") is considered.
# In (large) monorepos, this can be used to index only subfolders of the project root, e.g.
# ls_workspace_folders:
# - "./subproject1"
# - "./subproject2"
ls_workspace_folders:
- "."
# list of additional workspace folder paths for cross-package reference support.
# Paths can be absolute or relative to the project root.
# Each folder is registered as an LSP workspace folder, enabling language servers to discover
# symbols and references across package boundaries, but these folders are not indexed by Serena,
# i.e. the respective symbols will not be found using Serena's symbol search tools.
# Example:
# additional_workspace_folders:
# - ../sibling-package
# - ../shared-lib
ls_additional_workspace_folders: []
# list of additional paths to ignore in this project.
# Same syntax as gitignore, so you can use * and **.
# Important: quote patterns that start with `*`, otherwise YAML treats them as aliases.
# Example:
# ignored_paths:
# - "examples/**"
# - ".worktrees/**"
# - "**/bin/**"
# - "**/obj/**"
# Note: global ignored_paths from serena_config.yml are also applied additively.
ignored_paths: []
# whether the project is in read-only mode
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
# Added on 2025-04-18
read_only: false
# list of tool names to exclude.
# This extends the existing exclusions (e.g. from the global configuration)
# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
excluded_tools: []
# list of tools to include that would otherwise be disabled (particularly optional tools that are disabled by default).
# This extends the existing inclusions (e.g. from the global configuration).
# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
included_optional_tools: []
# fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of tools.
# This cannot be combined with non-empty excluded_tools or included_optional_tools.
# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
fixed_tools: []
# list of mode names that are to be activated by default, overriding the setting in the global configuration.
# The full set of modes to be activated is base_modes (from global config) + default_modes + added_modes.
# If the setting is undefined/empty, the default_modes from the global configuration (serena_config.yml) apply.
# Otherwise, this overrides the setting from the global configuration (serena_config.yml).
# Therefore, you can set this to [] if you do not want the default modes defined in the global config to apply
# for this project.
# This setting can, in turn, be overridden by CLI parameters (--mode).
# See https://oraios.github.io/serena/02-usage/050_configuration.html#modes
default_modes:
# list of mode names to be activated additionally for this project, e.g. ["query-projects"]
# The full set of modes to be activated is base_modes (from global config) + default_modes + added_modes.
# See https://oraios.github.io/serena/02-usage/050_configuration.html#modes
added_modes:
# initial prompt for the project. It will always be given to the LLM upon activating the project
# (contrary to the memories, which are loaded on demand).
initial_prompt: ""
# time budget (seconds) per tool call for the retrieval of additional symbol information
# such as docstrings or parameter information.
# This overrides the corresponding setting in the global configuration; see the documentation there.
# If null or missing, use the setting from the global configuration.
symbol_info_budget:
# list of regex patterns which, when matched, mark a memory entry as read‑only.
# Extends the list from the global configuration, merging the two lists.
read_only_memory_patterns: []
# list of regex patterns for memories to completely ignore.
# Matching memories will not appear in list_memories or activate_project output
# and cannot be accessed via read_memory or write_memory.
# To access ignored memory files, use the read_file tool on the raw file path.
# Extends the list from the global configuration, merging the two lists.
# Example: ["_archive/.*", "_episodes/.*"]
ignored_memory_patterns: []
+24 -2
View File
@@ -1,3 +1,25 @@
# timi-utils-ts
# timi-ts
Typescript 通用工具
平台无关的 TypeScript 通用工具库,供 `timi-web`、`timi-wxmp` 及其他业务项目复用。
## 内容
- `Events`:进程内事件管理
- `IOSize`:存储容量格式化与解析
- `MethodLocker`:异步任务串行执行
- `Prismjs`:代码文件类型元数据
- `Text`:文本、参数、单位格式化
- `Time`:时间格式化与解析
- `Toolkit`:对象、数组、随机数、防抖等纯工具
该包不依赖 Vue、浏览器 DOM、`window`、`document` 或微信 `wx` API。
## 本地开发
```bash
pnpm install
pnpm run check
pnpm run build
```
当前其他本地仓库声明依赖版本 `^0.1.0`,并通过各自 `package.json` 的 pnpm override 指向本地目录;发布到内部 npm 仓库后,移除该本地 override 即可使用正式版本。
+25
View File
@@ -0,0 +1,25 @@
{
"name": "timi-ts",
"version": "0.1.0",
"description": "平台无关的 TypeScript 通用工具库",
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"sideEffects": false,
"files": [
"dist/**",
"README.md",
"LICENSE",
"package.json"
],
"scripts": {
"build": "tsc -p tsconfig.json",
"check": "tsc -p tsconfig.json --noEmit"
},
"engines": {
"node": ">=16.0.0"
},
"devDependencies": {
"typescript": "^5.9.3"
}
}
+24
View File
@@ -0,0 +1,24 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
importers:
.:
devDependencies:
typescript:
specifier: ^5.9.3
version: 5.9.3
packages:
typescript@5.9.3:
resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
engines: {node: '>=14.17'}
hasBin: true
snapshots:
typescript@5.9.3: {}
+2
View File
@@ -0,0 +1,2 @@
export * from "./types";
export * from "./utils";
+7
View File
@@ -0,0 +1,7 @@
export type Merge<T, R> = { [K in keyof T]: T[K] } & { [K in keyof R]: R[K] };
type MergeIntersection<T> = Pick<T, keyof T>;
export type PickRequiredUnion<P, U extends keyof P> = MergeIntersection<Merge<Required<Pick<P, U>>, Omit<P, U>>>;
export type PickNotRequiredUnion<P, U extends keyof P> = MergeIntersection<Merge<Pick<P, U>, Required<Omit<P, U>>>>;
+66
View File
@@ -0,0 +1,66 @@
export type EventArguments = readonly unknown[];
type EventCallback<Arguments extends EventArguments> = (...args: Arguments) => void;
interface EventListener {
callback: unknown;
invoke: (args: EventArguments) => void;
}
type EventArgumentsOf<EventMap extends object, Key extends keyof EventMap> = EventMap[Key] extends EventArguments
? EventMap[Key]
: never;
/** 强类型的进程内事件管理。 */
export default class Events<EventMap extends object> {
private readonly listeners = new Map<keyof EventMap, EventListener[]>();
/** 注册事件(会叠加)。 */
public register<Key extends keyof EventMap>(key: Key, callback: EventCallback<EventArgumentsOf<EventMap, Key>>): () => void {
const listener: EventListener = {
callback,
invoke: args => callback(...(args as EventArgumentsOf<EventMap, Key>))
};
const observers = this.listeners.get(key) ?? [];
observers.push(listener);
this.listeners.set(key, observers);
return () => this.removeListener(key, callback);
}
/** 重置并注册事件(不会叠加)。 */
public reset<Key extends keyof EventMap>(key: Key, callback: EventCallback<EventArgumentsOf<EventMap, Key>>): void {
this.listeners.set(key, []);
this.register(key, callback);
}
/** 移除指定事件的全部监听。 */
public remove<Key extends keyof EventMap>(key: Key): void {
this.listeners.delete(key);
}
/** 移除指定事件的单个监听。 */
public removeListener<Key extends keyof EventMap>(key: Key, callback: EventCallback<EventArgumentsOf<EventMap, Key>>): void {
const observers = this.listeners.get(key);
if (!observers) {
return;
}
const nextObservers = observers.filter(observer => observer.callback !== callback);
if (nextObservers.length) {
this.listeners.set(key, nextObservers);
} else {
this.listeners.delete(key);
}
}
/** 触发事件。 */
public emit<Key extends keyof EventMap>(key: Key, ...args: EventArgumentsOf<EventMap, Key>): void {
const observers = this.listeners.get(key);
if (!observers) {
return;
}
for (const observer of [...observers]) {
observer.invoke(args);
}
}
}
+61
View File
@@ -0,0 +1,61 @@
import Text from "./Text";
export const UNITS = ["B", "KB", "MB", "GB", "TB", "PB", "EB"] as const;
export type Unit = (typeof UNITS)[number];
/** 存储容量工具。 */
export default class IOSize {
public static BYTE = 1;
public static KB = IOSize.BYTE << 10;
public static MB = IOSize.KB << 10;
public static GB = IOSize.MB << 10;
public static TB = IOSize.GB << 10;
public static PB = IOSize.TB << 10;
public static EB = IOSize.PB << 10;
public static format(size?: number | null, fixed = 2, stopUnit?: Unit): string {
if (size === undefined || size === null || size <= 0) {
return "0 B";
}
let value = size;
for (let index = 0; index < UNITS.length; index += 1) {
const unit = UNITS[index];
if (value <= 1000 || index === UNITS.length - 1 || unit === stopUnit) {
return index === 0 ? `${value} B` : `${value.toFixed(fixed)} ${unit}`;
}
value /= 1024;
}
return "0 B";
}
public static parse(sizeString?: string | null): number {
if (sizeString === undefined || sizeString === null || !sizeString.trim()) {
return 0;
}
const normalized = sizeString.trim();
const matcher = /^([-+]?\d+(?:\.\d+)?)\s*([a-zA-Z]+)$/.exec(normalized);
if (!matcher) {
if (/^\d+$/.test(normalized)) {
return Number.parseInt(normalized, 10);
}
throw new Error(`invalid size format: ${sizeString}`);
}
const value = Number.parseFloat(matcher[1]);
if (value < 0) {
throw new Error(`size cannot be negative: ${value}`);
}
const rawUnit = matcher[2].toUpperCase();
const unit = UNITS.includes(rawUnit as Unit)
? rawUnit as Unit
: ({ K: "KB", M: "MB", G: "GB", T: "TB", P: "PB", E: "EB", B: "B" } as Record<string, Unit>)[rawUnit[0]];
if (!unit) {
throw new Error(`Unknown unit: ${rawUnit}`);
}
return Math.round(value * Math.pow(1024, UNITS.indexOf(unit)));
}
public static speed(value?: number | null): string {
return value === undefined || value === null ? "" : Text.unit(this.format(value, 2), " / s");
}
}
+36
View File
@@ -0,0 +1,36 @@
export class MethodLocker<R> {
private isLocked = false;
private queue: Array<{
task: () => Promise<R>;
resolve: (value: R | PromiseLike<R>) => void;
reject: (reason?: unknown) => void;
}> = [];
/** 串行执行异步任务,后续任务会按提交顺序等待。 */
public execute(task: () => Promise<R>): Promise<R> {
return new Promise<R>((resolve, reject) => {
this.queue.push({ task, resolve, reject });
void this.dequeue();
});
}
private async dequeue(): Promise<void> {
if (this.isLocked) {
return;
}
const nextTask = this.queue.shift();
if (!nextTask) {
return;
}
this.isLocked = true;
try {
nextTask.resolve(await nextTask.task());
} catch (error) {
nextTask.reject(error);
} finally {
this.isLocked = false;
void this.dequeue();
}
}
}
+85
View File
@@ -0,0 +1,85 @@
export const PrismjsType = {
PlainText: "PlainText",
Markdown: "Markdown",
JavaScript: "JavaScript",
TypeScript: "TypeScript",
Initialization: "Initialization",
PHP: "PHP",
SQL: "SQL",
XML: "XML",
CSS: "CSS",
VUE: "VUE",
LESS: "LESS",
Markup: "Markup",
YAML: "YAML",
Json: "Json",
Java: "Java",
Properties: "Properties",
NginxConf: "NginxConf",
ApacheConf: "ApacheConf"
} as const;
export type PrismjsType = (typeof PrismjsType)[keyof typeof PrismjsType];
export const PrismjsViewer = {
MARKDOWN: "MARKDOWN",
CODE: "CODE",
TEXT: "TEXT"
} as const;
export type PrismjsViewer = (typeof PrismjsViewer)[keyof typeof PrismjsViewer];
export type PrismjsProperties = {
extensions: string[];
prismjs: string;
viewer: PrismjsViewer;
};
/** 文件类型元数据,不包含 Prism.js 或 DOM 运行时。 */
export default class Prismjs {
private static instance: Prismjs;
readonly map = new Map<PrismjsType, PrismjsProperties>();
private constructor() {
this.map.set(PrismjsType.PlainText, { extensions: ["txt"], prismjs: "", viewer: PrismjsViewer.TEXT });
this.map.set(PrismjsType.Markdown, { extensions: ["md"], prismjs: "md", viewer: PrismjsViewer.MARKDOWN });
this.map.set(PrismjsType.JavaScript, { extensions: ["js"], prismjs: "js", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.VUE, { extensions: ["vue"], prismjs: "html", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.TypeScript, { extensions: ["ts"], prismjs: "ts", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.Initialization, { extensions: ["ini"], prismjs: "ini", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.PHP, { extensions: ["php"], prismjs: "php", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.SQL, { extensions: ["sql"], prismjs: "sql", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.XML, { extensions: ["xml", "fxml", "wxml"], prismjs: "xml", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.CSS, { extensions: ["css", "wxss"], prismjs: "css", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.LESS, { extensions: ["less"], prismjs: "less", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.Markup, { extensions: ["htm", "html"], prismjs: "markup", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.YAML, { extensions: ["yml", "yaml"], prismjs: "yaml", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.Json, { extensions: ["json"], prismjs: "json", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.Java, { extensions: ["java"], prismjs: "java", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.Properties, { extensions: ["properties"], prismjs: "properties", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.NginxConf, { extensions: [], prismjs: "nginx", viewer: PrismjsViewer.CODE });
this.map.set(PrismjsType.ApacheConf, { extensions: [], prismjs: "apacheconf", viewer: PrismjsViewer.CODE });
}
private static getInstance(): Prismjs {
Prismjs.instance ??= new Prismjs();
return Prismjs.instance;
}
public static typeFromFileName(fileName: string): PrismjsType | undefined {
const extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (!extension) {
return undefined;
}
for (const [type, properties] of this.getInstance().map) {
if (properties.extensions.includes(extension)) {
return type;
}
}
return undefined;
}
public static getFileProperties(type: PrismjsType): PrismjsProperties | undefined {
return this.getInstance().map.get(type);
}
}
+84
View File
@@ -0,0 +1,84 @@
export default class Text {
public static keyValue(obj: object, assign: string, split: string): string {
let result = "";
Object.entries(obj).forEach(([key, value]) => {
result += `${key}${assign}${value}${split}`;
});
return result.substring(0, result.length - split.length);
}
public static urlArgs(obj?: Record<string, unknown>): string {
if (!obj) {
return "";
}
const args: string[] = [];
Object.entries(obj).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach(item => {
args.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(item))}`);
});
return;
}
if (value !== undefined && value !== null) {
args.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
}
});
return args.join("&");
}
public static template(template: string, variables: Record<string, unknown>): string {
return template.replace(/\$\{(\w+)}/g, (_, key: string) => String(variables[key]));
}
public static pad(value: number | string, length = 2, fill = "0"): string {
return value.toString().padStart(length, fill);
}
public static unitCompact(value: number | string | null | undefined, unit: string, fixed = 0): string {
return this.unit(value, unit, fixed, true);
}
public static unit(value: number | string | null | undefined, unit: string, fixed = 0, compact = false): string {
if (value === null || value === undefined) {
return "";
}
if (typeof value === "string" && !value.trim()) {
return "";
}
const text = typeof value === "number"
? Number.isNaN(value) ? "" : value.toFixed(fixed)
: value.trim();
return text ? `${text}${compact ? "" : " "}${unit}` : "";
}
public static display(value: string | number | null | undefined): string {
if (typeof value === "string") {
return value.trim();
}
if (typeof value === "number" && Number.isFinite(value)) {
return value.toString();
}
return "";
}
public static displayBool(value: boolean | null | undefined, onTrue = "true", onFalse = "false"): string {
if (value === null || value === undefined) {
return "";
}
return value ? onTrue : onFalse;
}
/** 根据背景色返回更易读的文本色。 */
public static readableColor(color: string): "#111" | "#FFF" {
const match = color.trim().match(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/);
if (!match) {
return "#111";
}
const hex = match[1];
const rgb = hex.length === 3
? [parseInt(hex[0] + hex[0], 16), parseInt(hex[1] + hex[1], 16), parseInt(hex[2] + hex[2], 16)]
: [parseInt(hex.slice(0, 2), 16), parseInt(hex.slice(2, 4), 16), parseInt(hex.slice(4, 6), 16)];
const luminance = 0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2];
return luminance < 186 ? "#FFF" : "#111";
}
}
+155
View File
@@ -0,0 +1,155 @@
import Toolkit from "./Toolkit";
import Text from "./Text";
export default class Time {
public static S = 1E3;
public static M = Time.S * 60;
public static H = Time.M * 60;
public static D = Time.H * 24;
public static now(): number {
return Date.now();
}
public static toTimestamp(date: Date): number {
return date.getTime();
}
public static toDateObject(unix?: number | Date): Date | undefined {
if (!unix) return undefined;
return unix instanceof Date ? unix : new Date(unix);
}
public static toTime(unix?: number | Date): string {
if (!unix) return "";
const date = unix instanceof Date ? unix : new Date(unix);
return `${Text.pad(date.getHours())}:${Text.pad(date.getMinutes())}`;
}
public static toLongTime(unix?: number): string {
if (!unix) return "";
const date = new Date(unix);
return `${Text.pad(date.getHours())}:${Text.pad(date.getMinutes())}:${Text.pad(date.getSeconds())}`;
}
public static toShortTime(unix?: number): string {
if (!unix) return "";
const date = new Date(unix);
return `${Text.pad(date.getMinutes())}:${Text.pad(date.getSeconds())}`;
}
public static toDate(unix?: number | Date): string {
const date = this.toDateObject(unix);
if (date) {
return `${date.getFullYear()}-${Text.pad(date.getMonth() + 1)}-${Text.pad(date.getDate())}`;
}
return "";
}
public static toDateTime(unix?: number | Date): string {
return unix ? `${this.toDate(unix)} ${this.toTime(unix)}` : "";
}
public static toLongDateTime(unix?: number): string {
return unix ? `${this.toDate(unix)} ${this.toLongTime(unix)}` : "";
}
/** 格式化相对日期;较远的时间显示为具体日期。 */
public static formatDate(unix?: number): string {
return this.formatDateTime(unix, false);
}
/** 格式化过去或未来的时间,返回相对描述或具体日期时间。 */
public static formatDateTime(unix?: number, withDetailTime = true): string {
if (!unix) return "";
const difference = unix - Date.now();
const duration = Math.abs(difference);
if (Time.D * 4 < duration) {
return withDetailTime ? this.toDateTime(unix) : this.toDate(unix);
}
const isFuture = 0 < difference;
return this.formatRelativeTime(duration, isFuture ? "后" : "前", isFuture ? "稍后" : "刚刚");
}
/** 将非负时间间隔转换为相对时间文案。 */
private static formatRelativeTime(duration: number, suffix: "前" | "后", fallback: "刚刚" | "稍后"): string {
if (duration < Time.M) return fallback;
if (duration < Time.H) return `${Math.floor(duration / Time.M)} 分钟${suffix}`;
if (duration < Time.D) return `${Math.floor(duration / Time.H)} 小时${suffix}`;
return `${Math.floor(duration / Time.D)} 天${suffix}`;
}
public static between(begin: Date, end = new Date()): {
l: number;
y: number;
d: number;
h: number;
m: number;
s: number;
ms: number
} {
const second = 1E3;
const minute = 6E4;
const hour = 36E5;
const day = 864E5;
const year = 31536E6;
const length = end.getTime() - begin.getTime();
const y = Math.floor(length / year);
const d = Math.floor(length / day - y * 365);
const h = Math.floor((length - (y * 365 + d) * day) / hour);
const m = Math.floor((length - (y * 365 + d) * day - h * hour) / minute);
const s = Math.floor((length - (y * 365 + d) * day - h * hour - m * minute) / second);
const ms = Math.floor(((length - (y * 365 + d) * day - h * hour - m * minute) / second - s) * second);
return { l: length, y, d, h, m, s, ms };
}
public static duration(totalMs?: number | null, includeMilliseconds = false): string {
if (totalMs === null || totalMs === undefined) return "";
let remain = Math.floor(totalMs);
const years = Math.floor(remain / (Time.D * 365));
remain %= Time.D * 365;
const days = Math.floor(remain / Time.D);
remain %= Time.D;
const hours = Math.floor(remain / Time.H);
remain %= Time.H;
const minutes = Math.floor(remain / Time.M);
remain %= Time.M;
const seconds = Math.floor(remain / Time.S);
remain %= Time.S;
const parts: string[] = [];
Toolkit.doWhere(years > 0, () => parts.push(`${years} 年`));
Toolkit.doWhere(days > 0, () => parts.push(`${days} 天`));
Toolkit.doWhere(hours > 0, () => parts.push(`${hours} 小时`));
Toolkit.doWhere(minutes > 0, () => parts.push(`${minutes} 分钟`));
Toolkit.doWhere(seconds > 0, () => parts.push(`${seconds} 秒`));
Toolkit.doWhere(includeMilliseconds && remain > 0, () => parts.push(`${remain} 毫秒`));
return parts.join(" ");
}
public static toMediaTime(seconds: number): string {
const value = Math.floor(seconds);
const hours = Math.floor(value / 3600);
const minutes = Math.floor((value % 3600) / 60);
const second = value % 60;
return hours > 0 ? `${hours}:${Text.pad(minutes)}:${Text.pad(second)}` : `${Text.pad(minutes)}:${Text.pad(second)}`;
}
public static parseToMS(timeString: string): number {
if (!timeString || !timeString.trim()) throw new Error("not found timeStr");
const matcher = /^(\d+(?:\.\d+)?)(ms|[dhms])?$/.exec(timeString.replace(/\s+/g, "").toLowerCase());
if (!matcher) throw new Error(`invalid format: ${timeString}`);
const value = Number.parseFloat(matcher[1]);
switch (matcher[2]) {
case "s":
return Math.round(value * Time.S);
case "m":
return Math.round(value * Time.M);
case "h":
return Math.round(value * Time.H);
case "d":
return Math.round(value * Time.D);
default:
return Math.round(value);
}
}
}
+136
View File
@@ -0,0 +1,136 @@
export default class Toolkit {
public static isFunction(value: unknown): value is (...args: any[]) => any { return typeof value === "function"; }
public static isArray(value: unknown): value is unknown[] { return Array.isArray(value); }
public static isString(value: unknown): value is string { return typeof value === "string"; }
public static isSymbol(value: unknown): value is symbol { return typeof value === "symbol"; }
public static isObject(value: unknown): value is Record<string, unknown> { return value !== null && typeof value === "object"; }
public static isNumber(value: unknown): value is number { return typeof value === "number" && !Number.isNaN(value); }
public static guid(): string {
const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
return `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4() + s4() + s4()}`;
}
public static className(...values: unknown[]): string {
const classes: string[] = [];
values.forEach(value => {
if (!value) return;
if (this.isString(value)) classes.push(value);
else if (this.isArray(value)) {
const nested = this.className(...value);
if (nested) classes.push(nested);
} else if (this.isObject(value)) {
Object.entries(value).forEach(([name, enabled]) => { if (enabled) classes.push(name); });
}
});
return classes.join(" ");
}
public static isEmpty(value: unknown): boolean {
if (this.isString(value)) return value.trim().length === 0;
if (this.isArray(value)) return value.length === 0;
if (this.isFunction(value)) return this.isEmpty(value());
return value === undefined || value === null;
}
public static isNotEmpty(value: unknown): boolean { return !this.isEmpty(value); }
public static async sleep(milliseconds: number): Promise<void> {
await new Promise<void>(resolve => setTimeout(resolve, milliseconds));
}
public static toNumber(value: string, fallback?: number): number | undefined {
if (!value) return fallback;
const number = Number(value);
return Number.isFinite(number) ? number : fallback;
}
public static async(callback: (...args: any[]) => any): void { setTimeout(callback, 0); }
public static random(min = 0, max = 100): number { return Math.floor(Math.random() * (max + 1 - min)) + min; }
public static randomDouble(min = 0, max = 1): number { return Math.random() * (max - min) + min; }
public static deepClone<T>(origin: T): T {
if (origin === null || typeof origin !== "object") return origin;
if (Array.isArray(origin)) return origin.map(item => this.deepClone(item)) as T;
const result: Record<string, unknown> = {};
Object.entries(origin as Record<string, unknown>).forEach(([key, value]) => { result[key] = this.deepClone(value); });
return result as T;
}
public static toObject(map: Map<unknown, unknown>): Record<string, unknown> {
return Array.from(map.entries()).reduce<Record<string, unknown>>((result, [key, value]) => {
result[String(key)] = value ?? null;
return result;
}, {});
}
public static uuid(): string {
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
const lengths = [8, 4, 4, 4, 12];
return lengths.map(length => {
let value = "";
for (let index = 0; index < length; index += 1) value += chars[this.random(0, chars.length - 1)];
return value;
}).join("-");
}
public static keyFromValue<T extends Record<string, unknown>>(object: T, value: unknown): string | undefined {
return Object.keys(object).find(key => object[key] === value);
}
public static debounce<T extends (...args: any[]) => any>(callback: T, immediate = true, delay = 300): ((...args: Parameters<T>) => void) & { cancel(): void } {
let timerId: ReturnType<typeof setTimeout> | null = null;
let leading = immediate;
const cancel = () => {
if (timerId !== null) { clearTimeout(timerId); timerId = null; }
leading = immediate;
};
const debounced = (...args: Parameters<T>): void => {
if (timerId !== null) { clearTimeout(timerId); timerId = null; }
if (leading) {
callback(...args);
leading = false;
timerId = setTimeout(() => { leading = immediate; timerId = null; }, delay);
} else {
timerId = setTimeout(() => { callback(...args); leading = immediate; timerId = null; }, delay);
}
};
debounced.cancel = cancel;
return debounced as ((...args: Parameters<T>) => void) & { cancel(): void };
}
public static doWhere(condition: boolean | (() => boolean), callback: () => void): void {
if (typeof condition === "function" ? condition() : condition) callback();
}
public static doNotNull<T>(value: T | null | undefined, callback: (value: T) => void): void {
if (value) callback(value);
}
public static setRandomInterval(config: {
handler: (() => void) | ((value: number) => void);
handleRate?: number;
interval?: number;
min?: number;
max?: number;
}): ReturnType<typeof setInterval> {
const { handler, handleRate = 1, interval, min, max } = config;
return setInterval(() => {
if (Math.random() >= handleRate) return;
if (min !== undefined && max !== undefined) (handler as (value: number) => void)(this.randomDouble(min, max));
else (handler as () => void)();
}, interval);
}
public static formatJson(jsonValue?: string | object): string {
if (jsonValue === undefined || jsonValue === null) return "";
if (typeof jsonValue === "string") {
const value = jsonValue.trim();
if (!value) return "";
try { return JSON.stringify(JSON.parse(value), null, 4); } catch { return value; }
}
return JSON.stringify(jsonValue, null, 4);
}
}
+10
View File
@@ -0,0 +1,10 @@
export { default as Events } from "./Events";
export { default as IOSize } from "./IOSize";
export { default as Prismjs } from "./Prismjs";
export { default as Text } from "./Text";
export { default as Time } from "./Time";
export { default as Toolkit } from "./Toolkit";
export * from "./IOSize";
export * from "./MethodLocker";
export * from "./Prismjs";
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2018",
"module": "CommonJS",
"moduleResolution": "Node",
"rootDir": "src",
"outDir": "dist",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"lib": ["ES2018", "DOM"]
},
"include": ["src/**/*.ts"]
}