HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
- var dirs = ['', 'x', 'y'];
- var nd = dirs.length;
- var trfs = [
- {
- func: { name: 'rotate', min: 0, max: 1 },
- args: { type: 'ang', min: 0, max: 1, ext: 180, lbl: 'rotation angle' }
- },
- {
- func: { name: 'scale', min: 0, max: nd },
- args: { type: 'num', min: 1, max: nd, ext: 1.5, lbl: 'scaling factor', step: .05 }
- },
- {
- func: { name: 'skew', min: 1, max: nd },
- args: { type: 'ang', min: 0, max: 1, ext: 60, lbl: 'shearing angle' }
- },
- ];
- var nt = trfs.length;
- var units = {
- ang: { deg: 1, rad: Math.PI/180, turn: 1/360/*, grad: .01*/ },
- len: { '%': 1, px: 1 }
- };
mixin var(name)
span.token--func var
span.token--punc (
span.token--args
span.token--arg
span.token--prop --#{name}
span.token--punc )
mixin perc(val)
span.token--num #{val}
span.token--unit %
mixin pad(dir)
- var dir = dir || 1;
span.item
span.token--func translate
span.token--punc (
span.token--args
- for(var i = 1; i < nd; i++) {
if(i > 1)
span.token--punc ,
span.token--arg
span.token--func calc
span.token--punc (
span.token--args
span.token--arg
if(dir > 0)
+perc(50)
else
+var(`o${dirs[i]}`)
|
span.token--oper -
|
if(dir < 0)
+perc(50)
else
+var(`o${dirs[i]}`)
span.token--punc )
- }
span.token--punc )
mixin trf(pad)
span.token--prop transform
span.token--punc :
span.token--val
if(pad)
+pad()
span.item
+var('transform')
if(pad)
+pad(-1)
pre#code-trf
- for(var i = 1; i < nd; i++) {
span.token--prop --o#{dirs[i]}
span.token--punc :
span.token--val
span.item(data-m='1' class=`o${dirs[i]}`)
span.ctrl
button.token--num(aria-haspopup='true' aria-expanded='false' aria-controls=`popvalo${dirs[i]}`) #{i*50}
form.popup(id=`popvalo${dirs[i]}` style=`--min: -50; --val: 0; --max: 150`)
.wrap
input(type='range' id=`ro${dirs[i]}` min='-50' value='0' max='150')
output(for=`ro${dirs[i]}` class=`o${dirs[i]}`) 0
label(for=`ro${dirs[i]}`) o#{dirs[i]}
span.token--unit %
span.token--punc ;
br
- }
span.token--prop --transform
span.token--punc :
span#trf-val.token--val
span.item(data-i='0' data-j='data-i')
span.ctrl
button.add.sym(aria-haspopup='true' aria-expanded='false' aria-controls='pop-0' data-j='aria-controls') add
form#pop-0.popup(data-j='id')
- for(var i = 0; i < nt; i++) {
input(type='radio' name='trf-0' id=`${trfs[i].func.name}-0` data-j='name id')
label.final(for=`${trfs[i].func.name}-0` data-j='for') #{trfs[i].func.name}
- }
input(type='checkbox' id='concurr')
//label(for='concurr') animate at same time
section#swipe
pre#code-orig.half
span.token--prop transform-origin
span.token--punc :
span.token--val
- for(var i = 1; i < nd; i++) {
span.item
+var(`o${dirs[i]}`)
- }
span.token--punc ;
br
+trf
pre#code-chain.half
+trf(1)
section#visual
button#run(disabled) Run
.box#box-initial(data-txt='transform: none')
.box#box-origin(data-txt='transform-origin')
.axes
.box#box-chain(data-txt='translate()')
.axes
.box#box-trigger
- for(var i = 0; i < nd; i++) {
- for(var j = 0; j < nd; j++) {
button.point(style=`--ox: ${i*50}%; --oy: ${j*50}%`)
- }
- }
button.point.sel
template#rem
span.ctrl
button.rem.sym remove
- for(var i = 0; i < nt; i++) {
template(id=trfs[i].func.name)
- var Δ = trfs[i].func.max - trfs[i].func.min;
if Δ > 1
span.ctrl(data-dir=dirs[trfs[i].func.min])
button.token--func(aria-haspopup='true' aria-expanded='false' aria-controls='popfnc-0' data-j='aria-controls') #{trfs[i].func.name}#{dirs[trfs[i].func.min].toUpperCase()}
form#popfnc-0.popup(data-j='id')
- for(var j = trfs[i].func.min; j < trfs[i].func.max; j++) {
input(type='radio' name=`${trfs[i].func.name}-0` id=`o${trfs[i].func.name}${dirs[j]}-0` data-dir=dirs[j] data-j='name id' checked=(j===trfs[i].func.min))
label(for=`o${trfs[i].func.name}${dirs[j]}-0` data-j='for') #{trfs[i].func.name}#{dirs[j].toUpperCase()}
if(!dirs[j])
input(type='checkbox' id=`${trfs[i].func.name}iso-0` data-j='id')
label(for=`${trfs[i].func.name}iso-0` data-j='for') isometric
- }
else
span.token--func #{trfs[i].func.name}
span.token--punc (
span.token--args
- for(var j = trfs[i].args.min; j < trfs[i].args.max; j++) {
if j > trfs[i].args.min
span.token--punc ,
span.token--arg(data-m='1' data-dir=dirs[j])
span.ctrl
- var max = trfs[i].args.ext, min = -max;
- var step = trfs[i].args.step;
- var gen = +(min + (max - min)*Math.random()).toFixed(2);
- var val = step?gen:Math.round(gen);
button.token--num(aria-haspopup='true' aria-expanded='false' aria-controls=`popnum${dirs[j]}-0` data-dir=dirs[j]?dirs[j]:null data-j='aria-controls') #{val}
form.popup(id=`popnum${dirs[j]}-0` style=`--min: ${min}; --val: ${val}; --max: ${max}` data-j='id')
.wrap
input(type='range' id=`${trfs[i].args.type}${dirs[j]}-0` min=min max=max value=val step=step?step:null data-j='id')
output(for=`${trfs[i].args.type}${dirs[j]}-0` data-j='for') #{val}
label(for=`${trfs[i].args.type}${dirs[j]}-0` data-dir=dirs[j] data-j='for') #{trfs[i].args.lbl}
if(units[trfs[i].args.type])
- var def = Object.keys(units[trfs[i].args.type])[0];
span.ctrl
button.token--unit(aria-haspopup='true' aria-expanded='false' aria-controls=`popuni${dirs[j]}-0` data-dir=dirs[j]?dirs[j]:null data-j='aria-controls') #{def}
form.popup(id=`popuni${dirs[j]}-0` data-j='id')
- for(p in units[trfs[i].args.type]) {
input(type='radio' name=`unit${trfs[i].args.type}${dirs[j]}-0` id=`unit${p}${dirs[j]}-0` data-val=`${units[trfs[i].args.type][p]}` value=p checked=p===def data-j='name id')
label(for=`unit${p}${dirs[j]}-0` data-j='for') #{p}
- }
- }
span.token--punc )
- }
@import 'compass/css3';
$dark: #222;
$light: #eee;
$mark-orange: #f90;
$mark-crimson: #a25;
$mark-tomato: #e43;
$mark-palblue: #09d;
$mark-green: #4a5;
$mark-khaki: #683;
$line-h: 1.5;
$track-w: 12.5em;
$track-h: .25em;
$thumb-d: 1.5em;
$dist: $track-w - $thumb-d;
$box-w: 38vmin;
$box-h: .5*$box-w;
//===
@mixin track() {
box-sizing: border-box;
border: none;
width: $track-w; height: $track-h;
background: $light;
}
@mixin thumb() {
box-sizing: border-box;
border: solid 4px #000;
width: $thumb-d; height: $thumb-d;
border-radius: 50%;
background: $light;
}
@mixin thumb-focus {
border-color: transparent;
background: $mark-orange
}
// ===
%visually-hidden { opacity: 0 }
// ===
*, :before, :after {
box-sizing: border-box;
margin: 0;
border: none;
padding: 0;
font: inherit
}
body, label { font: 1em/#{$line-h} trebuchet ms, sans-serif }
body {
--ox: 50%; --oy: 100%;
--transform: unquote(' ');
--dt: 0s;
display: flex;
flex-direction: column;
overflow-x: hidden;
min-width: 320px; min-height: 100vh
}
pre, code, .box { font-family: consolas, monaco, monospace }
pre {
padding: .5em;
background: $dark;
color: $light;
white-space: pre-wrap
}
span, button {
display: inline-block;
color: var(--c, inherit)
}
button {
border-radius: 3px;
&:not([disabled]) { cursor: pointer }
&:focus { outline: solid 1px rgba($light, .05) }
}
form {
position: absolute;
z-index: 2;
background: mix($dark, #000)
}
label {
display: block;
line-height: 2
}
code {
display: block;
font-weight: 700
}
//===
[id='code-trf'] {
box-shadow: inset 0 -1px #777, inset 0 -2px #000;
&:after {
position: absolute;
top: 0; right: 0;
padding: 0 .5em;
border-radius: 0 0 0 5px;
--left: calc(var(--max) - var(--curr));
background: hsl(calc(var(--left)*13), 100%, 35%);
font-weight: 700;
counter-reset: max var(--max) curr var(--curr) left var(--left);
content: counter(curr) ' (max of ' counter(max) '), ' counter(left) ' left'
}
}
.token {
&--prop { --c: #DBBAE5 }
&--func { --c: #B7E3C0 }
&--val {
span[class^='o'] { margin-left: .5em }
}
&--num {
--c: #F8F087;
.ctrl & {
min-width: $line-h*1em;
text-align: right
}
}
&--unit { --c: #F39DD4 }
&--oper { --c: #B8D0DD }
[data-dir='x'] ~ &--args & {
&--punc, &--arg[data-dir='y'] { display: none }
}
[data-dir='y'] ~ &--args & {
&--punc, &--arg[data-dir='x'] { display: none }
}
}
.item {
&:before {
white-space: pre;
content: ' '
}
}
.ctrl {
position: relative;
margin: .125em 1px;
white-space: normal;
&.iso[data-dir=''] ~ .token--args {
.token--punc, .token--arg[data-dir='y'] { display: none }
}
}
[disabled] {
&, + label { filter: saturate(.3) contrast(.3) }
}
.sym {
overflow: hidden;
margin-right: .25em;
width: $thumb-d; height: $thumb-d;
background: $light;
color: $dark;
text-indent: -100vw;
vertical-align: middle;
&:not([disabled]) {
&:hover, &:focus {
background: var(--c)
linear-gradient(rgba($dark, .35), rgba($dark, 0));
color: $light;
}
}
&:after {
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
transform: scale(1.5);
font-weight: 900;
text-indent: -.125em;
text-shadow: -.5px -.5px mix($dark, $light, 25%)
}
}
.add {
--c: #{$mark-green};
&:after { content: '+' }
}
.rem {
--c: #{$mark-tomato};
&:after { content: '-' }
}
[aria-haspopup] {
font-weight: 700;
&:not(.sym) {
padding: 0 1px;
background: none;
&:hover, &:focus { box-shadow: inset 0 0 0 1px var(--c) }
}
&[aria-expanded='true']:not(.sym) {
box-shadow: none;
background: var(--c);
color: $dark
}
}
.popup {
margin-top: .25em;
padding: .5em;
border-radius: 3px;
transform-origin: 50% 0;
--pos: translate(var(--x, 0)) perspective(35em);
transform: var(--pos);
box-shadow: 0 0 0 1px $mark-orange;
//transition: transform .3s;
[aria-expanded='false'] + & {
display: none;
//transform: var(--pos) rotatex(-90deg);
}
}
[type='radio'], [type='checkbox'] {
position: absolute;
left: -100vw;
+ label {
--c: var(--c-sel, var(--c-hl));
--c-hl: #{$light};
color: var(--c);
cursor: pointer;
&:not(.final) {
display: flex;
align-items: center;
margin-right: .25em;
&:before {
margin-right: .25em;
width: $thumb-d; height: $thumb-d;
transform: scale(.75);
box-shadow: 0 0 0 2px var(--c);
color: var(--c-sel, transparent);
}
}
}
&:focus + label, &:not([disabled]) + label:hover {
--c-hl: #{mix($light, $mark-orange)}
}
&:checked + label { --c-sel: #{$mark-orange} }
}
[type='radio'] + :not(.final):before {
border-radius: 50%;
padding: .25*$thumb-d;
background: currentcolor content-box;
content: ''
}
[type='checkbox'] + label {
.popup & {
margin-bottom: .75em;
margin-left: 1em
}
&:before {
display: flex;
align-items: center;
justify-content: center;
content: '✔'
}
}
.wrap {
position: relative;
width: $track-w; height: 2*$thumb-d;
~ label { text-align: center }
}
[type='range'] {
&, &::-webkit-slider-thumb { -webkit-appearance: none }
display: block;
width: $track-w; min-height: $thumb-d;
background: transparent;
cursor: pointer;
&::-webkit-slider-runnable-track { @include track() }
&::-moz-range-track { @include track }
&::-ms-track { @include track }
&::-webkit-slider-thumb {
margin-top: .5*($track-h - $thumb-d);
@include thumb
}
&::-moz-range-thumb { @include thumb }
&::-ms-thumb {
margin-top: 0;
@include thumb
}
&::-ms-tooltip { display: none }
+ output {
display: none;
.js & {
position: absolute;
left: .5*$thumb-d; top: calc(#{$thumb-d} + .125em);
padding: 0 .5em;
border-radius: 3px;
transform: translate(calc((var(--val) - var(--min))/(var(--max) - var(--min))*#{$dist} - 50%));
background: $mark-orange;
color: #000
}
}
&:focus {
outline: dashed 1px rgba(#000, .05);
&::-webkit-slider-thumb { @include thumb-focus }
&::-moz-range-thumb { @include thumb-focus }
&::-ms-thumb { @include thumb-focus }
.js & + output { display: block }
}
}
[for='concurr'] {
position: absolute;
z-index: 2;
bottom: 0;
padding: 0 .5em;
background: $dark;
}
[id='swipe'] {
[id='concurr']:not(:checked) ~ & {
display: flex;
width: 200%;
transform: translate(var(--tx, 0));
.half {
width: 50%;
}
}
&.left {
--tx: -50%;
:not(.running) > :not(:checked) + * + & + * [id='box-origin'] { @extend %visually-hidden }
}
:not(.running) > :not(:checked) + * + &:not(.left) + * [id='box-chain'] { @extend %visually-hidden }
&.smooth { transition: .3s transform }
}
.half {
position: relative;
padding-top: $line-h*1em;
&:before {
position: absolute;
top: 0; left: 0;
padding: 0 .5em;
border-radius: 0 0 5px 0;
background: gold;
color: $dark;
}
}
[id='code-orig'] {
&:before {
content: 'option 1: use transform-origin'
}
output:after { content: '%' }
}
[id='code-chain'] {
&:before {
content: 'option 2: use chained translations'
}
}
[id='visual'] {
flex: 1;
overflow: hidden;
position: relative;
min-height: 320px;
}
[id='run'] {
position: absolute;
margin: .5em;
padding: .125em .5em;
z-index: 3;
}
.box {
--j: 1;
position: absolute;
top: 50%; left: 50%;
min-width: 10em; min-height: 3*$line-h*1em;
width: $box-w; height: $box-h;
--pos: translate(-50%, -50%);
transform: var(--pos);
font-weight: 700;
&:after {
position: absolute;
left: 50%; top: calc(var(--j)*25%);
padding: 0 .25em;
border-radius: 5px;
transform: var(--pos);
background: var(--c, transparent);
white-space: nowrap;
content: attr(data-txt)
}
}
[id='box-initial'] {
background: $light;
code { margin-left: .5em }
}
[id='box-origin'], [id='box-chain'] {
box-shadow: inset 0 0 0 2px var(--c);
background: repeating-linear-gradient(var(--a, 45deg), var(--c), var(--c) 2px, transparent 2px, transparent 7px);
transition: opacity .3s;
[id='run'][disabled] ~ & { @extend %visually-hidden }
}
[id='box-origin'] {
--j: 2;
--c: #{rgba($mark-palblue, .5)};
transform-origin: var(--ox) var(--oy);
transform: var(--pos) var(--transform);
.axes { top: var(--oy); left: var(--ox) }
.running [id='concurr']:checked ~ * &,
.running [id='swipe']:not(.left) ~ * & {
animation: ani0 var(--dt) ease-out;
}
}
[id='box-chain'] {
--j: 3;
--c: #{rgba($mark-crimson, .5)};
--a: -45deg;
--dir: translate(calc(var(--ox) - 50%), calc(var(--oy) - 50%));
--rev: translate(calc(50% - var(--ox)), calc(50% - var(--oy)));
transform: var(--pos)
var(--dir)
var(--transform)
var(--rev);
.axes { top: 50%; left: 50% }
.running [id='concurr']:checked ~ * &,
.running [id='swipe'].left ~ * & {
animation: ani1 var(--dt) ease-out;
}
}
.axes {
position: absolute;
width: 65%; height: 65%;
box-shadow: -1px -1px currentcolor,
inset 1px 1px currentcolor;
&:before, &:after {
position: absolute;
border: .375em solid transparent;
width: 0; height: 0;
transform: translatey(-50%);
font: italic 700 1em/ .75 times new roman, serif;
text-indent: -.25em;
text-shadow: 1px 1px #fff, -1px -1px #fff;
content: 'x'
}
&:before {
left: calc(100% - 2px);
border-left-width: .75em;
border-left-color: currentcolor;
}
&:after {
top: calc(100% - 2px);
border-top-width: .75em;
border-top-color: currentcolor;
transform: translate(-50%);
line-height: 0;
text-indent: .25em;
content: 'y'
}
}
[id='box-trigger'] {
&:before {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
transform: scale(2);
content: ''
}
}
.point {
position: absolute;
left: var(--ox); top: var(--oy);
margin: -.5*$thumb-d;
border: solid 4px var(--c, transparent);
padding: 4px;
width: $thumb-d; height: $thumb-d;
border-radius: 50%;
background: var(--c, #{$mark-tomato}) content-box;
opacity: .5;
filter: drop-shadow(0 0 1px #fff) drop-shadow(1px 1px 1px #000);
&:hover, &:focus {
opacity: 1;
--c: #{$mark-orange};
}
&.sel {
opacity: 1;
--c: #{$mark-green}
}
}
const DIRS = ['x', 'y'], TRF = {}, O = {},
LIM = 8, PREC = 3,
_SWIPE = document.getElementById('swipe'),
_BOXO = document.getElementById('box-origin'),
_BOXC = document.getElementById('box-chain'),
_TRIG = document.getElementById('box-trigger'),
_RUN = document.getElementById('run'),
_S = document.createElement('style'),
BT = .5;
let popup = null, poplock = false, limreach = false,
r = null, act = null, x0 = null, y0 = null, running = false;
function fitPopup(_el) {
let cr = _el.getBoundingClientRect(),
dx = r.right - cr.right;
if(dx < 0) _el.style.setProperty('--x', `${Math.round(dx) - 1}px`)
};
function closePopup() {
/*
* close the currently open popup
* there can be only one, stored in
* global popup variable
*/
popup.previousElementSibling
.setAttribute('aria-expanded', false);
popup = null;
};
function size() {
r = document.body.getBoundingClientRect();
if(popup) closePopup();
};
function isIn(_el, cls) {
/*
* ckecks if _el or any of its ancestors
* all the way up to the body have the
* cls class
*/
if(_el === document.body) return false;
return (_el.classList.contains(cls) ?
true : isIn(_el.parentNode, cls))
};
function getAsc(_el, cls) {
/*
* get an ancestor of _el that has class cls
*/
if(_el === document.body) return null;
return _el.classList.contains(cls) ?
_el : getAsc(_el.parentNode, cls)
};
function updateIndices(i, dir = 1) {
let n = +TRF._last.dataset.i + dir;
for(let j = i; j <= n; j++) {
let list = [ j < n ? TRF.chain.list[j]._el : TRF._last];
list.push(...Array.from(list[0].querySelectorAll('[data-j]')));
list.forEach(c => {
let attr = c.dataset.j.split(' ');
attr.forEach(k => {
let curr = c.getAttribute(k).split('-');
curr[curr.length - 1] = j;
c.setAttribute(k, curr.join('-'));
});
});
}
document.body.style.setProperty('--curr', TRF.chain.list.length);
}
function textFrom(item) {
return `${item._fn.textContent.replace(/scale(X|Y)/gi, 'scale')}(${item._nums.map((c, j) => c.textContent + (item._unis.length ? item._unis[j].textContent : '')).join(', ')})`;
};
function prepAni() {
let n = TRF.chain.text.length + 4,
ani = [], u = 100/n;
for(var i = 0; i < 2; i++) {
let dir = ' var(--dir)',
kd = `${2*u}% { transform: var(--pos)${dir} }`,
rev = ' var(--rev)',
kr = `${(n - 2 + i)*u}%, 100% { transform: var(--pos)${dir} ${TRF.chain.text.join(' ')}${rev}`;
ani[i] = `@keyframes ani${i} {
0%, ${(2 - i)*u}% { transform: var(--pos) }
${i ? kd : ''}
${TRF.chain.text.map((c, j, a) => {
return `${(3 + j)*u}%${!i && j === TRF.chain.text.length - 1 ? ', 100%': ''} { transform: var(--pos)${i ? dir : ''} ${a.slice(0, j + 1).join(' ')} }`
}).join('\n')}
${i ? kr : ''}
}`
}
_S.textContent = ani.join('');
};
function updateTrf() {
document.body.style.setProperty('--transform', TRF.chain.text.join(' '));
if(TRF.chain.text.length) prepAni();
else _S.textContent = ''
};
function addTrf(data, nxt) {
let item = {
_el: TRF.temp._item.cloneNode(true),
name: data.name,
iso: false
},
fblock = TRF.temp[`_${data.name}`].cloneNode(true),
i = +nxt.dataset.i;
item._el.appendChild(TRF.temp._rem.cloneNode(true));
item._el.appendChild(fblock);
item._fn = item._el.querySelector('.token--func');
item._nums = Array.from(item._el.querySelectorAll('.token--num'));
item._unis = Array.from(item._el.querySelectorAll('.token--unit'));
TRF._adds.splice(i, 0, item._el.querySelector('.add'));
TRF.chain.list.splice(i, 0, item);
TRF.chain.text.splice(i, 0, textFrom(item));
updateTrf();
updateIndices(i);
TRF._wrap.insertBefore(item._el, nxt);
if(TRF.chain.list.length && _RUN.disabled) _RUN.disabled = false;
};
function remTrf(i) {
TRF._wrap.removeChild(TRF.chain.list[i]._el);
TRF._adds.splice(i, 1);
TRF.chain.list.splice(i, 1);
TRF.chain.text.splice(i, 1);
updateTrf();
updateIndices(i, -1);
if(limreach) {
TRF._adds.forEach(c => { c.removeAttribute('disabled') });
limreach = false;
}
if(!TRF.chain.list.length && !_RUN.disabled) _RUN.disabled = true
};
function rangeUpdate(_t) {
if(_t.type !== 'range') return;
let _pop = getAsc(_t, 'popup'),
_num = _pop.previousElementSibling,
_out = _t.nextElementSibling,
_arg = _num.parentNode.parentNode,
m = +_arg.dataset.m,
val = +_t.value;
_pop.style.setProperty('--val', val);
_num.textContent = _out.textContent = +(m*val).toFixed(PREC);
DIRS.forEach(c => {
if(_arg.classList.contains(`o${c}`)) {
document.body.style.setProperty(`--o${c}`, `${val}%`);
O[c]._num.forEach(k => { k.textContent = val })
O[c]._unit.forEach(k => { k.textContent = '%' })
}
});
if(_t.id.indexOf('-') !== -1) {
let i = +_t.id.split('-')[1],
item = TRF.chain.list[i];
if(item.iso) {
let _arg2 = _arg.nextElementSibling.nextElementSibling,
_num2 = _arg2.querySelector('.token--num'),
_pop2 = _num2.nextElementSibling,
_in2 = _arg2.querySelector('input'),
_out2 = _arg2.querySelector('input');
_pop2.style.setProperty('--val', val);
_num2.textContent = _in2.value = _out2.value = +(m*val).toFixed(PREC);
}
TRF.chain.text[i] = textFrom(item);
updateTrf();
}
};
function getE(ev) {
/* to unify click and touch */
return ev.touches ? ev.touches[0] : ev;
};
function lock(e, aname) {
/*
* lock in some values at the start of an action
* like swipe, drag
*/
act = aname;
x0 = e.clientX;
y0 = e.clientY;
if(aname === 'swipe') _SWIPE.classList.remove('smooth')
};
function preswipe(e) {
/*
* move panels a bit while the cursor is still moving and
* mouseup/ touchend haven't been triggered yet
*/
let x = e.clientX,
dx = x - x0,
s = 1*(dx > 0),
f = +(dx/r.width).toFixed(2);
if((dx > 0 && _SWIPE.classList.contains('left')) ||
(dx < 0 && !_SWIPE.classList.contains('left'))) {
running = false;
_RUN.textContent = 'Run';
document.body.style.setProperty('--dt', '0s');
document.body.classList.remove('running');
_SWIPE.style.setProperty('--tx', `${(f - s)*50}%`);
}
};
function swipe() {
/*
* fully move from one code option panel to the other
* on mouseup/ touchend
*/
if((!_SWIPE.classList.contains('left') &&
getComputedStyle(_SWIPE).getPropertyValue('--tx').trim() != 0) ||
(_SWIPE.classList.contains('left') &&
getComputedStyle(_SWIPE).getPropertyValue('--tx').trim() != '-50%')) {
_SWIPE.classList.add('smooth');
_SWIPE.style.removeProperty('--tx');
_SWIPE.classList.toggle('left');
}
act = null;
};
function downact(e) {
/*
* decides whether to start a swipe or drag action
* called on mousedown/ touchstart
*/
const _T = e.target;
if(_T.className.indexOf('token') === -1) lock(getE(e), 'swipe');
};
function moveact(e) {
/*
* decides whether to start a preswipe or predrag action
* called on mousemove/ touchmove
*/
if(act === 'swipe') preswipe(getE(e));
};
function upact(e) {
/*
* decides whether to end a swipe or drag action
* called on mouseup/ touchend
*/
if(act === 'swipe') swipe();
};
(function init() {
let _temp = Array.from(document.querySelectorAll('template'));
document.documentElement.classList.add('js');
size();
TRF._wrap = document.getElementById('trf-val');
TRF._last = TRF._wrap.querySelector('.item');
TRF.temp = { _item: TRF._last.cloneNode(true) };
_temp.forEach(_c => {
TRF.temp[`_${_c.id}`] = document.importNode(_c.content, true);
});
TRF.chain = { list: [], text: [] };
TRF._adds = [TRF._last.querySelector('.add')];
DIRS.forEach(c => {
O[c] = {
_num: Array.from(document.querySelectorAll(`.o${c} .token--num`)),
_unit: Array.from(document.querySelectorAll(`.o${c} .token--unit`)),
_pop: document.querySelector(`.o${c} .popup`),
_in: document.querySelector(`.o${c} input`),
_out: document.querySelector(`.o${c} output`)
}
});
document.body.appendChild(_S);
document.body.style.setProperty('--max', LIM)
document.body.style.setProperty('--curr', 0)
})();
addEventListener('click', e => {
let _t = e.target;
if(_t.hasAttribute('aria-haspopup')) {
let _nxt = _t.nextElementSibling;
if(popup !== _nxt) {
let _check = _nxt.querySelector(':checked');
if(popup) closePopup();
if(_check !== null && _check.nextElementSibling.classList.contains('final'))
_check.checked = false;
popup = _nxt;
_t.setAttribute('aria-expanded', poplock = true);
fitPopup(_nxt);
setTimeout(() => { poplock = false }, 500);
}
return
}
else if(popup && !isIn(_t, 'popup')) {
closePopup();
return
}
if(_t.classList.contains('final')) {
let _prv = _t.previousElementSibling;
addTrf({ name: _t.textContent }, getAsc(_t, 'item'));
closePopup();
if(+TRF._last.dataset.i === LIM) {
TRF._adds.forEach(c => { c.setAttribute('disabled', true) });
limreach = true;
}
return
}
if(_t.classList.contains('rem')) {
remTrf(+getAsc(_t, 'item').dataset.i);
return;
}
if(_t.classList.contains('point')) {
DIRS.forEach(c => {
let num = +_t.style.getPropertyValue(`--o${c}`).trim().replace('%', '');
document.body.style.setProperty(`--o${c}`, `${num}%`);
O[c]._num.forEach(k => { k.textContent = num })
O[c]._unit.forEach(k => { k.textContent = '%' })
O[c]._pop.style.setProperty(`--val`, O[c]._in.value = O[c]._out.value = num);
});
}
if(_t.id === 'run') {
running = !running;
_RUN.textContent = running ? 'Stop' : 'Run';
document.body.style.setProperty('--dt', `${running*(TRF.chain.list.length + 4)*BT}s`);
document.body.classList.toggle('running', running);
_SWIPE.classList.add('smooth');
}
}, false);
addEventListener('resize', size, false);
addEventListener('keyup', e => {
if(popup) {
let kc = e.keyCode;
if(!poplock && (kc === 13 || kc === 32))
closePopup()
}
}, false);
addEventListener('input', e => rangeUpdate(e.target), false);
addEventListener('change', e => {
let _t = e.target;
if(_t.type === 'range') {
rangeUpdate(_t);
return
}
if(_t.type === 'radio') {
let _lbl = _t.nextElementSibling;
if(!_lbl.classList.contains('final')) {
let _btn = getAsc(_t, 'popup').previousElementSibling,
i = +_t.id.split('-')[1],
item = TRF.chain.list[i];
_btn.textContent = _lbl.textContent;
if(_btn.classList.contains('token--func')) {
let dir = _t.dataset.dir,
_ctrl = _btn.parentNode,
_args = Array.from(item._el.querySelectorAll('.token--arg')),
_iso = item._el.querySelector('[type=checkbox]');
_ctrl.dataset.dir = dir;
if(item.name === 'scale') {
if(dir !== '') {
_iso.disabled = true;
_args.forEach(_c => {
if(_c.dataset.dir !== dir) {
let _num = _c.querySelector('.token--num'),
_pop = _num.nextElementSibling,
_in = _pop.querySelector('input'),
_out = _pop.querySelector('output');
_pop.style.setProperty('--val', _num.textContent = _in.value = _out.value = 1);
}
});
}
else {
_iso.disabled = false;
if(item.iso) {
let val = +_args[0].querySelector('.token--num').textContent;
_args.forEach((_c, i, a) => {
if(i > 0) {
let _num = _c.querySelector('.token--num'),
_pop = _num.nextElementSibling,
_in = _pop.querySelector('input'),
_out = _pop.querySelector('output');
_pop.style.setProperty('--val', _num.textContent = _in.value = _out.value = val);
}
});
}
}
}
}
else if(_btn.classList.contains('token--unit')) {
let _arg = _btn.parentNode.parentNode,
_num = _arg.querySelector('.token--num'),
_out = _arg.querySelector('output'),
m = +_t.dataset.val,
val = +_arg.querySelector('[type=range]').value;
_btn.textContent = _lbl.textContent;
_arg.dataset.m = m;
_num.textContent = _out.textContent = +(m*val).toFixed(PREC);
}
TRF.chain.text[i] = textFrom(item);
updateTrf();
return;
}
}
if(_t.type === 'checkbox') {
let i = +_t.id.split('-')[1],
item = TRF.chain.list[i],
_ctrl = getAsc(_t, 'ctrl'),
_args = Array.from(item._el.querySelectorAll('.token--arg'));
_ctrl.classList.toggle('iso');
item.iso = !item.iso;
if(item.iso) {
let val = +_args[0].querySelector('.token--num').textContent;
_args.forEach((_c, i, a) => {
if(i > 0) {
let _num = _c.querySelector('.token--num'),
_pop = _num.nextElementSibling,
_in = _pop.querySelector('input'),
_out = _pop.querySelector('output');
_pop.style.setProperty('--val', _num.textContent = _in.value = _out.value = val);
}
});
}
TRF.chain.text[i] = textFrom(item);
updateTrf();
return;
}
}, false);
addEventListener('mousedown', downact, false);
addEventListener('touchstart', downact, false);
addEventListener('mousemove', moveact, false);
addEventListener('touchmove', moveact, false);
addEventListener('mouseup', upact, false);
addEventListener('touchend', upact, false);
document.body.addEventListener('mouseout', upact, false);
addEventListener('animationend', e => {
_SWIPE.classList.toggle('left')
}, false);
Also see: Tab Triggers