chg: [widgets] Added support of scoped CSS

pull/5707/head
mokaddem 2020-03-19 14:05:37 +01:00
parent 55bcc4fa47
commit f9ae0bef48
No known key found for this signature in database
GPG Key ID: 164C473F627A06FA
1 changed files with 43 additions and 2 deletions

View File

@ -1,6 +1,47 @@
<div id="widgetContentInner_<?= h($widget_id) ?>">
<?php
function endsWith($haystack, $needle)
{
$length = strlen($needle);
if ($length == 0) {
return true;
}
return (substr($haystack, -$length) === $needle);
}
function preppendScopedId($widgetCSS, $seed)
{
$prependSelector = sprintf('[data-scoped="%s"]', $seed);
$cssLines = explode("\n", $widgetCSS);
foreach ($cssLines as $i => $line) {
if (strlen($line) > 0) {
if (endsWith($line, "{")) {
$cssLines[$i] = sprintf("%s %s", $prependSelector, $line);
}
}
}
$cssScopedLines = implode(PHP_EOL, $cssLines);
return sprintf("<style>%s%s%s</style>", PHP_EOL, $cssScopedLines, PHP_EOL);
}
$widgetHtml = $this->element('/dashboard/Widgets/' . $config['render']);
$widgetCSS = "";
$seed = "";
$styleTag = "<style scoped>";
$styleClosingTag = "</style>";
$styleTagIndex = strpos($widgetHtml, $styleTag);
$closingStyleTagIndex = strpos($widgetHtml, $styleClosingTag) + strlen($styleClosingTag);
if ($styleTagIndex !== false && $closingStyleTagIndex !== false && $closingStyleTagIndex > $styleTagIndex) { // enforced scoped css
$seed = rand();
$widgetCSS = substr($widgetHtml, $styleTagIndex, $closingStyleTagIndex);
$widgetHtml = str_replace($widgetCSS, "", $widgetHtml); // remove CSS
$widgetCSS = str_replace($styleTag, "", $widgetCSS); // remove the style node
$widgetCSS = str_replace($styleClosingTag, "", $widgetCSS); // remove closing style node
$widgetCSS = preppendScopedId($widgetCSS, $seed);
}
?>
<div id="widgetContentInner_<?= h($widget_id) ?>" <?php echo !empty($seed) ? sprintf("data-scoped=\"%s\" ", $seed) : "" ?>>
<?php
echo $this->element('/dashboard/Widgets/' . $config['render']);
echo $widgetHtml;
echo $widgetCSS;
?>
</div>
<script type="text/javascript">