added all files to project

This commit is contained in:
2022-03-10 10:36:59 +01:00
parent 09dd957b33
commit 46a936d7de
25351 changed files with 3883356 additions and 0 deletions
+18
View File
@@ -0,0 +1,18 @@
# Changelog
## 0.37.2
- Fixed: use HTTPS url instead of HTTP for postcss logo in README ([#39](https://github.com/stylelint/postcss-css-in-js/pull/39)).
## 0.37.1
- Fixed: maximum call stack size exceeded error ([#31](https://github.com/stylelint/postcss-css-in-js/pull/31)).
## 0.37.0
- Fixed: babel configuration conflict when using TypeScript ([#2](https://github.com/stylelint/postcss-css-in-js/pull/2)).
- Fixed: parsing/stringifying for nested tagged template literals ([#17](https://github.com/stylelint/postcss-css-in-js/pull/17)).
## Previous changes
See [postcss-jsx releases](https://github.com/gucong3000/postcss-jsx/releases).
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 刘祺
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+91
View File
@@ -0,0 +1,91 @@
# PostCSS CSS-in-JS Syntax
[![NPM version](https://img.shields.io/npm/v/@stylelint/postcss-css-in-js.svg)](https://www.npmjs.org/package/@stylelint/postcss-css-in-js) [![Build Status](https://github.com/stylelint/postcss-css-in-js/workflows/CI/badge.svg)](https://github.com/stylelint/postcss-css-in-js/actions)
<img align="right" width="95" height="95"
title="Philosopher’s stone, logo of PostCSS"
src="https://api.postcss.org/logo.svg">
[PostCSS](https://github.com/postcss/postcss) syntax for parsing [CSS in JS](https://github.com/MicheleBertoli/css-in-js) literals:
- [aphrodite](https://github.com/Khan/aphrodite)
- [astroturf](https://github.com/4Catalyzer/astroturf)
- [csjs](https://github.com/rtsao/csjs)
- [css-light](https://github.com/streamich/css-light)
- [cssobj](https://github.com/cssobj/cssobj)
- [electron-css](https://github.com/azukaar/electron-css)
- [emotion](https://github.com/emotion-js/emotion)
- [freestyler](https://github.com/streamich/freestyler)
- [glamor](https://github.com/threepointone/glamor)
- [glamorous](https://github.com/paypal/glamorous)
- [j2c](https://github.com/j2css/j2c)
- [linaria](https://github.com/callstack/linaria)
- [lit-css](https://github.com/bashmish/lit-css)
- [react-native](https://github.com/necolas/react-native-web)
- [react-style](https://github.com/js-next/react-style)
- [reactcss](https://github.com/casesandberg/reactcss)
- [styled-components](https://github.com/styled-components/styled-components)
- [styletron-react](https://github.com/rtsao/styletron)
- [styling](https://github.com/andreypopp/styling)
- [typestyle](https://github.com/typestyle/typestyle)
## Getting Started
First thing's first, install the module:
```
npm install postcss-syntax @stylelint/postcss-css-in-js --save-dev
```
## Use Cases
```js
const postcss = require("postcss");
const stylelint = require("stylelint");
const syntax = require("postcss-syntax");
postcss([stylelint({ fix: true })])
.process(source, { syntax: syntax })
.then(function (result) {
// An alias for the result.css property. Use it with syntaxes that generate non-CSS output.
result.content;
});
```
input:
```javascript
import glm from "glamorous";
const Component1 = glm.a({
flexDirectionn: "row",
display: "inline-block",
color: "#fff"
});
```
output:
```javascript
import glm from "glamorous";
const Component1 = glm.a({
color: "#fff",
display: "inline-block",
flexDirectionn: "row"
});
```
## Advanced Use Cases
Add support for more `css-in-js` package:
```js
const syntax = require("postcss-syntax")({
"i-css": (index, namespace) => namespace[index + 1] === "addStyles",
"styled-components": true
});
```
See: [postcss-syntax](https://github.com/gucong3000/postcss-syntax)
## Style Transformations
The main use case of this plugin is to apply PostCSS transformations to CSS code in template literals & styles as object literals.
+13
View File
@@ -0,0 +1,13 @@
'use strict';
function camelCase(str) {
return str.replace(/[\w-]+/g, (s) =>
/^-?[a-z]+(?:-[a-z]+)+$/.test(s)
? s
.replace(/^-(ms|moz|khtml|epub|(\w+-?)*webkit)(?=-)/i, '$1')
.replace(/-\w/g, (s) => s[1].toUpperCase())
: s,
);
}
module.exports = camelCase;
+462
View File
@@ -0,0 +1,462 @@
'use strict';
const getTemplate = require('./get-template');
const loadSyntax = require('postcss-syntax/load-syntax');
const { parse, types, traverse, loadOptions } = require('@babel/core');
const isStyleSheetCreate = expectAdjacentSibling(['create']);
const supports = {
// import styled from '@emotion/styled'
// import { styled } from 'glamor/styled'
// import { styled } from "styletron-react";
// import { styled } from 'linaria/react';
// import { styled } from '@material-ui/styles'
styled: true,
// import { style } from "typestyle";
style: true,
// import { StyleSheet, css } from 'aphrodite';
// import styled, { css } from 'astroturf';
// import { css } from 'lit-css';
// import { css } from 'glamor'
// require('css-light').css({color: 'red'});
// import { css } from 'linaria';
css: true,
// import { StyleSheet, css } from 'aphrodite';
// import { AppRegistry, StyleSheet, Text, View } from 'react-native';
StyleSheet: isStyleSheetCreate,
// import styled, { css } from 'astroturf';
astroturf: true,
// require('csjs')`css`;
csjs: true,
// require('cssobj')({color: 'red'})
cssobj: true,
// require('electron-css')({color: 'red'})
'electron-css': true,
// import styled from "react-emotion";
'react-emotion': true,
// import styled from 'preact-emotion'
'preact-emotion': true,
// https://github.com/streamich/freestyler
freestyler: true,
// https://github.com/paypal/glamorous
glamorous: true,
// https://github.com/irom-io/i-css
// "i-css": (i, nameSpace) => nameSpace[i + 1] === "addStyles" && nameSpace[i + 2] === "wrapper",
// https://github.com/j2css/j2c
j2c: expectAdjacentSibling(['inline', 'sheet']),
// var styles = StyleSheet.create({color: 'red'})
'react-inline': isStyleSheetCreate,
'react-style': isStyleSheetCreate,
// import reactCSS from 'reactcss'
reactcss: true,
// const StyledButton = injectSheet(styles)(Button)
'react-jss': true,
// import styled from 'styled-components';
'styled-components': true,
// import {withStyle} from "styletron-react";
'styletron-react': expectAdjacentSibling(['withStyle']),
styling: true,
// const rule = superstyle({ color: 'blue' })
superstyle: true,
// import { makeStyles } from '@material-ui/styles'
styles: expectAdjacentSibling(['makeStyles']),
};
const plugins = [
'jsx',
'typescript',
'objectRestSpread',
['decorators', { decoratorsBeforeExport: false }],
'classProperties',
'exportExtensions',
'asyncGenerators',
'functionBind',
'functionSent',
'dynamicImport',
'optionalCatchBinding',
];
function expectAdjacentSibling(names) {
return (i, nameSpace) => names.some((name) => nameSpace[i + 1] === name);
}
function loadBabelOpts(opts) {
const filename = opts.from && opts.from.replace(/\?.*$/, '');
opts = {
filename,
parserOpts: {
plugins,
sourceFilename: filename,
sourceType: filename && /\.m[tj]sx?$/.test(filename) ? 'module' : 'unambiguous',
allowImportExportEverywhere: true,
allowAwaitOutsideFunction: true,
allowReturnOutsideFunction: true,
allowSuperOutsideMethod: true,
},
};
let fileOpts;
try {
fileOpts =
filename &&
loadOptions({
filename,
});
} catch (ex) {
//
}
for (const key in fileOpts) {
if (Array.isArray(fileOpts[key]) && !fileOpts[key].length) {
continue;
}
opts[key] = fileOpts[key];
if (Array.isArray(fileOpts[key]) && Array.isArray(opts.parserOpts[key])) {
// combine arrays for plugins
opts.parserOpts[key] = opts.parserOpts[key].concat(fileOpts[key]);
} else {
// because some options need to be passed to parser also
opts.parserOpts[key] = fileOpts[key];
}
}
return opts;
}
function literalParser(source, opts, styles) {
let ast;
try {
ast = parse(source, loadBabelOpts(opts));
} catch (ex) {
// console.error(ex);
return styles || [];
}
const specifiers = new Map();
const variableDeclarator = new Map();
const objLiteral = new Set();
const tplLiteral = new Set();
const tplCallee = new Set();
const jobs = [];
function addObjectJob(path) {
jobs.push(() => {
addObjectValue(path);
});
}
function addObjectValue(path) {
if (path.isIdentifier()) {
const identifier = path.scope.getBindingIdentifier(path.node.name);
if (identifier) {
path = variableDeclarator.get(identifier);
if (path) {
variableDeclarator.delete(identifier);
path.forEach(addObjectExpression);
}
}
} else {
addObjectExpression(path);
}
}
function addObjectExpression(path) {
if (path.isObjectExpression()) {
path.get('properties').forEach((prop) => {
if (prop.isSpreadElement()) {
addObjectValue(prop.get('argument'));
}
});
objLiteral.add(path.node);
return path;
}
}
function setSpecifier(id, nameSpace) {
nameSpace.unshift(
...nameSpace
.shift()
.replace(/^\W+/, '')
.split(/[/\\]+/g),
);
if (types.isIdentifier(id)) {
specifiers.set(id.name, nameSpace);
specifiers.set(id, nameSpace);
} else if (types.isObjectPattern(id)) {
id.properties.forEach((property) => {
if (types.isObjectProperty(property)) {
const key = property.key;
nameSpace = nameSpace.concat(key.name || key.value);
id = property.value;
} else {
id = property.argument;
}
setSpecifier(id, nameSpace);
});
} else if (types.isArrayPattern(id)) {
id.elements.forEach((element, i) => {
setSpecifier(element, nameSpace.concat(String(i)));
});
}
}
function getNameSpace(path, nameSpace) {
let node = path.node;
if (path.isIdentifier() || path.isJSXIdentifier()) {
node = path.scope.getBindingIdentifier(node.name) || node;
const specifier = specifiers.get(node) || specifiers.get(node.name);
if (specifier) {
nameSpace.unshift(...specifier);
} else {
nameSpace.unshift(node.name);
}
} else {
['name', 'property', 'object', 'callee'].forEach((prop) => {
node[prop] && getNameSpace(path.get(prop), nameSpace);
});
}
return nameSpace;
}
function isStylePath(path) {
return getNameSpace(path, []).some(function (name, ...args) {
const result =
name &&
((Object.prototype.hasOwnProperty.call(supports, name) && supports[name]) ||
(Object.prototype.hasOwnProperty.call(opts.syntax.config, name) &&
opts.syntax.config[name]));
switch (typeof result) {
case 'function': {
return result.apply(this, args);
}
case 'boolean': {
return result;
}
default: {
return undefined;
}
}
});
}
const visitor = {
ImportDeclaration: (path) => {
const moduleId = path.node.source.value;
path.node.specifiers.forEach((specifier) => {
const nameSpace = [moduleId];
if (specifier.imported) {
nameSpace.push(specifier.imported.name);
}
setSpecifier(specifier.local, nameSpace);
});
},
JSXAttribute: (path) => {
if (/^(?:css|style)$/.test(path.node.name.name)) {
addObjectJob(path.get('value.expression'));
}
},
VariableDeclarator: (path) => {
variableDeclarator.set(path.node.id, path.node.init ? [path.get('init')] : []);
},
AssignmentExpression: (path) => {
if (types.isIdentifier(path.node.left) && types.isObjectExpression(path.node.right)) {
const identifier = path.scope.getBindingIdentifier(path.node.left.name);
const variable = variableDeclarator.get(identifier);
const valuePath = path.get('right');
if (variable) {
variable.push(valuePath);
} else {
variableDeclarator.set(identifier, [valuePath]);
}
}
},
CallExpression: (path) => {
const callee = path.node.callee;
if (
types.isIdentifier(callee, { name: 'require' }) &&
!path.scope.getBindingIdentifier(callee.name)
) {
path.node.arguments.filter(types.isStringLiteral).forEach((arg) => {
const moduleId = arg.value;
const nameSpace = [moduleId];
let currPath = path;
do {
let id = currPath.parent.id;
if (!id) {
id = currPath.parent.left;
if (id) {
id = path.scope.getBindingIdentifier(id.name) || id;
} else {
if (types.isIdentifier(currPath.parent.property)) {
nameSpace.push(currPath.parent.property.name);
}
currPath = currPath.parentPath;
continue;
}
}
setSpecifier(id, nameSpace);
break;
} while (currPath);
});
} else if (!tplCallee.has(callee) && isStylePath(path.get('callee'))) {
path.get('arguments').forEach((arg) => {
addObjectJob(arg.isFunction() ? arg.get('body') : arg);
});
}
},
TaggedTemplateExpression: (path) => {
if (isStylePath(path.get('tag'))) {
tplLiteral.add(path.node.quasi);
if (path.node.tag.callee) {
tplCallee.add(path.node.tag.callee);
}
}
},
};
traverse(ast, visitor);
jobs.forEach((job) => job());
const objLiteralStyles = Array.from(objLiteral).map((endNode) => {
const objectSyntax = require('./object-syntax');
let startNode = endNode;
if (startNode.leadingComments && startNode.leadingComments.length) {
startNode = startNode.leadingComments[0];
}
let startIndex = startNode.start;
const before = source.slice(startNode.start - startNode.loc.start.column, startNode.start);
if (/^\s+$/.test(before)) {
startIndex -= before.length;
}
return {
startIndex,
endIndex: endNode.end,
skipConvert: true,
content: source,
opts: {
node: endNode,
},
syntax: objectSyntax,
lang: 'object-literal',
};
});
const tplLiteralStyles = [];
Array.from(tplLiteral).forEach((node) => {
if (
objLiteralStyles.some((style) => style.startIndex <= node.end && node.start < style.endIndex)
) {
return;
}
const quasis = node.quasis.map((node) => ({
start: node.start,
end: node.end,
}));
const style = {
startIndex: quasis[0].start,
endIndex: quasis[quasis.length - 1].end,
content: getTemplate(node, source),
};
if (node.expressions.length) {
const expressions = node.expressions.map((node) => ({
start: node.start,
end: node.end,
}));
style.syntax = loadSyntax(opts, __dirname);
style.lang = 'template-literal';
style.opts = {
quasis,
expressions,
};
} else {
style.lang = 'css';
}
let parent = null;
let targetStyles = tplLiteralStyles;
while (targetStyles) {
const target = targetStyles.find(
(targetStyle) =>
targetStyle.opts &&
targetStyle.opts.expressions.some(
(expr) => expr.start <= style.startIndex && style.endIndex < expr.end,
),
);
if (target) {
parent = target;
targetStyles = target.opts.templateLiteralStyles;
} else {
break;
}
}
if (parent) {
const templateLiteralStyles =
parent.opts.templateLiteralStyles || (parent.opts.templateLiteralStyles = []);
templateLiteralStyles.push(style);
} else {
tplLiteralStyles.push(style);
}
});
return (styles || []).concat(objLiteralStyles).concat(tplLiteralStyles);
}
module.exports = literalParser;
+7
View File
@@ -0,0 +1,7 @@
'use strict';
function getTemplate(node, source) {
return source.slice(node.quasis[0].start, node.quasis[node.quasis.length - 1].end);
}
module.exports = getTemplate;
+6
View File
@@ -0,0 +1,6 @@
'use strict';
const extract = require('./extract');
const syntax = require('postcss-syntax/syntax')(extract, 'jsx');
module.exports = syntax;
+23
View File
@@ -0,0 +1,23 @@
'use strict';
const Container = require('postcss/lib/container');
/**
* Represents a JS literal
*
* @extends Container
*
* @example
* const root = postcss.parse('{}');
* const literal = root.first;
* literal.type //=> 'literal'
* literal.toString() //=> 'a{}'
*/
class Literal extends Container {
constructor(defaults) {
super(defaults);
this.type = 'literal';
}
}
module.exports = Literal;
+15
View File
@@ -0,0 +1,15 @@
'use strict';
const Input = require('postcss/lib/input');
const ObjectParser = require('./object-parser');
function objectParse(source, opts) {
const input = new Input(source, opts);
const parser = new ObjectParser(input);
parser.parse(opts.node);
return parser.root;
}
module.exports = objectParse;
+357
View File
@@ -0,0 +1,357 @@
'use strict';
const camelCase = require('./camel-case');
const getTemplate = require('./get-template');
const Literal = require('./literal');
const ObjectLiteral = require('./object');
const postcss = require('postcss');
const unCamelCase = require('./un-camel-case');
function forEach(arr, callback) {
arr && arr.forEach(callback);
}
const replaceProp = (fn) => (value) =>
value.replace(/(\(\s*)(.*?)(\s*:)/g, (s, prefix, prop, suffix) => prefix + fn(prop) + suffix);
const camelCaseProp = replaceProp(camelCase);
const unCamelCaseProp = replaceProp(unCamelCase);
function defineRaws(node, prop, prefix, suffix, props) {
if (!props) {
props = {};
}
const descriptor = {
enumerable: true,
get: () => node[prop],
set: (value) => {
node[prop] = value;
},
};
if (!props.raw) {
props.raw = descriptor;
} else if (props.raw === 'camel') {
props.raw = {
enumerable: true,
get: () => camelCase(node[prop]),
set: (value) => {
node[prop] = unCamelCase(value);
},
};
}
props.value = descriptor;
node.raws[prop] = Object.defineProperties(
{
prefix,
suffix,
},
props,
);
}
class objectParser {
constructor(input) {
this.input = input;
}
parse(node) {
const root = postcss.root({
source: {
input: this.input,
start: node.loc.start,
},
});
root.raws.node = node;
const obj = new ObjectLiteral({
raws: {
node,
},
});
root.push(obj);
this.process(node, obj);
this.sort(root);
this.raws(root);
const startNode = root.first.raws.node;
const endNode = root.last.raws.node;
const start = {
line: startNode.loc.start.line,
};
let before = root.source.input.css.slice(
startNode.start - startNode.loc.start.column,
startNode.start,
);
if (/^\s+$/.test(before)) {
start.column = 1;
} else {
before = '';
start.column = startNode.loc.start.column;
}
root.first.raws.before = before;
root.source.input.css = before + root.source.input.css.slice(startNode.start, endNode.end);
root.source.start = start;
this.root = root;
}
process(node, parent) {
['leadingComments', 'innerComments', 'trailingComments'].forEach((prop) => {
forEach(node[prop], (child) => {
this.source(child, this.comment(child, parent));
});
});
const child = (this[node.type] || this.literal).apply(this, [node, parent]);
this.source(node, child);
return child;
}
source(node, parent) {
parent.source = {
input: this.input,
start: node.loc.start,
end: node.loc.end,
};
return parent;
}
raws(parent, node) {
const source = this.input.css;
parent.nodes.forEach((child, i) => {
if (i) {
child.raws.before = source
.slice(parent.nodes[i - 1].raws.node.end, child.raws.node.start)
.replace(/^\s*,+/, '');
} else if (node) {
child.raws.before = source.slice(node.start, child.raws.node.start).replace(/^\s*{+/, '');
}
});
if (node) {
let semicolon;
let after;
if (parent.nodes.length) {
after = source.slice(parent.last.raws.node.end, node.end).replace(/^\s*,+/, () => {
semicolon = true;
return '';
});
} else {
after = source.slice(node.start, node.end).replace(/^\s*{/, '');
}
parent.raws.after = after.replace(/}+\s*$/, '');
parent.raws.semicolon = semicolon || false;
}
}
sort(node) {
node.nodes = node.nodes.sort((a, b) => a.raws.node.start - b.raws.node.start);
}
getNodeValue(node, wrappedValue) {
const source = this.input.css;
let rawValue;
let cookedValue;
switch (node.type) {
case 'Identifier': {
const isCssFloat = node.name === 'cssFloat';
return {
prefix: '',
suffix: '',
raw: isCssFloat && node.name,
value: isCssFloat ? 'float' : node.name,
};
}
case 'StringLiteral': {
rawValue = node.extra.raw.slice(1, -1);
cookedValue = node.value;
break;
}
case 'TemplateLiteral': {
rawValue = getTemplate(node, source);
break;
}
default: {
rawValue = source.slice(node.start, node.end);
break;
}
}
const valueWrap = wrappedValue.split(rawValue);
return {
prefix: valueWrap[0],
suffix: valueWrap[1],
value: cookedValue || rawValue,
};
}
ObjectExpression(node, parent) {
forEach(node.properties, (child) => {
this.process(child, parent);
});
this.sort(parent);
this.raws(parent, node);
return parent;
}
ObjectProperty(node, parent) {
const source = this.input.css;
let between = source.indexOf(':', node.key.end);
const rawKey = source.slice(node.start, between).trimRight();
const rawValue = source.slice(between + 1, node.end).trimLeft();
between = source.slice(node.start + rawKey.length, node.end - rawValue.length);
const key = this.getNodeValue(node.key, rawKey);
if (node.value.type === 'ObjectExpression') {
let rule;
if (/^@(\S+)(\s*)(.*)$/.test(key.value)) {
const name = RegExp.$1;
const afterName = RegExp.$2;
const params = RegExp.$3;
const atRule = postcss.atRule({
name: unCamelCase(name),
raws: {
afterName,
},
nodes: [],
});
defineRaws(atRule, 'name', key.prefix + '@', params ? '' : key.suffix, {
raw: 'camel',
});
if (params) {
atRule.params = unCamelCaseProp(params);
defineRaws(atRule, 'params', '', key.suffix, {
raw: {
enumerable: true,
get: () => camelCaseProp(atRule.params),
set: (value) => {
atRule.params = unCamelCaseProp(value);
},
},
});
}
rule = atRule;
} else {
// rule = this.rule(key, keyWrap, node.value, parent);
rule = postcss.rule({
selector: key.value,
});
defineRaws(rule, 'selector', key.prefix, key.suffix);
}
raw(rule);
this.ObjectExpression(node.value, rule);
return rule;
}
const value = this.getNodeValue(node.value, rawValue);
if (key.value[0] === '@') {
const atRule = postcss.atRule({
name: unCamelCase(key.value),
params: value.value,
});
defineRaws(atRule, 'name', key.prefix, key.suffix, {
raw: 'camel',
});
defineRaws(atRule, 'params', value.prefix, value.suffix);
raw(atRule);
return atRule;
} else {
let decl;
if (key.raw) {
decl = postcss.decl({
prop: key.value,
value: value.value,
raws: {
prop: key,
},
});
} else {
decl = postcss.decl({
prop: unCamelCase(key.value),
value: value.value,
});
defineRaws(decl, 'prop', key.prefix, key.suffix, {
raw: 'camel',
});
}
defineRaws(decl, 'value', value.prefix, value.suffix);
raw(decl);
return decl;
}
function raw(postcssNode) {
postcssNode.raws.between = between;
postcssNode.raws.node = node;
parent.push(postcssNode);
}
}
literal(node, parent) {
const literal = new Literal({
text: this.input.css.slice(node.start, node.end),
raws: {
node,
},
});
parent.push(literal);
return literal;
}
comment(node, parent) {
if (
!parent.nodes ||
(node.start < parent.raws.node.start && parent.type !== 'root' && parent.parent)
) {
return this.comment(node, parent.parent);
}
const text = node.value.match(/^(\s*)((?:\S[\s\S]*?)?)(\s*)$/);
const comment = postcss.comment({
text: text[2],
raws: {
node,
left: text[1],
right: text[3],
inline: node.type === 'CommentLine',
},
});
parent.push(comment);
return comment;
}
}
module.exports = objectParser;
+153
View File
@@ -0,0 +1,153 @@
'use strict';
const camelCase = require('./camel-case');
const Stringifier = require('postcss/lib/stringifier');
class ObjectStringifier extends Stringifier {
object(node) {
this.builder('{', node, 'start');
let after;
if (node.nodes && node.nodes.length) {
this.body(node);
after = this.raw(node, 'after');
} else {
after = this.raw(node, 'after', 'emptyBody');
}
if (after) this.builder(after);
this.builder('}', node, 'end');
}
literal(node, semicolon) {
this.builder(node.text + (semicolon ? ',' : ''), node);
}
decl(node, semicolon) {
let prop = this.rawValue(node, 'prop');
if (prop === 'float') {
prop = 'cssFloat';
}
let string = prop;
const isObjectShorthand = node.raws.node && node.raws.node.shorthand;
if (!isObjectShorthand) {
const between = this.raw(node, 'between', 'colon');
const value = this.rawValue(node, 'value');
string += between + value;
}
if (semicolon) string += ',';
this.builder(string, node);
}
rule(node, semicolon) {
this.block(node, this.rawValue(node, 'selector'), semicolon);
}
atrule(node, semicolon) {
const name = this.rawValue(node, 'name');
const params = this.rawValue(node, 'params');
if (node.nodes) {
let string;
if (params) {
const afterName = this.raw(node, 'afterName');
string = name + afterName + params;
} else {
string = name;
}
this.block(node, string, semicolon);
} else {
const between = this.raw(node, 'between', 'colon');
let string = name + between + params;
if (semicolon) string += ',';
this.builder(string, node);
}
}
block(node, start, semicolon) {
super.block(node, start);
if (semicolon) {
this.builder(',', node);
}
}
comment(node) {
const left = this.raw(node, 'left', 'commentLeft');
const right = this.raw(node, 'right', 'commentRight');
if (node.raws.inline) {
const text = node.raws.text || node.text;
this.builder('//' + left + text + right, node);
} else {
this.builder('/*' + left + node.text + right + '*/', node);
}
}
raw(node, own, detect) {
let value = super.raw(node, own, detect);
if (
(own === 'between' || (own === 'afterName' && node.type === 'atrule' && !node.nodes)) &&
!/:/.test(value)
) {
value = ':' + value;
} else if (own === 'before' && /^(decl|rule)$/.test(node.type)) {
value = value.replace(/\S+$/, '');
}
return value;
}
rawValue(node, prop) {
const raw = node.raws[prop];
if (raw) {
const descriptor = Object.getOwnPropertyDescriptor(raw, 'raw');
if (descriptor && descriptor.get) {
return raw.prefix + raw.raw + raw.suffix;
}
}
let value = super.rawValue(node, prop);
if (value === null || value === undefined) {
return value;
}
if (/^(prop|selector)$/i.test(prop)) {
value = camelCase(value);
if (node.raws.before && /(\S+)$/.test(node.raws.before)) {
value = RegExp.$1 + value;
} else if (value && !/\W/.test(value)) {
return value;
}
} else if (node.type === 'atrule') {
if (prop === 'name') {
value = '@' + value;
} else if (node.nodes) {
return;
}
if (node.nodes) {
value += this.raw(node, 'afterName');
value += super.rawValue(node, 'params');
}
}
value = JSON.stringify(value);
return value;
}
}
module.exports = ObjectStringifier;
+9
View File
@@ -0,0 +1,9 @@
'use strict';
const ObjectStringifier = require('./object-stringifier');
module.exports = function objectStringify(node, builder) {
const str = new ObjectStringifier(builder);
str.stringify(node);
};
+11
View File
@@ -0,0 +1,11 @@
'use strict';
const parse = require('./object-parse');
const stringify = require('./object-stringify');
const syntax = {
parse,
stringify,
};
module.exports = syntax;
+24
View File
@@ -0,0 +1,24 @@
'use strict';
const Container = require('postcss/lib/container');
/**
* Represents a JS Object Literal
*
* @extends Container
*
* @example
* const root = postcss.parse('{}');
* const obj = root.first;
* obj.type //=> 'object'
* obj.toString() //=> '{}'
*/
class ObjectLiteral extends Container {
constructor(defaults) {
super(defaults);
this.type = 'object';
this.nodes = [];
}
}
module.exports = ObjectLiteral;
+158
View File
@@ -0,0 +1,158 @@
{
"_args": [
[
"@stylelint/postcss-css-in-js@0.37.2",
"/home/pi/Desktop/smartMirrorTestEnvironment/MagicMirror"
]
],
"_development": true,
"_from": "@stylelint/postcss-css-in-js@0.37.2",
"_id": "@stylelint/postcss-css-in-js@0.37.2",
"_inBundle": false,
"_integrity": "sha512-nEhsFoJurt8oUmieT8qy4nk81WRHmJynmVwn/Vts08PL9fhgIsMhk1GId5yAN643OzqEEb5S/6At2TZW7pqPDA==",
"_location": "/@stylelint/postcss-css-in-js",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@stylelint/postcss-css-in-js@0.37.2",
"name": "@stylelint/postcss-css-in-js",
"escapedName": "@stylelint%2fpostcss-css-in-js",
"scope": "@stylelint",
"rawSpec": "0.37.2",
"saveSpec": null,
"fetchSpec": "0.37.2"
},
"_requiredBy": [
"/stylelint"
],
"_resolved": "https://registry.npmjs.org/@stylelint/postcss-css-in-js/-/postcss-css-in-js-0.37.2.tgz",
"_spec": "0.37.2",
"_where": "/home/pi/Desktop/smartMirrorTestEnvironment/MagicMirror",
"author": {
"name": "gucong3000"
},
"bugs": {
"url": "https://github.com/stylelint/postcss-css-in-js/issues"
},
"dependencies": {
"@babel/core": ">=7.9.0"
},
"description": "PostCSS syntax for parsing CSS in JS literals",
"devDependencies": {
"@stylelint/prettier-config": "^2.0.0",
"@stylelint/remark-preset": "^1.0.0",
"autoprefixer": "^9.7.6",
"chai": "^4.2.0",
"codecov": "^3.6.5",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.10.1",
"eslint-config-stylelint": "^12.0.0",
"husky": "^4.2.5",
"json5": "^2.1.3",
"lint-staged": "^10.1.3",
"mocha": "^7.1.1",
"np": "^6.3.2",
"npm-run-all": "^4.1.5",
"nyc": "^15.0.1",
"postcss": ">=7.0.27",
"postcss-parser-tests": "^6.5.0",
"postcss-safe-parser": "^4.0.2",
"postcss-syntax": ">=0.36.2",
"prettier": "^2.0.4",
"remark-cli": "^8.0.0"
},
"eslintConfig": {
"extends": [
"stylelint"
],
"rules": {
"array-callback-return": "off",
"no-confusing-arrow": "off",
"no-else-return": "off",
"prefer--template": "off",
"prefer-object-spread": "off",
"prefer-rest-params": "off",
"prefer-spread": "off",
"prefer-template": "off",
"jest/expect-expect": "off",
"jest/valid-expect": "off"
}
},
"files": [
"*.js"
],
"homepage": "https://github.com/stylelint/postcss-css-in-js#readme",
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"keywords": [
"postcss",
"syntax",
"emotion",
"aphrodite",
"glamor",
"glamorous",
"react-native",
"react-style",
"reactcss",
"styled-components",
"styletron-react",
"typestyle",
"css-in-js",
"css"
],
"license": "MIT",
"lint-staged": {
"*.js": "eslint --cache --fix",
"*.{js,md,yml}": "prettier --write"
},
"main": "index.js",
"name": "@stylelint/postcss-css-in-js",
"nyc": {
"all": true,
"cache": true,
"check-coverage": true,
"exclude": [
"coverage/**",
"test{,s}/**",
"**/.{prettier,eslint,mocha}rc.{js,cjs}"
],
"reporter": [
"lcov",
"text"
]
},
"peerDependencies": {
"postcss": ">=7.0.0",
"postcss-syntax": ">=0.36.2"
},
"prettier": "@stylelint/prettier-config",
"publishConfig": {
"access": "public"
},
"remarkConfig": {
"plugins": [
"@stylelint/remark-preset"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/stylelint/postcss-css-in-js.git"
},
"scripts": {
"debug": "npm run mocha -- --inspect-brk",
"format": "prettier . --write",
"lint": "npm-run-all --parallel lint:*",
"lint:formatting": "prettier . --check",
"lint:js": "eslint . --cache --max-warnings=0",
"lint:md": "remark . --quiet --frail",
"mocha": "mocha --no-timeouts",
"release": "np",
"test": "nyc npm run mocha",
"watch": "mocha --watch"
},
"version": "0.37.2"
}
+19
View File
@@ -0,0 +1,19 @@
'use strict';
const Input = require('postcss/lib/input');
const TemplateParser = require('./template-parser');
function templateParse(css, opts) {
const input = new Input(css, opts);
input.quasis = opts.quasis;
input.templateLiteralStyles = opts.templateLiteralStyles;
input.parseOptions = opts;
const parser = new TemplateParser(input);
parser.parse();
return parser.root;
}
module.exports = templateParse;
+260
View File
@@ -0,0 +1,260 @@
'use strict';
const Literal = require('./literal');
const postcssParse = require('postcss/lib/parse');
const reNewLine = /(?:\r?\n|\r)/gm;
const isLiteral = (token) => token[0] === 'word' && /^\$\{[\s\S]*\}$/.test(token[1]);
function literal(start) {
if (!isLiteral(start)) {
return;
}
const tokens = [];
let hasWord;
let type;
let token;
while ((token = this.tokenizer.nextToken())) {
tokens.push(token);
type = token[0];
if (type.length === 1) {
break;
} else if (type === 'word') {
hasWord = true;
}
}
while (tokens.length) {
this.tokenizer.back(tokens.pop());
}
if (type === '{' || (type === ':' && !hasWord)) {
return;
}
const node = new Literal({
text: start[1],
});
this.init(node, start[2], start[3]);
const input = this.input;
if (input.templateLiteralStyles) {
const offset = input.quasis[0].start;
const nodeIndex = getNodeIndex(node, input);
const start = offset + nodeIndex;
const end = start + node.text.length;
const templateLiteralStyles = input.templateLiteralStyles.filter(
(style) => style.startIndex <= end && start < style.endIndex,
);
if (templateLiteralStyles.length) {
const nodes = parseTemplateLiteralStyles(templateLiteralStyles, input, [
nodeIndex,
nodeIndex + node.text.length,
]);
if (nodes.length) {
node.nodes = nodes;
nodes.forEach((n) => (n.parent = node));
}
}
}
return node;
}
function freeSemicolon(token) {
this.spaces += token[1];
const nodes = this.current.nodes;
const prev = nodes && nodes[nodes.length - 1];
if (prev && /^(rule|literal)$/.test(prev.type) && !prev.raws.ownSemicolon) {
prev.raws.ownSemicolon = this.spaces;
this.spaces = '';
}
}
module.exports = {
freeSemicolon,
literal,
};
function parseTemplateLiteralStyles(styles, input, range) {
const offset = input.quasis[0].start;
const source = input.css;
const opts = Object.assign({}, input.parseOptions);
delete opts.templateLiteralStyles;
delete opts.expressions;
delete opts.quasis;
const parseStyle = docFixer(offset, source, opts);
const nodes = [];
let index = range[0];
styles
.sort((a, b) => a.startIndex - b.startIndex)
.forEach((style) => {
const root = parseStyle(style);
if (!root || !root.nodes.length) {
return;
}
root.raws.beforeStart = source.slice(index, style.startIndex - offset);
root.raws.afterEnd = '';
if (style.endIndex) {
index = style.endIndex - offset;
} else {
index = style.startIndex - offset + (style.content || root.source.input.css).length;
}
nodes.push(root);
});
if (nodes.length) {
nodes[nodes.length - 1].raws.afterEnd = source.slice(index, range[1]);
}
return nodes;
}
class LocalFixer {
constructor(offset, lines, style, templateParse) {
const startIndex = style.startIndex - offset;
let line = 0;
let column = startIndex;
lines.some((lineEndIndex, lineNumber) => {
if (lineEndIndex >= startIndex) {
line = lineNumber--;
if (lineNumber in lines) {
column = startIndex - lines[lineNumber] - 1;
}
return true;
}
});
this.line = line;
this.column = column;
this.style = style;
this.templateParse = templateParse;
}
object(object) {
if (object) {
if (object.line === 1) {
object.column += this.column;
}
object.line += this.line;
}
}
node(node) {
this.object(node.source.start);
this.object(node.source.end);
}
root(root) {
this.node(root);
root.walk((node) => {
this.node(node);
});
}
error(error) {
if (error && error.name === 'CssSyntaxError') {
this.object(error);
this.object(error.input);
error.message = error.message.replace(
/:\d+:\d+:/,
':' + error.line + ':' + error.column + ':',
);
}
return error;
}
parse(opts) {
const style = this.style;
const syntax = style.syntax;
let root = style.root;
try {
root = this.templateParse(
style.content,
Object.assign(
{},
opts,
{
map: false,
},
style.opts,
),
);
} catch (error) {
if (style.ignoreErrors) {
return;
} else if (!style.skipConvert) {
this.error(error);
}
throw error;
}
if (!style.skipConvert) {
this.root(root);
}
root.source.inline = Boolean(style.inline);
root.source.lang = style.lang;
root.source.syntax = syntax;
return root;
}
}
function docFixer(offset, source, opts) {
let match;
const lines = [];
reNewLine.lastIndex = 0;
while ((match = reNewLine.exec(source))) {
lines.push(match.index);
}
lines.push(source.length);
return function parseStyle(style) {
const parse = style.syntax ? style.syntax.parse : postcssParse;
return new LocalFixer(offset, lines, style, parse).parse(opts);
};
}
function getNodeIndex(node, input) {
const source = input.css;
let match;
let line = 1;
let lastIndex = -1;
reNewLine.lastIndex = 0;
while ((match = reNewLine.exec(source))) {
if (line === node.source.start.line) {
return lastIndex + node.source.start.column;
}
lastIndex = match.index;
line++;
}
if (line === node.source.start.line) {
return lastIndex + node.source.start.column;
}
return source.length;
}
+20
View File
@@ -0,0 +1,20 @@
'use strict';
const helper = require('./template-parser-helper');
const Parser = require('postcss/lib/parser');
const templateTokenize = require('./template-tokenize');
class TemplateParser extends Parser {
createTokenizer() {
this.tokenizer = templateTokenize(this.input);
}
other() {
const args = arguments;
return helper.literal.apply(this, args) || super.other.apply(this, args);
}
freeSemicolon() {
return helper.freeSemicolon.apply(this, arguments);
}
}
module.exports = TemplateParser;
+19
View File
@@ -0,0 +1,19 @@
'use strict';
const Input = require('postcss/lib/input');
const TemplateSafeParser = require('./template-safe-parser');
function templateSafeParse(css, opts) {
const input = new Input(css, opts);
input.quasis = opts.quasis;
input.templateLiteralStyles = opts.templateLiteralStyles;
input.parseOptions = opts;
const parser = new TemplateSafeParser(input);
parser.parse();
return parser.root;
}
module.exports = templateSafeParse;
+21
View File
@@ -0,0 +1,21 @@
'use strict';
const helper = require('./template-parser-helper');
// eslint-disable-next-line node/no-unpublished-require
const SafeParser = require('postcss-safe-parser/lib/safe-parser');
const templateTokenize = require('./template-tokenize');
class TemplateSafeParser extends SafeParser {
createTokenizer() {
this.tokenizer = templateTokenize(this.input, { ignoreErrors: true });
}
other() {
const args = arguments;
return helper.literal.apply(this, args) || super.other.apply(this, args);
}
freeSemicolon() {
return helper.freeSemicolon.apply(this, arguments);
}
}
module.exports = TemplateSafeParser;
+23
View File
@@ -0,0 +1,23 @@
'use strict';
const Stringifier = require('postcss/lib/stringifier');
class TemplateStringifier extends Stringifier {
literal(node) {
if (node.nodes && node.nodes.length) {
node.nodes.forEach((root) => {
this.builder(root.raws.beforeStart, root, 'beforeStart');
this.stringify(root);
this.builder(root.raws.afterEnd, root, 'afterEnd');
});
} else {
this.builder(node.text, node);
}
if (node.raws.ownSemicolon) {
this.builder(node.raws.ownSemicolon, node, 'end');
}
}
}
module.exports = TemplateStringifier;
+9
View File
@@ -0,0 +1,9 @@
'use strict';
const TemplateStringifier = require('./template-stringifier');
module.exports = function TemplateStringify(node, builder) {
const str = new TemplateStringifier(builder);
str.stringify(node);
};
+67
View File
@@ -0,0 +1,67 @@
'use strict';
const tokenize = require('postcss/lib/tokenize');
function templateTokenize(input) {
let pos = input.quasis[0].start;
const quasis = input.quasis.filter((quasi) => quasi.start !== quasi.end);
const tokenizer = tokenize.apply(this, arguments);
function tokenInExpressions(token, returned) {
const start = pos;
pos += token[1].length;
if (
!quasis.some((quasi) => start >= quasi.start && pos <= quasi.end) ||
(returned.length && token[0] === returned[0][0])
) {
return true;
} else if (returned.length) {
back(token);
}
}
function back(token) {
pos -= token[1].length;
return tokenizer.back.apply(tokenizer, arguments);
}
function nextToken() {
const args = arguments;
const returned = [];
let token;
let line;
let column;
while (
(token = tokenizer.nextToken.apply(tokenizer, args)) &&
tokenInExpressions(token, returned)
) {
line = token[4] || token[2] || line;
column = token[5] || token[3] || column;
returned.push(token);
}
if (returned.length) {
token = [
returned[0][0],
returned.map((token) => token[1]).join(''),
returned[0][2],
returned[0][3],
line,
column,
];
}
return token;
}
return Object.assign({}, tokenizer, {
back,
nextToken,
});
}
module.exports = templateTokenize;
+13
View File
@@ -0,0 +1,13 @@
'use strict';
function unCamelCase(str) {
return str.replace(/[\w-]+/g, (s) =>
/^[A-Z]?[a-z]*(?:[A-Z][a-z]*)+$/.test(s)
? s
.replace(/[A-Z]/g, (s) => '-' + s.toLowerCase())
.replace(/^(o|ms|moz|khtml|epub|(\w+-?)*webkit)(?=-)/i, '-$1')
: s,
);
}
module.exports = unCamelCase;