53 lines
1.4 KiB
TypeScript
53 lines
1.4 KiB
TypeScript
import { HTMLColorNameTable } from './HTMLColorNameTable';
|
|
import { HTMLColor } from './HTMLColor';
|
|
import { RGBColor } from './RGBColor';
|
|
import { HSLColor } from './HSLColor';
|
|
|
|
export class HTMLColorParser
|
|
{
|
|
static fromString( colorString:string )
|
|
{
|
|
colorString = colorString.trim();
|
|
|
|
let hexMatcher = /^#[0-9a-f]{6}([0-9a-f][0-9a-f])?$/i;
|
|
let rgbMatcher = /^rgba?\(/;
|
|
let hslMatcher = /^hsla?\(/;
|
|
|
|
|
|
if ( HTMLColorNameTable.contains( colorString ) )
|
|
{
|
|
colorString = HTMLColorNameTable.getHexColorFromName( colorString );
|
|
}
|
|
|
|
if ( hexMatcher.test( colorString ) )
|
|
{
|
|
return HTMLColorParser.fromStringHexColor( colorString );
|
|
}
|
|
else if ( rgbMatcher.test ( colorString ) )
|
|
{
|
|
return RGBColor.fromString( colorString );
|
|
}
|
|
else if ( hslMatcher.test( colorString ) )
|
|
{
|
|
return HSLColor.fromString( colorString );
|
|
}
|
|
|
|
console.warn( `Couldn't parse: "${colorString}"`)
|
|
return null;
|
|
|
|
}
|
|
|
|
static fromStringHexColor( colorString:string )
|
|
{
|
|
colorString = colorString.replace( "#", "" );
|
|
|
|
let r = parseInt( colorString.substring( 0, 2 ), 16 );
|
|
let g = parseInt( colorString.substring( 2, 4 ), 16 );
|
|
let b = parseInt( colorString.substring( 4, 6 ), 16 );
|
|
|
|
let a = colorString.length === 6 ?
|
|
255 : parseInt( colorString.substring( 6, 8 ), 16 );
|
|
|
|
return new RGBColor( r / 255, g / 255, b / 255, a / 255 );
|
|
}
|
|
} |