diff --git a/css-doodle.js b/css-doodle.js index 6257c8f..afa57b1 100644 --- a/css-doodle.js +++ b/css-doodle.js @@ -134,30 +134,48 @@ function remove_unit(str) { return unit ? +(str.replace(unit, '')) : str; } -const DEG = Math.PI / 180; +const { cos, sin, PI } = Math; +const DEG = PI / 180; -const polygon = function(sides, start = 0, deg) { - deg = deg || (Math.PI / (sides / 2)); - var points = []; - for (var i = 0; i < sides; ++i) { - var theta = start + deg * i; - points.push(` - ${ Math.cos(theta) * 50 + 50 }% ${ Math.sin(theta) * 50 + 50}% - `); +function polygon(option, fn) { + if (typeof arguments[0] == 'function') { + fn = option; + option = {}; } + + if (!fn) { + fn = theta => [ cos(theta), sin(theta) ]; + } + + var split = option.split || 120; + var scale = option.scale || 1; + var start = DEG * (option.start || 0); + var deg = option.deg ? (option.deg * DEG) : (PI / (split / 2)); + var points = []; + + for (var i = 0; i < split; ++i) { + var theta = start + deg * i; + var [x, y] = fn(theta); + points.push( + ((x * 50 * scale) + 50 + '% ') + + ((y * 50 * scale) + 50 + '%') + ); + } + return `polygon(${ points.join(',') })`; -}; +} + function circle() { return 'circle(49.5%)'; } -function siogon(sides) { - return polygon(minmax(sides, 3, 12)); +function siogon(sides = 3) { + return polygon({ split: minmax(sides, 3, 12) }); } function triangle() { - return polygon(3, DEG * -90); + return polygon({ split: 3, start: -90 }); } function rhombus() { @@ -165,15 +183,15 @@ function rhombus() { } function pentagon() { - return polygon(5, DEG * 54); + return polygon({ split: 5, start: 54 }); } function hexgon() { - return polygon(6, DEG * 30); + return polygon({ split: 6, start: 30 }); } function star() { - return polygon(5, DEG * 54, DEG * 144); + return polygon({ split: 5, start: 54, deg: 144 }); } function diamond() { @@ -188,48 +206,28 @@ function cross() { )`; } -const hypocycloid = memo('hypocycloid', function(k = 3) { +function clover(k = 3) { + k = minmax(k, 3, 5); + if (k == 4) k = 2; + return polygon({ split: 240 }, theta => [ + cos(k * theta) * cos(theta), + cos(k * theta) * sin(theta) + ]); +} + +function hypocycloid(k = 3) { k = minmax(k, 3, 6); - var split = 120; - var deg = Math.PI / (split / 2); - var R = 50; - var r = R / k; - var points = []; - for (var i = 0; i < split; ++i) { - var theta = deg * i + Math.PI; - var x = r * (1 - k) * Math.cos(theta) + r * Math.cos((1 - k) * (theta - Math.PI)); - var y = r * (1 - k) * Math.sin(theta) + r * Math.sin((1 - k) * (theta - Math.PI)); - points.push((x + 50 + '% ') + (y + 50+ '%')); - } - return `polygon(${ points.join(',') })`; -}); + var m = 1 - k; + return polygon({ scale: 1 / k }, theta => [ + m * cos(theta) + cos(m * (theta - PI)), + m * sin(theta) + sin(m * (theta - PI)) + ]); +} function astroid() { return hypocycloid(4); } -const clover = memo('clover', function(k = 3) { - switch (k) { - case 4: k = 2; break; - case 5: k = 5; break; - case 3: k = 3; - default: { - if (k > 5) k = 5; - else if (k < 3) k = 3; - } - } - var split = 240; - var deg = Math.PI / (split / 2); - var points = []; - for (var i = 0; i < split; ++i) { - var theta = deg * i; - var x = Math.cos(k * theta) * Math.cos(theta); - var y = Math.cos(k * theta) * Math.sin(theta); - points.push((x * 50 + 50 + '% ') + (y * 50 + 50+ '%')); - } - return `polygon(${ points.join(',') })`; -}); - var shapes = Object.freeze({ circle: circle, @@ -241,9 +239,9 @@ var shapes = Object.freeze({ star: star, diamond: diamond, cross: cross, + clover: clover, hypocycloid: hypocycloid, - astroid: astroid, - clover: clover + astroid: astroid }); function index(x, y, count) { diff --git a/css-doodle.min.js b/css-doodle.min.js index 9a98e8e..567bfb7 100644 --- a/css-doodle.min.js +++ b/css-doodle.min.js @@ -1 +1 @@ -!function(e,n){typeof exports==='object'&&typeof module!=='undefined'?n():typeof define==='function'&&define.amd?define(n):(n())}(this,(function(){"use strict";var e={even:e=>!!(e%2),odd:e=>!(e%2)};function n(e,n,t){return e=>e==t}function t(e,n){return(t,r)=>e==t&&n==r}function r(n,t,r){return t=>/^(even|odd)$/.test(t)?e[t](n-1):t==n}function u(n,t,r){return n=>/^(even|odd)$/.test(n)?e[n](t-1):n==t}function o(n,t,r){return n=>e.even(r-1)}function c(n,t,r){return n=>e.odd(r-1)}var s=Object.freeze({nth:n,at:t,row:r,col:u,even:o,odd:c});function i(e){if(Array.isArray(e))return e;return Object.keys(e).map(n=>e[n])}function l(e,...n){return n.reduce((e,n)=>e.apply(null,i(n)),e)}function a(e){return(e||[]).join('\n')}function p(e){return Array.isArray(e)?e:[e]}function f(e,n,t){return Math.max(n,Math.min(t,e))}function h(e){return`-webkit-${e}${e}`}function m(e,n){let t={};return function(...r){let u=e+r.join('-');if(t[u])return t[u];return t[u]=n.apply(null,r)}}function d(...e){let n=e.reduce((e,n)=>e.concat(n),[]);return n[Math.floor(Math.random()*n.length)]}function y(e,n,t){let r=0,u=e=>e>0&&e<1?.1:1,o=arguments.length;o==1&&([e,n]=[u(e),e]);o<3&&(t=u(e));let c=[];while(t>0&&en){c.push(e);e+=t;if(r++>=1e3)break}return c}function g(e){return function(...n){let t=_(n[0]);if(t){n=n.map(w);return x(e,t).apply(null,n)}return e.apply(null,n)}}function x(e,n){return function(...t){t=t.map(w);let r=e.apply(null,t);n&&(r=r.map(e=>e+n));return r}}function _(e){if(!e)return'';let n=/(%|cm|fr|rem|em|ex|in|mm|pc|pt|px|vh|vw|vmax|vmin|deg|ms|s)$/,t=''.trim.call(e).match(n);return t?t[0]:''}function w(e){let n=_(e);return n?+(e.replace(n,'')):e}let b=Math.PI/180,v=function(e,n = 0,t){t=t||Math.PI/(e/2);var r=[];for(var u=0;u5?(e=5):e<3&&(e=3)}}var n=240,t=Math.PI/(n/2),r=[];for(var u=0;ut}function q(e,n,t){return n=>e}function B(e,n,t){return e=>n}function E(){return function(...e){return d.apply(null,e)}}function O(){return E.apply(null,arguments)}function D(){return function(...e){return d(m('range',g(y)).apply(null,e))}}function F(e,n,t){return function(e,...n){if(e){e=e.trim();if(C[e]){return C[e].apply(null,n)}}}}var G=Object.freeze({index:R,row:q,col:B,any:E,pick:O,rand:D,shape:F});class J{constructor(e){this.tokens=e;this.rules={};this.props={};this.styles={host:'',cells:''}}add_rule(e,n){var t=this.rules[e];t||(t=this.rules[e]=[]);t.push.apply(t,p(n))}compose_selector(e,n = ''){return`.cell:nth-of-type(${e}) .shape${n}`}compose_argument(e,n){var t=e.map(e=>{if(e.type=='text'){return e.value}else if(e.type=='func'){var t=G[e.name.substr(1)];if(t){var r=e.arguments.map(e=>{return this.compose_argument(e,n)});return l(t,n,r)}}});return t.length>2?t.join(''):t[0]}compose_value(e,n){return e.reduce((e,t)=>{switch(t.type){case 'text':{e+=t.value;break};case 'func':{var r=G[t.name.substr(1)];if(r){var u=t.arguments.map(e=>{return this.compose_argument(e,n)});e+=l(r,n,u)}}}return e},'')}compose_rule(e,n){var t=e.property,r=this.compose_value(e.value,n);t=='transition'&&(this.props.has_transition=!0);var u=`${t}:${r};`;t=='clip-path'&&(u=h(u),u+=';overflow:hidden;');t=='size'&&(u=`width:${r};height:${r};`);return u}compose(e,n){(n||this.tokens).forEach((n,t)=>{if(n.skip)return!1;switch(n.type){case 'rule':this.add_rule(this.compose_selector(e.count),this.compose_rule(n,e));break;case 'psudo':{n.selector.startsWith(':doodle')&&(n.selector=n.selector.replace(/^\:+doodle/,':host'));var c=n.selector.startsWith(':host');c&&(n.skip=!0);var i=n.styles.map(n=>this.compose_rule(n,e)),a=c?n.selector:this.compose_selector(e.count,n.selector);this.add_rule(a,i);break};case 'cond':var o=s[n.name.substr(1)];if(o){var r=n.arguments.map(n=>{return this.compose_argument(n,e)}),u=l(o,e,r);u&&this.compose(e,n.styles)};break}})}output(){Object.keys(this.rules).forEach(e=>{var n=e.startsWith(':host');let t=n?'host':'cells';this.styles[t]+=`${e}{${a(this.rules[e])}}`});return{props:this.props,styles:this.styles}}}function K(e,n){var t=new J(e);for(var r=1,u=0;r<=n.x;++r){for(var o=1;o<=n.y;++o)t.compose({x:r,y:o,count:++u})}return t.output()}let N={func(e = ''){return{type:'func',name:e,arguments:[]}},argument(){return{type:'argument',value:[]}},text(e = ''){return{type:'text',value:e}},comment(e){return{type:'comment',value:e}},psudo(e = ''){return{type:'psudo',selector:e,styles:[]}},cond(e = ''){return{type:'cond',name:e,styles:[],arguments:[]}},rule(e = ''){return{type:'rule',property:e,value:[]}}},Q={'(':')','[':']','{':'}'},U={white_space(e){return /[\s\n\t]/.test(e)},open_bracket(e){return Q.hasOwnProperty(e)},close_bracket_of(e){var n=Q[e];return e=>e==n},number(e){return!isNaN(e)}};function V(e){var n=0,t=1,r=1;return{curr:(t = 0)=>e[n+t],end:()=>e.length<=n,info:()=>({index:n,col:t,line:r}),next:()=>{var u=e[n++];u=='\n'?(r++, t=0):t++;return u}}}function X(e,{col:n,line:t}){throw new Error(`(at line ${t}, column ${n}) ${e}`)}function Y(e){if(e.trim().length){return U.number(+e)?+e:e.trim()}else{return e}}function Z(e){var[n,t]=[e.curr(),e.curr()],r=U.close_bracket_of(t);e.next();while(!e.end()){if(r(t=e.curr())){n+=t;break}else U.open_bracket(t)?(n+=Z(e)):(n+=t);e.next()}return n}function $(e,n ={}){var t=N.comment(),r=e.curr();r!='#'&&e.next();e.next();while(!e.end()){if((r=e.curr())=='*'&&e.curr(1)=='/')break;else t.value+=r;r=e.curr();if(n.inline){if(r=='\n')return t}else{if(r=='*'&&e.curr(1)=='/')break}t.value+=r;e.next()}e.next();e.next();return t}function ee(e){var n='',t;while(!e.end()){if((t=e.curr())==':')break;else /[a-zA-Z\-]/.test(t)?U.white_space(t)||(n+=t):X('Syntax error:Bad property name.',e.info());e.next()}return n}function ne(e,n){var t='',r;e.next();while(!e.end()){if((r=e.curr())==n){if(e.curr(-1)!=='\\')break;else t+=r}else t+=r;e.next()}return t}function te(e){var n=[],t=[],r='',u;while(!e.end()){if(U.open_bracket(u=e.curr()))r+=Z(e);else if(/['"]/.test(u))r+=ne(e,u);else if(u=='@')t.length||(r=r.trimLeft()),r.length&&(t.push(N.text(r)),r=''),t.push(re(e));else if(/[,)]/.test(u)){r.length&&(t.length?(r=r.trimRight(),r.length&&t.push(N.text(r))):t.push(N.text(Y(r))));n.push(t.slice());[t,r]=[[],''];if(u==')')break}else r+=u;e.next()}return n}function re(e){var n=N.func(),t='',r;while(!e.end()){if((r=e.curr())==')')break;if(r=='('){e.next();n.name=t;n.arguments=te(e);break}else t+=r;e.next()}return n}function ue(e){var n=N.text(),t;let r=[];while(!e.end()){if((t=e.curr())=='\n'){e.next();continue}else if(/[;}]/.test(t)){n.value.length&&r.push(n);n=N.text();break}else t=='@'?(n.value.length&&r.push(n),n=N.text(),r.push(re(e))):(!U.white_space(t)||!U.white_space(e.curr(-1)))&&(t==':'&&X('Syntax error:Bad property name.',e.info()),n.value+=t);e.next()}n.value.length&&r.push(n);r.length&&(r[0].value=r[0].value.trimLeft());return r}function oe(e){var n='',t;while(!e.end()){if((t=e.curr())=='{')break;else U.white_space(t)||(n+=t);e.next()}return n}function ce(e){var n={name:'',arguments:[]},t;while(!e.end()){if((t=e.curr())=='(')e.next(),n.arguments=te(e);else if(/[){]/.test(t))break;else U.white_space(t)||(n.name+=t);e.next()}return n}function se(e){var n=N.psudo(),t;while(!e.end()){if((t=e.curr())=='}')break;if(U.white_space(t)){e.next();continue}else n.selector?n.styles.push(ie(e)):(n.selector=oe(e));e.next()}return n}function ie(e){var n=N.rule(),t;while(!e.end()){if((t=e.curr())==';')break;else if(!n.property.length)n.property=ee(e);else{n.value=ue(e);break}e.next()}return n}function le(e){var n=N.cond(),t;while(!e.end()){if((t=e.curr())=='}')break;else if(!n.name.length)Object.assign(n,ce(e));else if(t==':'){var r=se(e);r.selector&&n.styles.push(r)}else if(t=='@')n.styles.push(le(e));else if(!U.white_space(t)){var u=ie(e);u.property&&n.styles.push(u)}e.next()}return n}function ae(e){let n=V(e),t=[];while(!n.end()){var r=n.curr();if(U.white_space(r)){n.next();continue}else if(r=='/'&&n.curr(1)=='*')t.push($(n));else if(r=='#'||r=='/'&&n.curr(1)=='/')t.push($(n,{inline:!0}));else if(r==':'){var u=se(n);u.selector&&t.push(u)}else if(r=='@'){var o=le(n);o.name.length&&t.push(o)}else if(!U.white_space(r)){var c=ie(n);c.property&&t.push(c)}n.next()}return t}function pe(e,n){return K(ae(e),n)}let fe=1,he=16;function me(e){let[n,t]=(e+'').replace(/\s+/g,'').replace(/[,,xX]+/,'x').split('x').map(Number),r={x:f(n||fe,1,he),y:f(t||n||fe,1,he)};return Object.assign({},r,{count:r.x*r.y})}let de="\n:host{display:block;visibility:visible;width:1em;height:1em;}.container{position:relative;width:100%;height:100%\n}.container:after{content:'';display:block;clear:both;visibility:hidden\n}.cell{position:relative;float:left;line-height:0;box-sizing:border-box\n}.shape{box-sizing:border-box;line-height:0;position:absolute;width:100%;height:100%;transform-origin:center center;z-index:1;display:flex;align-items:center;justify-content:center\n}";class ye extends HTMLElement{constructor(){super();this.doodle=this.attachShadow({mode:'open'})}connectedCallback(){setTimeout(()=>{if(!this.innerHTML.trim()){return!1}let e;try{e=pe(this.innerHTML,this.size=me(this.getAttribute('grid')))}catch(e){this.innerHTML='';throw new Error(e)};let{has_transition:n}=e.props;this.doodle.innerHTML=`
${this.html_cells()}
`;n&&setTimeout(()=>{this.set_style('.style-cells',e.styles.cells)},50)})}style_size(){return`.cell{width:${100/this.size.y+'%'};height:${100/this.size.x+'%'};}`}html_cells(){let e="\n
";return e.repeat(this.size.count)}set_style(e,n){let t=this.shadowRoot.querySelector(e);t&&(t.styleSheet?(t.styleSheet.cssText=n):(t.innerHTML=n))}update(e){if(!e){return!1}this.size||(this.size=me(this.getAttribute('grid')));let n=pe(e,this.size);this.set_style('.style-container',this.style_size()+n.styles.host);this.set_style('.style-cells',n.styles.cells);this.innerHTML=e}refresh(){this.update(this.innerHTML)}get grid(){return Object.assign({},this.size)}set grid(e){this.setAttribute('grid',e);this.connectedCallback()}static get observedAttributes(){return['grid']}attributeChangedCallback(e,n,t){e=='grid'&&n&&(n!==t&&(this.grid=t))}}customElements.define('css-doodle',ye)})) \ No newline at end of file +!function(e,t){typeof exports==='object'&&typeof module!=='undefined'?t():typeof define==='function'&&define.amd?define(t):(t())}(this,(function(){"use strict";var e={even:e=>!!(e%2),odd:e=>!(e%2)};function t(e,t,n){return e=>e==n}function n(e,t){return(n,r)=>e==n&&t==r}function r(t,n,r){return n=>/^(even|odd)$/.test(n)?e[n](t-1):n==t}function u(t,n,r){return t=>/^(even|odd)$/.test(t)?e[t](n-1):t==n}function o(t,n,r){return t=>e.even(r-1)}function c(t,n,r){return t=>e.odd(r-1)}var s=Object.freeze({nth:t,at:n,row:r,col:u,even:o,odd:c});function i(e){if(Array.isArray(e))return e;return Object.keys(e).map(t=>e[t])}function l(e,...t){return t.reduce((e,t)=>e.apply(null,i(t)),e)}function a(e){return(e||[]).join('\n')}function p(e){return Array.isArray(e)?e:[e]}function f(e,t,n){return Math.max(t,Math.min(n,e))}function h(e){return`-webkit-${e}${e}`}function m(e,t){let n={};return function(...r){let u=e+r.join('-');if(n[u])return n[u];return n[u]=t.apply(null,r)}}function d(...e){let t=e.reduce((e,t)=>e.concat(t),[]);return t[Math.floor(Math.random()*t.length)]}function y(e,t,n){let r=0,u=e=>e>0&&e<1?.1:1,o=arguments.length;o==1&&([e,t]=[u(e),e]);o<3&&(n=u(e));let c=[];while(n>0&&et){c.push(e);e+=n;if(r++>=1e3)break}return c}function g(e){return function(...t){let n=_(t[0]);if(n){t=t.map(w);return x(e,n).apply(null,t)}return e.apply(null,t)}}function x(e,t){return function(...n){n=n.map(w);let r=e.apply(null,n);t&&(r=r.map(e=>e+t));return r}}function _(e){if(!e)return'';let t=/(%|cm|fr|rem|em|ex|in|mm|pc|pt|px|vh|vw|vmax|vmin|deg|ms|s)$/,n=''.trim.call(e).match(t);return n?n[0]:''}function w(e){let t=_(e);return t?+(e.replace(t,'')):e}let{cos:b,sin:v,PI:z}=Math,k=z/180;function L(e,t){typeof arguments[0]=='function'&&(t=e,e={});t||(t=e=>[b(e),v(e)]);var n=e.split||120,r=e.scale||1,u=k*(e.start||0),o=e.deg?e.deg*k:z/(n/2),c=[];for(var s=0;s[b(e*t)*b(t),b(e*t)*v(t)])}function B(e = 3){e=f(e,3,6);var t=1-e;return L({scale:1/e},e=>[t*b(e)+b(t*(e-z)),t*v(e)+v(t*(e-z))])}function E(){return B(4)}var O=Object.freeze({circle:T,siogon:H,triangle:M,rhombus:S,pentagon:j,hexgon:A,star:W,diamond:C,cross:R,clover:q,hypocycloid:B,astroid:E});function P(e,t,n){return e=>n}function D(e,t,n){return t=>e}function F(e,t,n){return e=>t}function G(){return function(...e){return d.apply(null,e)}}function I(){return G.apply(null,arguments)}function J(){return function(...e){return d(m('range',g(y)).apply(null,e))}}function K(e,t,n){return function(e,...t){if(e){e=e.trim();if(O[e]){return O[e].apply(null,t)}}}}var N=Object.freeze({index:P,row:D,col:F,any:G,pick:I,rand:J,shape:K});class Q{constructor(e){this.tokens=e;this.rules={};this.props={};this.styles={host:'',cells:''}}add_rule(e,t){var n=this.rules[e];n||(n=this.rules[e]=[]);n.push.apply(n,p(t))}compose_selector(e,t = ''){return`.cell:nth-of-type(${e}) .shape${t}`}compose_argument(e,t){var n=e.map(e=>{if(e.type=='text'){return e.value}else if(e.type=='func'){var n=N[e.name.substr(1)];if(n){var r=e.arguments.map(e=>{return this.compose_argument(e,t)});return l(n,t,r)}}});return n.length>2?n.join(''):n[0]}compose_value(e,t){return e.reduce((e,n)=>{switch(n.type){case 'text':{e+=n.value;break};case 'func':{var r=N[n.name.substr(1)];if(r){var u=n.arguments.map(e=>{return this.compose_argument(e,t)});e+=l(r,t,u)}}}return e},'')}compose_rule(e,t){var n=e.property,r=this.compose_value(e.value,t);n=='transition'&&(this.props.has_transition=!0);var u=`${n}:${r};`;n=='clip-path'&&(u=h(u),u+=';overflow:hidden;');n=='size'&&(u=`width:${r};height:${r};`);return u}compose(e,t){(t||this.tokens).forEach((t,n)=>{if(t.skip)return!1;switch(t.type){case 'rule':this.add_rule(this.compose_selector(e.count),this.compose_rule(t,e));break;case 'psudo':{t.selector.startsWith(':doodle')&&(t.selector=t.selector.replace(/^\:+doodle/,':host'));var c=t.selector.startsWith(':host');c&&(t.skip=!0);var i=t.styles.map(t=>this.compose_rule(t,e)),a=c?t.selector:this.compose_selector(e.count,t.selector);this.add_rule(a,i);break};case 'cond':var o=s[t.name.substr(1)];if(o){var r=t.arguments.map(t=>{return this.compose_argument(t,e)}),u=l(o,e,r);u&&this.compose(e,t.styles)};break}})}output(){Object.keys(this.rules).forEach(e=>{var t=e.startsWith(':host');let n=t?'host':'cells';this.styles[n]+=`${e}{${a(this.rules[e])}}`});return{props:this.props,styles:this.styles}}}function U(e,t){var n=new Q(e);for(var r=1,u=0;r<=t.x;++r){for(var o=1;o<=t.y;++o)n.compose({x:r,y:o,count:++u})}return n.output()}let V={func(e = ''){return{type:'func',name:e,arguments:[]}},argument(){return{type:'argument',value:[]}},text(e = ''){return{type:'text',value:e}},comment(e){return{type:'comment',value:e}},psudo(e = ''){return{type:'psudo',selector:e,styles:[]}},cond(e = ''){return{type:'cond',name:e,styles:[],arguments:[]}},rule(e = ''){return{type:'rule',property:e,value:[]}}},X={'(':')','[':']','{':'}'},Y={white_space(e){return /[\s\n\t]/.test(e)},open_bracket(e){return X.hasOwnProperty(e)},close_bracket_of(e){var t=X[e];return e=>e==t},number(e){return!isNaN(e)}};function Z(e){var t=0,n=1,r=1;return{curr:(n = 0)=>e[t+n],end:()=>e.length<=t,info:()=>({index:t,col:n,line:r}),next:()=>{var u=e[t++];u=='\n'?(r++, n=0):n++;return u}}}function $(e,{col:t,line:n}){throw new Error(`(at line ${n}, column ${t}) ${e}`)}function ee(e){if(e.trim().length){return Y.number(+e)?+e:e.trim()}else{return e}}function te(e){var[t,n]=[e.curr(),e.curr()],r=Y.close_bracket_of(n);e.next();while(!e.end()){if(r(n=e.curr())){t+=n;break}else Y.open_bracket(n)?(t+=te(e)):(t+=n);e.next()}return t}function ne(e,t ={}){var n=V.comment(),r=e.curr();r!='#'&&e.next();e.next();while(!e.end()){if((r=e.curr())=='*'&&e.curr(1)=='/')break;else n.value+=r;r=e.curr();if(t.inline){if(r=='\n')return n}else{if(r=='*'&&e.curr(1)=='/')break}n.value+=r;e.next()}e.next();e.next();return n}function re(e){var t='',n;while(!e.end()){if((n=e.curr())==':')break;else /[a-zA-Z\-]/.test(n)?Y.white_space(n)||(t+=n):$('Syntax error:Bad property name.',e.info());e.next()}return t}function ue(e,t){var n='',r;e.next();while(!e.end()){if((r=e.curr())==t){if(e.curr(-1)!=='\\')break;else n+=r}else n+=r;e.next()}return n}function oe(e){var t=[],n=[],r='',u;while(!e.end()){if(Y.open_bracket(u=e.curr()))r+=te(e);else if(/['"]/.test(u))r+=ue(e,u);else if(u=='@')n.length||(r=r.trimLeft()),r.length&&(n.push(V.text(r)),r=''),n.push(ce(e));else if(/[,)]/.test(u)){r.length&&(n.length?(r=r.trimRight(),r.length&&n.push(V.text(r))):n.push(V.text(ee(r))));t.push(n.slice());[n,r]=[[],''];if(u==')')break}else r+=u;e.next()}return t}function ce(e){var t=V.func(),n='',r;while(!e.end()){if((r=e.curr())==')')break;if(r=='('){e.next();t.name=n;t.arguments=oe(e);break}else n+=r;e.next()}return t}function se(e){var t=V.text(),n;let r=[];while(!e.end()){if((n=e.curr())=='\n'){e.next();continue}else if(/[;}]/.test(n)){t.value.length&&r.push(t);t=V.text();break}else n=='@'?(t.value.length&&r.push(t),t=V.text(),r.push(ce(e))):(!Y.white_space(n)||!Y.white_space(e.curr(-1)))&&(n==':'&&$('Syntax error:Bad property name.',e.info()),t.value+=n);e.next()}t.value.length&&r.push(t);r.length&&(r[0].value=r[0].value.trimLeft());return r}function ie(e){var t='',n;while(!e.end()){if((n=e.curr())=='{')break;else Y.white_space(n)||(t+=n);e.next()}return t}function le(e){var t={name:'',arguments:[]},n;while(!e.end()){if((n=e.curr())=='(')e.next(),t.arguments=oe(e);else if(/[){]/.test(n))break;else Y.white_space(n)||(t.name+=n);e.next()}return t}function ae(e){var t=V.psudo(),n;while(!e.end()){if((n=e.curr())=='}')break;if(Y.white_space(n)){e.next();continue}else t.selector?t.styles.push(pe(e)):(t.selector=ie(e));e.next()}return t}function pe(e){var t=V.rule(),n;while(!e.end()){if((n=e.curr())==';')break;else if(!t.property.length)t.property=re(e);else{t.value=se(e);break}e.next()}return t}function fe(e){var t=V.cond(),n;while(!e.end()){if((n=e.curr())=='}')break;else if(!t.name.length)Object.assign(t,le(e));else if(n==':'){var r=ae(e);r.selector&&t.styles.push(r)}else if(n=='@')t.styles.push(fe(e));else if(!Y.white_space(n)){var u=pe(e);u.property&&t.styles.push(u)}e.next()}return t}function he(e){let t=Z(e),n=[];while(!t.end()){var r=t.curr();if(Y.white_space(r)){t.next();continue}else if(r=='/'&&t.curr(1)=='*')n.push(ne(t));else if(r=='#'||r=='/'&&t.curr(1)=='/')n.push(ne(t,{inline:!0}));else if(r==':'){var u=ae(t);u.selector&&n.push(u)}else if(r=='@'){var o=fe(t);o.name.length&&n.push(o)}else if(!Y.white_space(r)){var c=pe(t);c.property&&n.push(c)}t.next()}return n}function me(e,t){return U(he(e),t)}let de=1,ye=16;function ge(e){let[t,n]=(e+'').replace(/\s+/g,'').replace(/[,,xX]+/,'x').split('x').map(Number),r={x:f(t||de,1,ye),y:f(n||t||de,1,ye)};return Object.assign({},r,{count:r.x*r.y})}let xe="\n:host{display:block;visibility:visible;width:1em;height:1em;}.container{position:relative;width:100%;height:100%\n}.container:after{content:'';display:block;clear:both;visibility:hidden\n}.cell{position:relative;float:left;line-height:0;box-sizing:border-box\n}.shape{box-sizing:border-box;line-height:0;position:absolute;width:100%;height:100%;transform-origin:center center;z-index:1;display:flex;align-items:center;justify-content:center\n}";class _e extends HTMLElement{constructor(){super();this.doodle=this.attachShadow({mode:'open'})}connectedCallback(){setTimeout(()=>{if(!this.innerHTML.trim()){return!1}let e;try{e=me(this.innerHTML,this.size=ge(this.getAttribute('grid')))}catch(e){this.innerHTML='';throw new Error(e)};let{has_transition:t}=e.props;this.doodle.innerHTML=`
${this.html_cells()}
`;t&&setTimeout(()=>{this.set_style('.style-cells',e.styles.cells)},50)})}style_size(){return`.cell{width:${100/this.size.y+'%'};height:${100/this.size.x+'%'};}`}html_cells(){let e="\n
";return e.repeat(this.size.count)}set_style(e,t){let n=this.shadowRoot.querySelector(e);n&&(n.styleSheet?(n.styleSheet.cssText=t):(n.innerHTML=t))}update(e){if(!e){return!1}this.size||(this.size=ge(this.getAttribute('grid')));let t=me(e,this.size);this.set_style('.style-container',this.style_size()+t.styles.host);this.set_style('.style-cells',t.styles.cells);this.innerHTML=e}refresh(){this.update(this.innerHTML)}get grid(){return Object.assign({},this.size)}set grid(e){this.setAttribute('grid',e);this.connectedCallback()}static get observedAttributes(){return['grid']}attributeChangedCallback(e,t,n){e=='grid'&&t&&(t!==n&&(this.grid=n))}}customElements.define('css-doodle',_e)})) \ No newline at end of file diff --git a/docs/lib/css-doodle.min.js b/docs/lib/css-doodle.min.js index 9a98e8e..567bfb7 100644 --- a/docs/lib/css-doodle.min.js +++ b/docs/lib/css-doodle.min.js @@ -1 +1 @@ -!function(e,n){typeof exports==='object'&&typeof module!=='undefined'?n():typeof define==='function'&&define.amd?define(n):(n())}(this,(function(){"use strict";var e={even:e=>!!(e%2),odd:e=>!(e%2)};function n(e,n,t){return e=>e==t}function t(e,n){return(t,r)=>e==t&&n==r}function r(n,t,r){return t=>/^(even|odd)$/.test(t)?e[t](n-1):t==n}function u(n,t,r){return n=>/^(even|odd)$/.test(n)?e[n](t-1):n==t}function o(n,t,r){return n=>e.even(r-1)}function c(n,t,r){return n=>e.odd(r-1)}var s=Object.freeze({nth:n,at:t,row:r,col:u,even:o,odd:c});function i(e){if(Array.isArray(e))return e;return Object.keys(e).map(n=>e[n])}function l(e,...n){return n.reduce((e,n)=>e.apply(null,i(n)),e)}function a(e){return(e||[]).join('\n')}function p(e){return Array.isArray(e)?e:[e]}function f(e,n,t){return Math.max(n,Math.min(t,e))}function h(e){return`-webkit-${e}${e}`}function m(e,n){let t={};return function(...r){let u=e+r.join('-');if(t[u])return t[u];return t[u]=n.apply(null,r)}}function d(...e){let n=e.reduce((e,n)=>e.concat(n),[]);return n[Math.floor(Math.random()*n.length)]}function y(e,n,t){let r=0,u=e=>e>0&&e<1?.1:1,o=arguments.length;o==1&&([e,n]=[u(e),e]);o<3&&(t=u(e));let c=[];while(t>0&&en){c.push(e);e+=t;if(r++>=1e3)break}return c}function g(e){return function(...n){let t=_(n[0]);if(t){n=n.map(w);return x(e,t).apply(null,n)}return e.apply(null,n)}}function x(e,n){return function(...t){t=t.map(w);let r=e.apply(null,t);n&&(r=r.map(e=>e+n));return r}}function _(e){if(!e)return'';let n=/(%|cm|fr|rem|em|ex|in|mm|pc|pt|px|vh|vw|vmax|vmin|deg|ms|s)$/,t=''.trim.call(e).match(n);return t?t[0]:''}function w(e){let n=_(e);return n?+(e.replace(n,'')):e}let b=Math.PI/180,v=function(e,n = 0,t){t=t||Math.PI/(e/2);var r=[];for(var u=0;u5?(e=5):e<3&&(e=3)}}var n=240,t=Math.PI/(n/2),r=[];for(var u=0;ut}function q(e,n,t){return n=>e}function B(e,n,t){return e=>n}function E(){return function(...e){return d.apply(null,e)}}function O(){return E.apply(null,arguments)}function D(){return function(...e){return d(m('range',g(y)).apply(null,e))}}function F(e,n,t){return function(e,...n){if(e){e=e.trim();if(C[e]){return C[e].apply(null,n)}}}}var G=Object.freeze({index:R,row:q,col:B,any:E,pick:O,rand:D,shape:F});class J{constructor(e){this.tokens=e;this.rules={};this.props={};this.styles={host:'',cells:''}}add_rule(e,n){var t=this.rules[e];t||(t=this.rules[e]=[]);t.push.apply(t,p(n))}compose_selector(e,n = ''){return`.cell:nth-of-type(${e}) .shape${n}`}compose_argument(e,n){var t=e.map(e=>{if(e.type=='text'){return e.value}else if(e.type=='func'){var t=G[e.name.substr(1)];if(t){var r=e.arguments.map(e=>{return this.compose_argument(e,n)});return l(t,n,r)}}});return t.length>2?t.join(''):t[0]}compose_value(e,n){return e.reduce((e,t)=>{switch(t.type){case 'text':{e+=t.value;break};case 'func':{var r=G[t.name.substr(1)];if(r){var u=t.arguments.map(e=>{return this.compose_argument(e,n)});e+=l(r,n,u)}}}return e},'')}compose_rule(e,n){var t=e.property,r=this.compose_value(e.value,n);t=='transition'&&(this.props.has_transition=!0);var u=`${t}:${r};`;t=='clip-path'&&(u=h(u),u+=';overflow:hidden;');t=='size'&&(u=`width:${r};height:${r};`);return u}compose(e,n){(n||this.tokens).forEach((n,t)=>{if(n.skip)return!1;switch(n.type){case 'rule':this.add_rule(this.compose_selector(e.count),this.compose_rule(n,e));break;case 'psudo':{n.selector.startsWith(':doodle')&&(n.selector=n.selector.replace(/^\:+doodle/,':host'));var c=n.selector.startsWith(':host');c&&(n.skip=!0);var i=n.styles.map(n=>this.compose_rule(n,e)),a=c?n.selector:this.compose_selector(e.count,n.selector);this.add_rule(a,i);break};case 'cond':var o=s[n.name.substr(1)];if(o){var r=n.arguments.map(n=>{return this.compose_argument(n,e)}),u=l(o,e,r);u&&this.compose(e,n.styles)};break}})}output(){Object.keys(this.rules).forEach(e=>{var n=e.startsWith(':host');let t=n?'host':'cells';this.styles[t]+=`${e}{${a(this.rules[e])}}`});return{props:this.props,styles:this.styles}}}function K(e,n){var t=new J(e);for(var r=1,u=0;r<=n.x;++r){for(var o=1;o<=n.y;++o)t.compose({x:r,y:o,count:++u})}return t.output()}let N={func(e = ''){return{type:'func',name:e,arguments:[]}},argument(){return{type:'argument',value:[]}},text(e = ''){return{type:'text',value:e}},comment(e){return{type:'comment',value:e}},psudo(e = ''){return{type:'psudo',selector:e,styles:[]}},cond(e = ''){return{type:'cond',name:e,styles:[],arguments:[]}},rule(e = ''){return{type:'rule',property:e,value:[]}}},Q={'(':')','[':']','{':'}'},U={white_space(e){return /[\s\n\t]/.test(e)},open_bracket(e){return Q.hasOwnProperty(e)},close_bracket_of(e){var n=Q[e];return e=>e==n},number(e){return!isNaN(e)}};function V(e){var n=0,t=1,r=1;return{curr:(t = 0)=>e[n+t],end:()=>e.length<=n,info:()=>({index:n,col:t,line:r}),next:()=>{var u=e[n++];u=='\n'?(r++, t=0):t++;return u}}}function X(e,{col:n,line:t}){throw new Error(`(at line ${t}, column ${n}) ${e}`)}function Y(e){if(e.trim().length){return U.number(+e)?+e:e.trim()}else{return e}}function Z(e){var[n,t]=[e.curr(),e.curr()],r=U.close_bracket_of(t);e.next();while(!e.end()){if(r(t=e.curr())){n+=t;break}else U.open_bracket(t)?(n+=Z(e)):(n+=t);e.next()}return n}function $(e,n ={}){var t=N.comment(),r=e.curr();r!='#'&&e.next();e.next();while(!e.end()){if((r=e.curr())=='*'&&e.curr(1)=='/')break;else t.value+=r;r=e.curr();if(n.inline){if(r=='\n')return t}else{if(r=='*'&&e.curr(1)=='/')break}t.value+=r;e.next()}e.next();e.next();return t}function ee(e){var n='',t;while(!e.end()){if((t=e.curr())==':')break;else /[a-zA-Z\-]/.test(t)?U.white_space(t)||(n+=t):X('Syntax error:Bad property name.',e.info());e.next()}return n}function ne(e,n){var t='',r;e.next();while(!e.end()){if((r=e.curr())==n){if(e.curr(-1)!=='\\')break;else t+=r}else t+=r;e.next()}return t}function te(e){var n=[],t=[],r='',u;while(!e.end()){if(U.open_bracket(u=e.curr()))r+=Z(e);else if(/['"]/.test(u))r+=ne(e,u);else if(u=='@')t.length||(r=r.trimLeft()),r.length&&(t.push(N.text(r)),r=''),t.push(re(e));else if(/[,)]/.test(u)){r.length&&(t.length?(r=r.trimRight(),r.length&&t.push(N.text(r))):t.push(N.text(Y(r))));n.push(t.slice());[t,r]=[[],''];if(u==')')break}else r+=u;e.next()}return n}function re(e){var n=N.func(),t='',r;while(!e.end()){if((r=e.curr())==')')break;if(r=='('){e.next();n.name=t;n.arguments=te(e);break}else t+=r;e.next()}return n}function ue(e){var n=N.text(),t;let r=[];while(!e.end()){if((t=e.curr())=='\n'){e.next();continue}else if(/[;}]/.test(t)){n.value.length&&r.push(n);n=N.text();break}else t=='@'?(n.value.length&&r.push(n),n=N.text(),r.push(re(e))):(!U.white_space(t)||!U.white_space(e.curr(-1)))&&(t==':'&&X('Syntax error:Bad property name.',e.info()),n.value+=t);e.next()}n.value.length&&r.push(n);r.length&&(r[0].value=r[0].value.trimLeft());return r}function oe(e){var n='',t;while(!e.end()){if((t=e.curr())=='{')break;else U.white_space(t)||(n+=t);e.next()}return n}function ce(e){var n={name:'',arguments:[]},t;while(!e.end()){if((t=e.curr())=='(')e.next(),n.arguments=te(e);else if(/[){]/.test(t))break;else U.white_space(t)||(n.name+=t);e.next()}return n}function se(e){var n=N.psudo(),t;while(!e.end()){if((t=e.curr())=='}')break;if(U.white_space(t)){e.next();continue}else n.selector?n.styles.push(ie(e)):(n.selector=oe(e));e.next()}return n}function ie(e){var n=N.rule(),t;while(!e.end()){if((t=e.curr())==';')break;else if(!n.property.length)n.property=ee(e);else{n.value=ue(e);break}e.next()}return n}function le(e){var n=N.cond(),t;while(!e.end()){if((t=e.curr())=='}')break;else if(!n.name.length)Object.assign(n,ce(e));else if(t==':'){var r=se(e);r.selector&&n.styles.push(r)}else if(t=='@')n.styles.push(le(e));else if(!U.white_space(t)){var u=ie(e);u.property&&n.styles.push(u)}e.next()}return n}function ae(e){let n=V(e),t=[];while(!n.end()){var r=n.curr();if(U.white_space(r)){n.next();continue}else if(r=='/'&&n.curr(1)=='*')t.push($(n));else if(r=='#'||r=='/'&&n.curr(1)=='/')t.push($(n,{inline:!0}));else if(r==':'){var u=se(n);u.selector&&t.push(u)}else if(r=='@'){var o=le(n);o.name.length&&t.push(o)}else if(!U.white_space(r)){var c=ie(n);c.property&&t.push(c)}n.next()}return t}function pe(e,n){return K(ae(e),n)}let fe=1,he=16;function me(e){let[n,t]=(e+'').replace(/\s+/g,'').replace(/[,,xX]+/,'x').split('x').map(Number),r={x:f(n||fe,1,he),y:f(t||n||fe,1,he)};return Object.assign({},r,{count:r.x*r.y})}let de="\n:host{display:block;visibility:visible;width:1em;height:1em;}.container{position:relative;width:100%;height:100%\n}.container:after{content:'';display:block;clear:both;visibility:hidden\n}.cell{position:relative;float:left;line-height:0;box-sizing:border-box\n}.shape{box-sizing:border-box;line-height:0;position:absolute;width:100%;height:100%;transform-origin:center center;z-index:1;display:flex;align-items:center;justify-content:center\n}";class ye extends HTMLElement{constructor(){super();this.doodle=this.attachShadow({mode:'open'})}connectedCallback(){setTimeout(()=>{if(!this.innerHTML.trim()){return!1}let e;try{e=pe(this.innerHTML,this.size=me(this.getAttribute('grid')))}catch(e){this.innerHTML='';throw new Error(e)};let{has_transition:n}=e.props;this.doodle.innerHTML=`
${this.html_cells()}
`;n&&setTimeout(()=>{this.set_style('.style-cells',e.styles.cells)},50)})}style_size(){return`.cell{width:${100/this.size.y+'%'};height:${100/this.size.x+'%'};}`}html_cells(){let e="\n
";return e.repeat(this.size.count)}set_style(e,n){let t=this.shadowRoot.querySelector(e);t&&(t.styleSheet?(t.styleSheet.cssText=n):(t.innerHTML=n))}update(e){if(!e){return!1}this.size||(this.size=me(this.getAttribute('grid')));let n=pe(e,this.size);this.set_style('.style-container',this.style_size()+n.styles.host);this.set_style('.style-cells',n.styles.cells);this.innerHTML=e}refresh(){this.update(this.innerHTML)}get grid(){return Object.assign({},this.size)}set grid(e){this.setAttribute('grid',e);this.connectedCallback()}static get observedAttributes(){return['grid']}attributeChangedCallback(e,n,t){e=='grid'&&n&&(n!==t&&(this.grid=t))}}customElements.define('css-doodle',ye)})) \ No newline at end of file +!function(e,t){typeof exports==='object'&&typeof module!=='undefined'?t():typeof define==='function'&&define.amd?define(t):(t())}(this,(function(){"use strict";var e={even:e=>!!(e%2),odd:e=>!(e%2)};function t(e,t,n){return e=>e==n}function n(e,t){return(n,r)=>e==n&&t==r}function r(t,n,r){return n=>/^(even|odd)$/.test(n)?e[n](t-1):n==t}function u(t,n,r){return t=>/^(even|odd)$/.test(t)?e[t](n-1):t==n}function o(t,n,r){return t=>e.even(r-1)}function c(t,n,r){return t=>e.odd(r-1)}var s=Object.freeze({nth:t,at:n,row:r,col:u,even:o,odd:c});function i(e){if(Array.isArray(e))return e;return Object.keys(e).map(t=>e[t])}function l(e,...t){return t.reduce((e,t)=>e.apply(null,i(t)),e)}function a(e){return(e||[]).join('\n')}function p(e){return Array.isArray(e)?e:[e]}function f(e,t,n){return Math.max(t,Math.min(n,e))}function h(e){return`-webkit-${e}${e}`}function m(e,t){let n={};return function(...r){let u=e+r.join('-');if(n[u])return n[u];return n[u]=t.apply(null,r)}}function d(...e){let t=e.reduce((e,t)=>e.concat(t),[]);return t[Math.floor(Math.random()*t.length)]}function y(e,t,n){let r=0,u=e=>e>0&&e<1?.1:1,o=arguments.length;o==1&&([e,t]=[u(e),e]);o<3&&(n=u(e));let c=[];while(n>0&&et){c.push(e);e+=n;if(r++>=1e3)break}return c}function g(e){return function(...t){let n=_(t[0]);if(n){t=t.map(w);return x(e,n).apply(null,t)}return e.apply(null,t)}}function x(e,t){return function(...n){n=n.map(w);let r=e.apply(null,n);t&&(r=r.map(e=>e+t));return r}}function _(e){if(!e)return'';let t=/(%|cm|fr|rem|em|ex|in|mm|pc|pt|px|vh|vw|vmax|vmin|deg|ms|s)$/,n=''.trim.call(e).match(t);return n?n[0]:''}function w(e){let t=_(e);return t?+(e.replace(t,'')):e}let{cos:b,sin:v,PI:z}=Math,k=z/180;function L(e,t){typeof arguments[0]=='function'&&(t=e,e={});t||(t=e=>[b(e),v(e)]);var n=e.split||120,r=e.scale||1,u=k*(e.start||0),o=e.deg?e.deg*k:z/(n/2),c=[];for(var s=0;s[b(e*t)*b(t),b(e*t)*v(t)])}function B(e = 3){e=f(e,3,6);var t=1-e;return L({scale:1/e},e=>[t*b(e)+b(t*(e-z)),t*v(e)+v(t*(e-z))])}function E(){return B(4)}var O=Object.freeze({circle:T,siogon:H,triangle:M,rhombus:S,pentagon:j,hexgon:A,star:W,diamond:C,cross:R,clover:q,hypocycloid:B,astroid:E});function P(e,t,n){return e=>n}function D(e,t,n){return t=>e}function F(e,t,n){return e=>t}function G(){return function(...e){return d.apply(null,e)}}function I(){return G.apply(null,arguments)}function J(){return function(...e){return d(m('range',g(y)).apply(null,e))}}function K(e,t,n){return function(e,...t){if(e){e=e.trim();if(O[e]){return O[e].apply(null,t)}}}}var N=Object.freeze({index:P,row:D,col:F,any:G,pick:I,rand:J,shape:K});class Q{constructor(e){this.tokens=e;this.rules={};this.props={};this.styles={host:'',cells:''}}add_rule(e,t){var n=this.rules[e];n||(n=this.rules[e]=[]);n.push.apply(n,p(t))}compose_selector(e,t = ''){return`.cell:nth-of-type(${e}) .shape${t}`}compose_argument(e,t){var n=e.map(e=>{if(e.type=='text'){return e.value}else if(e.type=='func'){var n=N[e.name.substr(1)];if(n){var r=e.arguments.map(e=>{return this.compose_argument(e,t)});return l(n,t,r)}}});return n.length>2?n.join(''):n[0]}compose_value(e,t){return e.reduce((e,n)=>{switch(n.type){case 'text':{e+=n.value;break};case 'func':{var r=N[n.name.substr(1)];if(r){var u=n.arguments.map(e=>{return this.compose_argument(e,t)});e+=l(r,t,u)}}}return e},'')}compose_rule(e,t){var n=e.property,r=this.compose_value(e.value,t);n=='transition'&&(this.props.has_transition=!0);var u=`${n}:${r};`;n=='clip-path'&&(u=h(u),u+=';overflow:hidden;');n=='size'&&(u=`width:${r};height:${r};`);return u}compose(e,t){(t||this.tokens).forEach((t,n)=>{if(t.skip)return!1;switch(t.type){case 'rule':this.add_rule(this.compose_selector(e.count),this.compose_rule(t,e));break;case 'psudo':{t.selector.startsWith(':doodle')&&(t.selector=t.selector.replace(/^\:+doodle/,':host'));var c=t.selector.startsWith(':host');c&&(t.skip=!0);var i=t.styles.map(t=>this.compose_rule(t,e)),a=c?t.selector:this.compose_selector(e.count,t.selector);this.add_rule(a,i);break};case 'cond':var o=s[t.name.substr(1)];if(o){var r=t.arguments.map(t=>{return this.compose_argument(t,e)}),u=l(o,e,r);u&&this.compose(e,t.styles)};break}})}output(){Object.keys(this.rules).forEach(e=>{var t=e.startsWith(':host');let n=t?'host':'cells';this.styles[n]+=`${e}{${a(this.rules[e])}}`});return{props:this.props,styles:this.styles}}}function U(e,t){var n=new Q(e);for(var r=1,u=0;r<=t.x;++r){for(var o=1;o<=t.y;++o)n.compose({x:r,y:o,count:++u})}return n.output()}let V={func(e = ''){return{type:'func',name:e,arguments:[]}},argument(){return{type:'argument',value:[]}},text(e = ''){return{type:'text',value:e}},comment(e){return{type:'comment',value:e}},psudo(e = ''){return{type:'psudo',selector:e,styles:[]}},cond(e = ''){return{type:'cond',name:e,styles:[],arguments:[]}},rule(e = ''){return{type:'rule',property:e,value:[]}}},X={'(':')','[':']','{':'}'},Y={white_space(e){return /[\s\n\t]/.test(e)},open_bracket(e){return X.hasOwnProperty(e)},close_bracket_of(e){var t=X[e];return e=>e==t},number(e){return!isNaN(e)}};function Z(e){var t=0,n=1,r=1;return{curr:(n = 0)=>e[t+n],end:()=>e.length<=t,info:()=>({index:t,col:n,line:r}),next:()=>{var u=e[t++];u=='\n'?(r++, n=0):n++;return u}}}function $(e,{col:t,line:n}){throw new Error(`(at line ${n}, column ${t}) ${e}`)}function ee(e){if(e.trim().length){return Y.number(+e)?+e:e.trim()}else{return e}}function te(e){var[t,n]=[e.curr(),e.curr()],r=Y.close_bracket_of(n);e.next();while(!e.end()){if(r(n=e.curr())){t+=n;break}else Y.open_bracket(n)?(t+=te(e)):(t+=n);e.next()}return t}function ne(e,t ={}){var n=V.comment(),r=e.curr();r!='#'&&e.next();e.next();while(!e.end()){if((r=e.curr())=='*'&&e.curr(1)=='/')break;else n.value+=r;r=e.curr();if(t.inline){if(r=='\n')return n}else{if(r=='*'&&e.curr(1)=='/')break}n.value+=r;e.next()}e.next();e.next();return n}function re(e){var t='',n;while(!e.end()){if((n=e.curr())==':')break;else /[a-zA-Z\-]/.test(n)?Y.white_space(n)||(t+=n):$('Syntax error:Bad property name.',e.info());e.next()}return t}function ue(e,t){var n='',r;e.next();while(!e.end()){if((r=e.curr())==t){if(e.curr(-1)!=='\\')break;else n+=r}else n+=r;e.next()}return n}function oe(e){var t=[],n=[],r='',u;while(!e.end()){if(Y.open_bracket(u=e.curr()))r+=te(e);else if(/['"]/.test(u))r+=ue(e,u);else if(u=='@')n.length||(r=r.trimLeft()),r.length&&(n.push(V.text(r)),r=''),n.push(ce(e));else if(/[,)]/.test(u)){r.length&&(n.length?(r=r.trimRight(),r.length&&n.push(V.text(r))):n.push(V.text(ee(r))));t.push(n.slice());[n,r]=[[],''];if(u==')')break}else r+=u;e.next()}return t}function ce(e){var t=V.func(),n='',r;while(!e.end()){if((r=e.curr())==')')break;if(r=='('){e.next();t.name=n;t.arguments=oe(e);break}else n+=r;e.next()}return t}function se(e){var t=V.text(),n;let r=[];while(!e.end()){if((n=e.curr())=='\n'){e.next();continue}else if(/[;}]/.test(n)){t.value.length&&r.push(t);t=V.text();break}else n=='@'?(t.value.length&&r.push(t),t=V.text(),r.push(ce(e))):(!Y.white_space(n)||!Y.white_space(e.curr(-1)))&&(n==':'&&$('Syntax error:Bad property name.',e.info()),t.value+=n);e.next()}t.value.length&&r.push(t);r.length&&(r[0].value=r[0].value.trimLeft());return r}function ie(e){var t='',n;while(!e.end()){if((n=e.curr())=='{')break;else Y.white_space(n)||(t+=n);e.next()}return t}function le(e){var t={name:'',arguments:[]},n;while(!e.end()){if((n=e.curr())=='(')e.next(),t.arguments=oe(e);else if(/[){]/.test(n))break;else Y.white_space(n)||(t.name+=n);e.next()}return t}function ae(e){var t=V.psudo(),n;while(!e.end()){if((n=e.curr())=='}')break;if(Y.white_space(n)){e.next();continue}else t.selector?t.styles.push(pe(e)):(t.selector=ie(e));e.next()}return t}function pe(e){var t=V.rule(),n;while(!e.end()){if((n=e.curr())==';')break;else if(!t.property.length)t.property=re(e);else{t.value=se(e);break}e.next()}return t}function fe(e){var t=V.cond(),n;while(!e.end()){if((n=e.curr())=='}')break;else if(!t.name.length)Object.assign(t,le(e));else if(n==':'){var r=ae(e);r.selector&&t.styles.push(r)}else if(n=='@')t.styles.push(fe(e));else if(!Y.white_space(n)){var u=pe(e);u.property&&t.styles.push(u)}e.next()}return t}function he(e){let t=Z(e),n=[];while(!t.end()){var r=t.curr();if(Y.white_space(r)){t.next();continue}else if(r=='/'&&t.curr(1)=='*')n.push(ne(t));else if(r=='#'||r=='/'&&t.curr(1)=='/')n.push(ne(t,{inline:!0}));else if(r==':'){var u=ae(t);u.selector&&n.push(u)}else if(r=='@'){var o=fe(t);o.name.length&&n.push(o)}else if(!Y.white_space(r)){var c=pe(t);c.property&&n.push(c)}t.next()}return n}function me(e,t){return U(he(e),t)}let de=1,ye=16;function ge(e){let[t,n]=(e+'').replace(/\s+/g,'').replace(/[,,xX]+/,'x').split('x').map(Number),r={x:f(t||de,1,ye),y:f(n||t||de,1,ye)};return Object.assign({},r,{count:r.x*r.y})}let xe="\n:host{display:block;visibility:visible;width:1em;height:1em;}.container{position:relative;width:100%;height:100%\n}.container:after{content:'';display:block;clear:both;visibility:hidden\n}.cell{position:relative;float:left;line-height:0;box-sizing:border-box\n}.shape{box-sizing:border-box;line-height:0;position:absolute;width:100%;height:100%;transform-origin:center center;z-index:1;display:flex;align-items:center;justify-content:center\n}";class _e extends HTMLElement{constructor(){super();this.doodle=this.attachShadow({mode:'open'})}connectedCallback(){setTimeout(()=>{if(!this.innerHTML.trim()){return!1}let e;try{e=me(this.innerHTML,this.size=ge(this.getAttribute('grid')))}catch(e){this.innerHTML='';throw new Error(e)};let{has_transition:t}=e.props;this.doodle.innerHTML=`
${this.html_cells()}
`;t&&setTimeout(()=>{this.set_style('.style-cells',e.styles.cells)},50)})}style_size(){return`.cell{width:${100/this.size.y+'%'};height:${100/this.size.x+'%'};}`}html_cells(){let e="\n
";return e.repeat(this.size.count)}set_style(e,t){let n=this.shadowRoot.querySelector(e);n&&(n.styleSheet?(n.styleSheet.cssText=t):(n.innerHTML=t))}update(e){if(!e){return!1}this.size||(this.size=ge(this.getAttribute('grid')));let t=me(e,this.size);this.set_style('.style-container',this.style_size()+t.styles.host);this.set_style('.style-cells',t.styles.cells);this.innerHTML=e}refresh(){this.update(this.innerHTML)}get grid(){return Object.assign({},this.size)}set grid(e){this.setAttribute('grid',e);this.connectedCallback()}static get observedAttributes(){return['grid']}attributeChangedCallback(e,t,n){e=='grid'&&t&&(t!==n&&(this.grid=n))}}customElements.define('css-doodle',_e)})) \ No newline at end of file diff --git a/src/shapes.js b/src/shapes.js index 9c9f6e8..f23dd58 100644 --- a/src/shapes.js +++ b/src/shapes.js @@ -1,28 +1,47 @@ import { minmax, memo } from './utils'; -const DEG = Math.PI / 180; -const polygon = function(sides, start = 0, deg) { - deg = deg || (Math.PI / (sides / 2)); - var points = []; - for (var i = 0; i < sides; ++i) { - var theta = start + deg * i; - points.push(` - ${ Math.cos(theta) * 50 + 50 }% ${ Math.sin(theta) * 50 + 50}% - `); +const { cos, sin, PI } = Math; +const DEG = PI / 180; + +function polygon(option, fn) { + if (typeof arguments[0] == 'function') { + fn = option; + option = {}; } + + if (!fn) { + fn = theta => [ cos(theta), sin(theta) ]; + } + + var split = option.split || 120; + var scale = option.scale || 1; + var start = DEG * (option.start || 0); + var deg = option.deg ? (option.deg * DEG) : (PI / (split / 2)); + var points = []; + + for (var i = 0; i < split; ++i) { + var theta = start + deg * i; + var [x, y] = fn(theta); + points.push( + ((x * 50 * scale) + 50 + '% ') + + ((y * 50 * scale) + 50 + '%') + ); + } + return `polygon(${ points.join(',') })`; -}; +} + export function circle() { return 'circle(49.5%)'; } -export function siogon(sides) { - return polygon(minmax(sides, 3, 12)); +export function siogon(sides = 3) { + return polygon({ split: minmax(sides, 3, 12) }); } export function triangle() { - return polygon(3, DEG * -90); + return polygon({ split: 3, start: -90 }); } export function rhombus() { @@ -30,15 +49,15 @@ export function rhombus() { } export function pentagon() { - return polygon(5, DEG * 54); + return polygon({ split: 5, start: 54 }); } export function hexgon() { - return polygon(6, DEG * 30); + return polygon({ split: 6, start: 30 }); } export function star() { - return polygon(5, DEG * 54, DEG * 144); + return polygon({ split: 5, start: 54, deg: 144 }); } export function diamond() { @@ -53,44 +72,24 @@ export function cross() { )`; } -export const hypocycloid = memo('hypocycloid', function(k = 3) { +export function clover(k = 3) { + k = minmax(k, 3, 5); + if (k == 4) k = 2; + return polygon({ split: 240 }, theta => [ + cos(k * theta) * cos(theta), + cos(k * theta) * sin(theta) + ]); +} + +export function hypocycloid(k = 3) { k = minmax(k, 3, 6); - var split = 120; - var deg = Math.PI / (split / 2); - var R = 50; - var r = R / k; - var points = []; - for (var i = 0; i < split; ++i) { - var theta = deg * i + Math.PI; - var x = r * (1 - k) * Math.cos(theta) + r * Math.cos((1 - k) * (theta - Math.PI)); - var y = r * (1 - k) * Math.sin(theta) + r * Math.sin((1 - k) * (theta - Math.PI)); - points.push((x + 50 + '% ') + (y + 50+ '%')); - } - return `polygon(${ points.join(',') })`; -}); + var m = 1 - k; + return polygon({ scale: 1 / k }, theta => [ + m * cos(theta) + cos(m * (theta - PI)), + m * sin(theta) + sin(m * (theta - PI)) + ]); +} export function astroid() { return hypocycloid(4); } - -export const clover = memo('clover', function(k = 3) { - switch (k) { - case 4: k = 2; break; - case 5: k = 5; break; - case 3: k = 3; - default: { - if (k > 5) k = 5; - else if (k < 3) k = 3; - } - } - var split = 240; - var deg = Math.PI / (split / 2); - var points = []; - for (var i = 0; i < split; ++i) { - var theta = deg * i; - var x = Math.cos(k * theta) * Math.cos(theta); - var y = Math.cos(k * theta) * Math.sin(theta); - points.push((x * 50 + 50 + '% ') + (y * 50 + 50+ '%')); - } - return `polygon(${ points.join(',') })`; -});