Skip to content

retain CSSList and Rule comments when rendering CSS #351

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Dec 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/CSSList/AtRuleBlockList.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,14 @@ public function __toString()
*/
public function render(OutputFormat $oOutputFormat)
{
$sResult = $oOutputFormat->comments($this);
$sResult .= $oOutputFormat->sBeforeAtRuleBlock;
$sArgs = $this->sArgs;
if ($sArgs) {
$sArgs = ' ' . $sArgs;
}
$sResult = $oOutputFormat->sBeforeAtRuleBlock;
$sResult .= "@{$this->sType}$sArgs{$oOutputFormat->spaceBeforeOpeningBrace()}{";
$sResult .= parent::render($oOutputFormat);
$sResult .= $this->renderListContents($oOutputFormat);
$sResult .= '}';
$sResult .= $oOutputFormat->sAfterAtRuleBlock;
return $sResult;
Expand Down
16 changes: 9 additions & 7 deletions src/CSSList/CSSList.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,9 @@ public static function parseList(ParserState $oParserState, CSSList $oList)
$oParserState = new ParserState($oParserState, Settings::create());
}
$bLenientParsing = $oParserState->getSettings()->bLenientParsing;
$aComments = [];
while (!$oParserState->isEnd()) {
$comments = $oParserState->consumeWhiteSpace();
$aComments = array_merge($aComments, $oParserState->consumeWhiteSpace());
$oListItem = null;
if ($bLenientParsing) {
try {
Expand All @@ -86,11 +87,12 @@ public static function parseList(ParserState $oParserState, CSSList $oList)
return;
}
if ($oListItem) {
$oListItem->setComments($comments);
$oListItem->addComments($aComments);
$oList->append($oListItem);
}
$oParserState->consumeWhiteSpace();
$aComments = $oParserState->consumeWhiteSpace();
}
$oList->addComments($aComments);
if (!$bIsRoot && !$bLenientParsing) {
throw new SourceException("Unexpected end of document", $oParserState->currentLine());
}
Expand Down Expand Up @@ -125,7 +127,7 @@ private static function parseListItem(ParserState $oParserState, CSSList $oList)
$oParserState->currentLine()
);
}
$oParserState->setCharset($oAtRule->getCharset()->getString());
$oParserState->setCharset($oAtRule->getCharset());
}
return $oAtRule;
} elseif ($oParserState->comes('}')) {
Expand Down Expand Up @@ -172,10 +174,10 @@ private static function parseAtRule(ParserState $oParserState)
$oParserState->consumeUntil([';', ParserState::EOF], true, true);
return new Import($oLocation, $sMediaQuery ?: null, $iIdentifierLineNum);
} elseif ($sIdentifier === 'charset') {
$sCharset = CSSString::parse($oParserState);
$oCharsetString = CSSString::parse($oParserState);
$oParserState->consumeWhiteSpace();
$oParserState->consumeUntil([';', ParserState::EOF], true, true);
return new Charset($sCharset, $iIdentifierLineNum);
return new Charset($oCharsetString, $iIdentifierLineNum);
} elseif (self::identifierIs($sIdentifier, 'keyframes')) {
$oResult = new KeyFrame($iIdentifierLineNum);
$oResult->setVendorKeyFrame($sIdentifier);
Expand Down Expand Up @@ -402,7 +404,7 @@ public function __toString()
/**
* @return string
*/
public function render(OutputFormat $oOutputFormat)
protected function renderListContents(OutputFormat $oOutputFormat)
{
$sResult = '';
$bIsFirst = true;
Expand Down
2 changes: 1 addition & 1 deletion src/CSSList/Document.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ public function render(OutputFormat $oOutputFormat = null)
if ($oOutputFormat === null) {
$oOutputFormat = new OutputFormat();
}
return parent::render($oOutputFormat);
return $oOutputFormat->comments($this) . $this->renderListContents($oOutputFormat);
}

/**
Expand Down
5 changes: 3 additions & 2 deletions src/CSSList/KeyFrame.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,9 @@ public function __toString()
*/
public function render(OutputFormat $oOutputFormat)
{
$sResult = "@{$this->vendorKeyFrame} {$this->animationName}{$oOutputFormat->spaceBeforeOpeningBrace()}{";
$sResult .= parent::render($oOutputFormat);
$sResult = $oOutputFormat->comments($this);
$sResult .= "@{$this->vendorKeyFrame} {$this->animationName}{$oOutputFormat->spaceBeforeOpeningBrace()}{";
$sResult .= $this->renderListContents($oOutputFormat);
$sResult .= '}';
return $sResult;
}
Expand Down
22 changes: 18 additions & 4 deletions src/OutputFormat.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,13 @@ class OutputFormat
*/
public $bIgnoreExceptions = false;

/**
* Render comments for lists and RuleSets
*
* @var bool
*/
public $bRenderComments = false;

/**
* @var OutputFormatter|null
*/
Expand Down Expand Up @@ -314,8 +321,12 @@ public static function create()
public static function createCompact()
{
$format = self::create();
$format->set('Space*Rules', "")->set('Space*Blocks', "")->setSpaceAfterRuleName('')
->setSpaceBeforeOpeningBrace('')->setSpaceAfterSelectorSeparator('');
$format->set('Space*Rules', "")
->set('Space*Blocks', "")
->setSpaceAfterRuleName('')
->setSpaceBeforeOpeningBrace('')
->setSpaceAfterSelectorSeparator('')
->setRenderComments(false);
return $format;
}

Expand All @@ -327,8 +338,11 @@ public static function createCompact()
public static function createPretty()
{
$format = self::create();
$format->set('Space*Rules', "\n")->set('Space*Blocks', "\n")
->setSpaceBetweenBlocks("\n\n")->set('SpaceAfterListArgumentSeparator', ['default' => '', ',' => ' ']);
$format->set('Space*Rules', "\n")
->set('Space*Blocks', "\n")
->setSpaceBetweenBlocks("\n\n")
->set('SpaceAfterListArgumentSeparator', ['default' => '', ',' => ' '])
->setRenderComments(true);
return $format;
}
}
23 changes: 23 additions & 0 deletions src/OutputFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Sabberworm\CSS;

use Sabberworm\CSS\Comment\Commentable;
use Sabberworm\CSS\Parsing\OutputException;

class OutputFormatter
Expand Down Expand Up @@ -211,6 +212,28 @@ public function removeLastSemicolon($sString)
return implode(';', $sString);
}

/**
*
* @param array<Commentable> $aComments
* @return string
*/
public function comments(Commentable $oCommentable)
{
if (!$this->oFormat->bRenderComments) {
return '';
}

$sResult = '';
$aComments = $oCommentable->getComments();
$iLastCommentIndex = count($aComments) - 1;

foreach ($aComments as $i => $oComment) {
$sResult .= $oComment->render($this->oFormat);
$sResult .= $i === $iLastCommentIndex ? $this->spaceAfterBlocks() : $this->spaceBetweenBlocks();
}
return $sResult;
}

/**
* @param string $sSpaceString
*
Expand Down
8 changes: 4 additions & 4 deletions src/Parsing/ParserState.php
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ public function parseCharacter($bIsForIdentifier)
*/
public function consumeWhiteSpace()
{
$comments = [];
$aComments = [];
do {
while (preg_match('/\\s/isSu', $this->peek()) === 1) {
$this->consume(1);
Expand All @@ -214,16 +214,16 @@ public function consumeWhiteSpace()
$oComment = $this->consumeComment();
} catch (UnexpectedEOFException $e) {
$this->iCurrentPosition = $this->iLength;
return;
return $aComments;
}
} else {
$oComment = $this->consumeComment();
}
if ($oComment !== false) {
$comments[] = $oComment;
$aComments[] = $oComment;
}
} while ($oComment !== false);
return $comments;
return $aComments;
}

/**
Expand Down
22 changes: 12 additions & 10 deletions src/Property/Charset.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Sabberworm\CSS\Comment\Comment;
use Sabberworm\CSS\OutputFormat;
use Sabberworm\CSS\Value\CSSString;

/**
* Class representing an `@charset` rule.
Expand All @@ -16,9 +17,9 @@
class Charset implements AtRule
{
/**
* @var string
* @var CSSString
*/
private $sCharset;
private $oCharset;

/**
* @var int
Expand All @@ -31,12 +32,12 @@ class Charset implements AtRule
protected $aComments;

/**
* @param string $sCharset
* @param CSSString $oCharset
* @param int $iLineNo
*/
public function __construct($sCharset, $iLineNo = 0)
public function __construct(CSSString $oCharset, $iLineNo = 0)
{
$this->sCharset = $sCharset;
$this->oCharset = $oCharset;
$this->iLineNo = $iLineNo;
$this->aComments = [];
}
Expand All @@ -50,21 +51,22 @@ public function getLineNo()
}

/**
* @param string $sCharset
* @param string|CSSString $oCharset
*
* @return void
*/
public function setCharset($sCharset)
{
$this->sCharset = $sCharset;
$sCharset = $sCharset instanceof CSSString ? $sCharset : new CSSString($sCharset);
$this->oCharset = $sCharset;
}

/**
* @return string
*/
public function getCharset()
{
return $this->sCharset;
return $this->oCharset->getString();
}

/**
Expand All @@ -80,7 +82,7 @@ public function __toString()
*/
public function render(OutputFormat $oOutputFormat)
{
return "@charset {$this->sCharset->render($oOutputFormat)};";
return "{$oOutputFormat->comments($this)}@charset {$this->oCharset->render($oOutputFormat)};";
}

/**
Expand All @@ -96,7 +98,7 @@ public function atRuleName()
*/
public function atRuleArgs()
{
return $this->sCharset;
return $this->oCharset;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Property/Import.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public function __toString()
*/
public function render(OutputFormat $oOutputFormat)
{
return "@import " . $this->oLocation->render($oOutputFormat)
return $oOutputFormat->comments($this) . "@import " . $this->oLocation->render($oOutputFormat)
. ($this->sMediaQuery === null ? '' : ' ' . $this->sMediaQuery) . ';';
}

Expand Down
4 changes: 2 additions & 2 deletions src/Rule/Rule.php
Original file line number Diff line number Diff line change
Expand Up @@ -346,8 +346,8 @@ public function __toString()
*/
public function render(OutputFormat $oOutputFormat)
{
$sResult = "{$this->sRule}:{$oOutputFormat->spaceAfterRuleName()}";
if ($this->mValue instanceof Value) { //Can also be a ValueList
$sResult = "{$oOutputFormat->comments($this)}{$this->sRule}:{$oOutputFormat->spaceAfterRuleName()}";
if ($this->mValue instanceof Value) { // Can also be a ValueList
$sResult .= $this->mValue->render($oOutputFormat);
} else {
$sResult .= $this->mValue;
Expand Down
5 changes: 3 additions & 2 deletions src/RuleSet/AtRuleSet.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,13 @@ public function __toString()
*/
public function render(OutputFormat $oOutputFormat)
{
$sResult = $oOutputFormat->comments($this);
$sArgs = $this->sArgs;
if ($sArgs) {
$sArgs = ' ' . $sArgs;
}
$sResult = "@{$this->sType}$sArgs{$oOutputFormat->spaceBeforeOpeningBrace()}{";
$sResult .= parent::render($oOutputFormat);
$sResult .= "@{$this->sType}$sArgs{$oOutputFormat->spaceBeforeOpeningBrace()}{";
$sResult .= $this->renderRules($oOutputFormat);
$sResult .= '}';
return $sResult;
}
Expand Down
5 changes: 3 additions & 2 deletions src/RuleSet/DeclarationBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -812,18 +812,19 @@ public function __toString()
*/
public function render(OutputFormat $oOutputFormat)
{
$sResult = $oOutputFormat->comments($this);
if (count($this->aSelectors) === 0) {
// If all the selectors have been removed, this declaration block becomes invalid
throw new OutputException("Attempt to print declaration block with missing selector", $this->iLineNo);
}
$sResult = $oOutputFormat->sBeforeDeclarationBlock;
$sResult .= $oOutputFormat->sBeforeDeclarationBlock;
$sResult .= $oOutputFormat->implode(
$oOutputFormat->spaceBeforeSelectorSeparator() . ',' . $oOutputFormat->spaceAfterSelectorSeparator(),
$this->aSelectors
);
$sResult .= $oOutputFormat->sAfterDeclarationBlockSelectors;
$sResult .= $oOutputFormat->spaceBeforeOpeningBrace() . '{';
$sResult .= parent::render($oOutputFormat);
$sResult .= $this->renderRules($oOutputFormat);
$sResult .= '}';
$sResult .= $oOutputFormat->sAfterDeclarationBlock;
return $sResult;
Expand Down
11 changes: 6 additions & 5 deletions src/RuleSet/RuleSet.php
Original file line number Diff line number Diff line change
Expand Up @@ -266,23 +266,24 @@ public function __toString()
/**
* @return string
*/
public function render(OutputFormat $oOutputFormat)
protected function renderRules(OutputFormat $oOutputFormat)
{
$sResult = '';
$bIsFirst = true;
$oNextLevel = $oOutputFormat->nextLevel();
foreach ($this->aRules as $aRules) {
foreach ($aRules as $oRule) {
$sRendered = $oOutputFormat->safely(function () use ($oRule, $oOutputFormat) {
return $oRule->render($oOutputFormat->nextLevel());
$sRendered = $oNextLevel->safely(function () use ($oRule, $oNextLevel) {
return $oRule->render($oNextLevel);
});
if ($sRendered === null) {
continue;
}
if ($bIsFirst) {
$bIsFirst = false;
$sResult .= $oOutputFormat->nextLevel()->spaceBeforeRules();
$sResult .= $oNextLevel->spaceBeforeRules();
} else {
$sResult .= $oOutputFormat->nextLevel()->spaceBetweenRules();
$sResult .= $oNextLevel->spaceBetweenRules();
}
$sResult .= $sRendered;
}
Expand Down
Loading