Compare commits

...

3 Commits

Author SHA1 Message Date
0142904414 Added color utilities
All checks were successful
Build / Build NPM Project (push) Successful in 1m21s
Build / Tag Version (push) Successful in 20s
Build / Publish Docs (push) Successful in 36s
2026-03-01 21:53:29 -05:00
ddaf5c9957 Exclude all JS keywords from template variable extraction
All checks were successful
Build / Publish Docs (push) Successful in 32s
Build / Build NPM Project (push) Successful in 52s
Build / Tag Version (push) Successful in 6s
2026-02-17 11:42:17 -05:00
18261dc5da Global TTS interrupt suppression (its being a bitch)
All checks were successful
Build / Publish Docs (push) Successful in 49s
Build / Build NPM Project (push) Successful in 1m9s
Build / Tag Version (push) Successful in 10s
2026-01-19 15:29:01 -05:00
6 changed files with 102 additions and 40 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.28.11", "version": "0.28.14",
"description": "Utility library", "description": "Utility library",
"author": "Zak Timson", "author": "Zak Timson",
"license": "MIT", "license": "MIT",

View File

@@ -1,12 +1,73 @@
import {dec2Hex} from './math.ts';
/** /**
* Determine if either black or white provides more contrast to the provided color * Determine if either black or white provides more contrast to the provided color
* @param {string} background Color to compare against * @param {string} color Color to compare against
* @return {"white" | "black"} Color with the most contrast * @return {"white" | "black"} Color with the most contrast
*/ */
export function contrast(background: string): 'white' | 'black' { export function contrast(color: string): 'white' | 'black' {
const exploded = background?.match(background.length >= 6 ? /[0-9a-fA-F]{2}/g : /[0-9a-fA-F]/g); const exploded = color?.match(color.length >= 6 ? /[0-9a-fA-F]{2}/g : /[0-9a-fA-F]/g);
if(!exploded || exploded?.length < 3) return 'black'; if(!exploded || exploded?.length < 3) return 'black';
const [r, g, b] = exploded.map(hex => parseInt(hex.length == 1 ? `${hex}${hex}` : hex, 16)); const [r, g, b] = exploded.map(hex => parseInt(hex.length == 1 ? `${hex}${hex}` : hex, 16));
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255; const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
return luminance > 0.5 ? 'black' : 'white'; return luminance > 0.5 ? 'black' : 'white';
} }
export function hex2Int(hex: string): {r: number, g: number, b: number} {
let r = 0, g = 0, b = 0;
if (hex.length === 4) {
r = parseInt(hex[1] + hex[1], 16);
g = parseInt(hex[2] + hex[2], 16);
b = parseInt(hex[3] + hex[3], 16);
} else {
r = parseInt(hex.slice(1, 3), 16);
g = parseInt(hex.slice(3, 5), 16);
b = parseInt(hex.slice(5, 7), 16);
}
return {r, g, b};
}
export function hue2rgb(p: number, q: number, t: number): number {
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1 / 6) return p + (q - p) * 6 * t;
if(t < 1 / 2) return q;
if(t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
export function int2Hex(r: number, g: number, b: number) {
return '#' + dec2Hex(r) + dec2Hex(g) + dec2Hex(b);
}
/**
* Adjusts the darkness of a hex color.
* @param {string} hex - The hex color (e.g., '#ff0000').
* @param {number} amount - A value between -1 (black) and 1 (white)
*/
export function shadeColor(hex: string, amount: number) {
let {r, g, b} = hex2Int(hex);
r /= 255; g /= 255; b /= 255;
const max = Math.max(r, g, b), min = Math.min(r, g, b);
let h, s, l = (max + min) / 2;
if (max === min) {
h = s = 0;
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
default: h = 0; break;
}
h /= 6;
}
// Adjust Lightness
l = Math.max(0, Math.min(1, l + amount));
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
return int2Hex(hue2rgb(p, q, h + 1/3), hue2rgb(p, q, h), hue2rgb(p, q, h - 1/3));
};

View File

@@ -30,6 +30,10 @@ export function dec2Frac(num: number, maxDen=1000): string {
(numerator ? numerator + '/' + closest.d : ''); (numerator ? numerator + '/' + closest.d : '');
} }
export function dec2Hex(num: number): string {
const hex = Math.round(num * 255).toString(16);
return hex.length === 1 ? '0' + hex : hex;
}
/** /**
* Convert fraction to decimal number * Convert fraction to decimal number
@@ -42,7 +46,7 @@ export function dec2Frac(num: number, maxDen=1000): string {
* @param {string} frac Fraction to convert * @param {string} frac Fraction to convert
* @return {number} Faction as a decimal * @return {number} Faction as a decimal
*/ */
export function fracToDec(frac: string) { export function frac2Dec(frac: string) {
let split = frac.split(' '); let split = frac.split(' ');
const whole = split.length == 2 ? Number(split[0]) : 0; const whole = split.length == 2 ? Number(split[0]) : 0;
split = (<string>split.pop()).split('/'); split = (<string>split.pop()).split('/');

View File

@@ -8,7 +8,16 @@ export class TemplateError extends BadRequestError { }
export function findTemplateVars(html: string): Record<string, any> { export function findTemplateVars(html: string): Record<string, any> {
const variables = new Set<string>(); const variables = new Set<string>();
const arrays = new Set<string>(); const arrays = new Set<string>();
const excluded = new Set<string>(['true', 'false', 'null', 'undefined']); const excluded = new Set([
'let', 'const', 'var', 'function', 'if', 'while', 'do', 'this', 'typeof',
'new', 'instanceof', 'in', 'for', 'else', 'case', 'break', 'continue',
'switch', 'default', 'with', 'eval', 'arguments', 'void', 'delete', 'null',
'undefined', 'true', 'false', 'async', 'await', 'try', 'catch', 'finally',
'throw', 'return', 'yield', 'debugger', 'extends', 'import', 'export',
'class', 'super', 'static', 'get', 'set', 'constructor', 'enum', 'implements',
'interface', 'package', 'private', 'protected', 'public', 'abstract', 'final',
'native', 'synchronized', 'throws', 'transient', 'volatile'
]);
// Extract & exclude loop variables, mark arrays // Extract & exclude loop variables, mark arrays
for (const loop of matchAll(html, /\{\{\s*?\*\s*?(.+?)\s+in\s+(.+?)\s*?}}/g)) { for (const loop of matchAll(html, /\{\{\s*?\*\s*?(.+?)\s+in\s+(.+?)\s*?}}/g)) {
@@ -70,6 +79,7 @@ export function findTemplateVars(html: string): Record<string, any> {
} }
return result; return result;
} }
export async function renderTemplate(template: string, data: any, fetch?: (file: string) => Promise<string>) { export async function renderTemplate(template: string, data: any, fetch?: (file: string) => Promise<string>) {
if(!fetch) fetch = (file) => { throw new TemplateError(`Unable to fetch template: ${file}`); } if(!fetch) fetch = (file) => { throw new TemplateError(`Unable to fetch template: ${file}`); }

View File

@@ -2,6 +2,7 @@ import {removeEmojis} from './string.ts';
export class TTS { export class TTS {
private static readonly QUALITY_PATTERNS = ['Google', 'Microsoft', 'Samantha', 'Premium', 'Natural', 'Neural']; private static readonly QUALITY_PATTERNS = ['Google', 'Microsoft', 'Samantha', 'Premium', 'Natural', 'Neural'];
private static _errorHandlerInstalled = false;
private _currentUtterance: SpeechSynthesisUtterance | null = null; private _currentUtterance: SpeechSynthesisUtterance | null = null;
private _voicesLoaded: Promise<void>; private _voicesLoaded: Promise<void>;
@@ -35,8 +36,8 @@ export class TTS {
if(this._currentUtterance && value) this._currentUtterance.voice = value; if(this._currentUtterance && value) this._currentUtterance.voice = value;
} }
/** Create a TTS instance with optional configuration */
constructor(config?: {rate?: number; pitch?: number; volume?: number; voice?: SpeechSynthesisVoice | null}) { constructor(config?: {rate?: number; pitch?: number; volume?: number; voice?: SpeechSynthesisVoice | null}) {
TTS.installErrorHandler();
this._voicesLoaded = this.initializeVoices(); this._voicesLoaded = this.initializeVoices();
if(config) { if(config) {
if(config.rate !== undefined) this._rate = config.rate; if(config.rate !== undefined) this._rate = config.rate;
@@ -46,7 +47,14 @@ export class TTS {
} }
} }
/** Initializes voice loading and sets default voice if needed */ private static installErrorHandler(): void {
if(this._errorHandlerInstalled) return;
window.addEventListener('unhandledrejection', (event) => {
if(event.reason?.error === 'interrupted' && event.reason instanceof SpeechSynthesisErrorEvent) event.preventDefault();
});
this._errorHandlerInstalled = true;
}
private initializeVoices(): Promise<void> { private initializeVoices(): Promise<void> {
return new Promise((resolve) => { return new Promise((resolve) => {
const voices = window.speechSynthesis.getVoices(); const voices = window.speechSynthesis.getVoices();
@@ -64,11 +72,6 @@ export class TTS {
}); });
} }
/**
* Selects the best available TTS voice, prioritizing high-quality options
* @param lang Speaking language
* @returns Highest quality voice
*/
private static bestVoice(lang = 'en'): SpeechSynthesisVoice | undefined { private static bestVoice(lang = 'en'): SpeechSynthesisVoice | undefined {
const voices = window.speechSynthesis.getVoices(); const voices = window.speechSynthesis.getVoices();
for (const pattern of this.QUALITY_PATTERNS) { for (const pattern of this.QUALITY_PATTERNS) {
@@ -78,14 +81,12 @@ export class TTS {
return voices.find(v => v.lang.startsWith(lang)); return voices.find(v => v.lang.startsWith(lang));
} }
/** Cleans text for TTS by removing emojis, markdown and code block */
private static cleanText(text: string): string { private static cleanText(text: string): string {
return removeEmojis(text) return removeEmojis(text)
.replace(/```[\s\S]*?```/g, ' code block ') .replace(/```[\s\S]*?```/g, ' code block ')
.replace(/[#*_~`]/g, ''); .replace(/[#*_~`]/g, '');
} }
/** Creates a speech utterance with current options */
private createUtterance(text: string): SpeechSynthesisUtterance { private createUtterance(text: string): SpeechSynthesisUtterance {
const cleanedText = TTS.cleanText(text); const cleanedText = TTS.cleanText(text);
const utterance = new SpeechSynthesisUtterance(cleanedText); const utterance = new SpeechSynthesisUtterance(cleanedText);
@@ -97,7 +98,6 @@ export class TTS {
return utterance; return utterance;
} }
/** Speaks text and returns a Promise which resolves once complete */
async speak(text: string): Promise<void> { async speak(text: string): Promise<void> {
if(!text.trim()) return Promise.resolve(); if(!text.trim()) return Promise.resolve();
await this._voicesLoaded; await this._voicesLoaded;
@@ -117,25 +117,12 @@ export class TTS {
}); });
} }
/** Stops all TTS */
stop(): void { stop(): void {
if(this._currentUtterance) this._stoppedUtterances.add(this._currentUtterance); if(this._currentUtterance) this._stoppedUtterances.add(this._currentUtterance);
window.speechSynthesis.cancel(); window.speechSynthesis.cancel();
this._currentUtterance = null; this._currentUtterance = null;
} }
/**
* Initialize a stream that chunks text into sentences and speak them.
*
* @example
* const stream = tts.speakStream();
* stream.next("Hello ");
* stream.next("World. How");
* stream.next(" are you?");
* await stream.done();
*
* @returns Object with next function for passing chunk of streamed text and done for completing the stream
*/
speakStream(): {next: (text: string) => void, done: () => Promise<void>} { speakStream(): {next: (text: string) => void, done: () => Promise<void>} {
let buffer = ''; let buffer = '';
let streamPromise: Promise<void> = Promise.resolve(); let streamPromise: Promise<void> = Promise.resolve();

View File

@@ -1,4 +1,4 @@
import { dec2Frac, fracToDec } from '../src'; import { dec2Frac, frac2Dec } from '../src';
describe('Math Utilities', () => { describe('Math Utilities', () => {
describe('dec2Frac', () => { describe('dec2Frac', () => {
@@ -27,25 +27,25 @@ describe('Math Utilities', () => {
describe('fracToDec', () => { describe('fracToDec', () => {
it('should convert mixed fraction to decimal', () => { it('should convert mixed fraction to decimal', () => {
expect(fracToDec('1 1/4')).toBeCloseTo(1.25); expect(frac2Dec('1 1/4')).toBeCloseTo(1.25);
expect(fracToDec('2 1/2')).toBeCloseTo(2.5); expect(frac2Dec('2 1/2')).toBeCloseTo(2.5);
expect(fracToDec('3 3/4')).toBeCloseTo(3.75); expect(frac2Dec('3 3/4')).toBeCloseTo(3.75);
}); });
it('should convert fraction without whole part to decimal', () => { it('should convert fraction without whole part to decimal', () => {
expect(fracToDec('3/4')).toBeCloseTo(0.75); expect(frac2Dec('3/4')).toBeCloseTo(0.75);
expect(fracToDec('1/2')).toBeCloseTo(0.5); expect(frac2Dec('1/2')).toBeCloseTo(0.5);
expect(fracToDec('1/10')).toBeCloseTo(0.1); expect(frac2Dec('1/10')).toBeCloseTo(0.1);
}); });
it('should convert whole number fraction', () => { it('should convert whole number fraction', () => {
expect(fracToDec('4 0/1')).toBeCloseTo(4); expect(frac2Dec('4 0/1')).toBeCloseTo(4);
expect(fracToDec('0/1')).toBeCloseTo(0); expect(frac2Dec('0/1')).toBeCloseTo(0);
}); });
it('should handle zero correctly', () => { it('should handle zero correctly', () => {
expect(fracToDec('0/1')).toBeCloseTo(0); expect(frac2Dec('0/1')).toBeCloseTo(0);
expect(fracToDec('0 0/1')).toBeCloseTo(0); expect(frac2Dec('0 0/1')).toBeCloseTo(0);
}); });
}); });
}); });