1
0
mirror of https://github.com/Jermolene/TiddlyWiki5 synced 2024-11-26 19:47:20 +00:00

Update contrastcolour macro to use color.js

This commit is contained in:
Jeremy Ruston 2024-11-16 14:37:14 +00:00
parent 809465b6e2
commit cfabc92945
3 changed files with 25 additions and 13 deletions

View File

@ -29,27 +29,28 @@ exports.params = [
Run the macro
*/
exports.run = function(target,fallbackTarget,colourA,colourB) {
var rgbTarget = $tw.utils.parseCSSColor(target) || $tw.utils.parseCSSColor(fallbackTarget);
var rgbTarget = $tw.utils.parseCSSColorObject(target) || $tw.utils.parseCSSColorObject(fallbackTarget);
if(!rgbTarget) {
return colourA;
}
var rgbColourA = $tw.utils.parseCSSColor(colourA),
rgbColourB = $tw.utils.parseCSSColor(colourB);
var rgbColourA = $tw.utils.parseCSSColorObject(colourA),
rgbColourB = $tw.utils.parseCSSColorObject(colourB);
if(rgbColourA && !rgbColourB) {
return rgbColourA;
return colourA;
}
if(rgbColourB && !rgbColourA) {
return rgbColourB;
return colourB;
}
if(!rgbColourA && !rgbColourB) {
// If neither colour is readable, return a crude inverse of the target
return [255 - rgbTarget[0],255 - rgbTarget[1],255 - rgbTarget[2],rgbTarget[3]];
rgbTarget.srgb.r = 1 - rgbTarget.srgb.r;
rgbTarget.srgb.g = 1 - rgbTarget.srgb.g;
rgbTarget.srgb.b = 1 - rgbTarget.srgb.b;
return rgbTarget.display();
}
// Colour brightness formula derived from http://www.w3.org/WAI/ER/WD-AERT/#color-contrast
var brightnessTarget = rgbTarget[0] * 0.299 + rgbTarget[1] * 0.587 + rgbTarget[2] * 0.114,
brightnessA = rgbColourA[0] * 0.299 + rgbColourA[1] * 0.587 + rgbColourA[2] * 0.114,
brightnessB = rgbColourB[0] * 0.299 + rgbColourB[1] * 0.587 + rgbColourB[2] * 0.114;
return Math.abs(brightnessTarget - brightnessA) > Math.abs(brightnessTarget - brightnessB) ? colourA : colourB;
var aContrast = rgbColourA.contrast(rgbTarget,"DeltaPhi"),
bContrast = rgbColourB.contrast(rgbTarget,"DeltaPhi");
return aContrast > bContrast ? colourA : colourB;
};
})();

View File

@ -32,8 +32,7 @@ exports.parseCSSColor = function(colourString) {
Preferred way to parse a Color.js colour
*/
exports.parseCSSColorObject = function(colourString) {
var Color = require("$:/core/modules/utils/dom/color.js").Color,
c = null;
var c = null;
try {
c = new Color(colourString);
} catch(e) {

View File

@ -0,0 +1,12 @@
title: Macros/ContrastColour/ContrastColourBasic
description: Basic usage of contrastcolour macro
type: text/vnd.tiddlywiki-multiple
tags: [[$:/tags/wiki-test-spec]]
title: Output
Colour: <<contrastcolour target:#1e90ff fallbackTarget:#eecc66 colourA:#333333 colourB:#ffffff>>
+
title: ExpectedResult
<p>Colour: #ffffff</p>