Differential D25540 Diff 1891 src/infrastructure/markup/markuprule/PhutilRemarkupHexColorCodeRule.php
Changeset View
Changeset View
Standalone View
Standalone View
src/infrastructure/markup/markuprule/PhutilRemarkupHexColorCodeRule.php
- This file was added.
<?php | |||||
final class PhutilRemarkupHexColorCodeRule | |||||
extends PhabricatorRemarkupCustomInlineRule { | |||||
public function getPriority() { | |||||
return 1000.0; | |||||
} | |||||
public function apply($text) { | |||||
// Match {#FFFFFF} | |||||
valerio.bozzolan: oh NO extra newline here (nuclear alarm sound) | |||||
return preg_replace_callback( | |||||
'@\B\{(#([0-9a-fA-F]{3}){1,2})\}@', | |||||
array($this, 'markupHexColorCodedText'), | |||||
Done Inline Actionsrepeat exactly 3 times for the 3 digit codes, then repeat that sequence exactly 1 or 2 times for 3 or 6 digits. 20after4: repeat exactly 3 times for the 3 digit codes, then repeat that sequence exactly 1 or 2 times… | |||||
$text); | |||||
} | |||||
protected function contrastingColor($color_code) { | |||||
$match = ltrim($color_code, '#'); | |||||
$colors_hex = str_split($match, strlen($match) / 3); | |||||
list($r, $g, $b) = array_map('hexdec', $colors_hex); | |||||
// Calculation adapted from Myndex, CC BY-SA 4.0 | |||||
// https://stackoverflow.com/a/69869976 | |||||
$y = pow((double)$r / 255.0, 2.2) * 0.2126 + | |||||
pow((double)$g / 255.0, 2.2) * 0.7152 + | |||||
Done Inline ActionsMaybe we can move public methods above, so to have protected methods below valerio.bozzolan: Maybe we can move public methods above, so to have protected methods below | |||||
pow((double)$b / 255.0, 2.2) * 0.0722; | |||||
return ($y < 0.34) ? 'white' : 'black'; | |||||
Done Inline Actionscan the repeat syntax say "exactly 6 times" avivey: can the repeat syntax say "exactly 6 times" | |||||
Done Inline ActionsGood catch. 20after4: Good catch. | |||||
} | |||||
protected function markupHexColorCodedText(array $matches) { | |||||
if ($this->getEngine()->isTextMode()) { | |||||
$result = $matches[1]; | |||||
} else { | |||||
if (count($matches) < 2) { | |||||
return $matches[0]; | |||||
} else { | |||||
$len = strlen($matches[1]); | |||||
if (7 !== $len && 4 !== $len) { | |||||
return $matches[0]; | |||||
} | |||||
} | |||||
$match = $matches[1]; | |||||
$fg = $this->contrastingColor($match); | |||||
$result = phutil_tag( | |||||
'tt', | |||||
Done Inline ActionsI think we use {$foo} avivey: I think we use `{$foo}` | |||||
array( | |||||
'class' => 'remarkup-monospaced', | |||||
'style' => "color: {$fg}; background-color: {$match};", | |||||
), | |||||
$match); | |||||
} | |||||
return $this->getEngine()->storeText($result); | |||||
} | |||||
} |
Content licensed under Creative Commons Attribution-ShareAlike 4.0 (CC-BY-SA) unless otherwise noted; code licensed under Apache 2.0 or other open source licenses. · CC BY-SA 4.0 · Apache 2.0
oh NO extra newline here (nuclear alarm sound)