UNPKG

ctr

Version:

The CSS Framework

1,451 lines (1,295 loc) 597 kB
/*! * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * Copyright 2015-2017 - CTR, LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* eslint-disable */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("lodash"), require("immutable"), require("te-flow"), require("defclass"), require("stylus"), require("fs"), require("path"), require("js-yaml"), require("colors")); else if(typeof define === 'function' && define.amd) define(["lodash", "immutable", "te-flow", "defclass", "stylus", "fs", "path", "js-yaml", "colors"], factory); else if(typeof exports === 'object') exports["ctr"] = factory(require("lodash"), require("immutable"), require("te-flow"), require("defclass"), require("stylus"), require("fs"), require("path"), require("js-yaml"), require("colors")); else root["ctr"] = factory(root["lodash"], root["immutable"], root["te-flow"], root["defclass"], root["stylus"], root["fs"], root["path"], root["js-yaml"], root["colors"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_0__, __WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_5__, __WEBPACK_EXTERNAL_MODULE_7__, __WEBPACK_EXTERNAL_MODULE_10__, __WEBPACK_EXTERNAL_MODULE_11__, __WEBPACK_EXTERNAL_MODULE_13__, __WEBPACK_EXTERNAL_MODULE_20__, __WEBPACK_EXTERNAL_MODULE_31__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 264); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { module.exports = require("lodash"); /***/ }), /* 1 */ /***/ (function(module, exports) { module.exports = require("immutable"); /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.QueueManager = __webpack_require__(107); exports.OptionManager = __webpack_require__(106); /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; //stylus exports.styleDefault = __webpack_require__(101); //add-on exports.edit = __webpack_require__(25); exports.clearfix = __webpack_require__(24); exports.ease = __webpack_require__(95); //util exports.util = __webpack_require__(27); exports.findKey = __webpack_require__(97); exports.helperKeys = __webpack_require__(26); //errors exports.throwErr = __webpack_require__(9); /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(0); var base = { position: 'relative', customComponentFilterImage: { option: { key: 'img', selector: false, //internal option prop conflictSrc: true }, width: '100%', 'z-index': '1' }, customElementFilterBefore: { option: { key: 'before', conflictSrc: true }, content: false, display: 'block', height: '100%', width: '100%', top: '0', left: '0', position: 'absolute', 'pointer-events': 'none', 'z-index': '2' }, customElementFilterAfter: { option: { key: 'after', conflictSrc: true }, content: false, display: 'block', height: '100%', width: '100%', top: '0', left: '0', position: 'absolute', 'pointer-events': 'none', 'z-index': '3' } }; /** * Merges with base to return * @return {obj} */ var mergeWithStyle = function mergeWithStyle(val) { var keyOrder = ['filter', 'position', 'customComponentFilterImage', 'customElementFilterBefore', 'customElementFilterAfter', 'customElementsFilter']; /** * Sorta, meh, but it sorts the obj into same order of that of CSSGram */ var sortObject = function sortObject(_obj) { return _.keys(_obj).sort(function (a, b) { var ax = keyOrder.indexOf(a); var bx = keyOrder.indexOf(b); if (ax === -1) { return 0; } else if (bx === -1) { return 1; } else if (ax > bx) { return 1; } else if (bx > ax) { return 0; } return 0; }).reduce(function (result, key) { result[key] = _obj[key]; return result; }, {}); }; //sort and return var obj = sortObject(_.defaultsDeep(val, _.clone(base))); return obj; }; module.exports = mergeWithStyle; /***/ }), /* 5 */ /***/ (function(module, exports) { module.exports = require("te-flow"); /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.merge = __webpack_require__(256); exports.selector = __webpack_require__(29); exports.util = __webpack_require__(18); exports.wrap = __webpack_require__(258); /***/ }), /* 7 */ /***/ (function(module, exports) { module.exports = require("defclass"); /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(0); var localHelpers = { /** * Format the data by assign the data to the struc * @param {obj} data -> raw data obj * @param {obj} struc -> The structur of data obj * @return {obj} -> Formated data obj based on struc */ formatData: function formatData(data, struc) { //format to string to array data = _.isString(data) ? [data] : data; //config data to struc if (data === true) { return struc; } else if (_.isArray(data)) { //note the order is not garenteed but fuck it right now var keys = _.keys(struc); return _.reduce(data, function (prv, val, index) { if (val !== 'default') { prv[keys[index]] = val; } return prv; }, struc); } else if (_.isObject(data)) { //accounts for default in object syntax data = _.reduce(data, function (prv, val, key) { if (val !== 'default') { prv[key] = val; } return prv; }, {}); return _.defaults(data, struc); } //default although it should not get here return struc; }, getSize: function getSize(gut, frac) { var move = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; gut = _.isString(gut) ? gut : gut.toString(); //format data var gutNum = parseFloat(gut.replace(/[^0-9\.]+/g, ''), 0); //config if (gutNum === 0) { return 'calc(99.9% * ' + frac + ')'; } if (move) { return 'calc(99.9% * ' + frac + ' - (' + gut + ' - ' + gut + ' * ' + frac + ')' + '+' + gut + ')'; } return 'calc(99.9% * ' + frac + ' - (' + gut + ' - ' + gut + ' * ' + frac + '))'; } }; module.exports = localHelpers; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _M = __webpack_require__(2); var colors = __webpack_require__(31); var throwErr = function throwErr(errData) { //set global error for ctr.js ref global._ctrNodeError_ = true; //get reff var errRef = _M._option.getIn(['errRef']); if (errRef.error === true) { return; } var id = errRef.id; var type = errData.type; var exp = errData.exp; var rec = errData.rec; var code = errData.code; var msg = errData.msg; colors.setTheme({ info: 'green', data: ['gray', 'bold'], warn: ['yellow', 'bold'], error: ['red', 'underline', 'bold'] }); console.info('~!!!~'.america, 'ctr error'.error, '~!!!~'.america); console.info('Type |=> '.data, 'A ', type.error, ' error... ', '(╯︵╰,)'.magenta.bold); console.info('Location |=> '.data, id); //error types if (type === 'Syntax') { rec = typeof rec; console.info('Info |=> '.data, 'I expected a ', exp, ', but got a ', rec); console.info('Code Ref |=> '.data, code); code = null; } if (code) { console.info('Code Ref |=> '.data, code); } //aux message if (msg) { if (msg === 'default') { msg = 'For your convince I will just use the set defaults.'; } console.info('Message |=> '.data, msg); } }; module.exports = throwErr; /***/ }), /* 10 */ /***/ (function(module, exports) { module.exports = require("stylus"); /***/ }), /* 11 */ /***/ (function(module, exports) { module.exports = require("fs"); /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.toStylus = __webpack_require__(73); exports.toJavascript = __webpack_require__(72); /***/ }), /* 13 */ /***/ (function(module, exports) { module.exports = require("path"); /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Immutable = __webpack_require__(1); var rcConfig = __webpack_require__(15); var _dataConfig = __webpack_require__(33); var _helpers = __webpack_require__(37); var _dataProcess = __webpack_require__(34); var _getCallerFile = __webpack_require__(36); var _objectProcess = __webpack_require__(38); var _objectReplace = __webpack_require__(39); var _extendReplace = __webpack_require__(35); var _parseYaml = __webpack_require__(40); var _render = __webpack_require__(41); var _resSetAdd = __webpack_require__(42); var _resetSet = __webpack_require__(43); var _throwErr = __webpack_require__(44); var _transformData = __webpack_require__(45); var _transformYamlData = __webpack_require__(46); var yaml = __webpack_require__(59); var writeFile = __webpack_require__(58); var setYamlTransform = __webpack_require__(57); var setVariable = __webpack_require__(56); var setTransform = __webpack_require__(55); var reset = __webpack_require__(50); var setReset = __webpack_require__(54); var setOption = __webpack_require__(53); var setClass = __webpack_require__(52); var setCallback = __webpack_require__(51); var getResult = __webpack_require__(49); var getLastResult = __webpack_require__(48); var create = __webpack_require__(47); /* The . oooo .o8 `888 .ooooo. .o888oo oooo d8b .ooooo. 888 .oooo. .oooo.o .oooo.o d88' `"Y8 888 `888""8P d88' `"Y8 888 `P )88b d88( "8 d88( "8 888 888 888 888 888 .oP"888 `"Y88b. `"Y88b. 888 .o8 888 . 888 888 .o8 888 d8( 888 o. )88b o. )88b `Y8bod8P' "888" d888b `Y8bod8P' o888o `Y888""8o 8""888P' 8""888P' */ /** * This class is our point man for the js api. All data runs through this class * including all stylus ctr stlyes. All public/private methods are located in * /ctr-js-nodes, and for the most part everything should be pretty striaght * foward. Here is the gits of the pipeline: 1. data comes in through create, internal class state vars get reset/reconfiged need be, by way of _resetSet and then data is handed off to _render 2. _render is the primary manager of sorts, in that it dispatches the data to the various config opperations to prep/format the data for ctr-nodes. Most the action/manipulation occurs when _render throws the data over to _dataConfig. In a nutshell, the options, variables, classes, are configed here via _objectReplace, _extendReplace, and friends. 3. After the data is configured _dataProcess takes on over and sets up the Stylus tango dance sending the data off to ./ctr-nodes which is a black box of twisted magic wrapped in youthful convoluted tomfoolery, most of which needs to be re-writen. Nevertheless, fingers crossed, the data is converted into proper CSS and returned in our pseudo render cb 4. From here the cb simply slings our now, CSS over to _resSetAdd, which adds the CSS to resultSet and resultDbMap. 5. The CSS then patiently waits to be called upon to inject dream-making possibilities upon the DOM in hopes of greatness 6. Profit. */ var CTR = /** * Constructor for ctr, can be called with or without new * @param {obj} instanceOption -> rc options for ctr instance */ function CTR(instanceOption) { _classCallCheck(this, CTR); var self = this; //dem arguments self.args = [].concat(Array.prototype.slice.call(arguments)); //results will be pushed into this Set self.resultSet = new Set(); //results will be stroed in this map self.resultDbMap = new Map(); //stores classes added via setClass self.ctrClass = Immutable.Map(); //stores raw classes for comparisions self._ctrClassRaw = Immutable.Map(); //stores the key to be used to set map on render result self.resultKey = null; //keys for the current set being processed self.resultKeySet = []; //inst option, need to keep in case rc runs again self.instanceOption = instanceOption; //config check of ctrrc var _rcConfig$call = rcConfig.call(self, { instanceOption }), rcVars = _rcConfig$call.rcVars, rcMtime = _rcConfig$call.rcMtime, rcFilePath = _rcConfig$call.rcFilePath, rcGlobalOption = _rcConfig$call.rcGlobalOption; //store rc's as private self._rcVars = Immutable.fromJS(rcVars); self._rcGlobalOption = Immutable.fromJS(rcGlobalOption); self._rcFilePath = rcFilePath || null; self._rcMtime = rcMtime || null; self._rcUserPath = null; //global vars //inherit default from rc self.vars = self._rcVars; //global option to be merged with every render //inherit default from rc self.globalOption = self._rcGlobalOption; //error saftey catch self.error = false; //stylus render error self.stylusError = false; //current result self.res = ''; //callback to invoke upon render self.callback = false; //transform function array self.transform = []; //yam transform function array self.yamlTransform = []; //if init style has been renered self.rendered = false; //local var key, this option is for the folks //who feel dirty about using a $$ key self.localVarKey = '$$'; self._rcConfigRan = false; //saftey for obj replace so we don't run into a infy loop self._infyLoopCount = 5000; //selector ref for error location self._selector = ''; /** * Private */ // (selector, data, option = {}) -> pre data prepper self._dataConfig = _dataConfig; // (selector, data, option = {}, cb) -> main man sends data through ctr-nodes self._dataProcess = _dataProcess; // (source) -> extend matching/replace self._extendReplace = _extendReplace; // () -> prepareStatckTrace for inst location self._getCallerFile = _getCallerFile; // {fileExists, defaultsDeep, get, has} -> i get high with a little help from my friends self._h = _helpers; // (data, fn) -> process object data to and extracts globals and such self._objectProcess = _objectProcess; // (_source, replacer, {privateReplacer = false, reportError = false, localVarUpdate = false} = {}) // the magic maker that handles var replcament -> matching string patterns self._objectReplace = _objectReplace; // (filePath, buffer = false, option = {}) -> wrapper for js-yaml load/read self._parseYaml = _parseYaml; // (transformFn = false) -> inits the stylus render dance, passes to _dataProcess self._render = _render; // (res, key = this.resultKey, cache = true) -> adds res to resultSet self._resSetAdd = _resSetAdd; // (configOverride = false) -> interal reset before _render self._resetSet = _resetSet; // ({error, msg, format = true}) -> console.error helper/reporter self._throwErr = _throwErr; // (res) -> setTransform result fn's self._transformData = _transformData; // (data) -> setYamlTransform fn's before _render self._transformYamlData = _transformYamlData; /** * Public */ // (selector, data, option = {}, transformFn = false) -> main entry to create style self.create = create; // (reset = false, raw = false) -> resets last set style self.getLastResult = getLastResult; self.getLastResultSet = getLastResult; // (reset = true, raw = false) -> gets result of styles self.getRes = getResult; self.getResult = getResult; // (resetDefaults = false) -> total reset self.reset = reset; // (cb, option = {}) -> sets render callback self.setCallback = setCallback; // (className, classData = false, option = {}) -> sets class self.addClass = setClass; self.setClass = setClass; // (ctrOptions = {}, option = {}) -> sets options self.setOption = setOption; // (resetDefaults = false) -> resets all sets self.development = setReset; self.setReset = setReset; // (transform, option = {reset: false, once: false}) -> sets transform self.setTransform = setTransform; // (vars = {}, option = {}) -> sets variables self.setVar = setVariable; self.setVariable = setVariable; // (transformFn, option = {}) -> sets yaml specific transform self.setYamlTransform = setYamlTransform; // (filePath = false, option = {}) -> write out res self.writeFile = writeFile; // (file, selector = '__yaml__', option = {}, transformFn = false) -> process yaml self.yaml = yaml; }; module.exports = CTR; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var fs = __webpack_require__(11); var path = __webpack_require__(13); var _ = __webpack_require__(0); var yaml = __webpack_require__(20); /** * Lookes for `.ctrrc.js` file in the root of the directory * for preconfiged ctr optins * @param {str} prvFilePath -> the prvious sucssful path look up to avoid * needless lookup calls * @param {str} rcPath -> custom rc path defined by user * @param {str} instanceOption -> new ctr instance options * @return {obj} -> ctr options of empy object */ var config = function config(_ref) { var _ref$prvFilePath = _ref.prvFilePath, prvFilePath = _ref$prvFilePath === undefined ? null : _ref$prvFilePath, _ref$rcPath = _ref.rcPath, rcPath = _ref$rcPath === undefined ? null : _ref$rcPath, _ref$localVarKey = _ref.localVarKey, localVarKey = _ref$localVarKey === undefined ? '$$' : _ref$localVarKey, _ref$instanceOption = _ref.instanceOption, instanceOption = _ref$instanceOption === undefined ? false : _ref$instanceOption; var self = this; var fileName = '.ctrrc.yml'; /** * Wrapper to check if file exsits * @param {str} filePath -> filepath * @return {bln} -> the truth */ var fileExists = function fileExists(filePath) { try { return fs.statSync(filePath).isFile(); } catch (err) { return false; } }; /** * Wrapper around yaml.load to parse the ctrrc file * @param {str} filePath -> filepath to the ctrrc * @return {---} -> obj of results or throws error */ var parseFile = function parseFile(filePath) { try { return yaml.safeLoad(fs.readFileSync(filePath)); } catch (err) { //currently not implment in stylus if (self._throwErr) { //throw error self._throwErr({ error: '.ctrrc.yml parse error! You need to fix your .ctrrc file!', msg: err }); } else { console.warn('.ctrrc.yml parse error! You need to fix your .ctrrc file!'); console.warn(err); } return false; } }; /** * Process the ctrrc.yml file and assings the vars * @param {str} filePath -> filepath to crtrc * @return {obj} -> configed rc options */ var requireCtr = function requireCtr(filePath) { var hasRc = _.isString(filePath); //read andparse the file var ctrRc = hasRc ? parseFile(filePath) : {}; // stats for ref return var rcStats = hasRc ? { rcFilePath: filePath, rcMtime: fs.statSync(filePath).mtime } : {}; //merge in new ctr instance options ctrRc = _.isPlainObject(instanceOption) ? _.defaultsDeep(_.cloneDeep(instanceOption), ctrRc || {}) : ctrRc; //config need be otherwise return the dice if (_.isPlainObject(ctrRc)) { //pull out config objects if any var varsConfig = ctrRc[localVarKey] || ctrRc.variable || {}; //check file specific condidtion -> means all props are options, filter option of course if (varsConfig === true) { varsConfig = _.omit(ctrRc, ['$ctr-option', 'ctrOption', 'option']); } var globalOption = ctrRc['$ctr-option'] || ctrRc.ctrOption || ctrRc.option || {}; //check file specific condidtion -> means all props are options if (globalOption === true) { globalOption = _.isEmpty(varsConfig) && _.isEmpty(globalOption) ? ctrRc : globalOption; } //default catch-all, assumes all props are options globalOption = _.isEmpty(varsConfig) && _.isEmpty(globalOption) ? ctrRc : globalOption; //check for global key, merge into base, unforunatly we need to duplicate the data right now globalOption = !_.isPlainObject(globalOption.global) ? globalOption : _.defaultsDeep(globalOption, globalOption.global); return _.defaults({ rcVars: varsConfig, rcGlobalOption: globalOption }, rcStats); } else if (_.isUndefined(ctrRc)) { //if undefined in all likelihood its just empty so we still return file info return _.defaults({ rcVars: {}, rcGlobalOption: {} }, rcStats); } return { rcVars: {}, rcGlobalOption: {} }; }; //check if user specied a custom path otherwise check prvFilePath //for the a prvFilePath if (rcPath) { return requireCtr(rcPath); } else if (prvFilePath) { return requireCtr(prvFilePath); } //home check var home = path.resolve(__dirname).split('/node_modules')[0]; if (home) { var homeExists = fileExists(path.join(home, fileName)); if (homeExists) { return requireCtr(path.join(home, fileName)); } } //argv check var argv = process ? process.argv : false; argv = argv ? argv[1] : argv; if (argv) { var argvExists = fileExists(path.join(home, fileName)); if (argvExists) { return requireCtr(path.join(home, fileName)); } } //process check var processExists = fileExists(path.join(process.cwd(), fileName)); if (processExists) { return requireCtr(path.join(process.cwd(), fileName)); } //instance option if (instanceOption) { return requireCtr(instanceOption); } //non, return to asing return { rcVars: {}, rcGlobalOption: {} }; }; module.exports = config; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Immutable = __webpack_require__(1); /** * Creates a Flexbox container. * * @param {string} [$direction=row] * The flex-direction the container should create. * This is typically opposite to the element you're creating * so a row() would need flex-container(column). * * @example * $flexbox = true * * section * flex-container() * figure * column('1/2') */ var flexContainer = function flexContainer(data) { var res = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var defaultDir = arguments[2]; //config direction var direction = void 0; var key = void 0; //config key based on the map if (Immutable.Map.isMap(defaultDir)) { key = data; res = {}; } else { key = defaultDir || data; } //if gate if (key === true) { //default to row direction = 'row wrap'; } else if (key === 'row') { direction = 'row wrap'; } else if (key === 'column') { direction = 'column nowrap'; } else { direction = key; } //set res res.display = 'flex'; res['flex-flow'] = direction; return res; }; module.exports = flexContainer; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(0); var animation = __webpack_require__(190); var state = __webpack_require__(248); var filter = __webpack_require__(218); var filterMod = __webpack_require__(219); var _H = __webpack_require__(3); var fuzzy = __webpack_require__(19); var getPreset = function getPreset() { var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'all'; var presetKey = arguments[1]; var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, stateType = _ref.stateType, modifiers = _ref.modifiers; var preset = null; if (type === 'animation') { //loopp to find preset match _.forEach(animation, function (collection) { if (collection[presetKey]) { preset = collection[presetKey]; //bust loop return false; } }); } else if (type === 'state') { _.forEach(state, function (collection) { if (collection[presetKey]) { //we have to do a bit of configuration with state due to the statetype preset = _.reduce(collection[presetKey], function (prv, val, key) { if (key === 'static') { prv[key] = val; } else if (key === stateType) { //want to inject these properties into root of object prv = _.reduce(val, function (_prv, _val, _key) { if (!_prv[_key]) { //set _prv[_key] = _val; } return _prv; }, prv); } return prv; }, {}); //bust loop return false; } }); } else if (type === 'filter') { //loopp to find preset match _.forEach(filter, function (collection) { if (collection[presetKey]) { preset = collection[presetKey]; //handle modifiers if (!_.isEmpty(modifiers.filter) || !_.isEmpty(modifiers.element)) { preset = filterMod(preset, modifiers); } //bust loop return false; } }); } //If no preset is found throw an error if (!preset) { /** * Helper to get preset keys to fuzz against * @return {arr} -> keys to fuzzy */ var getKeysToFuzzy = function getKeysToFuzzy() { var keys = []; //wrapper to push keys var pushKeys = function pushKeys(colType) { _.forEach(colType, function (col) { keys = _.union(keys, _.keys(col)); }); }; if (type === 'animation') { pushKeys(animation); } else if (type === 'state') { pushKeys(state); } else if (type === 'filter') { pushKeys(filter); } else { //all pushKeys(state, animation); } return keys; }; //throw error _H.throwErr({ type: 'Preset Not Found', msg: ['I could not find your preset:' + presetKey + '. Maybe you are trying to', 'use a preset that does not exist or you misspelled it. I misspell it all the time.', 'Like a good neighbor, let me fuzzy check it for you against all presets.\n', fuzzy(presetKey, getKeysToFuzzy())].join(' ') }); return false; } return preset; }; module.exports = getPreset; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _ = __webpack_require__(0); var Immutable = __webpack_require__(1); var targetSelector = __webpack_require__(29); /** * Will merge target data for two target instances * @param {map} target -> Target instance * @param {map} mergeTarget -> Target instance to be merged * @param {obj} parentObjRef -> Refrance to parent obj * @return {map} -> Merged target */ var targetUtil = { setStack: function setStack(target, type, id) { var stackProcess = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; if (!target.has('stack')) { target = target.set('stack', Immutable.List()); } //add to list and return var index = target.get(type); index = index ? index.size : 0; return target.update('stack', function (list) { return list.push(Immutable.Map({ type: type, index: index, id: id, process: stackProcess })); }); }, set: function set(dataMap) { var target = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var self = this; target = target ? target : Immutable.Map(); var type = dataMap.get('type'); var id = dataMap.get('id'); var stackProcess = dataMap.get('stackProcess'); stackProcess = _.isBoolean(stackProcess) ? stackProcess : true; target = this.setStack(target, type, id, stackProcess); //check if key exists, if not initilize if (!target.has(type)) { target = target.set(type, Immutable.List()); } //add to list and return target = target.update(type, function (list) { //update map dataMap = dataMap.withMutations(function (map) { //check for spe // let specificOption = map.get('specificOption'); return map.set('process', stackProcess).set('option', self.setOption(map.get('option'), map)); }); return list.push(dataMap); }); return target; }, update: function update(target, data) { var type = data.type; var id = data.id; var val = data.val; var key = data.key; var merge = data.merge || false; var overwrite = data.overwrite || false; if (_.isUndefined(val)) { return target; } return target.update(type, function (list) { //get index of id var _list$findEntry = list.findEntry(function (valMap) { return valMap.get('id') === id; }), _list$findEntry2 = _slicedToArray(_list$findEntry, 1), index = _list$findEntry2[0]; //update list with new val return list.update(index, function (valMap) { if (merge) { return _.cloneDeep(valMap.toJS(), val); // return util.merge(valMap.toJS(), val); } else if (!valMap.has(key) || overwrite) { valMap = valMap.set(key, val); } else { valMap = valMap.update(key, function (_val) { return _.cloneDeep(_val, val); }); } return valMap; }); }); }, //terminates we need to keep the reffrance terminator: function terminator(data) { var self = this; var id = data.id; var type = data.type; var target = data.target; var removedFromStack = _.isBoolean(data.removedFromStack) ? data.removedFromStack : false; //update process target = self.update(target, { id: id, val: false, type: type, key: 'process', overwrite: true }); if (!removedFromStack) { return self.terminator({ id: id, type: 'stack', target: target, removedFromStack: true }); } return target; }, setId: function setId(target) { var val = targetSelector.compose(target); var id = val.selectorCar; id += val.selector; id += val.selectorCdr; id += val.selectorMedia; //set id target = target.set('id', id); //update selectors _.forEach(_.keys(val), function (updateKey) { target = target.set(updateKey, val[updateKey]); }); //@todo do I need? target = target.set('hash', target.hashCode()); return target; }, setOption: function setOption(optionMap, dataMap) { //set default optionMap = optionMap ? optionMap : Immutable.Map(); //@todo childrenInherit var targetList = ['applyTo', 'attachTo', 'appendTo', 'root', 'override', 'inherit', 'inheritOpt', 'inheritProp', 'appendKey']; var updateOpt = function updateOpt(map, key, optVal, optKey, addOn) { return map.update(key, function (optMap) { if (!optMap.has(optKey)) { optMap = optMap.set(optKey, optVal); } else if (addOn) { optMap = optMap.set(optKey, optMap.update(optVal, function (_val) { _val += optVal; return _val; })); } return optMap; }); }; return optionMap.reduce(function (map, optVal, optKey) { //add in any raw options, will not be prefixed if (optKey.charAt(0) !== '_' && optKey !== 'andQuery' && optKey !== 'orQuery') { map = map.setIn(['raw', optKey], optVal); } if (_.includes(targetList, optKey)) { //target return updateOpt(map, 'target', optVal, optKey, dataMap.get('addOn')); } //specific return updateOpt(map, 'specific', optVal, optKey); }, Immutable.Map({ //@pr-193 target: Immutable.Map(), //@todo maybe change name to internal, and have raw be specific specific: Immutable.Map(), //any non-internal options raw: Immutable.Map() })); } }; module.exports = targetUtil; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(0); /** * Scores the matches * @param {str} pattern -> patter to match against * @param {str} str -> string in question * @return {obj} -> {score, render} */ var match = function match(pattern, str) { var result = []; var len = str.length; var compareString = str.toLowerCase(); var patternIdx = 0; var totalScore = 0; var currScore = 0; var ch = null; pattern = pattern.toLowerCase(); // For each character in the string, either add it to the result // or wrap in template if it's the next string in the pattern for (var i = 0; i < len; i++) { ch = str[i]; if (compareString[i] === pattern[patternIdx]) { patternIdx += 1; // consecutive characters should increase the score more than linearly currScore += 1 + currScore; } else { currScore = 0; } totalScore += currScore; result[result.length] = ch; } //return if there is any match, since we sort in res if (totalScore) { // if the string is an exact match with pattern, totalScore should be maxed totalScore = compareString === pattern ? Infinity : totalScore; return { rendered: result.join(''), score: totalScore }; } return null; }; /** * Basic fuzzy search * @param {str} pattern -> pattern to match against * @param {arr} list -> match array * @param {obj} option -> options * @return {str} -> fuzzy results */ var fuzzySearch = function fuzzySearch(pattern, list) { var option = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { count: 10, joinBy: ' ›—‹ ' }; //empty arg if (!list || list.length === 0) { return []; } //process var matchRes = _.reduce(list, function (prv, str) { var rendered = match(pattern, str); if (rendered !== null) { prv[str] = { string: rendered.rendered, score: rendered.score }; } return prv; }, {}); //return if (_.isEmpty(matchRes)) { return `Fuzzy search against "${pattern}" came back empty, sorry.`; } return `Fuzzy search results against "${pattern}": [${_.reduce(_.sortBy(matchRes, ['score']).reverse(), function (prv, val, index) { if (option.count > index) { prv.push(val.string); } return prv; }, []).join(option.joinBy)}]`; }; module.exports = fuzzySearch; /***/ }), /* 20 */ /***/ (function(module, exports) { module.exports = require("js-yaml"); /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _ = __webpack_require__(0); var path = __webpack_require__(13); var styl = __webpack_require__(10); var CTR = __webpack_require__(14); var config = __webpack_require__(15); var throwErr = __webpack_require__(9); var convert = __webpack_require__(12); var Nodes = styl.nodes; /** * Processes the stylus data by convertiting it to a js objcect and sending * it off to be complied by ctr * @param {obj} options.self -> Stylus ref from define * @param {obj} options.ctr -> the ctr instance * @param {obj} options.args -> Args for a CtrClass * @param {obj} options.data -> Stylus hash object */ var processStylus = fun