text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```scss
@font-face {
font-family: 'noto';
src: url('../fonts/noto-sans-regular.ttf') format('truetype');
font-weight: 300;
font-style: normal;
}
@font-face {
font-family: 'noto';
src: url('../fonts/noto-sans-italic.ttf') format('truetype');
font-weight: 300;
font-style: italic;
}
@font-face {
font-family: 'noto';
src: url('../fonts/noto-sans-700.ttf') format('truetype');
font-weight: 600;
font-style: normal;
}
@font-face {
font-family: 'noto';
src: url('../fonts/noto-sans-700italic.ttf') format('truetype');
font-weight: 600;
font-style: italic;
}
@font-face {
font-family: 'source code';
src: url('../fonts/source-code-pro-300.ttf') format('truetype');
font-weight: 300;
font-style: normal;
}
@font-face {
font-family: 'source code';
src: url('../fonts/source-code-pro-500.ttf') format('truetype');
font-weight: 600;
font-style: normal;
}
``` | /content/code_sandbox/app/assets/sass/_fonts.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 270 |
```scss
.btn {
border-radius: $border-radius-base;
padding: $padding-base $padding-lg;
font-size: $font-size-base;
line-height: 1.2;
text-decoration: none;
text-transform: uppercase;
cursor: pointer;
margin-left: $padding-base;
&-default {
border: 1px solid $blue;
color: $blue;
background-color: #fff;
&:hover {
background-color: $light-blue;
color: #fff;
}
}
&-lg {
padding: $padding-base $padding-lg*2;
font-size: round($font-size-base * 1.2);
}
&-sm {
padding: $padding-base $padding-base;
font-size: round($font-size-base * 0.9);
}
&-slim {
.fa { margin: 0};
}
&-link {
border: 0;
background-color: transparent;
color: $link-color;
padding: 0;
}
&-danger {
border: 1px solid $red;
color: $red;
text-transform: uppercase;
background-color: #fff;
&:hover {
background-color: $light-red;
}
}
&-primary {
border: 0;
background: $blue;
box-shadow: 1px 1px 1px $gray;
color: #ffffff;
&:hover {
background: $dark-blue;
}
}
&-close {
@extend .btn-slim;
border-radius: 50%;
box-shadow: 0;
line-height: 1.5;
border: 1px solid $line-color;
background-color: #fff;
}
}
.button-group {
button {
margin: 0;
background-color: $gray-lightest;
border-radius: 0;
float: left;
border: 1px solid $line-color;
cursor: pointer;
&:first-of-type {
border-top-left-radius: $border-radius-lg;
border-bottom-left-radius: $border-radius-lg;
}
&:last-of-type {
border-top-right-radius: $border-radius-lg;
border-bottom-right-radius: $border-radius-lg;
}
}
.selected {
background-color: $gray-light;
}
}
``` | /content/code_sandbox/app/assets/sass/_buttons.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 519 |
```scss
$connector-height: 12px;
$connector-line: 2px solid darken($line-color, 10%);
.plan {
padding-bottom: $padding-lg * 3;
margin-left: 100px;
ul {
display: flex;
padding-top: $connector-height;
position: relative;
margin: auto;
transition: all 0.5s;
margin-top: -5px;
// vertical connector
ul::before {
content: '';
position: absolute; top: 0; left: 50%;
border-left: $connector-line;
height: $connector-height;
width: 0;
}
li {
float: left; text-align: center;
list-style-type: none;
position: relative;
padding: $connector-height $padding-sm 0 $padding-sm;
transition: all 0.5s;
// connectors
&:before, &:after {
content: '';
position: absolute; top: 0; right: 50%;
border-top: $connector-line;
width: 50%; height: $connector-height;
}
&:after {
right: auto; left: 50%;
border-left: $connector-line;
}
&:only-child {
padding-top: 0;
&:after, &:before {
display: none;
}
}
&:first-child::before, &:last-child::after {
border: 0 none;
}
&:last-child::before {
border-right: $connector-line;
border-radius: 0 $border-radius-lg 0 0;
}
&:first-child::after {
border-radius: $border-radius-lg 0 0 0;
}
//hovers
.plan-node:hover+ul::before {
border-color: $highlight-color;
}
.plan-node:hover+ul li::after,
.plan-node:hover+ul li::before,
.plan-node:hover+ul ul::before{
border-color: $highlight-color-dark;
}
}
}
}
.plan-stats {
display: flex;
font-size: $font-size-base;
margin: $padding-lg auto $padding-lg auto;
padding-bottom: $padding-lg;
border-bottom: 1px solid $line-color;
border-radius: $border-radius-lg*2;
width: 650px;
position: relative;
div {
padding-right: $padding-lg;
flex-grow: 1;
}
.stat-value {
display: block;
text-align: center;
font-size: $font-size-lg;
}
.stat-label {
display: block;
text-align: center;
font-size: $font-size-sm;
}
$triangle-size: 9px;
&:after {
content:'';
position: absolute;
top: 100%;
left: 50%;
margin-left: $triangle-size*-1;
width: 0;
height: 0;
border-top: solid $triangle-size $line-color;
border-left: solid $triangle-size transparent;
border-right: solid $triangle-size transparent;
}
.btn-close {
padding: $padding-base;
background-color: transparent;
font-size: $font-size-lg;
text-align: center;
@extend .text-muted;
margin-left: $padding-base;
cursor: pointer;
border: 0;
}
}
``` | /content/code_sandbox/app/assets/sass/_plan.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 779 |
```scss
//vars
$page-width: 1000px;
$padding-base: 6px;
$padding-sm: 3px;
$padding-lg: 10px;
$padding-xl: 18px;
$font-size-base: 13px;
$font-size-xs: round($font-size-base * 0.7);
$font-size-sm: round($font-size-base * 0.9);
$font-size-lg: round($font-size-base * 1.3);
$font-size-xl: round($font-size-base * 1.7);
$font-family-sans-serif: 'noto';
$font-family-mono: 'source code';
$line-height-base: 1.3;
$gray-lightest: #f7f7f7;
$gray-light: darken($gray-lightest, 10%);
$gray: darken(#f7f7f7, 30%);
$gray-dark: darken(#f7f7f7, 50%);
$gray-darkest: darken($gray-lightest, 70%);
$blue: #00B5E2;
$dark-blue: #008CAF;
$light-blue: #65DDFB;
$red: #AF2F11;
$dark-red: #7C210C;
$light-red: #FB8165;
$green: #279404;
$yellow: #F8E400;
$bg-color: $gray-lightest;
$text-color: #4d525a;
$text-color-light: lighten($text-color, 30%);
$line-color: $gray-light;
$line-color-light: lighten($gray-light, 10%);
$link-color: $blue;
$border-radius-base: 3px;
$border-radius-lg: 6px;
$main-color: $blue;
$main-color-dark: $blue;
$highlight-color: $blue;
$highlight-color-dark: $dark-blue;
$alert-color: #FB4418;
``` | /content/code_sandbox/app/assets/sass/_variables.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 409 |
```scss
nav {
font-size: round($font-size-base * 1.3);
background-color: #fff;
padding: round($padding-lg * 1.5);
.nav-container {
width: $page-width;
margin: auto;
}
.about {
float: right;
line-height: 2;
margin-left: $padding-xl;
}
}
``` | /content/code_sandbox/app/assets/sass/_nav.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 83 |
```scss
// Spinning Icons
// --------------------------
.#{$fa-css-prefix}-spin {
-webkit-animation: fa-spin 2s infinite linear;
animation: fa-spin 2s infinite linear;
}
.#{$fa-css-prefix}-pulse {
-webkit-animation: fa-spin 1s infinite steps(8);
animation: fa-spin 1s infinite steps(8);
}
@-webkit-keyframes fa-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@keyframes fa-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
``` | /content/code_sandbox/app/assets/sass/font-awesome/_animated.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 195 |
```scss
// Icon Sizes
// -------------------------
/* makes the font 33% larger relative to the icon container */
.#{$fa-css-prefix}-lg {
font-size: (4em / 3);
line-height: (3em / 4);
vertical-align: -15%;
}
.#{$fa-css-prefix}-2x { font-size: 2em; }
.#{$fa-css-prefix}-3x { font-size: 3em; }
.#{$fa-css-prefix}-4x { font-size: 4em; }
.#{$fa-css-prefix}-5x { font-size: 5em; }
``` | /content/code_sandbox/app/assets/sass/font-awesome/_larger.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 128 |
```scss
/* FONT PATH
* -------------------------- */
@font-face {
font-family: 'FontAwesome';
src: url('#{$fa-font-path}/fontawesome-webfont.eot?v=#{$fa-version}');
src: url('#{$fa-font-path}/fontawesome-webfont.eot?#iefix&v=#{$fa-version}') format('embedded-opentype'),
url('#{$fa-font-path}/fontawesome-webfont.woff2?v=#{$fa-version}') format('woff2'),
url('#{$fa-font-path}/fontawesome-webfont.woff?v=#{$fa-version}') format('woff'),
url('#{$fa-font-path}/fontawesome-webfont.ttf?v=#{$fa-version}') format('truetype'),
url('#{$fa-font-path}/fontawesome-webfont.svg?v=#{$fa-version}#fontawesomeregular') format('svg');
// src: url('#{$fa-font-path}/FontAwesome.otf') format('opentype'); // used when developing fonts
font-weight: normal;
font-style: normal;
}
``` | /content/code_sandbox/app/assets/sass/font-awesome/_path.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 220 |
```scss
// Bordered & Pulled
// -------------------------
.#{$fa-css-prefix}-border {
padding: .2em .25em .15em;
border: solid .08em $fa-border-color;
border-radius: .1em;
}
.#{$fa-css-prefix}-pull-left { float: left; }
.#{$fa-css-prefix}-pull-right { float: right; }
.#{$fa-css-prefix} {
&.#{$fa-css-prefix}-pull-left { margin-right: .3em; }
&.#{$fa-css-prefix}-pull-right { margin-left: .3em; }
}
/* Deprecated as of 4.4.0 */
.pull-right { float: right; }
.pull-left { float: left; }
.#{$fa-css-prefix} {
&.pull-left { margin-right: .3em; }
&.pull-right { margin-left: .3em; }
}
``` | /content/code_sandbox/app/assets/sass/font-awesome/_bordered-pulled.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 190 |
```scss
// List Icons
// -------------------------
.#{$fa-css-prefix}-ul {
padding-left: 0;
margin-left: $fa-li-width;
list-style-type: none;
> li { position: relative; }
}
.#{$fa-css-prefix}-li {
position: absolute;
left: -$fa-li-width;
width: $fa-li-width;
top: (2em / 14);
text-align: center;
&.#{$fa-css-prefix}-lg {
left: -$fa-li-width + (4em / 14);
}
}
``` | /content/code_sandbox/app/assets/sass/font-awesome/_list.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 122 |
```scss
/*!
* Font Awesome 4.5.0 by @davegandy - path_to_url - @fontawesome
*/
@import "variables";
@import "mixins";
@import "path";
@import "core";
@import "larger";
@import "fixed-width";
@import "list";
@import "bordered-pulled";
@import "animated";
@import "rotated-flipped";
@import "stacked";
@import "icons";
``` | /content/code_sandbox/app/assets/sass/font-awesome/_styles.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 98 |
```scss
// Base Class Definition
// -------------------------
.#{$fa-css-prefix} {
display: inline-block;
font: normal normal normal #{$fa-font-size-base}/#{$fa-line-height-base} FontAwesome; // shortening font declaration
font-size: inherit; // can't have font-size inherit on line above, so need to override
text-rendering: auto; // optimizelegibility throws things off #1094
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
``` | /content/code_sandbox/app/assets/sass/font-awesome/_core.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 113 |
```scss
// Stacked Icons
// -------------------------
.#{$fa-css-prefix}-stack {
position: relative;
display: inline-block;
width: 2em;
height: 2em;
line-height: 2em;
vertical-align: middle;
}
.#{$fa-css-prefix}-stack-1x, .#{$fa-css-prefix}-stack-2x {
position: absolute;
left: 0;
width: 100%;
text-align: center;
}
.#{$fa-css-prefix}-stack-1x { line-height: inherit; }
.#{$fa-css-prefix}-stack-2x { font-size: 2em; }
.#{$fa-css-prefix}-inverse { color: $fa-inverse; }
``` | /content/code_sandbox/app/assets/sass/font-awesome/_stacked.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 155 |
```css
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}html{line-height:1}ol,ul{list-style:none}table{border-collapse:collapse;border-spacing:0}caption,th,td{text-align:left;font-weight:normal;vertical-align:middle}q,blockquote{quotes:none}q:before,q:after,blockquote:before,blockquote:after{content:"";content:none}a img{border:none}article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}/*!
* Font Awesome 4.5.0 by @davegandy - path_to_url - @fontawesome
*/@font-face{font-family:'FontAwesome';src:url("../fonts/fontawesome-webfont.eot?v=4.5.0");src:url("../fonts/fontawesome-webfont.eot?#iefix&v=4.5.0") format("embedded-opentype"),url("../fonts/fontawesome-webfont.woff2?v=4.5.0") format("woff2"),url("../fonts/fontawesome-webfont.woff?v=4.5.0") format("woff"),url("../fonts/fontawesome-webfont.ttf?v=4.5.0") format("truetype"),url("../fonts/fontawesome-webfont.svg?v=4.5.0#fontawesomeregular") format("svg");font-weight:normal;font-style:normal}.fa{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333em;line-height:0.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14286em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14286em;width:2.14286em;top:0.14286em;text-align:center}.fa-li.fa-lg{left:-1.85714em}.fa-border{padding:.2em .25em .15em;border:solid 0.08em #eee;border-radius:.1em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left{margin-right:.3em}.fa.fa-pull-right{margin-left:.3em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1);-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=0);-webkit-transform:scale(-1, 1);-ms-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);-webkit-transform:scale(1, -1);-ms-transform:scale(1, -1);transform:scale(1, -1)}:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-flip-horizontal,:root .fa-flip-vertical{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:""}.fa-music:before{content:""}.fa-search:before{content:""}.fa-envelope-o:before{content:""}.fa-heart:before{content:""}.fa-star:before{content:""}.fa-star-o:before{content:""}.fa-user:before{content:""}.fa-film:before{content:""}.fa-th-large:before{content:""}.fa-th:before{content:""}.fa-th-list:before{content:""}.fa-check:before{content:""}.fa-remove:before,.fa-close:before,.fa-times:before{content:""}.fa-search-plus:before{content:""}.fa-search-minus:before{content:""}.fa-power-off:before{content:""}.fa-signal:before{content:""}.fa-gear:before,.fa-cog:before{content:""}.fa-trash-o:before{content:""}.fa-home:before{content:""}.fa-file-o:before{content:""}.fa-clock-o:before{content:""}.fa-road:before{content:""}.fa-download:before{content:""}.fa-arrow-circle-o-down:before{content:""}.fa-arrow-circle-o-up:before{content:""}.fa-inbox:before{content:""}.fa-play-circle-o:before{content:""}.fa-rotate-right:before,.fa-repeat:before{content:""}.fa-refresh:before{content:""}.fa-list-alt:before{content:""}.fa-lock:before{content:""}.fa-flag:before{content:""}.fa-headphones:before{content:""}.fa-volume-off:before{content:""}.fa-volume-down:before{content:""}.fa-volume-up:before{content:""}.fa-qrcode:before{content:""}.fa-barcode:before{content:""}.fa-tag:before{content:""}.fa-tags:before{content:""}.fa-book:before{content:""}.fa-bookmark:before{content:""}.fa-print:before{content:""}.fa-camera:before{content:""}.fa-font:before{content:""}.fa-bold:before{content:""}.fa-italic:before{content:""}.fa-text-height:before{content:""}.fa-text-width:before{content:""}.fa-align-left:before{content:""}.fa-align-center:before{content:""}.fa-align-right:before{content:""}.fa-align-justify:before{content:""}.fa-list:before{content:""}.fa-dedent:before,.fa-outdent:before{content:""}.fa-indent:before{content:""}.fa-video-camera:before{content:""}.fa-photo:before,.fa-image:before,.fa-picture-o:before{content:""}.fa-pencil:before{content:""}.fa-map-marker:before{content:""}.fa-adjust:before{content:""}.fa-tint:before{content:""}.fa-edit:before,.fa-pencil-square-o:before{content:""}.fa-share-square-o:before{content:""}.fa-check-square-o:before{content:""}.fa-arrows:before{content:""}.fa-step-backward:before{content:""}.fa-fast-backward:before{content:""}.fa-backward:before{content:""}.fa-play:before{content:""}.fa-pause:before{content:""}.fa-stop:before{content:""}.fa-forward:before{content:""}.fa-fast-forward:before{content:""}.fa-step-forward:before{content:""}.fa-eject:before{content:""}.fa-chevron-left:before{content:""}.fa-chevron-right:before{content:""}.fa-plus-circle:before{content:""}.fa-minus-circle:before{content:""}.fa-times-circle:before{content:""}.fa-check-circle:before{content:""}.fa-question-circle:before{content:""}.fa-info-circle:before{content:""}.fa-crosshairs:before{content:""}.fa-times-circle-o:before{content:""}.fa-check-circle-o:before{content:""}.fa-ban:before{content:""}.fa-arrow-left:before{content:""}.fa-arrow-right:before{content:""}.fa-arrow-up:before{content:""}.fa-arrow-down:before{content:""}.fa-mail-forward:before,.fa-share:before{content:""}.fa-expand:before{content:""}.fa-compress:before{content:""}.fa-plus:before{content:""}.fa-minus:before{content:""}.fa-asterisk:before{content:""}.fa-exclamation-circle:before{content:""}.fa-gift:before{content:""}.fa-leaf:before{content:""}.fa-fire:before{content:""}.fa-eye:before{content:""}.fa-eye-slash:before{content:""}.fa-warning:before,.fa-exclamation-triangle:before{content:""}.fa-plane:before{content:""}.fa-calendar:before{content:""}.fa-random:before{content:""}.fa-comment:before{content:""}.fa-magnet:before{content:""}.fa-chevron-up:before{content:""}.fa-chevron-down:before{content:""}.fa-retweet:before{content:""}.fa-shopping-cart:before{content:""}.fa-folder:before{content:""}.fa-folder-open:before{content:""}.fa-arrows-v:before{content:""}.fa-arrows-h:before{content:""}.fa-bar-chart-o:before,.fa-bar-chart:before{content:""}.fa-twitter-square:before{content:""}.fa-facebook-square:before{content:""}.fa-camera-retro:before{content:""}.fa-key:before{content:""}.fa-gears:before,.fa-cogs:before{content:""}.fa-comments:before{content:""}.fa-thumbs-o-up:before{content:""}.fa-thumbs-o-down:before{content:""}.fa-star-half:before{content:""}.fa-heart-o:before{content:""}.fa-sign-out:before{content:""}.fa-linkedin-square:before{content:""}.fa-thumb-tack:before{content:""}.fa-external-link:before{content:""}.fa-sign-in:before{content:""}.fa-trophy:before{content:""}.fa-github-square:before{content:""}.fa-upload:before{content:""}.fa-lemon-o:before{content:""}.fa-phone:before{content:""}.fa-square-o:before{content:""}.fa-bookmark-o:before{content:""}.fa-phone-square:before{content:""}.fa-twitter:before{content:""}.fa-facebook-f:before,.fa-facebook:before{content:""}.fa-github:before{content:""}.fa-unlock:before{content:""}.fa-credit-card:before{content:""}.fa-feed:before,.fa-rss:before{content:""}.fa-hdd-o:before{content:""}.fa-bullhorn:before{content:""}.fa-bell:before{content:""}.fa-certificate:before{content:""}.fa-hand-o-right:before{content:""}.fa-hand-o-left:before{content:""}.fa-hand-o-up:before{content:""}.fa-hand-o-down:before{content:""}.fa-arrow-circle-left:before{content:""}.fa-arrow-circle-right:before{content:""}.fa-arrow-circle-up:before{content:""}.fa-arrow-circle-down:before{content:""}.fa-globe:before{content:""}.fa-wrench:before{content:""}.fa-tasks:before{content:""}.fa-filter:before{content:""}.fa-briefcase:before{content:""}.fa-arrows-alt:before{content:""}.fa-group:before,.fa-users:before{content:""}.fa-chain:before,.fa-link:before{content:""}.fa-cloud:before{content:""}.fa-flask:before{content:""}.fa-cut:before,.fa-scissors:before{content:""}.fa-copy:before,.fa-files-o:before{content:""}.fa-paperclip:before{content:""}.fa-save:before,.fa-floppy-o:before{content:""}.fa-square:before{content:""}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content:""}.fa-list-ul:before{content:""}.fa-list-ol:before{content:""}.fa-strikethrough:before{content:""}.fa-underline:before{content:""}.fa-table:before{content:""}.fa-magic:before{content:""}.fa-truck:before{content:""}.fa-pinterest:before{content:""}.fa-pinterest-square:before{content:""}.fa-google-plus-square:before{content:""}.fa-google-plus:before{content:""}.fa-money:before{content:""}.fa-caret-down:before{content:""}.fa-caret-up:before{content:""}.fa-caret-left:before{content:""}.fa-caret-right:before{content:""}.fa-columns:before{content:""}.fa-unsorted:before,.fa-sort:before{content:""}.fa-sort-down:before,.fa-sort-desc:before{content:""}.fa-sort-up:before,.fa-sort-asc:before{content:""}.fa-envelope:before{content:""}.fa-linkedin:before{content:""}.fa-rotate-left:before,.fa-undo:before{content:""}.fa-legal:before,.fa-gavel:before{content:""}.fa-dashboard:before,.fa-tachometer:before{content:""}.fa-comment-o:before{content:""}.fa-comments-o:before{content:""}.fa-flash:before,.fa-bolt:before{content:""}.fa-sitemap:before{content:""}.fa-umbrella:before{content:""}.fa-paste:before,.fa-clipboard:before{content:""}.fa-lightbulb-o:before{content:""}.fa-exchange:before{content:""}.fa-cloud-download:before{content:""}.fa-cloud-upload:before{content:""}.fa-user-md:before{content:""}.fa-stethoscope:before{content:""}.fa-suitcase:before{content:""}.fa-bell-o:before{content:""}.fa-coffee:before{content:""}.fa-cutlery:before{content:""}.fa-file-text-o:before{content:""}.fa-building-o:before{content:""}.fa-hospital-o:before{content:""}.fa-ambulance:before{content:""}.fa-medkit:before{content:""}.fa-fighter-jet:before{content:""}.fa-beer:before{content:""}.fa-h-square:before{content:""}.fa-plus-square:before{content:""}.fa-angle-double-left:before{content:""}.fa-angle-double-right:before{content:""}.fa-angle-double-up:before{content:""}.fa-angle-double-down:before{content:""}.fa-angle-left:before{content:""}.fa-angle-right:before{content:""}.fa-angle-up:before{content:""}.fa-angle-down:before{content:""}.fa-desktop:before{content:""}.fa-laptop:before{content:""}.fa-tablet:before{content:""}.fa-mobile-phone:before,.fa-mobile:before{content:""}.fa-circle-o:before{content:""}.fa-quote-left:before{content:""}.fa-quote-right:before{content:""}.fa-spinner:before{content:""}.fa-circle:before{content:""}.fa-mail-reply:before,.fa-reply:before{content:""}.fa-github-alt:before{content:""}.fa-folder-o:before{content:""}.fa-folder-open-o:before{content:""}.fa-smile-o:before{content:""}.fa-frown-o:before{content:""}.fa-meh-o:before{content:""}.fa-gamepad:before{content:""}.fa-keyboard-o:before{content:""}.fa-flag-o:before{content:""}.fa-flag-checkered:before{content:""}.fa-terminal:before{content:""}.fa-code:before{content:""}.fa-mail-reply-all:before,.fa-reply-all:before{content:""}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:""}.fa-location-arrow:before{content:""}.fa-crop:before{content:""}.fa-code-fork:before{content:""}.fa-unlink:before,.fa-chain-broken:before{content:""}.fa-question:before{content:""}.fa-info:before{content:""}.fa-exclamation:before{content:""}.fa-superscript:before{content:""}.fa-subscript:before{content:""}.fa-eraser:before{content:""}.fa-puzzle-piece:before{content:""}.fa-microphone:before{content:""}.fa-microphone-slash:before{content:""}.fa-shield:before{content:""}.fa-calendar-o:before{content:""}.fa-fire-extinguisher:before{content:""}.fa-rocket:before{content:""}.fa-maxcdn:before{content:""}.fa-chevron-circle-left:before{content:""}.fa-chevron-circle-right:before{content:""}.fa-chevron-circle-up:before{content:""}.fa-chevron-circle-down:before{content:""}.fa-html5:before{content:""}.fa-css3:before{content:""}.fa-anchor:before{content:""}.fa-unlock-alt:before{content:""}.fa-bullseye:before{content:""}.fa-ellipsis-h:before{content:""}.fa-ellipsis-v:before{content:""}.fa-rss-square:before{content:""}.fa-play-circle:before{content:""}.fa-ticket:before{content:""}.fa-minus-square:before{content:""}.fa-minus-square-o:before{content:""}.fa-level-up:before{content:""}.fa-level-down:before{content:""}.fa-check-square:before{content:""}.fa-pencil-square:before{content:""}.fa-external-link-square:before{content:""}.fa-share-square:before{content:""}.fa-compass:before{content:""}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:""}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:""}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:""}.fa-euro:before,.fa-eur:before{content:""}.fa-gbp:before{content:""}.fa-dollar:before,.fa-usd:before{content:""}.fa-rupee:before,.fa-inr:before{content:""}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:""}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:""}.fa-won:before,.fa-krw:before{content:""}.fa-bitcoin:before,.fa-btc:before{content:""}.fa-file:before{content:""}.fa-file-text:before{content:""}.fa-sort-alpha-asc:before{content:""}.fa-sort-alpha-desc:before{content:""}.fa-sort-amount-asc:before{content:""}.fa-sort-amount-desc:before{content:""}.fa-sort-numeric-asc:before{content:""}.fa-sort-numeric-desc:before{content:""}.fa-thumbs-up:before{content:""}.fa-thumbs-down:before{content:""}.fa-youtube-square:before{content:""}.fa-youtube:before{content:""}.fa-xing:before{content:""}.fa-xing-square:before{content:""}.fa-youtube-play:before{content:""}.fa-dropbox:before{content:""}.fa-stack-overflow:before{content:""}.fa-instagram:before{content:""}.fa-flickr:before{content:""}.fa-adn:before{content:""}.fa-bitbucket:before{content:""}.fa-bitbucket-square:before{content:""}.fa-tumblr:before{content:""}.fa-tumblr-square:before{content:""}.fa-long-arrow-down:before{content:""}.fa-long-arrow-up:before{content:""}.fa-long-arrow-left:before{content:""}.fa-long-arrow-right:before{content:""}.fa-apple:before{content:""}.fa-windows:before{content:""}.fa-android:before{content:""}.fa-linux:before{content:""}.fa-dribbble:before{content:""}.fa-skype:before{content:""}.fa-foursquare:before{content:""}.fa-trello:before{content:""}.fa-female:before{content:""}.fa-male:before{content:""}.fa-gittip:before,.fa-gratipay:before{content:""}.fa-sun-o:before{content:""}.fa-moon-o:before{content:""}.fa-archive:before{content:""}.fa-bug:before{content:""}.fa-vk:before{content:""}.fa-weibo:before{content:""}.fa-renren:before{content:""}.fa-pagelines:before{content:""}.fa-stack-exchange:before{content:""}.fa-arrow-circle-o-right:before{content:""}.fa-arrow-circle-o-left:before{content:""}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:""}.fa-dot-circle-o:before{content:""}.fa-wheelchair:before{content:""}.fa-vimeo-square:before{content:""}.fa-turkish-lira:before,.fa-try:before{content:""}.fa-plus-square-o:before{content:""}.fa-space-shuttle:before{content:""}.fa-slack:before{content:""}.fa-envelope-square:before{content:""}.fa-wordpress:before{content:""}.fa-openid:before{content:""}.fa-institution:before,.fa-bank:before,.fa-university:before{content:""}.fa-mortar-board:before,.fa-graduation-cap:before{content:""}.fa-yahoo:before{content:""}.fa-google:before{content:""}.fa-reddit:before{content:""}.fa-reddit-square:before{content:""}.fa-stumbleupon-circle:before{content:""}.fa-stumbleupon:before{content:""}.fa-delicious:before{content:""}.fa-digg:before{content:""}.fa-pied-piper:before{content:""}.fa-pied-piper-alt:before{content:""}.fa-drupal:before{content:""}.fa-joomla:before{content:""}.fa-language:before{content:""}.fa-fax:before{content:""}.fa-building:before{content:""}.fa-child:before{content:""}.fa-paw:before{content:""}.fa-spoon:before{content:""}.fa-cube:before{content:""}.fa-cubes:before{content:""}.fa-behance:before{content:""}.fa-behance-square:before{content:""}.fa-steam:before{content:""}.fa-steam-square:before{content:""}.fa-recycle:before{content:""}.fa-automobile:before,.fa-car:before{content:""}.fa-cab:before,.fa-taxi:before{content:""}.fa-tree:before{content:""}.fa-spotify:before{content:""}.fa-deviantart:before{content:""}.fa-soundcloud:before{content:""}.fa-database:before{content:""}.fa-file-pdf-o:before{content:""}.fa-file-word-o:before{content:""}.fa-file-excel-o:before{content:""}.fa-file-powerpoint-o:before{content:""}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:""}.fa-file-zip-o:before,.fa-file-archive-o:before{content:""}.fa-file-sound-o:before,.fa-file-audio-o:before{content:""}.fa-file-movie-o:before,.fa-file-video-o:before{content:""}.fa-file-code-o:before{content:""}.fa-vine:before{content:""}.fa-codepen:before{content:""}.fa-jsfiddle:before{content:""}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:""}.fa-circle-o-notch:before{content:""}.fa-ra:before,.fa-rebel:before{content:""}.fa-ge:before,.fa-empire:before{content:""}.fa-git-square:before{content:""}.fa-git:before{content:""}.fa-y-combinator-square:before,.fa-yc-square:before,.fa-hacker-news:before{content:""}.fa-tencent-weibo:before{content:""}.fa-qq:before{content:""}.fa-wechat:before,.fa-weixin:before{content:""}.fa-send:before,.fa-paper-plane:before{content:""}.fa-send-o:before,.fa-paper-plane-o:before{content:""}.fa-history:before{content:""}.fa-circle-thin:before{content:""}.fa-header:before{content:""}.fa-paragraph:before{content:""}.fa-sliders:before{content:""}.fa-share-alt:before{content:""}.fa-share-alt-square:before{content:""}.fa-bomb:before{content:""}.fa-soccer-ball-o:before,.fa-futbol-o:before{content:""}.fa-tty:before{content:""}.fa-binoculars:before{content:""}.fa-plug:before{content:""}.fa-slideshare:before{content:""}.fa-twitch:before{content:""}.fa-yelp:before{content:""}.fa-newspaper-o:before{content:""}.fa-wifi:before{content:""}.fa-calculator:before{content:""}.fa-paypal:before{content:""}.fa-google-wallet:before{content:""}.fa-cc-visa:before{content:""}.fa-cc-mastercard:before{content:""}.fa-cc-discover:before{content:""}.fa-cc-amex:before{content:""}.fa-cc-paypal:before{content:""}.fa-cc-stripe:before{content:""}.fa-bell-slash:before{content:""}.fa-bell-slash-o:before{content:""}.fa-trash:before{content:""}.fa-copyright:before{content:""}.fa-at:before{content:""}.fa-eyedropper:before{content:""}.fa-paint-brush:before{content:""}.fa-birthday-cake:before{content:""}.fa-area-chart:before{content:""}.fa-pie-chart:before{content:""}.fa-line-chart:before{content:""}.fa-lastfm:before{content:""}.fa-lastfm-square:before{content:""}.fa-toggle-off:before{content:""}.fa-toggle-on:before{content:""}.fa-bicycle:before{content:""}.fa-bus:before{content:""}.fa-ioxhost:before{content:""}.fa-angellist:before{content:""}.fa-cc:before{content:""}.fa-shekel:before,.fa-sheqel:before,.fa-ils:before{content:""}.fa-meanpath:before{content:""}.fa-buysellads:before{content:""}.fa-connectdevelop:before{content:""}.fa-dashcube:before{content:""}.fa-forumbee:before{content:""}.fa-leanpub:before{content:""}.fa-sellsy:before{content:""}.fa-shirtsinbulk:before{content:""}.fa-simplybuilt:before{content:""}.fa-skyatlas:before{content:""}.fa-cart-plus:before{content:""}.fa-cart-arrow-down:before{content:""}.fa-diamond:before{content:""}.fa-ship:before{content:""}.fa-user-secret:before{content:""}.fa-motorcycle:before{content:""}.fa-street-view:before{content:""}.fa-heartbeat:before{content:""}.fa-venus:before{content:""}.fa-mars:before{content:""}.fa-mercury:before{content:""}.fa-intersex:before,.fa-transgender:before{content:""}.fa-transgender-alt:before{content:""}.fa-venus-double:before{content:""}.fa-mars-double:before{content:""}.fa-venus-mars:before{content:""}.fa-mars-stroke:before{content:""}.fa-mars-stroke-v:before{content:""}.fa-mars-stroke-h:before{content:""}.fa-neuter:before{content:""}.fa-genderless:before{content:""}.fa-facebook-official:before{content:""}.fa-pinterest-p:before{content:""}.fa-whatsapp:before{content:""}.fa-server:before{content:""}.fa-user-plus:before{content:""}.fa-user-times:before{content:""}.fa-hotel:before,.fa-bed:before{content:""}.fa-viacoin:before{content:""}.fa-train:before{content:""}.fa-subway:before{content:""}.fa-medium:before{content:""}.fa-yc:before,.fa-y-combinator:before{content:""}.fa-optin-monster:before{content:""}.fa-opencart:before{content:""}.fa-expeditedssl:before{content:""}.fa-battery-4:before,.fa-battery-full:before{content:""}.fa-battery-3:before,.fa-battery-three-quarters:before{content:""}.fa-battery-2:before,.fa-battery-half:before{content:""}.fa-battery-1:before,.fa-battery-quarter:before{content:""}.fa-battery-0:before,.fa-battery-empty:before{content:""}.fa-mouse-pointer:before{content:""}.fa-i-cursor:before{content:""}.fa-object-group:before{content:""}.fa-object-ungroup:before{content:""}.fa-sticky-note:before{content:""}.fa-sticky-note-o:before{content:""}.fa-cc-jcb:before{content:""}.fa-cc-diners-club:before{content:""}.fa-clone:before{content:""}.fa-balance-scale:before{content:""}.fa-hourglass-o:before{content:""}.fa-hourglass-1:before,.fa-hourglass-start:before{content:""}.fa-hourglass-2:before,.fa-hourglass-half:before{content:""}.fa-hourglass-3:before,.fa-hourglass-end:before{content:""}.fa-hourglass:before{content:""}.fa-hand-grab-o:before,.fa-hand-rock-o:before{content:""}.fa-hand-stop-o:before,.fa-hand-paper-o:before{content:""}.fa-hand-scissors-o:before{content:""}.fa-hand-lizard-o:before{content:""}.fa-hand-spock-o:before{content:""}.fa-hand-pointer-o:before{content:""}.fa-hand-peace-o:before{content:""}.fa-trademark:before{content:""}.fa-registered:before{content:""}.fa-creative-commons:before{content:""}.fa-gg:before{content:""}.fa-gg-circle:before{content:""}.fa-tripadvisor:before{content:""}.fa-odnoklassniki:before{content:""}.fa-odnoklassniki-square:before{content:""}.fa-get-pocket:before{content:""}.fa-wikipedia-w:before{content:""}.fa-safari:before{content:""}.fa-chrome:before{content:""}.fa-firefox:before{content:""}.fa-opera:before{content:""}.fa-internet-explorer:before{content:""}.fa-tv:before,.fa-television:before{content:""}.fa-contao:before{content:""}.fa-500px:before{content:""}.fa-amazon:before{content:""}.fa-calendar-plus-o:before{content:""}.fa-calendar-minus-o:before{content:""}.fa-calendar-times-o:before{content:""}.fa-calendar-check-o:before{content:""}.fa-industry:before{content:""}.fa-map-pin:before{content:""}.fa-map-signs:before{content:""}.fa-map-o:before{content:""}.fa-map:before{content:""}.fa-commenting:before{content:""}.fa-commenting-o:before{content:""}.fa-houzz:before{content:""}.fa-vimeo:before{content:""}.fa-black-tie:before{content:""}.fa-fonticons:before{content:""}.fa-reddit-alien:before{content:""}.fa-edge:before{content:""}.fa-credit-card-alt:before{content:""}.fa-codiepie:before{content:""}.fa-modx:before{content:""}.fa-fort-awesome:before{content:""}.fa-usb:before{content:""}.fa-product-hunt:before{content:""}.fa-mixcloud:before{content:""}.fa-scribd:before{content:""}.fa-pause-circle:before{content:""}.fa-pause-circle-o:before{content:""}.fa-stop-circle:before{content:""}.fa-stop-circle-o:before{content:""}.fa-shopping-bag:before{content:""}.fa-shopping-basket:before{content:""}.fa-hashtag:before{content:""}.fa-bluetooth:before{content:""}.fa-bluetooth-b:before{content:""}.fa-percent:before{content:""}@font-face{font-family:'noto';src:url("../fonts/noto-sans-regular.ttf") format("truetype");font-weight:300;font-style:normal}@font-face{font-family:'noto';src:url("../fonts/noto-sans-italic.ttf") format("truetype");font-weight:300;font-style:italic}@font-face{font-family:'noto';src:url("../fonts/noto-sans-700.ttf") format("truetype");font-weight:600;font-style:normal}@font-face{font-family:'noto';src:url("../fonts/noto-sans-700italic.ttf") format("truetype");font-weight:600;font-style:italic}@font-face{font-family:'source code';src:url("../fonts/source-code-pro-300.ttf") format("truetype");font-weight:300;font-style:normal}@font-face{font-family:'source code';src:url("../fonts/source-code-pro-500.ttf") format("truetype");font-weight:600;font-style:normal}html{height:100%}body{font-size:13px;font-weight:300;color:#4d525a;height:100%;width:100%;background-color:#f7f7f7;line-height:1.3}strong{font-weight:600}body,input,a,button,textarea{font-family:"noto";font-weight:300}.text-muted,.plan-stats .btn-close{color:#999ea7}.text-warning{color:#FB4418}.hero-container{margin:30px;font-size:22px;text-align:center}.pull-right{float:right}.align-right{text-align:right}a{color:#00B5E2;text-decoration:none}.fa{margin-right:3px}.clickable{cursor:pointer}code,.code{font-family:"source code";font-weight:600}.pad-left{margin-left:10px}.pad-top{margin-top:10px}.pad-bottom{margin-bottom:10px}[tooltip]:before{width:150px;text-transform:none;text-align:left;content:attr(tooltip);position:absolute;opacity:0;transition:all 0.15s ease;padding:10px;color:#fff;border-radius:6px;margin-top:-10px;margin-left:20px;z-index:5;pointer-events:none}[tooltip]:hover:before{opacity:1;background:#008CAF}.btn{border-radius:3px;padding:6px 10px;font-size:13px;line-height:1.2;text-decoration:none;text-transform:uppercase;cursor:pointer;margin-left:6px}.btn-default{border:1px solid #00B5E2;color:#00B5E2;background-color:#fff}.btn-default:hover{background-color:#65DDFB;color:#fff}.btn-lg{padding:6px 20px;font-size:16px}.btn-sm{padding:6px 6px;font-size:12px}.btn-slim .fa,.btn-close .fa{margin:0}.btn-link{border:0;background-color:transparent;color:#00B5E2;padding:0}.btn-danger{border:1px solid #AF2F11;color:#AF2F11;text-transform:uppercase;background-color:#fff}.btn-danger:hover{background-color:#FB8165}.btn-primary{border:0;background:#00B5E2;box-shadow:1px 1px 1px #ababab;color:#ffffff}.btn-primary:hover{background:#008CAF}.btn-close{border-radius:50%;box-shadow:0;line-height:1.5;border:1px solid #dedede;background-color:#fff}.button-group button{margin:0;background-color:#f7f7f7;border-radius:0;float:left;border:1px solid #dedede;cursor:pointer}.button-group button:first-of-type{border-top-left-radius:6px;border-bottom-left-radius:6px}.button-group button:last-of-type{border-top-right-radius:6px;border-bottom-right-radius:6px}.button-group .selected{background-color:#dedede}.input-box:-moz-placeholder{color:#ababab;font-size:18px}.input-box::-moz-placeholder{color:#ababab;font-size:18px}.input-box:-ms-input-placeholder{color:#ababab;font-size:18px}.input-box::-webkit-input-placeholder{color:#ababab;font-size:18px}.input-box:focus{box-shadow:0 0 5px #51cbee}.input-box-main{font-size:18px;width:700px;border:0;border-bottom:2px solid #00B5E2;padding:10px;margin-top:10px;margin-bottom:10px}.input-box-lg{width:98%;height:210px;margin-bottom:6px;margin-bottom:10px;border-radius:3px;border:1px solid #dedede;padding:10px}.error-message{background-color:#FB4418;padding:6px;color:#fff}nav{font-size:17px;background-color:#fff;padding:15px}nav .nav-container{width:1000px;margin:auto}nav .about{float:right;line-height:2;margin-left:18px}.plan{padding-bottom:30px;margin-left:100px}.plan ul{display:flex;padding-top:12px;position:relative;margin:auto;transition:all 0.5s;margin-top:-5px}.plan ul ul::before{content:'';position:absolute;top:0;left:50%;border-left:2px solid #c4c4c4;height:12px;width:0}.plan ul li{float:left;text-align:center;list-style-type:none;position:relative;padding:12px 3px 0 3px;transition:all 0.5s}.plan ul li:before,.plan ul li:after{content:'';position:absolute;top:0;right:50%;border-top:2px solid #c4c4c4;width:50%;height:12px}.plan ul li:after{right:auto;left:50%;border-left:2px solid #c4c4c4}.plan ul li:only-child{padding-top:0}.plan ul li:only-child:after,.plan ul li:only-child:before{display:none}.plan ul li:first-child::before,.plan ul li:last-child::after{border:0 none}.plan ul li:last-child::before{border-right:2px solid #c4c4c4;border-radius:0 6px 0 0}.plan ul li:first-child::after{border-radius:6px 0 0 0}.plan ul li .plan-node:hover+ul::before{border-color:#00B5E2}.plan ul li .plan-node:hover+ul li::after,.plan ul li .plan-node:hover+ul li::before,.plan ul li .plan-node:hover+ul ul::before{border-color:#008CAF}.plan-stats{display:flex;font-size:13px;margin:10px auto 10px auto;padding-bottom:10px;border-bottom:1px solid #dedede;border-radius:12px;width:650px;position:relative}.plan-stats div{padding-right:10px;flex-grow:1}.plan-stats .stat-value{display:block;text-align:center;font-size:17px}.plan-stats .stat-label{display:block;text-align:center;font-size:12px}.plan-stats:after{content:'';position:absolute;top:100%;left:50%;margin-left:-9px;width:0;height:0;border-top:solid 9px #dedede;border-left:solid 9px transparent;border-right:solid 9px transparent}.plan-stats .btn-close{padding:6px;background-color:transparent;font-size:17px;text-align:center;margin-left:6px;cursor:pointer;border:0}.plan-node{text-decoration:none;color:#4d525a;display:inline-block;transition:all 0.1s;position:relative;padding:6px 10px;background-color:#fff;font-size:12px;border:1px solid #dedede;margin-bottom:4px;border-radius:3px;overflow-wrap:break-word;word-wrap:break-word;word-break:break-all;width:240px;box-shadow:1px 1px 3px 0px rgba(0,0,0,0.1)}.plan-node header{margin-bottom:6px;overflow:hidden;cursor:pointer}.plan-node header:hover{background-color:#f7f7f7}.plan-node header h4{font-size:13px;float:left;font-weight:600}.plan-node header .node-duration{float:right;margin-left:10px;font-size:13px}.plan-node .prop-list{float:left;text-align:left;overflow-wrap:break-word;word-wrap:break-word;word-break:break-all;margin-top:10px;margin-bottom:6px}.plan-node .relation-name{text-align:left}.plan-node .planner-estimate{border-top:1px solid #dedede;text-align:left;padding-top:3px;margin-top:6px;width:100%}.plan-node .tags{margin-top:6px;text-align:left}.plan-node .tags span{display:inline-block;background-color:#FB4418;color:#fff;font-size:10px;font-weight:600;margin-right:3px;margin-bottom:3px;padding:3px;border-radius:3px;line-height:1.1}.plan-node:hover{border-color:#00B5E2}.plan-node .node-description{text-align:left;font-style:italic;padding-top:10px;word-break:normal}.plan-node .node-description .node-type{font-weight:600;background-color:#00B5E2;color:#fff;padding:0 6px}.plan-node .btn-default{border:0}.node-bar-container{height:5px;margin-top:10px;margin-bottom:3px;border-radius:6px;background-color:#dedede;position:relative}.node-bar-container .node-bar{border-radius:6px;height:100%;text-align:left;position:absolute;left:0;top:0}.node-bar-label{text-align:left;display:block}.expanded{width:400px !important;overflow:visible !important;padding:6px 10px !important}.expanded .tags span{margin-right:3px !important}.compact{width:140px}.dot{width:30px;overflow:hidden;padding:3px}.dot .tags span{margin-right:1px}.dot .node-bar-container{margin-top:3px}.menu{width:190px;height:260px;position:absolute;font-size:12px;top:115px;left:0;background-color:#777;box-shadow:1px 1px 2px 1px rgba(0,0,0,0.2);color:#fff;border-top-right-radius:3px;border-bottom-right-radius:3px;z-index:1}.menu header h3{padding-top:10px;margin-bottom:6px;font-size:16px;font-weight:600;line-height:2;text-align:right;padding-right:20px}.menu ul{margin-left:10px}.menu ul li{line-height:2.5}.menu-toggle{font-size:22px;float:left;padding-left:6px;line-height:2;cursor:pointer}.menu-hidden{width:45px;height:45px;border-top-right-radius:50%;border-bottom-right-radius:50%}.menu-hidden ul,.menu-hidden h3{visibility:hidden}.menu .button-group{display:flex;margin-bottom:6px}.page,.page-stretch{padding-top:10px;margin:auto;width:1000px;min-height:600px}.page em,.page-stretch em{font-style:italic}.page-content h2{font-size:26px;line-height:2}.page-content h3{font-size:22px;margin-top:18px;line-height:2}.page-content p,.page-content ul{font-size:16px;line-height:1.5;margin-bottom:18px}.page-content ul{list-style-type:disc;position:relative;left:18px}.page-stretch{margin:auto;width:95%}.page-stretch h2{text-align:left;font-size:17px;max-width:1000px;margin:auto;margin-bottom:20px}.page-stretch h2 .sub-title{font-size:13px;font-style:italic}.table{width:100%}.table td{border-bottom:1px solid #dedede;padding:6px}.table tr:hover{background-color:#f7f7f7}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000;opacity:0.1}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;transition:all 1s}.modal .modal-dialog{position:relative;transform:translate(0);margin:100px auto;width:500px;opacity:1}.modal .modal-dialog .modal-content{padding:30px;position:relative;background-color:#fff;background-clip:padding-box;border:1px solid #999;border:1px solid rgba(0,0,0,0.2);border-radius:6px;outline:0;box-shadow:0 2px 2px rgba(0,0,0,0.5);display:block}.modal .modal-dialog .modal-content .modal-body{padding:3px;margin-bottom:18px;text-align:left;line-height:1.5}.modal .modal-dialog .modal-content .modal-footer{text-align:right}.modal .modal-dialog .modal-content .modal-footer button{margin-left:3px}footer{border-top:2px solid #dedede;margin:20px;padding:20px;color:#ababab;text-align:center;width:600px;margin:auto}footer .fa{font-size:17px;margin-left:6px}.plan-query-container{border:1px solid #dedede;padding:18px;background-color:#fff;position:absolute;box-shadow:0px 0px 10px 2px rgba(0,0,0,0.3);border-radius:3px;margin-bottom:18px;z-index:6;left:0}.plan-query-container code{font-weight:300}.plan-query-container .plan-query-text{background-color:#fff;font-family:"source code";text-align:left}.plan-query-container .plan-query-text .code-key-item{background-color:#F8E400;font-weight:600;padding:1px}.plan-query-container h3{font-size:17px;width:93%;text-align:left;border-bottom:1px solid #dedede;padding-bottom:6px;margin-bottom:10px}.hljs,.hljs-subst{color:#4d525a}.hljs-keyword,.hljs-attribute,.hljs-selector-tag,.hljs-meta-keyword,.hljs-doctag,.hljs-name{color:#008CAF;font-weight:bold}.hljs-built_in,.hljs-literal,.hljs-bullet,.hljs-code,.hljs-addition{color:#008CAF;font-weight:bold}.hljs-regexp,.hljs-symbol,.hljs-variable,.hljs-template-variable,.hljs-link,.hljs-selector-attr,.hljs-selector-pseudo{color:#008CAF;font-weight:bold}.hljs-type,.hljs-string,.hljs-number,.hljs-selector-id,.hljs-selector-class,.hljs-quote,.hljs-template-tag,.hljs-deletion{color:#279404;font-weight:600}.hljs-title,.hljs-section{color:#008CAF;font-weight:bold}.hljs-comment{color:#999ea7;font-style:italic}.hljs-meta{color:#999ea7}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:600}
``` | /content/code_sandbox/app/assets/styles.css | css | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 10,718 |
```scss
// Variables
// --------------------------
$fa-font-path: "../fonts" !default;
$fa-font-size-base: 14px !default;
$fa-line-height-base: 1 !default;
//$fa-font-path: "//netdna.bootstrapcdn.com/font-awesome/4.5.0/fonts" !default; // for referencing Bootstrap CDN font files directly
$fa-css-prefix: fa !default;
$fa-version: "4.5.0" !default;
$fa-border-color: #eee !default;
$fa-inverse: #fff !default;
$fa-li-width: (30em / 14) !default;
$fa-var-500px: "\f26e";
$fa-var-adjust: "\f042";
$fa-var-adn: "\f170";
$fa-var-align-center: "\f037";
$fa-var-align-justify: "\f039";
$fa-var-align-left: "\f036";
$fa-var-align-right: "\f038";
$fa-var-amazon: "\f270";
$fa-var-ambulance: "\f0f9";
$fa-var-anchor: "\f13d";
$fa-var-android: "\f17b";
$fa-var-angellist: "\f209";
$fa-var-angle-double-down: "\f103";
$fa-var-angle-double-left: "\f100";
$fa-var-angle-double-right: "\f101";
$fa-var-angle-double-up: "\f102";
$fa-var-angle-down: "\f107";
$fa-var-angle-left: "\f104";
$fa-var-angle-right: "\f105";
$fa-var-angle-up: "\f106";
$fa-var-apple: "\f179";
$fa-var-archive: "\f187";
$fa-var-area-chart: "\f1fe";
$fa-var-arrow-circle-down: "\f0ab";
$fa-var-arrow-circle-left: "\f0a8";
$fa-var-arrow-circle-o-down: "\f01a";
$fa-var-arrow-circle-o-left: "\f190";
$fa-var-arrow-circle-o-right: "\f18e";
$fa-var-arrow-circle-o-up: "\f01b";
$fa-var-arrow-circle-right: "\f0a9";
$fa-var-arrow-circle-up: "\f0aa";
$fa-var-arrow-down: "\f063";
$fa-var-arrow-left: "\f060";
$fa-var-arrow-right: "\f061";
$fa-var-arrow-up: "\f062";
$fa-var-arrows: "\f047";
$fa-var-arrows-alt: "\f0b2";
$fa-var-arrows-h: "\f07e";
$fa-var-arrows-v: "\f07d";
$fa-var-asterisk: "\f069";
$fa-var-at: "\f1fa";
$fa-var-automobile: "\f1b9";
$fa-var-backward: "\f04a";
$fa-var-balance-scale: "\f24e";
$fa-var-ban: "\f05e";
$fa-var-bank: "\f19c";
$fa-var-bar-chart: "\f080";
$fa-var-bar-chart-o: "\f080";
$fa-var-barcode: "\f02a";
$fa-var-bars: "\f0c9";
$fa-var-battery-0: "\f244";
$fa-var-battery-1: "\f243";
$fa-var-battery-2: "\f242";
$fa-var-battery-3: "\f241";
$fa-var-battery-4: "\f240";
$fa-var-battery-empty: "\f244";
$fa-var-battery-full: "\f240";
$fa-var-battery-half: "\f242";
$fa-var-battery-quarter: "\f243";
$fa-var-battery-three-quarters: "\f241";
$fa-var-bed: "\f236";
$fa-var-beer: "\f0fc";
$fa-var-behance: "\f1b4";
$fa-var-behance-square: "\f1b5";
$fa-var-bell: "\f0f3";
$fa-var-bell-o: "\f0a2";
$fa-var-bell-slash: "\f1f6";
$fa-var-bell-slash-o: "\f1f7";
$fa-var-bicycle: "\f206";
$fa-var-binoculars: "\f1e5";
$fa-var-birthday-cake: "\f1fd";
$fa-var-bitbucket: "\f171";
$fa-var-bitbucket-square: "\f172";
$fa-var-bitcoin: "\f15a";
$fa-var-black-tie: "\f27e";
$fa-var-bluetooth: "\f293";
$fa-var-bluetooth-b: "\f294";
$fa-var-bold: "\f032";
$fa-var-bolt: "\f0e7";
$fa-var-bomb: "\f1e2";
$fa-var-book: "\f02d";
$fa-var-bookmark: "\f02e";
$fa-var-bookmark-o: "\f097";
$fa-var-briefcase: "\f0b1";
$fa-var-btc: "\f15a";
$fa-var-bug: "\f188";
$fa-var-building: "\f1ad";
$fa-var-building-o: "\f0f7";
$fa-var-bullhorn: "\f0a1";
$fa-var-bullseye: "\f140";
$fa-var-bus: "\f207";
$fa-var-buysellads: "\f20d";
$fa-var-cab: "\f1ba";
$fa-var-calculator: "\f1ec";
$fa-var-calendar: "\f073";
$fa-var-calendar-check-o: "\f274";
$fa-var-calendar-minus-o: "\f272";
$fa-var-calendar-o: "\f133";
$fa-var-calendar-plus-o: "\f271";
$fa-var-calendar-times-o: "\f273";
$fa-var-camera: "\f030";
$fa-var-camera-retro: "\f083";
$fa-var-car: "\f1b9";
$fa-var-caret-down: "\f0d7";
$fa-var-caret-left: "\f0d9";
$fa-var-caret-right: "\f0da";
$fa-var-caret-square-o-down: "\f150";
$fa-var-caret-square-o-left: "\f191";
$fa-var-caret-square-o-right: "\f152";
$fa-var-caret-square-o-up: "\f151";
$fa-var-caret-up: "\f0d8";
$fa-var-cart-arrow-down: "\f218";
$fa-var-cart-plus: "\f217";
$fa-var-cc: "\f20a";
$fa-var-cc-amex: "\f1f3";
$fa-var-cc-diners-club: "\f24c";
$fa-var-cc-discover: "\f1f2";
$fa-var-cc-jcb: "\f24b";
$fa-var-cc-mastercard: "\f1f1";
$fa-var-cc-paypal: "\f1f4";
$fa-var-cc-stripe: "\f1f5";
$fa-var-cc-visa: "\f1f0";
$fa-var-certificate: "\f0a3";
$fa-var-chain: "\f0c1";
$fa-var-chain-broken: "\f127";
$fa-var-check: "\f00c";
$fa-var-check-circle: "\f058";
$fa-var-check-circle-o: "\f05d";
$fa-var-check-square: "\f14a";
$fa-var-check-square-o: "\f046";
$fa-var-chevron-circle-down: "\f13a";
$fa-var-chevron-circle-left: "\f137";
$fa-var-chevron-circle-right: "\f138";
$fa-var-chevron-circle-up: "\f139";
$fa-var-chevron-down: "\f078";
$fa-var-chevron-left: "\f053";
$fa-var-chevron-right: "\f054";
$fa-var-chevron-up: "\f077";
$fa-var-child: "\f1ae";
$fa-var-chrome: "\f268";
$fa-var-circle: "\f111";
$fa-var-circle-o: "\f10c";
$fa-var-circle-o-notch: "\f1ce";
$fa-var-circle-thin: "\f1db";
$fa-var-clipboard: "\f0ea";
$fa-var-clock-o: "\f017";
$fa-var-clone: "\f24d";
$fa-var-close: "\f00d";
$fa-var-cloud: "\f0c2";
$fa-var-cloud-download: "\f0ed";
$fa-var-cloud-upload: "\f0ee";
$fa-var-cny: "\f157";
$fa-var-code: "\f121";
$fa-var-code-fork: "\f126";
$fa-var-codepen: "\f1cb";
$fa-var-codiepie: "\f284";
$fa-var-coffee: "\f0f4";
$fa-var-cog: "\f013";
$fa-var-cogs: "\f085";
$fa-var-columns: "\f0db";
$fa-var-comment: "\f075";
$fa-var-comment-o: "\f0e5";
$fa-var-commenting: "\f27a";
$fa-var-commenting-o: "\f27b";
$fa-var-comments: "\f086";
$fa-var-comments-o: "\f0e6";
$fa-var-compass: "\f14e";
$fa-var-compress: "\f066";
$fa-var-connectdevelop: "\f20e";
$fa-var-contao: "\f26d";
$fa-var-copy: "\f0c5";
$fa-var-copyright: "\f1f9";
$fa-var-creative-commons: "\f25e";
$fa-var-credit-card: "\f09d";
$fa-var-credit-card-alt: "\f283";
$fa-var-crop: "\f125";
$fa-var-crosshairs: "\f05b";
$fa-var-css3: "\f13c";
$fa-var-cube: "\f1b2";
$fa-var-cubes: "\f1b3";
$fa-var-cut: "\f0c4";
$fa-var-cutlery: "\f0f5";
$fa-var-dashboard: "\f0e4";
$fa-var-dashcube: "\f210";
$fa-var-database: "\f1c0";
$fa-var-dedent: "\f03b";
$fa-var-delicious: "\f1a5";
$fa-var-desktop: "\f108";
$fa-var-deviantart: "\f1bd";
$fa-var-diamond: "\f219";
$fa-var-digg: "\f1a6";
$fa-var-dollar: "\f155";
$fa-var-dot-circle-o: "\f192";
$fa-var-download: "\f019";
$fa-var-dribbble: "\f17d";
$fa-var-dropbox: "\f16b";
$fa-var-drupal: "\f1a9";
$fa-var-edge: "\f282";
$fa-var-edit: "\f044";
$fa-var-eject: "\f052";
$fa-var-ellipsis-h: "\f141";
$fa-var-ellipsis-v: "\f142";
$fa-var-empire: "\f1d1";
$fa-var-envelope: "\f0e0";
$fa-var-envelope-o: "\f003";
$fa-var-envelope-square: "\f199";
$fa-var-eraser: "\f12d";
$fa-var-eur: "\f153";
$fa-var-euro: "\f153";
$fa-var-exchange: "\f0ec";
$fa-var-exclamation: "\f12a";
$fa-var-exclamation-circle: "\f06a";
$fa-var-exclamation-triangle: "\f071";
$fa-var-expand: "\f065";
$fa-var-expeditedssl: "\f23e";
$fa-var-external-link: "\f08e";
$fa-var-external-link-square: "\f14c";
$fa-var-eye: "\f06e";
$fa-var-eye-slash: "\f070";
$fa-var-eyedropper: "\f1fb";
$fa-var-facebook: "\f09a";
$fa-var-facebook-f: "\f09a";
$fa-var-facebook-official: "\f230";
$fa-var-facebook-square: "\f082";
$fa-var-fast-backward: "\f049";
$fa-var-fast-forward: "\f050";
$fa-var-fax: "\f1ac";
$fa-var-feed: "\f09e";
$fa-var-female: "\f182";
$fa-var-fighter-jet: "\f0fb";
$fa-var-file: "\f15b";
$fa-var-file-archive-o: "\f1c6";
$fa-var-file-audio-o: "\f1c7";
$fa-var-file-code-o: "\f1c9";
$fa-var-file-excel-o: "\f1c3";
$fa-var-file-image-o: "\f1c5";
$fa-var-file-movie-o: "\f1c8";
$fa-var-file-o: "\f016";
$fa-var-file-pdf-o: "\f1c1";
$fa-var-file-photo-o: "\f1c5";
$fa-var-file-picture-o: "\f1c5";
$fa-var-file-powerpoint-o: "\f1c4";
$fa-var-file-sound-o: "\f1c7";
$fa-var-file-text: "\f15c";
$fa-var-file-text-o: "\f0f6";
$fa-var-file-video-o: "\f1c8";
$fa-var-file-word-o: "\f1c2";
$fa-var-file-zip-o: "\f1c6";
$fa-var-files-o: "\f0c5";
$fa-var-film: "\f008";
$fa-var-filter: "\f0b0";
$fa-var-fire: "\f06d";
$fa-var-fire-extinguisher: "\f134";
$fa-var-firefox: "\f269";
$fa-var-flag: "\f024";
$fa-var-flag-checkered: "\f11e";
$fa-var-flag-o: "\f11d";
$fa-var-flash: "\f0e7";
$fa-var-flask: "\f0c3";
$fa-var-flickr: "\f16e";
$fa-var-floppy-o: "\f0c7";
$fa-var-folder: "\f07b";
$fa-var-folder-o: "\f114";
$fa-var-folder-open: "\f07c";
$fa-var-folder-open-o: "\f115";
$fa-var-font: "\f031";
$fa-var-fonticons: "\f280";
$fa-var-fort-awesome: "\f286";
$fa-var-forumbee: "\f211";
$fa-var-forward: "\f04e";
$fa-var-foursquare: "\f180";
$fa-var-frown-o: "\f119";
$fa-var-futbol-o: "\f1e3";
$fa-var-gamepad: "\f11b";
$fa-var-gavel: "\f0e3";
$fa-var-gbp: "\f154";
$fa-var-ge: "\f1d1";
$fa-var-gear: "\f013";
$fa-var-gears: "\f085";
$fa-var-genderless: "\f22d";
$fa-var-get-pocket: "\f265";
$fa-var-gg: "\f260";
$fa-var-gg-circle: "\f261";
$fa-var-gift: "\f06b";
$fa-var-git: "\f1d3";
$fa-var-git-square: "\f1d2";
$fa-var-github: "\f09b";
$fa-var-github-alt: "\f113";
$fa-var-github-square: "\f092";
$fa-var-gittip: "\f184";
$fa-var-glass: "\f000";
$fa-var-globe: "\f0ac";
$fa-var-google: "\f1a0";
$fa-var-google-plus: "\f0d5";
$fa-var-google-plus-square: "\f0d4";
$fa-var-google-wallet: "\f1ee";
$fa-var-graduation-cap: "\f19d";
$fa-var-gratipay: "\f184";
$fa-var-group: "\f0c0";
$fa-var-h-square: "\f0fd";
$fa-var-hacker-news: "\f1d4";
$fa-var-hand-grab-o: "\f255";
$fa-var-hand-lizard-o: "\f258";
$fa-var-hand-o-down: "\f0a7";
$fa-var-hand-o-left: "\f0a5";
$fa-var-hand-o-right: "\f0a4";
$fa-var-hand-o-up: "\f0a6";
$fa-var-hand-paper-o: "\f256";
$fa-var-hand-peace-o: "\f25b";
$fa-var-hand-pointer-o: "\f25a";
$fa-var-hand-rock-o: "\f255";
$fa-var-hand-scissors-o: "\f257";
$fa-var-hand-spock-o: "\f259";
$fa-var-hand-stop-o: "\f256";
$fa-var-hashtag: "\f292";
$fa-var-hdd-o: "\f0a0";
$fa-var-header: "\f1dc";
$fa-var-headphones: "\f025";
$fa-var-heart: "\f004";
$fa-var-heart-o: "\f08a";
$fa-var-heartbeat: "\f21e";
$fa-var-history: "\f1da";
$fa-var-home: "\f015";
$fa-var-hospital-o: "\f0f8";
$fa-var-hotel: "\f236";
$fa-var-hourglass: "\f254";
$fa-var-hourglass-1: "\f251";
$fa-var-hourglass-2: "\f252";
$fa-var-hourglass-3: "\f253";
$fa-var-hourglass-end: "\f253";
$fa-var-hourglass-half: "\f252";
$fa-var-hourglass-o: "\f250";
$fa-var-hourglass-start: "\f251";
$fa-var-houzz: "\f27c";
$fa-var-html5: "\f13b";
$fa-var-i-cursor: "\f246";
$fa-var-ils: "\f20b";
$fa-var-image: "\f03e";
$fa-var-inbox: "\f01c";
$fa-var-indent: "\f03c";
$fa-var-industry: "\f275";
$fa-var-info: "\f129";
$fa-var-info-circle: "\f05a";
$fa-var-inr: "\f156";
$fa-var-instagram: "\f16d";
$fa-var-institution: "\f19c";
$fa-var-internet-explorer: "\f26b";
$fa-var-intersex: "\f224";
$fa-var-ioxhost: "\f208";
$fa-var-italic: "\f033";
$fa-var-joomla: "\f1aa";
$fa-var-jpy: "\f157";
$fa-var-jsfiddle: "\f1cc";
$fa-var-key: "\f084";
$fa-var-keyboard-o: "\f11c";
$fa-var-krw: "\f159";
$fa-var-language: "\f1ab";
$fa-var-laptop: "\f109";
$fa-var-lastfm: "\f202";
$fa-var-lastfm-square: "\f203";
$fa-var-leaf: "\f06c";
$fa-var-leanpub: "\f212";
$fa-var-legal: "\f0e3";
$fa-var-lemon-o: "\f094";
$fa-var-level-down: "\f149";
$fa-var-level-up: "\f148";
$fa-var-life-bouy: "\f1cd";
$fa-var-life-buoy: "\f1cd";
$fa-var-life-ring: "\f1cd";
$fa-var-life-saver: "\f1cd";
$fa-var-lightbulb-o: "\f0eb";
$fa-var-line-chart: "\f201";
$fa-var-link: "\f0c1";
$fa-var-linkedin: "\f0e1";
$fa-var-linkedin-square: "\f08c";
$fa-var-linux: "\f17c";
$fa-var-list: "\f03a";
$fa-var-list-alt: "\f022";
$fa-var-list-ol: "\f0cb";
$fa-var-list-ul: "\f0ca";
$fa-var-location-arrow: "\f124";
$fa-var-lock: "\f023";
$fa-var-long-arrow-down: "\f175";
$fa-var-long-arrow-left: "\f177";
$fa-var-long-arrow-right: "\f178";
$fa-var-long-arrow-up: "\f176";
$fa-var-magic: "\f0d0";
$fa-var-magnet: "\f076";
$fa-var-mail-forward: "\f064";
$fa-var-mail-reply: "\f112";
$fa-var-mail-reply-all: "\f122";
$fa-var-male: "\f183";
$fa-var-map: "\f279";
$fa-var-map-marker: "\f041";
$fa-var-map-o: "\f278";
$fa-var-map-pin: "\f276";
$fa-var-map-signs: "\f277";
$fa-var-mars: "\f222";
$fa-var-mars-double: "\f227";
$fa-var-mars-stroke: "\f229";
$fa-var-mars-stroke-h: "\f22b";
$fa-var-mars-stroke-v: "\f22a";
$fa-var-maxcdn: "\f136";
$fa-var-meanpath: "\f20c";
$fa-var-medium: "\f23a";
$fa-var-medkit: "\f0fa";
$fa-var-meh-o: "\f11a";
$fa-var-mercury: "\f223";
$fa-var-microphone: "\f130";
$fa-var-microphone-slash: "\f131";
$fa-var-minus: "\f068";
$fa-var-minus-circle: "\f056";
$fa-var-minus-square: "\f146";
$fa-var-minus-square-o: "\f147";
$fa-var-mixcloud: "\f289";
$fa-var-mobile: "\f10b";
$fa-var-mobile-phone: "\f10b";
$fa-var-modx: "\f285";
$fa-var-money: "\f0d6";
$fa-var-moon-o: "\f186";
$fa-var-mortar-board: "\f19d";
$fa-var-motorcycle: "\f21c";
$fa-var-mouse-pointer: "\f245";
$fa-var-music: "\f001";
$fa-var-navicon: "\f0c9";
$fa-var-neuter: "\f22c";
$fa-var-newspaper-o: "\f1ea";
$fa-var-object-group: "\f247";
$fa-var-object-ungroup: "\f248";
$fa-var-odnoklassniki: "\f263";
$fa-var-odnoklassniki-square: "\f264";
$fa-var-opencart: "\f23d";
$fa-var-openid: "\f19b";
$fa-var-opera: "\f26a";
$fa-var-optin-monster: "\f23c";
$fa-var-outdent: "\f03b";
$fa-var-pagelines: "\f18c";
$fa-var-paint-brush: "\f1fc";
$fa-var-paper-plane: "\f1d8";
$fa-var-paper-plane-o: "\f1d9";
$fa-var-paperclip: "\f0c6";
$fa-var-paragraph: "\f1dd";
$fa-var-paste: "\f0ea";
$fa-var-pause: "\f04c";
$fa-var-pause-circle: "\f28b";
$fa-var-pause-circle-o: "\f28c";
$fa-var-paw: "\f1b0";
$fa-var-paypal: "\f1ed";
$fa-var-pencil: "\f040";
$fa-var-pencil-square: "\f14b";
$fa-var-pencil-square-o: "\f044";
$fa-var-percent: "\f295";
$fa-var-phone: "\f095";
$fa-var-phone-square: "\f098";
$fa-var-photo: "\f03e";
$fa-var-picture-o: "\f03e";
$fa-var-pie-chart: "\f200";
$fa-var-pied-piper: "\f1a7";
$fa-var-pied-piper-alt: "\f1a8";
$fa-var-pinterest: "\f0d2";
$fa-var-pinterest-p: "\f231";
$fa-var-pinterest-square: "\f0d3";
$fa-var-plane: "\f072";
$fa-var-play: "\f04b";
$fa-var-play-circle: "\f144";
$fa-var-play-circle-o: "\f01d";
$fa-var-plug: "\f1e6";
$fa-var-plus: "\f067";
$fa-var-plus-circle: "\f055";
$fa-var-plus-square: "\f0fe";
$fa-var-plus-square-o: "\f196";
$fa-var-power-off: "\f011";
$fa-var-print: "\f02f";
$fa-var-product-hunt: "\f288";
$fa-var-puzzle-piece: "\f12e";
$fa-var-qq: "\f1d6";
$fa-var-qrcode: "\f029";
$fa-var-question: "\f128";
$fa-var-question-circle: "\f059";
$fa-var-quote-left: "\f10d";
$fa-var-quote-right: "\f10e";
$fa-var-ra: "\f1d0";
$fa-var-random: "\f074";
$fa-var-rebel: "\f1d0";
$fa-var-recycle: "\f1b8";
$fa-var-reddit: "\f1a1";
$fa-var-reddit-alien: "\f281";
$fa-var-reddit-square: "\f1a2";
$fa-var-refresh: "\f021";
$fa-var-registered: "\f25d";
$fa-var-remove: "\f00d";
$fa-var-renren: "\f18b";
$fa-var-reorder: "\f0c9";
$fa-var-repeat: "\f01e";
$fa-var-reply: "\f112";
$fa-var-reply-all: "\f122";
$fa-var-retweet: "\f079";
$fa-var-rmb: "\f157";
$fa-var-road: "\f018";
$fa-var-rocket: "\f135";
$fa-var-rotate-left: "\f0e2";
$fa-var-rotate-right: "\f01e";
$fa-var-rouble: "\f158";
$fa-var-rss: "\f09e";
$fa-var-rss-square: "\f143";
$fa-var-rub: "\f158";
$fa-var-ruble: "\f158";
$fa-var-rupee: "\f156";
$fa-var-safari: "\f267";
$fa-var-save: "\f0c7";
$fa-var-scissors: "\f0c4";
$fa-var-scribd: "\f28a";
$fa-var-search: "\f002";
$fa-var-search-minus: "\f010";
$fa-var-search-plus: "\f00e";
$fa-var-sellsy: "\f213";
$fa-var-send: "\f1d8";
$fa-var-send-o: "\f1d9";
$fa-var-server: "\f233";
$fa-var-share: "\f064";
$fa-var-share-alt: "\f1e0";
$fa-var-share-alt-square: "\f1e1";
$fa-var-share-square: "\f14d";
$fa-var-share-square-o: "\f045";
$fa-var-shekel: "\f20b";
$fa-var-sheqel: "\f20b";
$fa-var-shield: "\f132";
$fa-var-ship: "\f21a";
$fa-var-shirtsinbulk: "\f214";
$fa-var-shopping-bag: "\f290";
$fa-var-shopping-basket: "\f291";
$fa-var-shopping-cart: "\f07a";
$fa-var-sign-in: "\f090";
$fa-var-sign-out: "\f08b";
$fa-var-signal: "\f012";
$fa-var-simplybuilt: "\f215";
$fa-var-sitemap: "\f0e8";
$fa-var-skyatlas: "\f216";
$fa-var-skype: "\f17e";
$fa-var-slack: "\f198";
$fa-var-sliders: "\f1de";
$fa-var-slideshare: "\f1e7";
$fa-var-smile-o: "\f118";
$fa-var-soccer-ball-o: "\f1e3";
$fa-var-sort: "\f0dc";
$fa-var-sort-alpha-asc: "\f15d";
$fa-var-sort-alpha-desc: "\f15e";
$fa-var-sort-amount-asc: "\f160";
$fa-var-sort-amount-desc: "\f161";
$fa-var-sort-asc: "\f0de";
$fa-var-sort-desc: "\f0dd";
$fa-var-sort-down: "\f0dd";
$fa-var-sort-numeric-asc: "\f162";
$fa-var-sort-numeric-desc: "\f163";
$fa-var-sort-up: "\f0de";
$fa-var-soundcloud: "\f1be";
$fa-var-space-shuttle: "\f197";
$fa-var-spinner: "\f110";
$fa-var-spoon: "\f1b1";
$fa-var-spotify: "\f1bc";
$fa-var-square: "\f0c8";
$fa-var-square-o: "\f096";
$fa-var-stack-exchange: "\f18d";
$fa-var-stack-overflow: "\f16c";
$fa-var-star: "\f005";
$fa-var-star-half: "\f089";
$fa-var-star-half-empty: "\f123";
$fa-var-star-half-full: "\f123";
$fa-var-star-half-o: "\f123";
$fa-var-star-o: "\f006";
$fa-var-steam: "\f1b6";
$fa-var-steam-square: "\f1b7";
$fa-var-step-backward: "\f048";
$fa-var-step-forward: "\f051";
$fa-var-stethoscope: "\f0f1";
$fa-var-sticky-note: "\f249";
$fa-var-sticky-note-o: "\f24a";
$fa-var-stop: "\f04d";
$fa-var-stop-circle: "\f28d";
$fa-var-stop-circle-o: "\f28e";
$fa-var-street-view: "\f21d";
$fa-var-strikethrough: "\f0cc";
$fa-var-stumbleupon: "\f1a4";
$fa-var-stumbleupon-circle: "\f1a3";
$fa-var-subscript: "\f12c";
$fa-var-subway: "\f239";
$fa-var-suitcase: "\f0f2";
$fa-var-sun-o: "\f185";
$fa-var-superscript: "\f12b";
$fa-var-support: "\f1cd";
$fa-var-table: "\f0ce";
$fa-var-tablet: "\f10a";
$fa-var-tachometer: "\f0e4";
$fa-var-tag: "\f02b";
$fa-var-tags: "\f02c";
$fa-var-tasks: "\f0ae";
$fa-var-taxi: "\f1ba";
$fa-var-television: "\f26c";
$fa-var-tencent-weibo: "\f1d5";
$fa-var-terminal: "\f120";
$fa-var-text-height: "\f034";
$fa-var-text-width: "\f035";
$fa-var-th: "\f00a";
$fa-var-th-large: "\f009";
$fa-var-th-list: "\f00b";
$fa-var-thumb-tack: "\f08d";
$fa-var-thumbs-down: "\f165";
$fa-var-thumbs-o-down: "\f088";
$fa-var-thumbs-o-up: "\f087";
$fa-var-thumbs-up: "\f164";
$fa-var-ticket: "\f145";
$fa-var-times: "\f00d";
$fa-var-times-circle: "\f057";
$fa-var-times-circle-o: "\f05c";
$fa-var-tint: "\f043";
$fa-var-toggle-down: "\f150";
$fa-var-toggle-left: "\f191";
$fa-var-toggle-off: "\f204";
$fa-var-toggle-on: "\f205";
$fa-var-toggle-right: "\f152";
$fa-var-toggle-up: "\f151";
$fa-var-trademark: "\f25c";
$fa-var-train: "\f238";
$fa-var-transgender: "\f224";
$fa-var-transgender-alt: "\f225";
$fa-var-trash: "\f1f8";
$fa-var-trash-o: "\f014";
$fa-var-tree: "\f1bb";
$fa-var-trello: "\f181";
$fa-var-tripadvisor: "\f262";
$fa-var-trophy: "\f091";
$fa-var-truck: "\f0d1";
$fa-var-try: "\f195";
$fa-var-tty: "\f1e4";
$fa-var-tumblr: "\f173";
$fa-var-tumblr-square: "\f174";
$fa-var-turkish-lira: "\f195";
$fa-var-tv: "\f26c";
$fa-var-twitch: "\f1e8";
$fa-var-twitter: "\f099";
$fa-var-twitter-square: "\f081";
$fa-var-umbrella: "\f0e9";
$fa-var-underline: "\f0cd";
$fa-var-undo: "\f0e2";
$fa-var-university: "\f19c";
$fa-var-unlink: "\f127";
$fa-var-unlock: "\f09c";
$fa-var-unlock-alt: "\f13e";
$fa-var-unsorted: "\f0dc";
$fa-var-upload: "\f093";
$fa-var-usb: "\f287";
$fa-var-usd: "\f155";
$fa-var-user: "\f007";
$fa-var-user-md: "\f0f0";
$fa-var-user-plus: "\f234";
$fa-var-user-secret: "\f21b";
$fa-var-user-times: "\f235";
$fa-var-users: "\f0c0";
$fa-var-venus: "\f221";
$fa-var-venus-double: "\f226";
$fa-var-venus-mars: "\f228";
$fa-var-viacoin: "\f237";
$fa-var-video-camera: "\f03d";
$fa-var-vimeo: "\f27d";
$fa-var-vimeo-square: "\f194";
$fa-var-vine: "\f1ca";
$fa-var-vk: "\f189";
$fa-var-volume-down: "\f027";
$fa-var-volume-off: "\f026";
$fa-var-volume-up: "\f028";
$fa-var-warning: "\f071";
$fa-var-wechat: "\f1d7";
$fa-var-weibo: "\f18a";
$fa-var-weixin: "\f1d7";
$fa-var-whatsapp: "\f232";
$fa-var-wheelchair: "\f193";
$fa-var-wifi: "\f1eb";
$fa-var-wikipedia-w: "\f266";
$fa-var-windows: "\f17a";
$fa-var-won: "\f159";
$fa-var-wordpress: "\f19a";
$fa-var-wrench: "\f0ad";
$fa-var-xing: "\f168";
$fa-var-xing-square: "\f169";
$fa-var-y-combinator: "\f23b";
$fa-var-y-combinator-square: "\f1d4";
$fa-var-yahoo: "\f19e";
$fa-var-yc: "\f23b";
$fa-var-yc-square: "\f1d4";
$fa-var-yelp: "\f1e9";
$fa-var-yen: "\f157";
$fa-var-youtube: "\f167";
$fa-var-youtube-play: "\f16a";
$fa-var-youtube-square: "\f166";
``` | /content/code_sandbox/app/assets/sass/font-awesome/_variables.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 7,871 |
```scss
// Rotated & Flipped Icons
// -------------------------
.#{$fa-css-prefix}-rotate-90 { @include fa-icon-rotate(90deg, 1); }
.#{$fa-css-prefix}-rotate-180 { @include fa-icon-rotate(180deg, 2); }
.#{$fa-css-prefix}-rotate-270 { @include fa-icon-rotate(270deg, 3); }
.#{$fa-css-prefix}-flip-horizontal { @include fa-icon-flip(-1, 1, 0); }
.#{$fa-css-prefix}-flip-vertical { @include fa-icon-flip(1, -1, 2); }
// Hook for IE8-9
// -------------------------
:root .#{$fa-css-prefix}-rotate-90,
:root .#{$fa-css-prefix}-rotate-180,
:root .#{$fa-css-prefix}-rotate-270,
:root .#{$fa-css-prefix}-flip-horizontal,
:root .#{$fa-css-prefix}-flip-vertical {
filter: none;
}
``` | /content/code_sandbox/app/assets/sass/font-awesome/_rotated-flipped.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 217 |
```scss
// Fixed Width Icons
// -------------------------
.#{$fa-css-prefix}-fw {
width: (18em / 14);
text-align: center;
}
``` | /content/code_sandbox/app/assets/sass/font-awesome/_fixed-width.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 34 |
```scss
// Mixins
// --------------------------
@mixin fa-icon() {
display: inline-block;
font: normal normal normal #{$fa-font-size-base}/#{$fa-line-height-base} FontAwesome; // shortening font declaration
font-size: inherit; // can't have font-size inherit on line above, so need to override
text-rendering: auto; // optimizelegibility throws things off #1094
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
@mixin fa-icon-rotate($degrees, $rotation) {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=#{$rotation});
-webkit-transform: rotate($degrees);
-ms-transform: rotate($degrees);
transform: rotate($degrees);
}
@mixin fa-icon-flip($horiz, $vert, $rotation) {
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=#{$rotation});
-webkit-transform: scale($horiz, $vert);
-ms-transform: scale($horiz, $vert);
transform: scale($horiz, $vert);
}
``` | /content/code_sandbox/app/assets/sass/font-awesome/_mixins.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 239 |
```scss
/* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen
readers do not read off random characters that represent icons */
.#{$fa-css-prefix}-glass:before { content: $fa-var-glass; }
.#{$fa-css-prefix}-music:before { content: $fa-var-music; }
.#{$fa-css-prefix}-search:before { content: $fa-var-search; }
.#{$fa-css-prefix}-envelope-o:before { content: $fa-var-envelope-o; }
.#{$fa-css-prefix}-heart:before { content: $fa-var-heart; }
.#{$fa-css-prefix}-star:before { content: $fa-var-star; }
.#{$fa-css-prefix}-star-o:before { content: $fa-var-star-o; }
.#{$fa-css-prefix}-user:before { content: $fa-var-user; }
.#{$fa-css-prefix}-film:before { content: $fa-var-film; }
.#{$fa-css-prefix}-th-large:before { content: $fa-var-th-large; }
.#{$fa-css-prefix}-th:before { content: $fa-var-th; }
.#{$fa-css-prefix}-th-list:before { content: $fa-var-th-list; }
.#{$fa-css-prefix}-check:before { content: $fa-var-check; }
.#{$fa-css-prefix}-remove:before,
.#{$fa-css-prefix}-close:before,
.#{$fa-css-prefix}-times:before { content: $fa-var-times; }
.#{$fa-css-prefix}-search-plus:before { content: $fa-var-search-plus; }
.#{$fa-css-prefix}-search-minus:before { content: $fa-var-search-minus; }
.#{$fa-css-prefix}-power-off:before { content: $fa-var-power-off; }
.#{$fa-css-prefix}-signal:before { content: $fa-var-signal; }
.#{$fa-css-prefix}-gear:before,
.#{$fa-css-prefix}-cog:before { content: $fa-var-cog; }
.#{$fa-css-prefix}-trash-o:before { content: $fa-var-trash-o; }
.#{$fa-css-prefix}-home:before { content: $fa-var-home; }
.#{$fa-css-prefix}-file-o:before { content: $fa-var-file-o; }
.#{$fa-css-prefix}-clock-o:before { content: $fa-var-clock-o; }
.#{$fa-css-prefix}-road:before { content: $fa-var-road; }
.#{$fa-css-prefix}-download:before { content: $fa-var-download; }
.#{$fa-css-prefix}-arrow-circle-o-down:before { content: $fa-var-arrow-circle-o-down; }
.#{$fa-css-prefix}-arrow-circle-o-up:before { content: $fa-var-arrow-circle-o-up; }
.#{$fa-css-prefix}-inbox:before { content: $fa-var-inbox; }
.#{$fa-css-prefix}-play-circle-o:before { content: $fa-var-play-circle-o; }
.#{$fa-css-prefix}-rotate-right:before,
.#{$fa-css-prefix}-repeat:before { content: $fa-var-repeat; }
.#{$fa-css-prefix}-refresh:before { content: $fa-var-refresh; }
.#{$fa-css-prefix}-list-alt:before { content: $fa-var-list-alt; }
.#{$fa-css-prefix}-lock:before { content: $fa-var-lock; }
.#{$fa-css-prefix}-flag:before { content: $fa-var-flag; }
.#{$fa-css-prefix}-headphones:before { content: $fa-var-headphones; }
.#{$fa-css-prefix}-volume-off:before { content: $fa-var-volume-off; }
.#{$fa-css-prefix}-volume-down:before { content: $fa-var-volume-down; }
.#{$fa-css-prefix}-volume-up:before { content: $fa-var-volume-up; }
.#{$fa-css-prefix}-qrcode:before { content: $fa-var-qrcode; }
.#{$fa-css-prefix}-barcode:before { content: $fa-var-barcode; }
.#{$fa-css-prefix}-tag:before { content: $fa-var-tag; }
.#{$fa-css-prefix}-tags:before { content: $fa-var-tags; }
.#{$fa-css-prefix}-book:before { content: $fa-var-book; }
.#{$fa-css-prefix}-bookmark:before { content: $fa-var-bookmark; }
.#{$fa-css-prefix}-print:before { content: $fa-var-print; }
.#{$fa-css-prefix}-camera:before { content: $fa-var-camera; }
.#{$fa-css-prefix}-font:before { content: $fa-var-font; }
.#{$fa-css-prefix}-bold:before { content: $fa-var-bold; }
.#{$fa-css-prefix}-italic:before { content: $fa-var-italic; }
.#{$fa-css-prefix}-text-height:before { content: $fa-var-text-height; }
.#{$fa-css-prefix}-text-width:before { content: $fa-var-text-width; }
.#{$fa-css-prefix}-align-left:before { content: $fa-var-align-left; }
.#{$fa-css-prefix}-align-center:before { content: $fa-var-align-center; }
.#{$fa-css-prefix}-align-right:before { content: $fa-var-align-right; }
.#{$fa-css-prefix}-align-justify:before { content: $fa-var-align-justify; }
.#{$fa-css-prefix}-list:before { content: $fa-var-list; }
.#{$fa-css-prefix}-dedent:before,
.#{$fa-css-prefix}-outdent:before { content: $fa-var-outdent; }
.#{$fa-css-prefix}-indent:before { content: $fa-var-indent; }
.#{$fa-css-prefix}-video-camera:before { content: $fa-var-video-camera; }
.#{$fa-css-prefix}-photo:before,
.#{$fa-css-prefix}-image:before,
.#{$fa-css-prefix}-picture-o:before { content: $fa-var-picture-o; }
.#{$fa-css-prefix}-pencil:before { content: $fa-var-pencil; }
.#{$fa-css-prefix}-map-marker:before { content: $fa-var-map-marker; }
.#{$fa-css-prefix}-adjust:before { content: $fa-var-adjust; }
.#{$fa-css-prefix}-tint:before { content: $fa-var-tint; }
.#{$fa-css-prefix}-edit:before,
.#{$fa-css-prefix}-pencil-square-o:before { content: $fa-var-pencil-square-o; }
.#{$fa-css-prefix}-share-square-o:before { content: $fa-var-share-square-o; }
.#{$fa-css-prefix}-check-square-o:before { content: $fa-var-check-square-o; }
.#{$fa-css-prefix}-arrows:before { content: $fa-var-arrows; }
.#{$fa-css-prefix}-step-backward:before { content: $fa-var-step-backward; }
.#{$fa-css-prefix}-fast-backward:before { content: $fa-var-fast-backward; }
.#{$fa-css-prefix}-backward:before { content: $fa-var-backward; }
.#{$fa-css-prefix}-play:before { content: $fa-var-play; }
.#{$fa-css-prefix}-pause:before { content: $fa-var-pause; }
.#{$fa-css-prefix}-stop:before { content: $fa-var-stop; }
.#{$fa-css-prefix}-forward:before { content: $fa-var-forward; }
.#{$fa-css-prefix}-fast-forward:before { content: $fa-var-fast-forward; }
.#{$fa-css-prefix}-step-forward:before { content: $fa-var-step-forward; }
.#{$fa-css-prefix}-eject:before { content: $fa-var-eject; }
.#{$fa-css-prefix}-chevron-left:before { content: $fa-var-chevron-left; }
.#{$fa-css-prefix}-chevron-right:before { content: $fa-var-chevron-right; }
.#{$fa-css-prefix}-plus-circle:before { content: $fa-var-plus-circle; }
.#{$fa-css-prefix}-minus-circle:before { content: $fa-var-minus-circle; }
.#{$fa-css-prefix}-times-circle:before { content: $fa-var-times-circle; }
.#{$fa-css-prefix}-check-circle:before { content: $fa-var-check-circle; }
.#{$fa-css-prefix}-question-circle:before { content: $fa-var-question-circle; }
.#{$fa-css-prefix}-info-circle:before { content: $fa-var-info-circle; }
.#{$fa-css-prefix}-crosshairs:before { content: $fa-var-crosshairs; }
.#{$fa-css-prefix}-times-circle-o:before { content: $fa-var-times-circle-o; }
.#{$fa-css-prefix}-check-circle-o:before { content: $fa-var-check-circle-o; }
.#{$fa-css-prefix}-ban:before { content: $fa-var-ban; }
.#{$fa-css-prefix}-arrow-left:before { content: $fa-var-arrow-left; }
.#{$fa-css-prefix}-arrow-right:before { content: $fa-var-arrow-right; }
.#{$fa-css-prefix}-arrow-up:before { content: $fa-var-arrow-up; }
.#{$fa-css-prefix}-arrow-down:before { content: $fa-var-arrow-down; }
.#{$fa-css-prefix}-mail-forward:before,
.#{$fa-css-prefix}-share:before { content: $fa-var-share; }
.#{$fa-css-prefix}-expand:before { content: $fa-var-expand; }
.#{$fa-css-prefix}-compress:before { content: $fa-var-compress; }
.#{$fa-css-prefix}-plus:before { content: $fa-var-plus; }
.#{$fa-css-prefix}-minus:before { content: $fa-var-minus; }
.#{$fa-css-prefix}-asterisk:before { content: $fa-var-asterisk; }
.#{$fa-css-prefix}-exclamation-circle:before { content: $fa-var-exclamation-circle; }
.#{$fa-css-prefix}-gift:before { content: $fa-var-gift; }
.#{$fa-css-prefix}-leaf:before { content: $fa-var-leaf; }
.#{$fa-css-prefix}-fire:before { content: $fa-var-fire; }
.#{$fa-css-prefix}-eye:before { content: $fa-var-eye; }
.#{$fa-css-prefix}-eye-slash:before { content: $fa-var-eye-slash; }
.#{$fa-css-prefix}-warning:before,
.#{$fa-css-prefix}-exclamation-triangle:before { content: $fa-var-exclamation-triangle; }
.#{$fa-css-prefix}-plane:before { content: $fa-var-plane; }
.#{$fa-css-prefix}-calendar:before { content: $fa-var-calendar; }
.#{$fa-css-prefix}-random:before { content: $fa-var-random; }
.#{$fa-css-prefix}-comment:before { content: $fa-var-comment; }
.#{$fa-css-prefix}-magnet:before { content: $fa-var-magnet; }
.#{$fa-css-prefix}-chevron-up:before { content: $fa-var-chevron-up; }
.#{$fa-css-prefix}-chevron-down:before { content: $fa-var-chevron-down; }
.#{$fa-css-prefix}-retweet:before { content: $fa-var-retweet; }
.#{$fa-css-prefix}-shopping-cart:before { content: $fa-var-shopping-cart; }
.#{$fa-css-prefix}-folder:before { content: $fa-var-folder; }
.#{$fa-css-prefix}-folder-open:before { content: $fa-var-folder-open; }
.#{$fa-css-prefix}-arrows-v:before { content: $fa-var-arrows-v; }
.#{$fa-css-prefix}-arrows-h:before { content: $fa-var-arrows-h; }
.#{$fa-css-prefix}-bar-chart-o:before,
.#{$fa-css-prefix}-bar-chart:before { content: $fa-var-bar-chart; }
.#{$fa-css-prefix}-twitter-square:before { content: $fa-var-twitter-square; }
.#{$fa-css-prefix}-facebook-square:before { content: $fa-var-facebook-square; }
.#{$fa-css-prefix}-camera-retro:before { content: $fa-var-camera-retro; }
.#{$fa-css-prefix}-key:before { content: $fa-var-key; }
.#{$fa-css-prefix}-gears:before,
.#{$fa-css-prefix}-cogs:before { content: $fa-var-cogs; }
.#{$fa-css-prefix}-comments:before { content: $fa-var-comments; }
.#{$fa-css-prefix}-thumbs-o-up:before { content: $fa-var-thumbs-o-up; }
.#{$fa-css-prefix}-thumbs-o-down:before { content: $fa-var-thumbs-o-down; }
.#{$fa-css-prefix}-star-half:before { content: $fa-var-star-half; }
.#{$fa-css-prefix}-heart-o:before { content: $fa-var-heart-o; }
.#{$fa-css-prefix}-sign-out:before { content: $fa-var-sign-out; }
.#{$fa-css-prefix}-linkedin-square:before { content: $fa-var-linkedin-square; }
.#{$fa-css-prefix}-thumb-tack:before { content: $fa-var-thumb-tack; }
.#{$fa-css-prefix}-external-link:before { content: $fa-var-external-link; }
.#{$fa-css-prefix}-sign-in:before { content: $fa-var-sign-in; }
.#{$fa-css-prefix}-trophy:before { content: $fa-var-trophy; }
.#{$fa-css-prefix}-github-square:before { content: $fa-var-github-square; }
.#{$fa-css-prefix}-upload:before { content: $fa-var-upload; }
.#{$fa-css-prefix}-lemon-o:before { content: $fa-var-lemon-o; }
.#{$fa-css-prefix}-phone:before { content: $fa-var-phone; }
.#{$fa-css-prefix}-square-o:before { content: $fa-var-square-o; }
.#{$fa-css-prefix}-bookmark-o:before { content: $fa-var-bookmark-o; }
.#{$fa-css-prefix}-phone-square:before { content: $fa-var-phone-square; }
.#{$fa-css-prefix}-twitter:before { content: $fa-var-twitter; }
.#{$fa-css-prefix}-facebook-f:before,
.#{$fa-css-prefix}-facebook:before { content: $fa-var-facebook; }
.#{$fa-css-prefix}-github:before { content: $fa-var-github; }
.#{$fa-css-prefix}-unlock:before { content: $fa-var-unlock; }
.#{$fa-css-prefix}-credit-card:before { content: $fa-var-credit-card; }
.#{$fa-css-prefix}-feed:before,
.#{$fa-css-prefix}-rss:before { content: $fa-var-rss; }
.#{$fa-css-prefix}-hdd-o:before { content: $fa-var-hdd-o; }
.#{$fa-css-prefix}-bullhorn:before { content: $fa-var-bullhorn; }
.#{$fa-css-prefix}-bell:before { content: $fa-var-bell; }
.#{$fa-css-prefix}-certificate:before { content: $fa-var-certificate; }
.#{$fa-css-prefix}-hand-o-right:before { content: $fa-var-hand-o-right; }
.#{$fa-css-prefix}-hand-o-left:before { content: $fa-var-hand-o-left; }
.#{$fa-css-prefix}-hand-o-up:before { content: $fa-var-hand-o-up; }
.#{$fa-css-prefix}-hand-o-down:before { content: $fa-var-hand-o-down; }
.#{$fa-css-prefix}-arrow-circle-left:before { content: $fa-var-arrow-circle-left; }
.#{$fa-css-prefix}-arrow-circle-right:before { content: $fa-var-arrow-circle-right; }
.#{$fa-css-prefix}-arrow-circle-up:before { content: $fa-var-arrow-circle-up; }
.#{$fa-css-prefix}-arrow-circle-down:before { content: $fa-var-arrow-circle-down; }
.#{$fa-css-prefix}-globe:before { content: $fa-var-globe; }
.#{$fa-css-prefix}-wrench:before { content: $fa-var-wrench; }
.#{$fa-css-prefix}-tasks:before { content: $fa-var-tasks; }
.#{$fa-css-prefix}-filter:before { content: $fa-var-filter; }
.#{$fa-css-prefix}-briefcase:before { content: $fa-var-briefcase; }
.#{$fa-css-prefix}-arrows-alt:before { content: $fa-var-arrows-alt; }
.#{$fa-css-prefix}-group:before,
.#{$fa-css-prefix}-users:before { content: $fa-var-users; }
.#{$fa-css-prefix}-chain:before,
.#{$fa-css-prefix}-link:before { content: $fa-var-link; }
.#{$fa-css-prefix}-cloud:before { content: $fa-var-cloud; }
.#{$fa-css-prefix}-flask:before { content: $fa-var-flask; }
.#{$fa-css-prefix}-cut:before,
.#{$fa-css-prefix}-scissors:before { content: $fa-var-scissors; }
.#{$fa-css-prefix}-copy:before,
.#{$fa-css-prefix}-files-o:before { content: $fa-var-files-o; }
.#{$fa-css-prefix}-paperclip:before { content: $fa-var-paperclip; }
.#{$fa-css-prefix}-save:before,
.#{$fa-css-prefix}-floppy-o:before { content: $fa-var-floppy-o; }
.#{$fa-css-prefix}-square:before { content: $fa-var-square; }
.#{$fa-css-prefix}-navicon:before,
.#{$fa-css-prefix}-reorder:before,
.#{$fa-css-prefix}-bars:before { content: $fa-var-bars; }
.#{$fa-css-prefix}-list-ul:before { content: $fa-var-list-ul; }
.#{$fa-css-prefix}-list-ol:before { content: $fa-var-list-ol; }
.#{$fa-css-prefix}-strikethrough:before { content: $fa-var-strikethrough; }
.#{$fa-css-prefix}-underline:before { content: $fa-var-underline; }
.#{$fa-css-prefix}-table:before { content: $fa-var-table; }
.#{$fa-css-prefix}-magic:before { content: $fa-var-magic; }
.#{$fa-css-prefix}-truck:before { content: $fa-var-truck; }
.#{$fa-css-prefix}-pinterest:before { content: $fa-var-pinterest; }
.#{$fa-css-prefix}-pinterest-square:before { content: $fa-var-pinterest-square; }
.#{$fa-css-prefix}-google-plus-square:before { content: $fa-var-google-plus-square; }
.#{$fa-css-prefix}-google-plus:before { content: $fa-var-google-plus; }
.#{$fa-css-prefix}-money:before { content: $fa-var-money; }
.#{$fa-css-prefix}-caret-down:before { content: $fa-var-caret-down; }
.#{$fa-css-prefix}-caret-up:before { content: $fa-var-caret-up; }
.#{$fa-css-prefix}-caret-left:before { content: $fa-var-caret-left; }
.#{$fa-css-prefix}-caret-right:before { content: $fa-var-caret-right; }
.#{$fa-css-prefix}-columns:before { content: $fa-var-columns; }
.#{$fa-css-prefix}-unsorted:before,
.#{$fa-css-prefix}-sort:before { content: $fa-var-sort; }
.#{$fa-css-prefix}-sort-down:before,
.#{$fa-css-prefix}-sort-desc:before { content: $fa-var-sort-desc; }
.#{$fa-css-prefix}-sort-up:before,
.#{$fa-css-prefix}-sort-asc:before { content: $fa-var-sort-asc; }
.#{$fa-css-prefix}-envelope:before { content: $fa-var-envelope; }
.#{$fa-css-prefix}-linkedin:before { content: $fa-var-linkedin; }
.#{$fa-css-prefix}-rotate-left:before,
.#{$fa-css-prefix}-undo:before { content: $fa-var-undo; }
.#{$fa-css-prefix}-legal:before,
.#{$fa-css-prefix}-gavel:before { content: $fa-var-gavel; }
.#{$fa-css-prefix}-dashboard:before,
.#{$fa-css-prefix}-tachometer:before { content: $fa-var-tachometer; }
.#{$fa-css-prefix}-comment-o:before { content: $fa-var-comment-o; }
.#{$fa-css-prefix}-comments-o:before { content: $fa-var-comments-o; }
.#{$fa-css-prefix}-flash:before,
.#{$fa-css-prefix}-bolt:before { content: $fa-var-bolt; }
.#{$fa-css-prefix}-sitemap:before { content: $fa-var-sitemap; }
.#{$fa-css-prefix}-umbrella:before { content: $fa-var-umbrella; }
.#{$fa-css-prefix}-paste:before,
.#{$fa-css-prefix}-clipboard:before { content: $fa-var-clipboard; }
.#{$fa-css-prefix}-lightbulb-o:before { content: $fa-var-lightbulb-o; }
.#{$fa-css-prefix}-exchange:before { content: $fa-var-exchange; }
.#{$fa-css-prefix}-cloud-download:before { content: $fa-var-cloud-download; }
.#{$fa-css-prefix}-cloud-upload:before { content: $fa-var-cloud-upload; }
.#{$fa-css-prefix}-user-md:before { content: $fa-var-user-md; }
.#{$fa-css-prefix}-stethoscope:before { content: $fa-var-stethoscope; }
.#{$fa-css-prefix}-suitcase:before { content: $fa-var-suitcase; }
.#{$fa-css-prefix}-bell-o:before { content: $fa-var-bell-o; }
.#{$fa-css-prefix}-coffee:before { content: $fa-var-coffee; }
.#{$fa-css-prefix}-cutlery:before { content: $fa-var-cutlery; }
.#{$fa-css-prefix}-file-text-o:before { content: $fa-var-file-text-o; }
.#{$fa-css-prefix}-building-o:before { content: $fa-var-building-o; }
.#{$fa-css-prefix}-hospital-o:before { content: $fa-var-hospital-o; }
.#{$fa-css-prefix}-ambulance:before { content: $fa-var-ambulance; }
.#{$fa-css-prefix}-medkit:before { content: $fa-var-medkit; }
.#{$fa-css-prefix}-fighter-jet:before { content: $fa-var-fighter-jet; }
.#{$fa-css-prefix}-beer:before { content: $fa-var-beer; }
.#{$fa-css-prefix}-h-square:before { content: $fa-var-h-square; }
.#{$fa-css-prefix}-plus-square:before { content: $fa-var-plus-square; }
.#{$fa-css-prefix}-angle-double-left:before { content: $fa-var-angle-double-left; }
.#{$fa-css-prefix}-angle-double-right:before { content: $fa-var-angle-double-right; }
.#{$fa-css-prefix}-angle-double-up:before { content: $fa-var-angle-double-up; }
.#{$fa-css-prefix}-angle-double-down:before { content: $fa-var-angle-double-down; }
.#{$fa-css-prefix}-angle-left:before { content: $fa-var-angle-left; }
.#{$fa-css-prefix}-angle-right:before { content: $fa-var-angle-right; }
.#{$fa-css-prefix}-angle-up:before { content: $fa-var-angle-up; }
.#{$fa-css-prefix}-angle-down:before { content: $fa-var-angle-down; }
.#{$fa-css-prefix}-desktop:before { content: $fa-var-desktop; }
.#{$fa-css-prefix}-laptop:before { content: $fa-var-laptop; }
.#{$fa-css-prefix}-tablet:before { content: $fa-var-tablet; }
.#{$fa-css-prefix}-mobile-phone:before,
.#{$fa-css-prefix}-mobile:before { content: $fa-var-mobile; }
.#{$fa-css-prefix}-circle-o:before { content: $fa-var-circle-o; }
.#{$fa-css-prefix}-quote-left:before { content: $fa-var-quote-left; }
.#{$fa-css-prefix}-quote-right:before { content: $fa-var-quote-right; }
.#{$fa-css-prefix}-spinner:before { content: $fa-var-spinner; }
.#{$fa-css-prefix}-circle:before { content: $fa-var-circle; }
.#{$fa-css-prefix}-mail-reply:before,
.#{$fa-css-prefix}-reply:before { content: $fa-var-reply; }
.#{$fa-css-prefix}-github-alt:before { content: $fa-var-github-alt; }
.#{$fa-css-prefix}-folder-o:before { content: $fa-var-folder-o; }
.#{$fa-css-prefix}-folder-open-o:before { content: $fa-var-folder-open-o; }
.#{$fa-css-prefix}-smile-o:before { content: $fa-var-smile-o; }
.#{$fa-css-prefix}-frown-o:before { content: $fa-var-frown-o; }
.#{$fa-css-prefix}-meh-o:before { content: $fa-var-meh-o; }
.#{$fa-css-prefix}-gamepad:before { content: $fa-var-gamepad; }
.#{$fa-css-prefix}-keyboard-o:before { content: $fa-var-keyboard-o; }
.#{$fa-css-prefix}-flag-o:before { content: $fa-var-flag-o; }
.#{$fa-css-prefix}-flag-checkered:before { content: $fa-var-flag-checkered; }
.#{$fa-css-prefix}-terminal:before { content: $fa-var-terminal; }
.#{$fa-css-prefix}-code:before { content: $fa-var-code; }
.#{$fa-css-prefix}-mail-reply-all:before,
.#{$fa-css-prefix}-reply-all:before { content: $fa-var-reply-all; }
.#{$fa-css-prefix}-star-half-empty:before,
.#{$fa-css-prefix}-star-half-full:before,
.#{$fa-css-prefix}-star-half-o:before { content: $fa-var-star-half-o; }
.#{$fa-css-prefix}-location-arrow:before { content: $fa-var-location-arrow; }
.#{$fa-css-prefix}-crop:before { content: $fa-var-crop; }
.#{$fa-css-prefix}-code-fork:before { content: $fa-var-code-fork; }
.#{$fa-css-prefix}-unlink:before,
.#{$fa-css-prefix}-chain-broken:before { content: $fa-var-chain-broken; }
.#{$fa-css-prefix}-question:before { content: $fa-var-question; }
.#{$fa-css-prefix}-info:before { content: $fa-var-info; }
.#{$fa-css-prefix}-exclamation:before { content: $fa-var-exclamation; }
.#{$fa-css-prefix}-superscript:before { content: $fa-var-superscript; }
.#{$fa-css-prefix}-subscript:before { content: $fa-var-subscript; }
.#{$fa-css-prefix}-eraser:before { content: $fa-var-eraser; }
.#{$fa-css-prefix}-puzzle-piece:before { content: $fa-var-puzzle-piece; }
.#{$fa-css-prefix}-microphone:before { content: $fa-var-microphone; }
.#{$fa-css-prefix}-microphone-slash:before { content: $fa-var-microphone-slash; }
.#{$fa-css-prefix}-shield:before { content: $fa-var-shield; }
.#{$fa-css-prefix}-calendar-o:before { content: $fa-var-calendar-o; }
.#{$fa-css-prefix}-fire-extinguisher:before { content: $fa-var-fire-extinguisher; }
.#{$fa-css-prefix}-rocket:before { content: $fa-var-rocket; }
.#{$fa-css-prefix}-maxcdn:before { content: $fa-var-maxcdn; }
.#{$fa-css-prefix}-chevron-circle-left:before { content: $fa-var-chevron-circle-left; }
.#{$fa-css-prefix}-chevron-circle-right:before { content: $fa-var-chevron-circle-right; }
.#{$fa-css-prefix}-chevron-circle-up:before { content: $fa-var-chevron-circle-up; }
.#{$fa-css-prefix}-chevron-circle-down:before { content: $fa-var-chevron-circle-down; }
.#{$fa-css-prefix}-html5:before { content: $fa-var-html5; }
.#{$fa-css-prefix}-css3:before { content: $fa-var-css3; }
.#{$fa-css-prefix}-anchor:before { content: $fa-var-anchor; }
.#{$fa-css-prefix}-unlock-alt:before { content: $fa-var-unlock-alt; }
.#{$fa-css-prefix}-bullseye:before { content: $fa-var-bullseye; }
.#{$fa-css-prefix}-ellipsis-h:before { content: $fa-var-ellipsis-h; }
.#{$fa-css-prefix}-ellipsis-v:before { content: $fa-var-ellipsis-v; }
.#{$fa-css-prefix}-rss-square:before { content: $fa-var-rss-square; }
.#{$fa-css-prefix}-play-circle:before { content: $fa-var-play-circle; }
.#{$fa-css-prefix}-ticket:before { content: $fa-var-ticket; }
.#{$fa-css-prefix}-minus-square:before { content: $fa-var-minus-square; }
.#{$fa-css-prefix}-minus-square-o:before { content: $fa-var-minus-square-o; }
.#{$fa-css-prefix}-level-up:before { content: $fa-var-level-up; }
.#{$fa-css-prefix}-level-down:before { content: $fa-var-level-down; }
.#{$fa-css-prefix}-check-square:before { content: $fa-var-check-square; }
.#{$fa-css-prefix}-pencil-square:before { content: $fa-var-pencil-square; }
.#{$fa-css-prefix}-external-link-square:before { content: $fa-var-external-link-square; }
.#{$fa-css-prefix}-share-square:before { content: $fa-var-share-square; }
.#{$fa-css-prefix}-compass:before { content: $fa-var-compass; }
.#{$fa-css-prefix}-toggle-down:before,
.#{$fa-css-prefix}-caret-square-o-down:before { content: $fa-var-caret-square-o-down; }
.#{$fa-css-prefix}-toggle-up:before,
.#{$fa-css-prefix}-caret-square-o-up:before { content: $fa-var-caret-square-o-up; }
.#{$fa-css-prefix}-toggle-right:before,
.#{$fa-css-prefix}-caret-square-o-right:before { content: $fa-var-caret-square-o-right; }
.#{$fa-css-prefix}-euro:before,
.#{$fa-css-prefix}-eur:before { content: $fa-var-eur; }
.#{$fa-css-prefix}-gbp:before { content: $fa-var-gbp; }
.#{$fa-css-prefix}-dollar:before,
.#{$fa-css-prefix}-usd:before { content: $fa-var-usd; }
.#{$fa-css-prefix}-rupee:before,
.#{$fa-css-prefix}-inr:before { content: $fa-var-inr; }
.#{$fa-css-prefix}-cny:before,
.#{$fa-css-prefix}-rmb:before,
.#{$fa-css-prefix}-yen:before,
.#{$fa-css-prefix}-jpy:before { content: $fa-var-jpy; }
.#{$fa-css-prefix}-ruble:before,
.#{$fa-css-prefix}-rouble:before,
.#{$fa-css-prefix}-rub:before { content: $fa-var-rub; }
.#{$fa-css-prefix}-won:before,
.#{$fa-css-prefix}-krw:before { content: $fa-var-krw; }
.#{$fa-css-prefix}-bitcoin:before,
.#{$fa-css-prefix}-btc:before { content: $fa-var-btc; }
.#{$fa-css-prefix}-file:before { content: $fa-var-file; }
.#{$fa-css-prefix}-file-text:before { content: $fa-var-file-text; }
.#{$fa-css-prefix}-sort-alpha-asc:before { content: $fa-var-sort-alpha-asc; }
.#{$fa-css-prefix}-sort-alpha-desc:before { content: $fa-var-sort-alpha-desc; }
.#{$fa-css-prefix}-sort-amount-asc:before { content: $fa-var-sort-amount-asc; }
.#{$fa-css-prefix}-sort-amount-desc:before { content: $fa-var-sort-amount-desc; }
.#{$fa-css-prefix}-sort-numeric-asc:before { content: $fa-var-sort-numeric-asc; }
.#{$fa-css-prefix}-sort-numeric-desc:before { content: $fa-var-sort-numeric-desc; }
.#{$fa-css-prefix}-thumbs-up:before { content: $fa-var-thumbs-up; }
.#{$fa-css-prefix}-thumbs-down:before { content: $fa-var-thumbs-down; }
.#{$fa-css-prefix}-youtube-square:before { content: $fa-var-youtube-square; }
.#{$fa-css-prefix}-youtube:before { content: $fa-var-youtube; }
.#{$fa-css-prefix}-xing:before { content: $fa-var-xing; }
.#{$fa-css-prefix}-xing-square:before { content: $fa-var-xing-square; }
.#{$fa-css-prefix}-youtube-play:before { content: $fa-var-youtube-play; }
.#{$fa-css-prefix}-dropbox:before { content: $fa-var-dropbox; }
.#{$fa-css-prefix}-stack-overflow:before { content: $fa-var-stack-overflow; }
.#{$fa-css-prefix}-instagram:before { content: $fa-var-instagram; }
.#{$fa-css-prefix}-flickr:before { content: $fa-var-flickr; }
.#{$fa-css-prefix}-adn:before { content: $fa-var-adn; }
.#{$fa-css-prefix}-bitbucket:before { content: $fa-var-bitbucket; }
.#{$fa-css-prefix}-bitbucket-square:before { content: $fa-var-bitbucket-square; }
.#{$fa-css-prefix}-tumblr:before { content: $fa-var-tumblr; }
.#{$fa-css-prefix}-tumblr-square:before { content: $fa-var-tumblr-square; }
.#{$fa-css-prefix}-long-arrow-down:before { content: $fa-var-long-arrow-down; }
.#{$fa-css-prefix}-long-arrow-up:before { content: $fa-var-long-arrow-up; }
.#{$fa-css-prefix}-long-arrow-left:before { content: $fa-var-long-arrow-left; }
.#{$fa-css-prefix}-long-arrow-right:before { content: $fa-var-long-arrow-right; }
.#{$fa-css-prefix}-apple:before { content: $fa-var-apple; }
.#{$fa-css-prefix}-windows:before { content: $fa-var-windows; }
.#{$fa-css-prefix}-android:before { content: $fa-var-android; }
.#{$fa-css-prefix}-linux:before { content: $fa-var-linux; }
.#{$fa-css-prefix}-dribbble:before { content: $fa-var-dribbble; }
.#{$fa-css-prefix}-skype:before { content: $fa-var-skype; }
.#{$fa-css-prefix}-foursquare:before { content: $fa-var-foursquare; }
.#{$fa-css-prefix}-trello:before { content: $fa-var-trello; }
.#{$fa-css-prefix}-female:before { content: $fa-var-female; }
.#{$fa-css-prefix}-male:before { content: $fa-var-male; }
.#{$fa-css-prefix}-gittip:before,
.#{$fa-css-prefix}-gratipay:before { content: $fa-var-gratipay; }
.#{$fa-css-prefix}-sun-o:before { content: $fa-var-sun-o; }
.#{$fa-css-prefix}-moon-o:before { content: $fa-var-moon-o; }
.#{$fa-css-prefix}-archive:before { content: $fa-var-archive; }
.#{$fa-css-prefix}-bug:before { content: $fa-var-bug; }
.#{$fa-css-prefix}-vk:before { content: $fa-var-vk; }
.#{$fa-css-prefix}-weibo:before { content: $fa-var-weibo; }
.#{$fa-css-prefix}-renren:before { content: $fa-var-renren; }
.#{$fa-css-prefix}-pagelines:before { content: $fa-var-pagelines; }
.#{$fa-css-prefix}-stack-exchange:before { content: $fa-var-stack-exchange; }
.#{$fa-css-prefix}-arrow-circle-o-right:before { content: $fa-var-arrow-circle-o-right; }
.#{$fa-css-prefix}-arrow-circle-o-left:before { content: $fa-var-arrow-circle-o-left; }
.#{$fa-css-prefix}-toggle-left:before,
.#{$fa-css-prefix}-caret-square-o-left:before { content: $fa-var-caret-square-o-left; }
.#{$fa-css-prefix}-dot-circle-o:before { content: $fa-var-dot-circle-o; }
.#{$fa-css-prefix}-wheelchair:before { content: $fa-var-wheelchair; }
.#{$fa-css-prefix}-vimeo-square:before { content: $fa-var-vimeo-square; }
.#{$fa-css-prefix}-turkish-lira:before,
.#{$fa-css-prefix}-try:before { content: $fa-var-try; }
.#{$fa-css-prefix}-plus-square-o:before { content: $fa-var-plus-square-o; }
.#{$fa-css-prefix}-space-shuttle:before { content: $fa-var-space-shuttle; }
.#{$fa-css-prefix}-slack:before { content: $fa-var-slack; }
.#{$fa-css-prefix}-envelope-square:before { content: $fa-var-envelope-square; }
.#{$fa-css-prefix}-wordpress:before { content: $fa-var-wordpress; }
.#{$fa-css-prefix}-openid:before { content: $fa-var-openid; }
.#{$fa-css-prefix}-institution:before,
.#{$fa-css-prefix}-bank:before,
.#{$fa-css-prefix}-university:before { content: $fa-var-university; }
.#{$fa-css-prefix}-mortar-board:before,
.#{$fa-css-prefix}-graduation-cap:before { content: $fa-var-graduation-cap; }
.#{$fa-css-prefix}-yahoo:before { content: $fa-var-yahoo; }
.#{$fa-css-prefix}-google:before { content: $fa-var-google; }
.#{$fa-css-prefix}-reddit:before { content: $fa-var-reddit; }
.#{$fa-css-prefix}-reddit-square:before { content: $fa-var-reddit-square; }
.#{$fa-css-prefix}-stumbleupon-circle:before { content: $fa-var-stumbleupon-circle; }
.#{$fa-css-prefix}-stumbleupon:before { content: $fa-var-stumbleupon; }
.#{$fa-css-prefix}-delicious:before { content: $fa-var-delicious; }
.#{$fa-css-prefix}-digg:before { content: $fa-var-digg; }
.#{$fa-css-prefix}-pied-piper:before { content: $fa-var-pied-piper; }
.#{$fa-css-prefix}-pied-piper-alt:before { content: $fa-var-pied-piper-alt; }
.#{$fa-css-prefix}-drupal:before { content: $fa-var-drupal; }
.#{$fa-css-prefix}-joomla:before { content: $fa-var-joomla; }
.#{$fa-css-prefix}-language:before { content: $fa-var-language; }
.#{$fa-css-prefix}-fax:before { content: $fa-var-fax; }
.#{$fa-css-prefix}-building:before { content: $fa-var-building; }
.#{$fa-css-prefix}-child:before { content: $fa-var-child; }
.#{$fa-css-prefix}-paw:before { content: $fa-var-paw; }
.#{$fa-css-prefix}-spoon:before { content: $fa-var-spoon; }
.#{$fa-css-prefix}-cube:before { content: $fa-var-cube; }
.#{$fa-css-prefix}-cubes:before { content: $fa-var-cubes; }
.#{$fa-css-prefix}-behance:before { content: $fa-var-behance; }
.#{$fa-css-prefix}-behance-square:before { content: $fa-var-behance-square; }
.#{$fa-css-prefix}-steam:before { content: $fa-var-steam; }
.#{$fa-css-prefix}-steam-square:before { content: $fa-var-steam-square; }
.#{$fa-css-prefix}-recycle:before { content: $fa-var-recycle; }
.#{$fa-css-prefix}-automobile:before,
.#{$fa-css-prefix}-car:before { content: $fa-var-car; }
.#{$fa-css-prefix}-cab:before,
.#{$fa-css-prefix}-taxi:before { content: $fa-var-taxi; }
.#{$fa-css-prefix}-tree:before { content: $fa-var-tree; }
.#{$fa-css-prefix}-spotify:before { content: $fa-var-spotify; }
.#{$fa-css-prefix}-deviantart:before { content: $fa-var-deviantart; }
.#{$fa-css-prefix}-soundcloud:before { content: $fa-var-soundcloud; }
.#{$fa-css-prefix}-database:before { content: $fa-var-database; }
.#{$fa-css-prefix}-file-pdf-o:before { content: $fa-var-file-pdf-o; }
.#{$fa-css-prefix}-file-word-o:before { content: $fa-var-file-word-o; }
.#{$fa-css-prefix}-file-excel-o:before { content: $fa-var-file-excel-o; }
.#{$fa-css-prefix}-file-powerpoint-o:before { content: $fa-var-file-powerpoint-o; }
.#{$fa-css-prefix}-file-photo-o:before,
.#{$fa-css-prefix}-file-picture-o:before,
.#{$fa-css-prefix}-file-image-o:before { content: $fa-var-file-image-o; }
.#{$fa-css-prefix}-file-zip-o:before,
.#{$fa-css-prefix}-file-archive-o:before { content: $fa-var-file-archive-o; }
.#{$fa-css-prefix}-file-sound-o:before,
.#{$fa-css-prefix}-file-audio-o:before { content: $fa-var-file-audio-o; }
.#{$fa-css-prefix}-file-movie-o:before,
.#{$fa-css-prefix}-file-video-o:before { content: $fa-var-file-video-o; }
.#{$fa-css-prefix}-file-code-o:before { content: $fa-var-file-code-o; }
.#{$fa-css-prefix}-vine:before { content: $fa-var-vine; }
.#{$fa-css-prefix}-codepen:before { content: $fa-var-codepen; }
.#{$fa-css-prefix}-jsfiddle:before { content: $fa-var-jsfiddle; }
.#{$fa-css-prefix}-life-bouy:before,
.#{$fa-css-prefix}-life-buoy:before,
.#{$fa-css-prefix}-life-saver:before,
.#{$fa-css-prefix}-support:before,
.#{$fa-css-prefix}-life-ring:before { content: $fa-var-life-ring; }
.#{$fa-css-prefix}-circle-o-notch:before { content: $fa-var-circle-o-notch; }
.#{$fa-css-prefix}-ra:before,
.#{$fa-css-prefix}-rebel:before { content: $fa-var-rebel; }
.#{$fa-css-prefix}-ge:before,
.#{$fa-css-prefix}-empire:before { content: $fa-var-empire; }
.#{$fa-css-prefix}-git-square:before { content: $fa-var-git-square; }
.#{$fa-css-prefix}-git:before { content: $fa-var-git; }
.#{$fa-css-prefix}-y-combinator-square:before,
.#{$fa-css-prefix}-yc-square:before,
.#{$fa-css-prefix}-hacker-news:before { content: $fa-var-hacker-news; }
.#{$fa-css-prefix}-tencent-weibo:before { content: $fa-var-tencent-weibo; }
.#{$fa-css-prefix}-qq:before { content: $fa-var-qq; }
.#{$fa-css-prefix}-wechat:before,
.#{$fa-css-prefix}-weixin:before { content: $fa-var-weixin; }
.#{$fa-css-prefix}-send:before,
.#{$fa-css-prefix}-paper-plane:before { content: $fa-var-paper-plane; }
.#{$fa-css-prefix}-send-o:before,
.#{$fa-css-prefix}-paper-plane-o:before { content: $fa-var-paper-plane-o; }
.#{$fa-css-prefix}-history:before { content: $fa-var-history; }
.#{$fa-css-prefix}-circle-thin:before { content: $fa-var-circle-thin; }
.#{$fa-css-prefix}-header:before { content: $fa-var-header; }
.#{$fa-css-prefix}-paragraph:before { content: $fa-var-paragraph; }
.#{$fa-css-prefix}-sliders:before { content: $fa-var-sliders; }
.#{$fa-css-prefix}-share-alt:before { content: $fa-var-share-alt; }
.#{$fa-css-prefix}-share-alt-square:before { content: $fa-var-share-alt-square; }
.#{$fa-css-prefix}-bomb:before { content: $fa-var-bomb; }
.#{$fa-css-prefix}-soccer-ball-o:before,
.#{$fa-css-prefix}-futbol-o:before { content: $fa-var-futbol-o; }
.#{$fa-css-prefix}-tty:before { content: $fa-var-tty; }
.#{$fa-css-prefix}-binoculars:before { content: $fa-var-binoculars; }
.#{$fa-css-prefix}-plug:before { content: $fa-var-plug; }
.#{$fa-css-prefix}-slideshare:before { content: $fa-var-slideshare; }
.#{$fa-css-prefix}-twitch:before { content: $fa-var-twitch; }
.#{$fa-css-prefix}-yelp:before { content: $fa-var-yelp; }
.#{$fa-css-prefix}-newspaper-o:before { content: $fa-var-newspaper-o; }
.#{$fa-css-prefix}-wifi:before { content: $fa-var-wifi; }
.#{$fa-css-prefix}-calculator:before { content: $fa-var-calculator; }
.#{$fa-css-prefix}-paypal:before { content: $fa-var-paypal; }
.#{$fa-css-prefix}-google-wallet:before { content: $fa-var-google-wallet; }
.#{$fa-css-prefix}-cc-visa:before { content: $fa-var-cc-visa; }
.#{$fa-css-prefix}-cc-mastercard:before { content: $fa-var-cc-mastercard; }
.#{$fa-css-prefix}-cc-discover:before { content: $fa-var-cc-discover; }
.#{$fa-css-prefix}-cc-amex:before { content: $fa-var-cc-amex; }
.#{$fa-css-prefix}-cc-paypal:before { content: $fa-var-cc-paypal; }
.#{$fa-css-prefix}-cc-stripe:before { content: $fa-var-cc-stripe; }
.#{$fa-css-prefix}-bell-slash:before { content: $fa-var-bell-slash; }
.#{$fa-css-prefix}-bell-slash-o:before { content: $fa-var-bell-slash-o; }
.#{$fa-css-prefix}-trash:before { content: $fa-var-trash; }
.#{$fa-css-prefix}-copyright:before { content: $fa-var-copyright; }
.#{$fa-css-prefix}-at:before { content: $fa-var-at; }
.#{$fa-css-prefix}-eyedropper:before { content: $fa-var-eyedropper; }
.#{$fa-css-prefix}-paint-brush:before { content: $fa-var-paint-brush; }
.#{$fa-css-prefix}-birthday-cake:before { content: $fa-var-birthday-cake; }
.#{$fa-css-prefix}-area-chart:before { content: $fa-var-area-chart; }
.#{$fa-css-prefix}-pie-chart:before { content: $fa-var-pie-chart; }
.#{$fa-css-prefix}-line-chart:before { content: $fa-var-line-chart; }
.#{$fa-css-prefix}-lastfm:before { content: $fa-var-lastfm; }
.#{$fa-css-prefix}-lastfm-square:before { content: $fa-var-lastfm-square; }
.#{$fa-css-prefix}-toggle-off:before { content: $fa-var-toggle-off; }
.#{$fa-css-prefix}-toggle-on:before { content: $fa-var-toggle-on; }
.#{$fa-css-prefix}-bicycle:before { content: $fa-var-bicycle; }
.#{$fa-css-prefix}-bus:before { content: $fa-var-bus; }
.#{$fa-css-prefix}-ioxhost:before { content: $fa-var-ioxhost; }
.#{$fa-css-prefix}-angellist:before { content: $fa-var-angellist; }
.#{$fa-css-prefix}-cc:before { content: $fa-var-cc; }
.#{$fa-css-prefix}-shekel:before,
.#{$fa-css-prefix}-sheqel:before,
.#{$fa-css-prefix}-ils:before { content: $fa-var-ils; }
.#{$fa-css-prefix}-meanpath:before { content: $fa-var-meanpath; }
.#{$fa-css-prefix}-buysellads:before { content: $fa-var-buysellads; }
.#{$fa-css-prefix}-connectdevelop:before { content: $fa-var-connectdevelop; }
.#{$fa-css-prefix}-dashcube:before { content: $fa-var-dashcube; }
.#{$fa-css-prefix}-forumbee:before { content: $fa-var-forumbee; }
.#{$fa-css-prefix}-leanpub:before { content: $fa-var-leanpub; }
.#{$fa-css-prefix}-sellsy:before { content: $fa-var-sellsy; }
.#{$fa-css-prefix}-shirtsinbulk:before { content: $fa-var-shirtsinbulk; }
.#{$fa-css-prefix}-simplybuilt:before { content: $fa-var-simplybuilt; }
.#{$fa-css-prefix}-skyatlas:before { content: $fa-var-skyatlas; }
.#{$fa-css-prefix}-cart-plus:before { content: $fa-var-cart-plus; }
.#{$fa-css-prefix}-cart-arrow-down:before { content: $fa-var-cart-arrow-down; }
.#{$fa-css-prefix}-diamond:before { content: $fa-var-diamond; }
.#{$fa-css-prefix}-ship:before { content: $fa-var-ship; }
.#{$fa-css-prefix}-user-secret:before { content: $fa-var-user-secret; }
.#{$fa-css-prefix}-motorcycle:before { content: $fa-var-motorcycle; }
.#{$fa-css-prefix}-street-view:before { content: $fa-var-street-view; }
.#{$fa-css-prefix}-heartbeat:before { content: $fa-var-heartbeat; }
.#{$fa-css-prefix}-venus:before { content: $fa-var-venus; }
.#{$fa-css-prefix}-mars:before { content: $fa-var-mars; }
.#{$fa-css-prefix}-mercury:before { content: $fa-var-mercury; }
.#{$fa-css-prefix}-intersex:before,
.#{$fa-css-prefix}-transgender:before { content: $fa-var-transgender; }
.#{$fa-css-prefix}-transgender-alt:before { content: $fa-var-transgender-alt; }
.#{$fa-css-prefix}-venus-double:before { content: $fa-var-venus-double; }
.#{$fa-css-prefix}-mars-double:before { content: $fa-var-mars-double; }
.#{$fa-css-prefix}-venus-mars:before { content: $fa-var-venus-mars; }
.#{$fa-css-prefix}-mars-stroke:before { content: $fa-var-mars-stroke; }
.#{$fa-css-prefix}-mars-stroke-v:before { content: $fa-var-mars-stroke-v; }
.#{$fa-css-prefix}-mars-stroke-h:before { content: $fa-var-mars-stroke-h; }
.#{$fa-css-prefix}-neuter:before { content: $fa-var-neuter; }
.#{$fa-css-prefix}-genderless:before { content: $fa-var-genderless; }
.#{$fa-css-prefix}-facebook-official:before { content: $fa-var-facebook-official; }
.#{$fa-css-prefix}-pinterest-p:before { content: $fa-var-pinterest-p; }
.#{$fa-css-prefix}-whatsapp:before { content: $fa-var-whatsapp; }
.#{$fa-css-prefix}-server:before { content: $fa-var-server; }
.#{$fa-css-prefix}-user-plus:before { content: $fa-var-user-plus; }
.#{$fa-css-prefix}-user-times:before { content: $fa-var-user-times; }
.#{$fa-css-prefix}-hotel:before,
.#{$fa-css-prefix}-bed:before { content: $fa-var-bed; }
.#{$fa-css-prefix}-viacoin:before { content: $fa-var-viacoin; }
.#{$fa-css-prefix}-train:before { content: $fa-var-train; }
.#{$fa-css-prefix}-subway:before { content: $fa-var-subway; }
.#{$fa-css-prefix}-medium:before { content: $fa-var-medium; }
.#{$fa-css-prefix}-yc:before,
.#{$fa-css-prefix}-y-combinator:before { content: $fa-var-y-combinator; }
.#{$fa-css-prefix}-optin-monster:before { content: $fa-var-optin-monster; }
.#{$fa-css-prefix}-opencart:before { content: $fa-var-opencart; }
.#{$fa-css-prefix}-expeditedssl:before { content: $fa-var-expeditedssl; }
.#{$fa-css-prefix}-battery-4:before,
.#{$fa-css-prefix}-battery-full:before { content: $fa-var-battery-full; }
.#{$fa-css-prefix}-battery-3:before,
.#{$fa-css-prefix}-battery-three-quarters:before { content: $fa-var-battery-three-quarters; }
.#{$fa-css-prefix}-battery-2:before,
.#{$fa-css-prefix}-battery-half:before { content: $fa-var-battery-half; }
.#{$fa-css-prefix}-battery-1:before,
.#{$fa-css-prefix}-battery-quarter:before { content: $fa-var-battery-quarter; }
.#{$fa-css-prefix}-battery-0:before,
.#{$fa-css-prefix}-battery-empty:before { content: $fa-var-battery-empty; }
.#{$fa-css-prefix}-mouse-pointer:before { content: $fa-var-mouse-pointer; }
.#{$fa-css-prefix}-i-cursor:before { content: $fa-var-i-cursor; }
.#{$fa-css-prefix}-object-group:before { content: $fa-var-object-group; }
.#{$fa-css-prefix}-object-ungroup:before { content: $fa-var-object-ungroup; }
.#{$fa-css-prefix}-sticky-note:before { content: $fa-var-sticky-note; }
.#{$fa-css-prefix}-sticky-note-o:before { content: $fa-var-sticky-note-o; }
.#{$fa-css-prefix}-cc-jcb:before { content: $fa-var-cc-jcb; }
.#{$fa-css-prefix}-cc-diners-club:before { content: $fa-var-cc-diners-club; }
.#{$fa-css-prefix}-clone:before { content: $fa-var-clone; }
.#{$fa-css-prefix}-balance-scale:before { content: $fa-var-balance-scale; }
.#{$fa-css-prefix}-hourglass-o:before { content: $fa-var-hourglass-o; }
.#{$fa-css-prefix}-hourglass-1:before,
.#{$fa-css-prefix}-hourglass-start:before { content: $fa-var-hourglass-start; }
.#{$fa-css-prefix}-hourglass-2:before,
.#{$fa-css-prefix}-hourglass-half:before { content: $fa-var-hourglass-half; }
.#{$fa-css-prefix}-hourglass-3:before,
.#{$fa-css-prefix}-hourglass-end:before { content: $fa-var-hourglass-end; }
.#{$fa-css-prefix}-hourglass:before { content: $fa-var-hourglass; }
.#{$fa-css-prefix}-hand-grab-o:before,
.#{$fa-css-prefix}-hand-rock-o:before { content: $fa-var-hand-rock-o; }
.#{$fa-css-prefix}-hand-stop-o:before,
.#{$fa-css-prefix}-hand-paper-o:before { content: $fa-var-hand-paper-o; }
.#{$fa-css-prefix}-hand-scissors-o:before { content: $fa-var-hand-scissors-o; }
.#{$fa-css-prefix}-hand-lizard-o:before { content: $fa-var-hand-lizard-o; }
.#{$fa-css-prefix}-hand-spock-o:before { content: $fa-var-hand-spock-o; }
.#{$fa-css-prefix}-hand-pointer-o:before { content: $fa-var-hand-pointer-o; }
.#{$fa-css-prefix}-hand-peace-o:before { content: $fa-var-hand-peace-o; }
.#{$fa-css-prefix}-trademark:before { content: $fa-var-trademark; }
.#{$fa-css-prefix}-registered:before { content: $fa-var-registered; }
.#{$fa-css-prefix}-creative-commons:before { content: $fa-var-creative-commons; }
.#{$fa-css-prefix}-gg:before { content: $fa-var-gg; }
.#{$fa-css-prefix}-gg-circle:before { content: $fa-var-gg-circle; }
.#{$fa-css-prefix}-tripadvisor:before { content: $fa-var-tripadvisor; }
.#{$fa-css-prefix}-odnoklassniki:before { content: $fa-var-odnoklassniki; }
.#{$fa-css-prefix}-odnoklassniki-square:before { content: $fa-var-odnoklassniki-square; }
.#{$fa-css-prefix}-get-pocket:before { content: $fa-var-get-pocket; }
.#{$fa-css-prefix}-wikipedia-w:before { content: $fa-var-wikipedia-w; }
.#{$fa-css-prefix}-safari:before { content: $fa-var-safari; }
.#{$fa-css-prefix}-chrome:before { content: $fa-var-chrome; }
.#{$fa-css-prefix}-firefox:before { content: $fa-var-firefox; }
.#{$fa-css-prefix}-opera:before { content: $fa-var-opera; }
.#{$fa-css-prefix}-internet-explorer:before { content: $fa-var-internet-explorer; }
.#{$fa-css-prefix}-tv:before,
.#{$fa-css-prefix}-television:before { content: $fa-var-television; }
.#{$fa-css-prefix}-contao:before { content: $fa-var-contao; }
.#{$fa-css-prefix}-500px:before { content: $fa-var-500px; }
.#{$fa-css-prefix}-amazon:before { content: $fa-var-amazon; }
.#{$fa-css-prefix}-calendar-plus-o:before { content: $fa-var-calendar-plus-o; }
.#{$fa-css-prefix}-calendar-minus-o:before { content: $fa-var-calendar-minus-o; }
.#{$fa-css-prefix}-calendar-times-o:before { content: $fa-var-calendar-times-o; }
.#{$fa-css-prefix}-calendar-check-o:before { content: $fa-var-calendar-check-o; }
.#{$fa-css-prefix}-industry:before { content: $fa-var-industry; }
.#{$fa-css-prefix}-map-pin:before { content: $fa-var-map-pin; }
.#{$fa-css-prefix}-map-signs:before { content: $fa-var-map-signs; }
.#{$fa-css-prefix}-map-o:before { content: $fa-var-map-o; }
.#{$fa-css-prefix}-map:before { content: $fa-var-map; }
.#{$fa-css-prefix}-commenting:before { content: $fa-var-commenting; }
.#{$fa-css-prefix}-commenting-o:before { content: $fa-var-commenting-o; }
.#{$fa-css-prefix}-houzz:before { content: $fa-var-houzz; }
.#{$fa-css-prefix}-vimeo:before { content: $fa-var-vimeo; }
.#{$fa-css-prefix}-black-tie:before { content: $fa-var-black-tie; }
.#{$fa-css-prefix}-fonticons:before { content: $fa-var-fonticons; }
.#{$fa-css-prefix}-reddit-alien:before { content: $fa-var-reddit-alien; }
.#{$fa-css-prefix}-edge:before { content: $fa-var-edge; }
.#{$fa-css-prefix}-credit-card-alt:before { content: $fa-var-credit-card-alt; }
.#{$fa-css-prefix}-codiepie:before { content: $fa-var-codiepie; }
.#{$fa-css-prefix}-modx:before { content: $fa-var-modx; }
.#{$fa-css-prefix}-fort-awesome:before { content: $fa-var-fort-awesome; }
.#{$fa-css-prefix}-usb:before { content: $fa-var-usb; }
.#{$fa-css-prefix}-product-hunt:before { content: $fa-var-product-hunt; }
.#{$fa-css-prefix}-mixcloud:before { content: $fa-var-mixcloud; }
.#{$fa-css-prefix}-scribd:before { content: $fa-var-scribd; }
.#{$fa-css-prefix}-pause-circle:before { content: $fa-var-pause-circle; }
.#{$fa-css-prefix}-pause-circle-o:before { content: $fa-var-pause-circle-o; }
.#{$fa-css-prefix}-stop-circle:before { content: $fa-var-stop-circle; }
.#{$fa-css-prefix}-stop-circle-o:before { content: $fa-var-stop-circle-o; }
.#{$fa-css-prefix}-shopping-bag:before { content: $fa-var-shopping-bag; }
.#{$fa-css-prefix}-shopping-basket:before { content: $fa-var-shopping-basket; }
.#{$fa-css-prefix}-hashtag:before { content: $fa-var-hashtag; }
.#{$fa-css-prefix}-bluetooth:before { content: $fa-var-bluetooth; }
.#{$fa-css-prefix}-bluetooth-b:before { content: $fa-var-bluetooth-b; }
.#{$fa-css-prefix}-percent:before { content: $fa-var-percent; }
``` | /content/code_sandbox/app/assets/sass/font-awesome/_icons.scss | scss | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 12,756 |
```emacs lisp
((emacs-lisp-mode
(indent-tabs-mode . nil)
(tab-width . 2))
(git-commit-mode
(git-commit-major-mode . git-commit-elisp-text-mode)))
``` | /content/code_sandbox/.dir-locals.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 42 |
```org
# -*- fill-column: 100 -*-
#+STARTUP: content
* Changelog
** current master
- Deprecated ~treemacs-window-background-color~ in favour of ~treemacs-window-background-face~ and
~treemacs-hl-line-face~
- Added ~treemacs-copy-absolute-path-at-point~
- Added ~treemacs-start-on-boot~
- Made it possible to disable workspace with a ~COMMENT~ directive
- Added option to sort alphabetic-numerically (as with ~string-version-lessp~)
- Added ~:on-expand~ and ~:on-collapse~ options to treelib nodes
- Added options to define visit-actions in extensions api.
- Added ~treemacs-after-visit-functions~.
- Added option to disable moving files by dragging with your mouse.
- Better performance when ~treemacs-collapse-dirs~ is used for many sub-directories.
** v3.1
- Added ~treemacs-create-workspace-from-project~ command
- Added ~treemacs-project-follow-into-home~ option
- Treemacs can now be resized with the mouse, even when it width is locked
- Added support for directory-specific icons
- Bug fixes
** v3
- Complete rewrite of the extension api
- Added ~treemacs-bulk-file-actions~
- Added support for moving files via mouse drag
- Added ~treemacs-hide-dot-git-directory~
- Added ~treemacs-git-commit-diff-mode~
** v2.10
- Added ~treemacs-width-increment~ and the ability to resize the treemacs window incrementally
- Added ~treemacs-indent-guide-mode~
- Added option to close treemacs when visiting nodes with a double prefix arg
- Added ~treemacs-visit-node-close-treemacs~
- Added ~treemacs-fit-widdow-width~
- Added ~treemacs-extra-wide-toggle~
- Added ~treemacs-next-workspace~
- Added ~treemacs-find-workspace-method~
- Added option for ~treemacs-select-window~ to close treemacs when it is already selected
- Added ~detailed~ option for ~treemacs-eldoc-display~
- Added ~treemacs-select-directory~
- Added option to select workspace when starting/selecting treemacs
- Added ~treemacs-indicate-top-scroll-mode~
- Promoted peeking into a proper minor mode
** v2.9
- Published ~treemacs-all-the-icons~
- Added ~treemacs-workspace-switch-cleanup~
- Added support for disabling the mode line
- Added ~treemacs-user-header-line-format~
- Added ~treemacs-display-current-project-exclusively~
- Added ~treemacs-icon-catalogue~
- Added ~treemacs-read-string-input~
- Split the helpful hydra in 2, so it can fit on smaller screens
- Replaced ~treemacs-select-hook~ with ~treemacs-select-functions~ because it is
now called with treemacs' previous visibility
- Added imenu support
+ Added ~treemacs-imenu-scope~
- Added ~treemacs-copy-relative-path-at-point~
- Added ~treemacs-expand-added-projects~
- Added ~treemacs-window-background-color~
- Added ~treemacs-define-custom-image-icon~
- Added ~treemacs-narrow-to-current-file~
- Added ~treemacs-cleanup-litter~
- Added ~treemacs-expand-after-init~
- Added ~treemacs-width-is-initially-locked~
- Added ~treemacs-hide-gitignored-files-mode~
- Added ~treemacs-select-when-already-in-treemacs~
- Added ~treemacs-text-scale~
- Added option to only show the fringe indicator when the treemacs window is
selected
- Implemented one hand navigation with ~h~ collapsing nodes and ~l~ functioning like ~RET~, ~M-H/L~
is used now for changing root nodes.
- Reduced ~treemacs-file-event-delay~ to 2000ms
- New icons
- Bug Fixes
** v2.8
- Made workspaces lazy-loaded as needed
- Published ~treemacs-persp~
- Added ~treemacs-file-extension-regex~
- Added ~treemacs-directory-name-transformer~
- Added ~treemacs-file-name-transformer~
- Added ~treemacs-move-forward-on-expand~
- Added ~treemacs-user-mode-line-format~
- Many more and better icons.
- Bug fixes
** v2.7
- Suppor for icon themes
- Integration with bookmarks
- Performance improvements
- Changed icon selection to allow icons for specific file names
- New functions to run shell commands for current node or project
- Feature-completion of workspaces api
- New Icons
- Bug Fixes
** v2.6
- Added ~treemacs-add-and-display-current-project~ (both projectile and project.el)
- Added ~treemacs-eldoc-display~
- Added ~treemacs-visit-node-in-most-recently-used-window~
- Added ~treemacs-wrap-around~
- Basic theme support
- Added hooks for selecting, quitting and killing treemacs
- Moved completely to python3, improved python3 detection
- Expansion of and fixes for the extension api
- Split similar command keybinds into common keymaps
- New Icons
- Bug Fixes
** v2.5
- Added ~treemacs-magit~ helper package.
- Added ~treemacs-recenter-after-project-jump~ option.
- Added ~treemacs-recenter-after-project-expand~ option.
- ~recenter-after-x~ can now be set to ~always~ or ~on-distance~.
- Replaced ~treemacs-follow-recenter-distance~ with ~treemacs-recenter-distance~.
- Added ~treemacs-copy-file~ command.
- Added ~treemacs-move-file~ command.
** 2.4
- Add support for using ~org-store-link~ inside treemacs.
- Introduce the ~treemacs-icons-dired~ package.
- Add ability to control workspaces and projects by editing an org-mode file.
- Introduce ~treemacs-collapse-parent-node~.
- Add mouse right-click menu.
- New Icons
- Bug fixes
** 2.3
- Added ~treemacs-single-click-expand-action~ for single leftclick node expansion.
- Added ~deferred~ variant of ~treemacs-git-mode~.
- Added ~treemacs-show-cursor~ to keep the cursor visible.
- Added ~treemacs-display-in-side-window~.
- Added ~treemacs-move-project-up~ and ~-down~ to change the order of projects.
- Added ~treemacs-git-command-pipe~ to append filters to the git status command.
- Added ~treemacs-move-project-up/down~ to change the order of projects.
- Added preliminary version of a rightclick menu.
- Changed ~treemacs-follow-mode~ to run with an idle timer and added ~treemacs-file-follow-delay~
to control the delay.
- Switch to org-mode syntax as persistence format (in preparation for making it editable).
- Started using vscode icons.
- Introduce extension API.
- Bug fixes.
- Performance improvements.
** 2.2
- Reduced minimum required emacs version to 25.2.
- Integrated symlinks with git-mode (symlinks will always be resolved).
- Added ~fringe-indicator-minor-mode~ to make point more visible.
- Made all GUI icons resizable with ~treemacs-resize-icons~.
- Added ~treemacs-space-between-projects~ config option.
- Added ~treemacs-peek~ command.
- Added ~treemacs-next/previous-page-other-window~ commands.
- Bug fixes.
** v2.1
- Add ~treemacs-show-changelog~ command,
- Add ~treemacs-project-follow-cleanup~ option.
- ~default-directory~ will not be set based on the (nearest) path at point.
- New scala and sbt icon.
- Delete files by moving them to the trash by default.
- Much improved file & directory creation interface.
- Add commands to close all/current/other projects.
- Reintroduces free navigation with h & l when there's only 1 project in the workspace.
- ~treemacs-find-file~ can now ask for the file to be found.
- Various bug fixes.
** v2
* Start keeping changelog and retroactively fill it.
* Major refactoring to allow display of multiple projects in a workspace.
* Full removal of functions and variables previously declared obsolete.
* New java icon.
* New kotlin icon.
* New vue.js icon.
* New case-sensitive option for ~treemacs-sorting~.
* Many bugfixes & performance improvements.
** v1.18
- New golang icon.
- Refactor left-click mouse interface to behave like a graphical application would.
- Make TAB & RET particularly configurable.
- Improved imenu-expression for more accurate tags in elisp.
- Introduce smarter recenter with (tag-)follow-mode with ~treemacs-follow-recenter-distance~.
- Bug fixes.
** v1.17
- Added license.
- Bug fixes and internal refactoring.
** V1.16
- Use pulse.el for visual feedback.
- Add ~treemacs-next/previous-line-other-window~.
- Bug fixes.
** v1.15
- New yaml icon.
- Added ~treemacs-recenter-after-tag/file-follow~.
- Added ~treemacs-tag-follow-cleanup~.
- Added ~treemacs-git-mode~.
- Added ~treemacs-bookmark~.
- Bug fixes.
** v1.14
- Added ~treemacs-pre-file-insert-predicates~.
- Added ~treemacs-directory-collapsed-face~.
- Added ~treemacs-pre/post-refresh-hook~.
- Bug fixes.
** v1.13
- Make treemacs buffers unique for every frame.
- Make all icons customizable.
- Make treemacs buffers invisible in the buffer list.
- Bug fixes.
** v1.12
- New hy icon.
- Added ~treemacs-tag-follow-mode~.
- Added ~treemacs-find-tag~.
- Added ~treemacs-resort~.
- Bug fixes.
``` | /content/code_sandbox/Changelog.org | org | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 2,079 |
```org
# -*- fill-column: 120 -*-
* Content :TOC:noexport:
- [[#treemacs-extension-tutorial][Treemacs Extension Tutorial]]
- [[#intro][Intro]]
- [[#setup-basics][Setup Basics]]
- [[#defining-node-types][Defining Node Types]]
- [[#enabling-the-extension][Enabling the Extension]]
- [[#asynchronous-nodes][Asynchronous Nodes]]
- [[#asynchronous-caching-and-updates][Asynchronous Caching and Updates]]
- [[#variadic-nodes-and-non-treemacs-buffers][Variadic Nodes and Non-Treemacs Buffers]]
- [[#monotyped-nodes][Monotyped Nodes]]
- [[#setting-the-default-directory][Setting the Default-Directory]]
- [[#about-properties][About Properties]]
* Treemacs Extension Tutorial
** Intro
The following is a step-by-step guide on how to create extensions for treemacs using its ~treelib~ api. The example
used is a simple view of all existing buffers, except those that are hidden, grouped by their major-mode.
The code in this file is loadable with ~org-babel-load-file~, you can see the results by calling
~showcase-buffer-groups~. (Evaluating the code blocks one by one will not work since lexical scope is required in some
cases)
** Setup Basics
First our basic dependencies:
#+BEGIN_SRC emacs-lisp
;; -*- lexical-binding: t -*-
(require 'dash)
(require 'treemacs)
(require 'treemacs-treelib)
#+END_SRC
Since we are grouping buffers by their major-mode we will need two data sources:
- The list of the major-modes of all current buffers as our entry point
- The list of all buffers for a given major-mode
Both sources are filtered for hidden buffers whose names start with a space.
#+BEGIN_SRC emacs-lisp
(defun treemacs-showcase--buffer-major-modes ()
(->> (buffer-list)
(--reject (string-prefix-p " " (buffer-name it)))
(--map (buffer-local-value 'major-mode it))
(-distinct)))
(defun treemacs-showcase--buffers-by-mode (mode)
(->> (buffer-list)
(--filter (eq mode (buffer-local-value 'major-mode it)))
(--reject (string-prefix-p " " (buffer-name it)))))
#+END_SRC
We will also define a command to open a buffer using RET:
(The ignored argument is the prefix arg; the ~:buffer~ text property will be stored by ourselves)
#+BEGIN_SRC emacs-lisp
(defun treemacs-showcase-RET-buffer-action (&optional _)
(let ((buffer (-some-> (treemacs-current-button)
(treemacs-button-get :buffer))))
(when (buffer-live-p buffer)
(pop-to-buffer buffer))))
#+END_SRC
And another command to visit buffers via the ~treemacs-visit-node-***~ family of commands:
#+BEGIN_SRC emacs-lisp
(defun treemacs-showcase-visit-buffer-action (btn)
(let ((buffer (treemacs-safe-button-get btn :buffer)))
(when (buffer-live-p buffer)
(pop-to-buffer buffer))))
#+END_SRC
** Defining Node Types
Now comes the interesting part, we will use treemacs' api to tell it how we want our new trees to look, how they should
fetch the information they display, and where to put them.
The entry point for an extension is created with ~treemacs-define-entry-node-type~. A detailed explanation and
documentation for every single argument can be found in the eldoc of ~treemacs-do-define-extension-type~, so here we'll
only summarise the most important points:
- ~:label~ is the text next to the icon.
- The ~:key~ of every extension should be semi-unique - it does not need to be unique all on its own, but the "path" of
all the parent nodes' keys leading to a node must serve as a unique identifier for it, otherwise treemacs will not be
able to find the node and operations like updating it will not work. At the end of this example a node identifying a
specific buffer will have a path in the form of ~('showcase-buffers <major-mode-symbol> <buffer-name>)~
- The ~:children~ are what gets displayed when you expand a node of this type. Other than being a list there are no
rules for the structure or content of the items returned here. The nodes we define just need to be able to extract the
information they need from this list (as we'll see in a bit).
- The argument values or not just static. They can contain arbitrary code that will be executed on every access (though
of course it should be kept lean on account of performance). When applicable they will also have implicit access to
the individual ~:children~ being rendered as we'll see in the next example.
#+BEGIN_SRC emacs-lisp
(treemacs-define-entry-node-type showcase-buffers
:label (propertize "Buffers" 'face 'font-lock-keyword-face)
:key 'showcase-buffers
:open-icon (treemacs-get-icon-value 'list)
:closed-icon (treemacs-get-icon-value 'list)
:children (treemacs-showcase--buffer-major-modes)
:child-type 'showcase-buffer-group)
#+END_SRC
We have created our entry point whose ~:children~ will be our buffers' major-modes. We set its ~:child-type~ to be
~showcase-buffer-group~, and that means that we now must create a node type with just that name.
Simple expandable nodes that are neither entry points nor leaves in our tree can be defined with
~treemacs-define-expandable-node-type~.
Here we can see that the individual item, as returned by the previous nodes definition's ~:children~ (in this case the
major mode symbol), is bound as ~item~, so we can use it to extract the information we need. We can save additional
information as text properties in our node with ~:more-properties~ (a plist). We use that to save the exact major-mode
so we can later use it query a buffer-group node's children.
Finally ~:children~ is special in that it has access to 2 parameters:
- The ~item~ being rendered, as returned by its parent's ~:children~ data source
- The ~btn~ for the node at point, as returned by ~treemacs-current-button~
(the value is a text-properties button as it would be created by the builtin button.el library, hence the name)
~:on-expand~ and ~on-collapse~ are optional callbacks that are called at the end of the expand/collapse cycle. They too are
called with ~btn~ as their parameter.
#+BEGIN_SRC emacs-lisp
(treemacs-define-expandable-node-type showcase-buffer-group
:closed-icon "+ "
:open-icon "- "
:label (propertize (symbol-name item) 'face 'font-lock-variable-name-face)
:key item
:children (treemacs-showcase--buffers-by-mode (treemacs-button-get btn :major-mode))
:child-type 'showcase-buffer-leaf
:more-properties `(:major-mode ,item)
:on-expand (message "Expanding node with key %s" (treemacs-button-get btn :key))
:on-collapse (message "Collapsing node with key %s" (treemacs-button-get btn :key)))
#+END_SRC
Finally all that's left is to define the leaves of our tree - the nodes for the individual buffers.
Nothing new is happening here, we merely save the buffers in a text property so the commands to open and visit them that
we have defined above can use that information.
#+BEGIN_SRC emacs-lisp
(treemacs-define-leaf-node-type showcase-buffer-leaf
:icon " "
:label (propertize (or (buffer-name item) "#<killed buffer>")
'face 'font-lock-string-face)
:key item
:more-properties `(:buffer ,item)
:visit-action #'treemacs-showcase-visit-buffer-action
:ret-action #'treemacs-showcase-RET-buffer-action)
#+END_SRC
Killed buffers also need to be taken into account. This is a precaution for when we later turn our buffer extension
asynchronous. The chapter on [[Asynchronous Caching and Updates][async caching]] will explain exactly why this is necessary.
** Enabling the Extension
All that's left now it to tell treemacs to actually use the extension we have created. There are 3 options for where the
it should be placed:
- at the top-level, the same level as your projects
- under a project
- under a directory
We can also decide whether our extension goes at the top or the bottom of its location.
The latter two options may also accept a ~:predicate~ argument, so it is possible to determine exactly which projects
and directories an extension will be used for.
For our example we will place the extension as the first item under the first project in the workspace:
#+BEGIN_SRC emacs-lisp
(treemacs-enable-project-extension
:extension 'showcase-buffers
:position 'top
:predicate (lambda (project) (eq project (car (treemacs-workspace->projects (treemacs-current-workspace))))))
#+END_SRC
The argument passed to ~:extension~ must be the same symbol that was used for ~treemacs-define-entry-node-type~.
** Asynchronous Nodes
Treemacs also supports nodes that fetch their content from an asynchronous source like a language server.
For our simple example we will re-use the buffer code from above and use timers to fake asynchronicity.
Most of the code is the same, there are only 2 differences:
- async nodes must set the ~:async~ flag to a non-nil value
- ~:children~ is different in that it receives a third argument: a ~callback~ function that must be called with the
produced items once they are available
#+BEGIN_SRC emacs-lisp
(treemacs-define-entry-node-type showcase-async-buffers
:key 'showcase-buffers-async
:label (propertize"Async Buffers" 'face 'font-lock-keyword-face)
:open-icon (treemacs-get-icon-value 'list)
:closed-icon (treemacs-get-icon-value 'list)
:children
(let ((items (treemacs-showcase--buffer-major-modes)))
(run-with-timer
(1+ (random 3)) nil
(lambda () (funcall callback items))))
:child-type 'showcase-async-buffer-group
:async? t)
#+END_SRC
Leaves have no asynchronous parts, so the previous definition can be re-used directly.
#+BEGIN_SRC emacs-lisp
(treemacs-define-expandable-node-type showcase-async-buffer-group
:closed-icon "+ "
:open-icon "- "
:label (propertize (symbol-name item) 'face 'font-lock-variable-name-face)
:key item
:children
(let ((items (treemacs-showcase--buffers-by-mode (treemacs-button-get btn :major-mode))))
(run-with-timer
(1+ (random 3)) nil
(lambda () (funcall callback items))))
:child-type 'showcase-buffer-leaf
:more-properties `(:major-mode ,item)
:async? t)
#+END_SRC
We'll enable the asynchronous extension at the bottom of first project in treemacs:
#+BEGIN_SRC emacs-lisp
(treemacs-enable-project-extension
:extension 'showcase-async-buffers
:predicate (lambda (project) (eq project (car (treemacs-workspace->projects (treemacs-current-workspace)))))
:position 'bottom)
#+END_SRC
The next time you update your first project both extensions will be there, restarting treemacs is /not/ necessary.
** Asynchronous Caching and Updates
*** Why a Cache Is Needed
When you try out this async extension you will notice that the first time a node is expanded treemacs adds a /Loading.../
annotation, and the node is only expanded after the 1-3 second delay we have introduced. However every subsequent
expansion happens instantly, though sometimes buffers may appear or disappear, or their order changes.
The reason for this behaviour is that all results of asynchronous calls are cached in treemacs, and then re-used for
instant updates. This setup is necessary to ensure a smooth experience in the treemacs UI. Imagine what an update would
look like without this cache. The basic update procedure in treemacs is the same process as hitting TAB twice - close
the node and open it again (this does not apply to ~filewatch-mode~ and ~git-mode~, which are both capable of making only
the necessary changes).
All this is not visible to the user, all you see is an instant change. This would not be the case for asynchronous
nodes. Even if the delay in a real use-case can be measured in milliseconds, you would still see your tree collapse,
then add the /Loading.../ annotation, then it would open, then all its previously open subtrees would only open after the
same delay, and so on. In addition to that if your point was somewhere in the updated tree it would be moved around,
which would be quite annoying if the update happened automatically.
*** The 2-Step Update Process
The async cache prevents all that from happening. A real update, fetching new information, does happen, but it happens
in the background. Whenever an async node is expanded the cache for the entire subtree is refreshed. Once that is done a
second update is run using the /new/ cache.
That is why you sometimes see buffers (dis)appear, or their order change (we don't do any sorting). That is also why we
previously needed to ensure that we can explicitly label killed buffers (since calling ~buffer-name~ on a killed buffer
throws an error). The initial refresh uses a potentially stale cache. Buffers that were shown once may since have been
deleted. They'll be removed from the view the next time we take a real look at the ~buffer-list~, but in the meantime
we'll have to show a stopgap ~#<killed buffer>~ entry.
*** Programmatic Updates
Using ~treemacs-update-node~ will iniate this 2-step update process. If you want to avoid that and directly run just the
background update part you can use ~treemacs-update-async-node~ instead.
** Variadic Nodes and Non-Treemacs Buffers
Treemacs' extensions do not have to be used exclusively within treemacs itself, they may also be put into their own
buffers. When doing so it might be useful for an extension to produce multiple top-level nodes from the start, instead
of having one single entry point, like the ~Buffers~ node from the first example.
Treemacs calls this concept ~variadic~ nodes. The following example will demonsrate how to set up such a variadic
extension that will produce major-mode buffer group nodes at the top level, and how display this extension in its own
side window.
Most of the code from above can be re-used, we just need a new entry point, which we create with
~treemacs-define-variadic-entry-node-type~. The setup is a subset of ~treemacs-define-entry-node-type~ - we are effectively
creating an invisible entry point that is always extended, so it needs only a small subset of the usual information. Of
particular note is the ~key~ which allows us the update all nodes created by this variadic entry in one go.
#+BEGIN_SRC emacs-lisp
(treemacs-define-variadic-entry-node-type showcase-buffers-variadic
:key 'showcase-buffers-variadic
:children (->> (buffer-list)
(--reject (string-prefix-p " " (buffer-name it)))
(--map (buffer-local-value 'major-mode it))
(-distinct))
:child-type 'showcase-buffer-group)
#+END_SRC
That's it. Now we just need to define an interactive command that will display our buffers for us:
#+BEGIN_SRC emacs-lisp
(defun showcase-buffer-groups ()
(interactive)
(let ((bufname "*Showcase Buffers*"))
(--when-let (get-buffer bufname) (kill-buffer it))
(let ((buf (get-buffer-create bufname)))
(pop-to-buffer buf)
(treemacs-initialize showcase-buffers-variadic
:with-expand-depth 'all
:and-do (setf treemacs-space-between-root-nodes t)))))
#+END_SRC
~treemacs-initialize~ must be called for the buffer to be used by treemacs. It can optionally accept two keyword
arguments:
- ~:with-expand-depth~ :: Indicates the extra depth that this extension should be expanded with. Can be either a number or
a symbol like ~'all~ to expand everything.
- ~:and-do~ :: General purpose form for code that should run as part of your setup, like setting buffer-local values
(which could otherwise be overridden when initialisation enabled ~treemacs-mode~)
** Monotyped Nodes
Defining every node type individually is not necessary, it is possible to make do with a single definition. Some
verbosity will remain because now it is necessary to dispatch (at a high enough scale, probably thousands of items, it
might even impact performance), but it can still be worth it if the number of node types for your use-case is
exceptionally high.
Treemacs calls this the ~monotyped~ approach to defining extensions.
In this example we combine both the buffer groups and individual buffer leaves into a single definition.
(Note how the name of the extension and the ~:child-type~ are one and the same)
#+BEGIN_SRC emacs-lisp
(treemacs-define-expandable-node-type showcase-monotype-buffers
:closed-icon
(if (bufferp item)
" "
"+ ")
:open-icon
(if (bufferp item)
""
"- ")
:label
(if (bufferp item)
(propertize (buffer-name item) 'face 'font-lock-string-face)
(propertize (symbol-name item) 'face 'font-lock-variable-name-face))
:key
(if (bufferp item)
(buffer-name item)
item)
:children
(when (symbolp item)
(treemacs-showcase--buffers-by-mode item))
:child-type
'showcase-monotype-buffers
:more-properties
(if (bufferp item)
`(:buffer ,item :leaf t)
`(:major-mode ,item)))
#+END_SRC
Note that a non-nil ~:leaf~ property must be placed manually via ~:more-properties~, since without a distinct node state
this is the only way for treemacs to know that the node is a leaf and cannot be expanded.
Entry points cannot be combined, they still need to be set up individually:
#+BEGIN_SRC emacs-lisp
(treemacs-define-entry-node-type showcase-buffers-monotype-entry
:key 'showcase-buffers-monotype-entry
:label (propertize "Monotype Buffers" 'face 'font-lock-keyword-face)
:open-icon (treemacs-get-icon-value 'list)
:closed-icon (treemacs-get-icon-value 'list)
:children (treemacs-showcase--buffer-major-modes)
:more-properties nil
:child-type 'showcase-monotype-buffers)
#+END_SRC
Finally we'll enable the new extension to appear in our first project:
#+BEGIN_SRC emacs-lisp
(treemacs-enable-project-extension
:extension 'showcase-buffers-monotype-entry
:predicate (lambda (project) (eq project (car (treemacs-workspace->projects (treemacs-current-workspace)))))
:position 'top)
#+END_SRC
** Setting the Default-Directory
Treemacs sets the value of ~default-directory~ based on the nearest path at point. This allows commands like ~find-file~
and ~magit-status~ to do what you mean based on the current context. This option is also available for custom nodes:
just set the property ~:default-directory~ and treemacs will make use of its value when the node is in focus.
** About Properties
The following property names are already in use by treemacs and should *not* be used in extensions' ~:more-properties~
parameter:
- ~:project~
- ~:state~
- ~:depth~
- ~:path~
- ~:key~
- ~:item~
- ~:no-git~
- ~:parent~
- ~:default-face~
- ~:symlink~
- ~:marker~
- ~:leaf~
- ~:index~
- ~:busy~
- ~:custom~
- ~'button~
- ~'category~
- ~'face~
- ~'keymap~
``` | /content/code_sandbox/Extensions.org | org | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 4,510 |
```org
# -*- fill-column: 120 org-list-indent-offset: 1 toc-org-max-depth: 2 org-hide-emphasis-markers: nil -*-
#+STARTUP: noinlineimages
[[path_to_url
[[path_to_url#/treemacs][file:path_to_url
[[path_to_url#/treemacs][file:path_to_url
* Treemacs - a tree layout file explorer for Emacs :noexport:
[[file:screenshots/screenshot.png]]
* Content :TOC:noexport:
- [[#state-of-development][State of Development]]
- [[#quick-feature-overview][Quick Feature Overview]]
- [[#fancy-gifs][Fancy Gifs!]]
- [[#quick-start][Quick Start]]
- [[#detailed-feature-list][Detailed Feature List]]
- [[#projects-and-workspaces][Projects and Workspaces]]
- [[#conveniently-editing-your-projects-and-workspaces][Conveniently Editing Your Projects and Workspaces]]
- [[#navigation-without-projects-and-workspaces][Navigation without Projects and Workspaces]]
- [[#frame-locality][Frame Locality]]
- [[#mouse-interface][Mouse Interface]]
- [[#follow-mode][Follow-mode]]
- [[#tag-follow-mode][Tag-follow-mode]]
- [[#fringe-indicator-mode][Fringe-indicator-mode]]
- [[#git-mode][Git-mode]]
- [[#filewatch-mode][Filewatch-mode]]
- [[#file-management][File Management]]
- [[#indent-guide-mode][Indent-guide-mode]]
- [[#git-commit-diff-mode][Git-commit-diff-mode]]
- [[#session-persistence][Session Persistence]]
- [[#terminal-compatibility][Terminal Compatibility]]
- [[#tag-view][Tag View]]
- [[#current-directory-awareness][Current-Directory Awareness]]
- [[#tramp-support][Tramp Support]]
- [[#org-support][Org Support]]
- [[#theme-support][Theme Support]]
- [[#peeking][Peeking]]
- [[#additional-packages][Additional Packages]]
- [[#treemacs-as-a-framework][Treemacs as a Framework]]
- [[#installation][Installation]]
- [[#configuration][Configuration]]
- [[#variables][Variables]]
- [[#faces][Faces]]
- [[#evil-compatibility][Evil compatibility]]
- [[#customizing-themes-and-icons][Customizing Themes and Icons]]
- [[#keymap][Keymap]]
- [[#unbound-functions][Unbound functions]]
- [[#default-keymaps][Default keymaps]]
- [[#compatibility][Compatibility]]
- [[#faq][FAQ]]
- [[#contributing][Contributing]]
- [[#working-with-the-code-base][Working With The Code Base]]
- [[#dependencies][Dependencies]]
* State of Development
Treemacs is currently in an active - but low intensity - state of development. New features are worked on, PRs will be
looked at and issues answered - eventually. My time budget is limited, so looking for new work just means looking at
whatever is currently at the top of my inbox. If you feel like the ticket you've opened has gone unanswered for a while
feel free to give it a bump - you are explicitly encouraged to do so.
* Quick Feature Overview
Treemacs is a file and project explorer similar to NeoTree or vim's NerdTree, but largely inspired by the Project
Explorer in Eclipse. It shows the file system outlines of your projects in a simple tree layout allowing quick
navigation and exploration, while also possessing *basic* file management utilities. Specifically a quick feature
overview looks as follows:
* Project management :: Treemacs lets you view multiple file trees - projects - at once and quickly add or remove them,
and groups projects in workspaces.
* Easy navigation :: quickly move between projects or use shortcuts to jump to parent or neighbouring nodes.
* Versatile file access :: decide exactly how and where a file will be opened, including using ~ace-window~ to choose
a window or launching an external application.
* Understanding of frames :: every frame will receive its own treemacs buffer that will live and die with that frame.
* Finding of files and tags :: Treemacs can follow along and keep in focus the currently selected file or even the tag
at point, either manually or automatically using either ~treemacs-follow-mode~ or ~treemacs-tag-follow-mode~.
* Git Integration :: Treemacs can use different faces for files and directories based on their git status.
The git process is run asynchronously, minimizing its performance impact.
* [[path_to_url & [[path_to_url compatibility :: The presence of treemacs will not interfere with winum's and ace-window's
usual layouts.
* [[path_to_url integration :: the ~treemacs-projectile~ package lets you quickly add your projectile projects
to the treemacs workspace. ~project.el~ compatibility is built-in.
* Simple mouse interface :: Left clicks will work the same as you're used to from with graphical applications
* Session persistence :: Treemacs automatically saves and restores your workspaces.
* Dashing good looks :: Treemacs uses (optionally resizable) png images in HD 22x22 resolution for its icons. When run
in a terminal a simple fallback is used.
* Tag view :: Treemacs can display files' tags. All file types that Emacs can generate a (semantic) imenu index for are
supported.
* Visual feedback :: When it would otherwise be difficult to see the message in the minibuffer success/failure is
indicated with pulse.el.
* Theming support :: Treemacs supports using multiple icon themes that can be changed at will.
* Ease of use :: Treemacs offers many configuration options, but comes with a set of (what hopefully should be) sane
defaults. Installation aside there are two obligatory pieces of setup: 1) Choosing convenient keybindings to run
treemacs and 2) If you use evil: requiring ~treemacs-evil~ to integrate treemacs with evil and enable j/k navigation.
More on both below. You can also summon helpful hydras with ~?~ and ~C-?~ that will remind you of treemacs' many
keybindings and features.
* Bookmark integration :: Running ~bookmark-set~ on a Treemacs item will store a bookmark to Treemacs buffer for that item.
** Fancy Gifs!
(The font used in the gifs is Fantasque Sans Mono)
Various ways to open files:
[[file:screenshots/open-files.gif]]
Workspace administration with org-mode:
[[file:screenshots/workspace-edit.gif]]
Automatic reaction to changes in the file system:
[[file:screenshots/filewatch.gif]]
Automatic reaction to changes in git:
[[file:screenshots/git.gif]]
Full-featured mouse interface:
[[file:screenshots/mouse-interface.gif]]
Including moving and opening files via mouse drag:
[[file:screenshots/mouse-drag.gif]]
Resizable icons:
[[file:screenshots/icon-resize.gif]]
* Quick Start
If you don't care about reading the full readme here's a list of some bare bones basics to get you started:
* First of all: press ~?~ to summon the helpful hydra:
[[file:screenshots/hydra.png]]
* If you use evil don't forget to also install ~treemacs-evil~
* If you use projectile you can install ~treemacs-projectile~ to allow quickly add your projectile projects to
treemacs.
* Treemacs doesn't bind any global keys, you need to use whatever fits you best. A full install setup can be found
[[#installation][below]]. Otherwise just add a keybind for ~treemacs~.
* For navigation use n/p (j/k when evil), M-n/M-p to move to same-height neighbour, u to go to parent, and C-j/C-k to
move between projects.
* There's half a dozen different ways to open nodes, all bound under o as prefix. Pick your favourite.
* TAB and RET are particularly configurable. See ~treemacs-TAB/RET-actions-config~.
* Projects administration is bound under the ~C-c C-p~ prefix.
* Detailed Feature List
** Projects and Workspaces
If you've previously used a different explorer like NeoTree or NerdTree - or an earlier version of treemacs for that
matter - you are probably used to a display system wherein you see exactly a single file tree whose exact root you can
arbitrarily change. This system makes it difficult to work on and switch between multiple projects. Treemacs used to
(and still does) remedy that limitation by making every treemacs buffer unique to its frame, but it has now been
redesigned to be able to display multiple file trees - projects - at once.
In treemacs a workspace is simply a (named) collection of projects, while a project mostly consists of 2 things: its
location in the file system and its name. This is the info that you need to provide when you want to add a new project
to your workspace. Just like projects you can add, remove, rename and switch between workspaces at any time.
This design approach has various advantages and disadvantages. It is now no longer possible to "free roam" in the file
system with treemacs, i.e. you can no longer arbitrarily switch the single file tree's root to the directory at point or
the current root's parent. Another restriction is that the same part of the file system may not appear more than once as
part of the workspace. For example, it is not possible to have both /Documents and /Documents/ProjectX as projects in the
same workspace, since internally treemacs heavily relies on every node having a unique natural key in its absolute path.
Nonetheless the pros certainly outweigh the cons, as a multiroot setup allows to work on multiple projects with any
combination concern/buffer separating frameworks, be it persp/perspective, eyebrowse, tab-bar-mode, or
project.el/projectile. It also opens the potential for concurrent display not only of the file system, but e.g. the
currently open buffers.
*** Workspace Selection
When a workspace is first needed, treemacs will select a workspace in the following manner:
If the current buffer is editing a file then treemacs will try to find the first workspace with a project containing
that file. If that fails treemacs will resort to using the /fallback workspace/ which is defined as simply the /first/
element in the list of all workspace.
The order of workspaces is the same that you see when calling ~treemacs-edit-workspaces~ (see next chapter). You can
interactively set the fallback workspace by calling ~treemacs-set-fallback-workspace~.
This selection will happen when treemacs is first started (with a command like ~treemacs-select-window~) or when a
function that requires the current workspace to be known is used (like adding or removing a project).
*** Disabling workspaces & projects
It is possible to disable a workspace or project so it won't appear in treemacs, but still remains a part of your
loadout, keeping it visible when you go edit your workspaces. To do so simply start the name of the workspace or project
with "COMMENT":
[[file:screenshots/disable-project.png]]
** Conveniently Editing Your Projects and Workspaces
There are two ways to edit your projects and workspaces: call up single add/remove/rename/switch commands under either
the ~C-c C-p~ or ~C-c C-w~ prefix, or call ~treemacs-edit-workspaces~ and edit your entire layout in the form of a
single org-mode buffer.
The used org-format is quite simple: level 1 headlines are names of workspaces, level 2 headlines are names of projects
in a workspace, and every project's path is given as a description list, starting with a ~-~ (and an optional leading
space). Empty lines and lines starting with ~#~ are ignored, and everything else leads to an error.
You needn't worry about making mistakes either. If there's something wrong when you call ~treemacs-finish-edit~
(C-c C-c) then treemacs will point you at the incorrect line and tell you what's missing:
[[file:screenshots/workspace-edit.png]]
(Note that the list with the path property allows an indentation of 0 or 1 spaces only. The much greater visible
indentation is caused by ~org-indent-mode~)
** Navigation without Projects and Workspaces
If a strict workspace and project structure, as described above, is too stringent for your use-case there are multiple
other ways to use treemacs in a more "free-form" style:
- You can use ~treemacs-display-current-project-exclusively~ to display only the current project (removing all other
projects from the workspace).
- You can enable ~treemacs-project-follow-mode~ to make treemacs automatically switch to the project for the current
buffer.
- As long as there is exactly /a single project/ in your workspace you can also use ~M-H~ and ~M-L~ (or
~treemacs-root-up~ and ~treemacs-root-down~) to arbitrarily change the project's root and freely navigate through
your your file system, similar to dired. ~M-H~ will navigate one level upward in the file system, ~M-L~ will move into
the directory at point.
** Frame Locality
Treemacs buffers have a limited scope they are visible in: the frames they are created in. A treemacs buffer, once
created, lives alongside and inside its frame, and is also destroyed with that frame. Calling ~treemacs~ while inside a
new frame will create a new buffer for it, regardless how many other treemacs buffers already exist. While there can be
multiple unique treemacs buffer they will all still show the same workspace and the same projects.
A treemacs buffer that does not belong to a frame may still be made visible by manually selecting in the buffer list.
This would break various assumptions in treemacs' code base and effectively falls under undefined behaviour - a bad idea
all around.
** Mouse Interface
Treemacs handles left clicks in much the same way as modern graphical applications do: a single click sets the focus, a
double click expands or collapses a directory or tag section node and visits a file/moves to a tag for a file/tag node.
Additionally tag sections can be expanded or collapsed by a single click on the file/tag section icon.
If you prefer to expand/collapse nodes with a single mouse click you can also use ~treemacs-single-click-expand-action~:
#+BEGIN_SRC emacs-lisp
(with-eval-after-load 'treemacs
(define-key treemacs-mode-map [mouse-1] #'treemacs-single-click-expand-action))
#+END_SRC
A right click popup-menu is also available:
[[file:screenshots/right-click.png]]
You can move and open files by dragging them with the mouse.
** Follow-mode
~treemacs-follow-mode~ is a global minor mode which allows the treemacs view to always move its focus to the currently
selected file. This mode runs on an idle timer - the exact duration of inactivity (in seconds) before a move is called
is determined by ~treemacs-tag-follow-delay~.
** Tag-follow-mode
~treemacs-tag-follow-mode~ is a global minor mode which extends and effectively replaces ~treemacs-follow-mode~. When
activated it follows not just the current file, but also the current tag. This works alongside treemacs' integration
with imenu, so all file types providing an imenu implementation are compatible.
This mode, like follow-mode, runs on an idle timer - the exact duration of inactivity (in seconds) before a move is
called is determined by ~treemacs-tag-follow-delay~.
Note that in order to move to a tag in treemacs the treemacs buffer's window needs to be temporarily selected, which
will reset ~blink-cursor-mode~'s timer if it is enabled. This will result in the cursor blinking seemingly pausing for a
short time and giving the appearance of the tag follow action lasting much longer than it really does.
** Fringe-indicator-mode
~treemacs-fringe-indicator-mode~ is a global minor mode that displays a little icon in the fringe that moves with the
cursor. It can make the selected line more visible if ~hl-line-mode~ doesn't stand out with your theme.
The indicator can either be permanently visible, or be only shown when the treemacs window is selected by calling it
either with the ~always~ or ~only-when-focused~ argument.
** Git-mode
~treemacs-git-mode~ is a global minor mode which enables treemacs to check for files' and directories' git status
information and highlight them accordingly (see also the ~treemacs-git-...~ faces). The mode is available in 3 variants:
~simple~, ~extended~ and ~deferred~:
* The simple variant starts a git status process and parses its output in elisp. The parsing is kept quick and simple,
so some info is missed: this version includes git status information only for files, but not directories.
* The extended variant highlights both files and directories. This greatly increases the complexity and length of the
parsing process, and is therefore done in an asynchronous python process for the sake of performance. The extended
variant requires python3 to work.
* The deferred variant is the same as extended, except the tasks of rendering nodes and highlighting them are
separated. The former happens immediately, the latter after ~treemacs-deferred-git-apply-delay~ seconds of idle time.
This may be faster (if not in truth then at least in appereance) as the git process is given a much greater amount of
time to finish. The downside is that the effect of nodes changing their colors may be somewhat jarring, though this
effect is largely mitigated due to the use of a caching layer.
When called interactively ~treemacs-git-mode~ will ask for the variant to use. In lisp code an appropriate symbol can
be directly passed to the minor mode function:
#+BEGIN_SRC emacs-lisp
(treemacs-git-mode 'deferred)
#+END_SRC
All versions use an asynchronous git process and are optimized to not do more work than necessary, so their performance
cost should, for the most part, be the constant amount of time it takes to fork a subprocess. For repositories where
this is not the case ~treemacs-max-git-entries~ (default value 5000) will limit the number of git status entries
treemacs will process before ignoring the rest.
** Filewatch-mode
~treemacs-filewatch-mode~ is a global minor mode which enables treemacs to watch the files it is displaying for changes
and automatically refresh itself when it detects a change in the file system that it decides is relevant.
A change event is relevant for treemacs if a new file has been created or deleted or a file has been changed and
~treemacs-git-mode~ is enabled. Events caused by files that are ignored as per ~treemacs-ignored-file-predicates~ are
likewise counted as not relevant.
The refresh is not called immediately after an event was received, treemacs instead waits ~treemacs-file-event-delay~ ms
to see if any more files have changed to avoid having to refresh multiple times over a short period of time. Treemacs
will not refresh the entire view to make the detected changes visible, but will instead only make updates to the
directories where the change(s) happened. Using this mode is therefore by far not as expensive as a full refresh on
every change and save.
The mode only applies to directories opened *after* this mode has been activated. This means that to enable file
watching in an already existing treemacs buffer it needs to be killed and rebuilt. Turning off this mode is, on the
other hand, instantaneous - it will immediately turn off all existing file watch processes and outstanding refresh
actions.
_Known limitations_:
- Staging and committing changes does not produce any file change events of its own, if you use ~treemacs-git-mode~ you
still need to do a manual refresh to see your files' faces go from 'changed' and 'untracked' to 'unchanged' after a
commit. The ~treemacs-magit~ package provides the necessary hooks to fill this gap.
- Filewatch-mode may not be able to track file modifications on MacOS, making git-mode miss potential changes, see also
[[path_to_url#issuecomment-941093929][this comment]].
** File Management
Treemacs is no dired, but it supports the basic file management facilities of creating, deleting, moving, copying and
renaming files.
It is also possible to mark multiple files to act on them. ~M-m~ will summon a hydra for bulk file actions. *NOTE:* The
bulk action implementation is using treemacs' (yet to be documented) annotation api, which is set up to provide
/permanent/ annotations like colouring based on flycheck's error/warning/info output. This means that marking files will
likewise be permanent, even if you collapse the directories containing those files and they are no longer visible.
** Indent-guide-mode
~treemacs-indent-guide-mode~ is a simple visual helper based on the options provided by the ~treemacs-indentation~
and ~treemacs-indentation-string~ settings. Its appearance is dictated by ~treemacs-indent-guide-style~, the options are
either ~line~:
[[file:screenshots/indent-guide-line.png]]
or ~block~:
[[file:screenshots/indent-guide-block.png]]
** Git-commit-diff-mode
~treemacs-git-commit-diff-mode~ will annotate git-tracked project to show how many commits the local repo
is ahead or behind its remote counterpart:
[[file:screenshots/git-commit-diff.png]]
** Session Persistence
Treemacs' sessions - your workspace and the projects it contains - are saved when Emacs shuts down and restored when
treemacs is first loaded. This persistence process is fully automatic and independent, and should therefore be fully
compatible with ~desktop-save-mode~.
The persisted state is saved under ~user-emacs-directory/.cache/treemacs-persist~ by default. The exact file location
is saved in the variable ~treemacs-persist-file~.
If something goes wrong when loading the file the erroneous state will be saved in ~treemacs-last-error-persist-file~
for debugging.
** Terminal Compatibility
When run in a terminal treemacs will fall back to a much simpler rendering system, foregoing its usual png icons and
using simple ~+~ and ~-~ characters instead. The exact characters used are [[#custom-icons][highly customizable]].
** Tag View
Treemacs is able to display not only the file system, but also tags found in individual files. The tags list is sourced
using emacs' builtin imenu functionality, so all file types that emacs can generate an imenu index for are supported.
Imenu caches its result, so to avoid stale tag lists setting ~imenu-auto-rescan~ to t is recommended. Tags generated
with the help of ~semantic-mode~ are likewise supported.
*** ggtags
Treemacs can show the tags produced by ggtags if you switch a buffer's imenu index function to use ggtags:
#+BEGIN_SRC emacs-lisp
(setq-local imenu-create-index-function #'ggtags-build-imenu-index)
#+END_SRC
** Current-Directory Awareness
Treemacs always sets the ~default-directory~ variable based on the (nearest) path at the current node, falling back to
your home directory when there is no node or path at point. That means that various commands like ~find-file~, ~ediff~
~magit-status~ or ~helm-projectile-ag~ will correctly act based on the current directory or project context.
** Tramp Support
Treemacs supports projects on remote directories, e.g. ~/scp:remote-server:path/to/directory~.
However tramp support has some restrictions: ~treemacs-use-collapsed-directories~ has no effect on remote directories.
** Org Support
Treemacs supports storing links to its file nodes by means of ~org-store-link~.
** Theme Support
Using a different treemacs theme works the same way as using a different Emacs theme: just call ~treemacs-load-theme~,
either programmatically or interactively. In the former case you need to supply the name of the theme as a string, like
this:
#+BEGIN_SRC emacs-lisp
(treemacs-load-theme "Default")
#+END_SRC
Do keep in mind that by default treemacs' theme support is all theory: the standard installation includes only the
default theme; this feature is meant to easily allow *others* to extend, create and distribute themes for treemacs.
A detailed explanation on modifying themes and icons can be found in the [[#customizing-themes-and-icons][Configuration]] section.
** Peeking
If you want to look at files from within treemacs, without opening them with ~RET~ and switching to another window, you
can do so with ~P~ which activates ~treemacs-peek-mode~. When peek-mode is active treemacs will automatically preview the
file at point.
To quit peek-mode either press ~P~ again to disable it or open a file with ~RET~. Either way upon exiting peek-mode all
files that have been opened due to peeking will be closed again (with the exception of the one that you opened with ~RET~,
of course).
You can scroll the window being peeked (and in general ~other-window~ when you are in treemacs) with ~M-N/P~ or ~M-J/K~ if you
use ~treemacs-evil~.
** Additional Packages
Next to treemacs itself you can optionally install:
*** treemacs-evil
Must be installed and loaded if you use evil. The keybindings and the cursor will not be setup properly otherwise. It'll
also enable navigation with j/k instead of n/p.
*** treemacs-projectile
Allows to quickly add your projectile projects to the treemacs workspace.
*** treemacs-magit
A small utility package to fill the small gaps left by using filewatch-mode and git-mode in conjunction with magit: it
will inform treemacs about (un)staging of files and commits happening in magit.
*** treemacs-icons-dired
Allows you to use treemacs icons in dired buffers with ~treemacs-icons-dired-mode~:
[[file:screenshots/dired-icons.png]]
*** treemacs-persp/treemacs-perspective
Integration with persp-mode or perspective.el that allows treemacs buffers to be unique inside the active perspective
instead of the default frame-based buffer scope.
*** treemacs-tab-bar
Integration with tab-bar-mode that allows treemacs buffers to be unique inside the active tab
instead of the default frame-based buffer scope.
*** treemacs-all-the-icons
Provides a theme using [[path_to_url
** Treemacs as a Framework
Treemacs can be extended to display arbitrary nodes as well as be used as a general rendering backend for any tree-like
structures. [[file:Extensions.org][See here]] for an extended tutorial and demonstration.
* Installation
Treemacs is included in Spacemacs (for now only on the dev branch). If you are using the development version of
Spacemacs you can simply add treemacs to ~dotspacemacs-configuration-layers~ to replace the default NeoTree. Check ~SPC
h SPC treemacs~ for details. Otherwise you will need to add treemacs to ~dotspacemacs-additional-packages~.
Treemacs is also available on MELPA. If you just want to quickly start using it grab the ~use-package~ example below,
and customize it as needed (remove ~treemacs-evil~ if you don't use it, customize the keybindings to you taste, etc).
Either way keep in mind that treemacs has /no default keybindings/ for its globally callable initialization functions. Each
user is supposed to select keybindings for functions like ~treemacs-find-file~ based on whatever they find convenient.
You can find an exhaustive overview of all functions, their keybindings and functions you need to bind yourself [[#keymap][below]].
The following ~use-package~ snippet includes a list of /all/ of treemacs' configuration options in their default
setting. Setting them, or activating the minor modes yourself is not necessary, they are only listed here to encourage
discoverability.
#+BEGIN_SRC emacs-lisp
(use-package treemacs
:ensure t
:defer t
:init
(with-eval-after-load 'winum
(define-key winum-keymap (kbd "M-0") #'treemacs-select-window))
:config
(progn
(setq treemacs-collapse-dirs (if treemacs-python-executable 3 0)
treemacs-deferred-git-apply-delay 0.5
treemacs-directory-name-transformer #'identity
treemacs-display-in-side-window t
treemacs-eldoc-display 'simple
treemacs-file-event-delay 2000
treemacs-file-extension-regex treemacs-last-period-regex-value
treemacs-file-follow-delay 0.2
treemacs-file-name-transformer #'identity
treemacs-follow-after-init t
treemacs-expand-after-init t
treemacs-find-workspace-method 'find-for-file-or-pick-first
treemacs-git-command-pipe ""
treemacs-goto-tag-strategy 'refetch-index
treemacs-header-scroll-indicators '(nil . "^^^^^^")
treemacs-hide-dot-git-directory t
treemacs-indentation 2
treemacs-indentation-string " "
treemacs-is-never-other-window nil
treemacs-max-git-entries 5000
treemacs-missing-project-action 'ask
treemacs-move-files-by-mouse-dragging t
treemacs-move-forward-on-expand nil
treemacs-no-png-images nil
treemacs-no-delete-other-windows t
treemacs-project-follow-cleanup nil
treemacs-persist-file (expand-file-name ".cache/treemacs-persist" user-emacs-directory)
treemacs-position 'left
treemacs-read-string-input 'from-child-frame
treemacs-recenter-distance 0.1
treemacs-recenter-after-file-follow nil
treemacs-recenter-after-tag-follow nil
treemacs-recenter-after-project-jump 'always
treemacs-recenter-after-project-expand 'on-distance
treemacs-litter-directories '("/node_modules" "/.venv" "/.cask")
treemacs-project-follow-into-home nil
treemacs-show-cursor nil
treemacs-show-hidden-files t
treemacs-silent-filewatch nil
treemacs-silent-refresh nil
treemacs-sorting 'alphabetic-asc
treemacs-select-when-already-in-treemacs 'move-back
treemacs-space-between-root-nodes t
treemacs-tag-follow-cleanup t
treemacs-tag-follow-delay 1.5
treemacs-text-scale nil
treemacs-user-mode-line-format nil
treemacs-user-header-line-format nil
treemacs-wide-toggle-width 70
treemacs-width 35
treemacs-width-increment 1
treemacs-width-is-initially-locked t
treemacs-workspace-switch-cleanup nil)
;; The default width and height of the icons is 22 pixels. If you are
;; using a Hi-DPI display, uncomment this to double the icon size.
;;(treemacs-resize-icons 44)
(treemacs-follow-mode t)
(treemacs-filewatch-mode t)
(treemacs-fringe-indicator-mode 'always)
(when treemacs-python-executable
(treemacs-git-commit-diff-mode t))
(pcase (cons (not (null (executable-find "git")))
(not (null treemacs-python-executable)))
(`(t . t)
(treemacs-git-mode 'deferred))
(`(t . _)
(treemacs-git-mode 'simple)))
(treemacs-hide-gitignored-files-mode nil))
:bind
(:map global-map
("M-0" . treemacs-select-window)
("C-x t 1" . treemacs-delete-other-windows)
("C-x t t" . treemacs)
("C-x t d" . treemacs-select-directory)
("C-x t B" . treemacs-bookmark)
("C-x t C-t" . treemacs-find-file)
("C-x t M-t" . treemacs-find-tag)))
(use-package treemacs-evil
:after (treemacs evil)
:ensure t)
(use-package treemacs-projectile
:after (treemacs projectile)
:ensure t)
(use-package treemacs-icons-dired
:hook (dired-mode . treemacs-icons-dired-enable-once)
:ensure t)
(use-package treemacs-magit
:after (treemacs magit)
:ensure t)
(use-package treemacs-persp ;;treemacs-perspective if you use perspective.el vs. persp-mode
:after (treemacs persp-mode) ;;or perspective vs. persp-mode
:ensure t
:config (treemacs-set-scope-type 'Perspectives))
(use-package treemacs-tab-bar ;;treemacs-tab-bar if you use tab-bar-mode
:after (treemacs)
:ensure t
:config (treemacs-set-scope-type 'Tabs))
(treemacs-start-on-boot)
#+END_SRC
* Configuration
** Variables
Treemacs offers the following configuration options (~describe-variable~ will usually offers more details):
| Variable | Default | Description |
|------------------------------------------+--------------------------------------------------+your_sha256_hashyour_sha256_hashyour_sha256_hash--------------------------------------|
| treemacs-indentation | 2 | The number of times each level is indented in the file tree. If specified as '(INTEGER px), indentation will be a single INTEGER pixels wide space. |
| treemacs-indentation-string | " " | The string that is used to create indentation when ~treemacs-indentation~ is not specified as pixels. |
| treemacs-width | 35 | Width of the treemacs window. |
| treemacs-wide-toggle-width | 70 | Width of the treemacs window when using ~treemacs-extra-wide-toggle~. |
| treemacs-width-increment | 1 | When resizing, this value is added or substracted from the window width. |
| treemacs-show-hidden-files | t | Dotfiles will be shown if this is set to t and be hidden otherwise. |
| treemacs-follow-after-init | t | When non-nil follow the currently selected file after initializing the treemacs buffer, regardless of ~treemacs-follow-mode~ setting. |
| treemacs-expand-after-init | t | When non-nil expand the first project after treemacs is first initialsed. |
| treemacs-sorting | alphabetic-asc | Indicates how treemacs will sort its files and directories. (Files will always be shown after directories.) |
| treemacs-ignored-file-predicates | (treemacs--std-ignore-file-predicate) | List of predicates to test for files and directories ignored by Emacs. Ignored files will *never* be shown in the treemacs buffer. |
| treemacs-pre-file-insert-predicates | nil | List of predicates to test for files and directories not to be rendered. Unlike ~treemacs-ignored-file-predicates~ these predicates apply when files' git status information is available. |
| treemacs-file-event-delay | 2000 | How long (in milliseconds) to collect file events before refreshing. See also ~treemacs-filewatch-mode~. |
| treemacs-goto-tag-strategy | refetch-index | Indicates how to move to a tag when its buffer is dead. |
| treemacs-default-visit-action | treemacs-visit-node-no-split | Default action for opening a node (e.g. file, directory, tag). ~treemacs-visit-file-default~ action in ~treemacs-*-actions-config~ calls this function. |
| treemacs-RET-actions-config | Prefers visiting nodes over closing/opening | Alist defining the behaviour of ~treemacs-RET-action~. |
| treemacs-TAB-actions-config | Prefers closing/opening nodes over visiting | Alist defining the behaviour of ~treemacs-TAB-action~. |
| treemacs-doubleclick-actions-config | Closes/opens tags and visits files | Alist defining the behaviour of ~treemacs-doubleclick-action~. |
| treemacs-collapse-dirs | 0 | Collapse this many directories into one, when possible. A directory is collapsible when its content consists of nothing but another directory. |
| treemacs-silent-refresh | nil | When non-nil a completed refresh will not be announced with a log message. This applies both to manual refreshing as well as automatic (due to ~treemacs-filewatch-mode~). |
| treemacs-silent-filewatch | nil | When non-nil a refresh due to ~filewatch-mode~ will cause no log message. |
| treemacs-is-never-other-window | nil | Prevents treemacs from being selected with ~other-window~. |
| treemacs-position | left | Position of treemacs buffer. Valid values are ~left~, ~right~. |
| treemacs-tag-follow-delay | 1.5 | Delay in seconds of inactivity for ~treemacs-tag-follow-mode~ to trigger. |
| treemacs-tag-follow-cleanup | t | When non-nil ~treemacs-tag-follow-mode~ will keep only the current file's tags visible. |
| treemacs-project-follow-cleanup | nil | When non-nil ~treemacs-follow-mode~ will keep only the current project expanded and all others closed. |
| treemacs-no-png-images | nil | When non-nil treemacs will use TUI string icons even when running in a GUI. |
| treemacs-python-executable | (treemacs--find-python3) | Python 3 binary used by treemacs. |
| treemacs-recenter-after-file-follow | nil | Decides if and when to call ~recenter~ when ~treemacs-follow-mode~ moves to a new file. |
| treemacs-recenter-after-tag-follow | nil | Decides if and when to call ~recenter~ when ~treemacs-tag-follow-mode~ moves to a new tag. |
| treemacs-recenter-after-project-jump | 'always | Decides if and when to call ~recenter~ when navigating between projects. |
| treemacs-recenter-after-project-expand | 'on-distance | Decides if and when to call ~recenter~ when expanding a project node. |
| treemacs-recenter-distance | 0.1 | Minimum distance from window top/bottom (0.1 = 10%) before treemacs calls ~recenter~ in tag/file-follow-mode. |
| treemacs-pulse-on-success | t | When non-nil treemacs will pulse the current line as a success indicator, e.g. when creating a file. |
| treemacs-pulse-on-failure | t | When non-nil treemacs will pulse the current line as a failure indicator, e.g. when failing to find a file's tags. |
| treemacs-elisp-imenu-expression | [too large to list] | The imenu expression treemacs uses in elisp buffers. |
| treemacs-persist-file | ~/.emacs.d/.cache/treemacs-persist | Path to the file treemacs uses to persist its state. |
| treemacs-last-error-persist-file | ~/.emacs.d/.cache/treemacs-persist-at-last-error | Path to the file treemacs uses to persist its state. |
| treemacs-space-between-root-nodes | t | When non-nil treemacs will separate root nodes with an empty line. |
| treemacs-wrap-around | t | When non-nil treemacs will wrap around at the buffer edges when moving between lines. |
| treemacs--fringe-indicator-bitmap | [vertical bar] | The fringe bitmap used by the fringe-indicator minor mode. |
| treemacs-deferred-git-apply-delay | 0.5 | Seconds of idle time for git highlighting to apply when using the deferred ~treemacs-git-mode~. |
| treemacs-file-follow-delay | 0.2 | Delay in seconds of idle time for treemacs to follow the selected window. |
| treemacs-display-in-side-window | t | When non-nil treemacs will use a dedicated [[path_to_url |
| treemacs-max-git-entries | 5000 | Maximum number of git status entries treemacs will process. Anything above that number will be ignored. |
| treemacs-missing-project-action | ask | When a persisted project is missing from filesystem, ~ask~ will prompt for action, ~keep~ will keep the project in the project list, and ~remove~ will remove it from it without prompt. |
| treemacs-show-cursor | nil | When non-nil the cursor will stay visible in the treemacs buffer. |
| treemacs-git-command-pipe | "" | Text to be appended to treemacs' git command. Useful for filtering with something like grep. |
| treemacs-no-delete-other-windows | t | Prevents the treemacs window from being deleted by commands like ~delete-other-windows~ and ~magit-status~. |
| treemacs-eldoc-display | 'simple | Enables eldoc display of the file path at point. Requires ~eldoc-mode~. |
| treemacs-bookmark-title-template | "Treemacs - ${project}: ${label}" | When using ~bookmark-set~ in Treemacs, the default template for a bookmark label. The following patterns are available: "${project}", "${label}", "${label:N}", ${label-path}", "${label-path:N}", "${file-path}", "${file-path:N}". |
| treemacs-file-extension-regex | Text after last period | Determines how treemacs detects a file extension. Can be set to use text after first or last period. |
| treemacs-directory-name-transformer | identity | Transformer function that is applied to directory names before rendering for any sort of cosmetic effect. |
| treemacs-file-name-transformer | identity | Transformer function that is applied to file names before rendering for any sort of cosmetic effect. |
| treemacs-user-mode-line-format | nil | When non-nil treemacs will use it as a mode line format (otherwise format provided by ~spaceline~, ~moody-mode-line~ and ~doom-modeline~ will be used or, finally, "Treemacs" text will be displayed) |
| treemacs-user-header-line-format | nil | When non-nil treemacs will use it as a header line format |
| treemacs-move-forward-on-expand | nil | When non-nil treemacs will move to the first child of an expanded node. |
| treemacs-workspace-switch-cleanup | nil | Indicates which, if any, buffers should be deleted on a workspace switch. Valid values are ~nil~, ~files~, ~all~. |
| treemacs-read-string-input | 'from-child-frame | Indicates whether simple string input like project names should be read from a child frame or the minibuffer. |
| treemacs-expand-added-projects | t | Indicates whether newly added projects should be expanded. |
| treemacs-imenu-scope | 'everything | Determines which items treemacs' imenu function will collect. |
| treemacs-litter-directories | ("/node_modules" "/.venv" "/.cask") | List of directories affected by ~treemacs-cleanup-litter~. |
| treemacs-width-is-initially-locked | t | Indicates whether the treemacs windows starts with a locked width or not. |
| treemacs-select-when-already-in-treemacs | 'move-back | Indicates how ~treemacs-select-window~ behaves when treemacs is already selected. |
| treemacs-text-scale | nil | Scaling for text in treemacs, used via ~text-scale-increase~. |
| treemacs-indent-guide-style | line | Appearance option for ~treemacs-indent-guide~, either a thin line or a thick block. |
| treemacs-find-workspace-method | 'find-for-file-or-pick-first | Determines how treemacs selects the workspace when it first starts. |
| treemacs-header-scroll-indicators | '(nil . "^^^^^^") | Indicators used for ~treemacs-indicate-top-scroll-mode~. |
| treemacs-hide-dot-git-directory | t | Indicates whether ~.git~ directories should always be hidden. |
| treemacs-project-follow-into-home | nil | Indicates whether ~treemacs-project-follow-mode~ can follow into the $HOME directory. |
| treemacs-move-files-by-mouse-dragging | t | When non-nil treemacs will move files by dragging with your mouse inside treemacs. |
** Faces
Treemacs defines and uses the following faces:
| Face | Based on | Description |
|----------------------------------------+--------------------------------------------------+your_sha256_hash--------------|
| treemacs-directory-face | font-lock-function-name-face | Face used for directories. |
| treemacs-directory-collapsed-face | treemacs-directory-face | Face used for collapsed part of directories. |
| treemacs-file-face | default | Face used for files. |
| treemacs-root-face | font-lock-constant-face | Face used for project roots. |
| treemacs-root-unreadable-face | treemacs-root-face | Face used for local unreadable project roots. |
| treemacs-root-remote-face | font-lock-function-name-face, treemacs-root-face | Face used for readable remote (Tramp) project roots. |
| treemacs-root-remote-unreadable-face | treemacs-root-unreadable-face | Face used for unreadable remote (Tramp) project roots. |
| treemacs-root-remote-disconnected-face | warning, treemacs-root-face | Face used for disconnected remote (Tramp) project roots. |
| treemacs-tags-face | font-lock-builtin-face | Face used for tags. |
| treemacs-help-title-face | font-lock-constant-face | Face used for the title of the helpful hydra. |
| treemacs-help-column-face | font-lock-keyword-face | Face used for the column headers of the helpful hydra. |
| treemacs-git-*-face | various font lock faces | Faces used by treemacs for various git states. |
| treemacs-term-node-face | font-lock-string-face | Face for directory node symbols used by treemacs when it runs in a terminal. |
| treemacs-on-success-pulse-face | :fg #111111 :bg #669966 | Pulse face used when pulsing on a successful action. |
| treemacs-on-failure-puse-face | :fg #111111 :bg #ab3737 | Pulse face used when pulsing on a failed action. |
| treemacs-marked-file-face | :fg #f0c674 :bg #ab3737 | Face for files marked for bulk file management. |
| treemacs-fringe-indicator-face | cursor | Face for the fringe indicator. |
| treemacs-header-button-face | font-lock-keyword-face | Face for header buttons. |
| treemacs-git-commit-diff-face | font-lock-comment-face | Face used for ~treemacs-indicate-top-scroll-mode~ annotations. |
| treemacs-window-background-face | default | Face used for the background of the treemacs window. |
| treemacs-hl-line-face | hl-line | Face used for hl-line overlay inside the treemacs buffer. |
** Evil compatibility
To make treemacs get along with evil-mode you need to install and load ~treemacs-evil~. It does not define any functions
or offer any configuration options, making sure it is loaded is sufficient.
** Customizing Themes and Icons
*** Creating and Modifying Themes
Creating and modifying themes and icons is all done in a single step using dedicated macros.
To create a theme use ~treemacs-create-theme~. It requires the name of the theme and accepts 3 optional keyword
arguments: the directory the theme's icons are stored in (if it's using png icons), the name of the theme it's extending
and the config, a final form that's responsible for creating all the theme's icons. A config will typically consist of
nothing but calls to ~treemacs-create-icon~:
#+BEGIN_SRC emacs-lisp
(treemacs-create-theme "Default"
:icon-directory (treemacs-join-path treemacs-dir "icons/default")
:config
(progn
(treemacs-create-icon :file "root-open.png" :fallback "" :extensions (root-open))
(treemacs-create-icon :file "root-closed.png" :fallback "" :extensions (root-closed))
(treemacs-create-icon :file "emacs.png" :fallback " " :extensions ("el" "elc"))
(treemacs-create-icon :file "readme.png" :fallback " " :extensions ("readme.md"))
(treemacs-create-icon :file "src-closed.png" :fallback " " :extensions ("src-closed"))
(treemacs-create-icon :file "src-open.png" :fallback " " :extensions ("src-open"))
(treemacs-create-icon :icon (all-the-icons-icon-for-file "yaml") :extensions ("yml" "yaml"))))
#+END_SRC
The ~:file~ argument is relative to the icon directory of the theme being created. When not using image icons the
~:icon-directory~ argument can be omitted and the ~:file~ argument can be switched for ~:icon~ to supply the icon string
directly. The TUI fallback is also optional, " " is used by default. Finally the list of extensions determines which
file extensions the icon should be used for.
For treemacs an extension is either the entire file name or the text after the last period (unless
~treemacs-file-extension-regex~ is customized). This means it can match normal file names like "init.el", extensionless
file names like "Makefile". Because the full name is checked first it is possible to give special files their own icon,
for example "Readme.md" can use a different icon than normal markdown files.
Directories can likewise have their own icons. In that case you just need to give the directory's name and the suffix
"-open" or "-closed", like the "src" directory in the example above.
Instead of a string extension a symbol can also be used. In this case treemacs will also create a variable for that icon
named ~treemacs-icon-$symbol~. Treemacs uses several such icon variables and any new theme should define their own
versions (it's not extending the default theme). The following icons are used:
- root-open
- root-closed
- dir-closed
- dir-open
- fallback
- tag-open
- tag-closed
- tag-leaf
- error
- info
- warning
Analogous to creating a new theme ~treemacs-modify-theme~ can be used to change, or add to, an existing theme:
#+BEGIN_SRC emacs-lisp
(treemacs-modify-theme "Default"
:icon-directory "/other/icons/dir"
:config
(progn
(treemacs-create-icon :icon "+" :extensions (dir-closed))
(treemacs-create-icon :icon "-" :extensions (dir-open))))
#+END_SRC
Finally keep in mind that treemacs' icons are all buffer-local values, and will most likely not be defined when trying
to access their values directly. When you need to programmatically access some of treemacs' icons you should use
~treemacs-get-icon-value~:
#+BEGIN_SRC emacs-lisp
(treemacs-get-icon-value 'root-closed nil "Default")
(treemacs-get-icon-value "org" t)
#+END_SRC
*** Custom Icons
Treemacs also offers a quick and straighforward way to add a (gui) icon to the currently active theme, without caring
for its name or declaring icon directories:
#+BEGIN_SRC emacs-lisp
(defvar treemacs-custom-html-icon (all-the-icons-icon-for-file "name.html"))
(treemacs-define-custom-icon treemacs-custom-html-icon "html" "htm")
#+END_SRC
*Important*: There is a restriction that all icons must must be exactly 2 characters long. That's including the space
that will separate an icon from the filename.
If you want to create an icon based on an image you can use ~treemacs-define-custom-image-icon~ instead:
#+BEGIN_SRC emacs-lisp
(treemacs-define-custom-image-icon "/path/to/icon.png" "htm" "html")
#+END_SRC
For icons of directories two icon variants are needed: one for an open and one for a closed directory state. These can
be indicated with a simple ~"-open"~ and ~"-closed"~ suffix. For example the following lines will add special icons for
directories named "scripts":
#+BEGIN_SRC emacs-lisp
(treemacs-define-custom-icon "X " "scripts-closed")
(treemacs-define-custom-icon "Y " "scripts-open")
#+END_SRC
**** Icons according to ~auto-mode-alist~
For some file extensions, like ".cc" or ".hh", it is not immediately obvious which major mode will open these files, and
thus which icon they should be assigned. Treemacs offers the option that automate this decision based on
~auto-mode-alist~. You can use the function ~treemacs-map-icons-with-auto-mode-alist~ to change the assigned icons for a
list of file extensions based on the major mode the icons are mapped to in ~auto-mode-alist~.
~treemacs-map-icons-with-auto-mode-alist~ takes 2 arguments: first a list of file extensions, then an alist that decides
which icon should be used for which mapped major mode. For example, the code to decide the icons for ".hh" and ".cc"
files with ~auto-mode-alist~ would look like this:
#+BEGIN_SRC emacs-lisp
(treemacs-map-icons-with-auto-mode-alist
'(".cc" ".hh")
`((c-mode . ,(treemacs-get-icon-value "c"))
(c++-mode . ,(treemacs-get-icon-value "cpp"))))
#+END_SRC
**** GUI vs TUI
It is possible to force treemacs to use the simple TUI icons in GUI mode by setting ~treemacs-no-png-images~ to t.
**** Resizing Icons
If your emacs has been compiled with Imagemagick support, or you're using Emacs >= 27.1, you can arbitrarily change the size of treemacs' icons by
(interactively or programmatically) calling ~treemacs-resize-icons~.
*** all-the-icons indent issues
Depending on your font you may experience the problem of treemacs' icons seemingly jumping around left and right when
they are expanded and collapsed when using the all-the-icons theme. The straighforward solution is to use a different
font. You may also try a workaround of using a different font that applies only to the TAB characters used to align
treemacs' all-the-icons-based icons. To do that do not load ~treemacs-all-the-icons~ with ~require~. Instead use the
following alternative provided by treemacs itself:
#+BEGIN_SRC elisp
(treemacs-load-all-the-icons-with-workaround-font "Hermit")
#+END_SRC
The Hermit font used here is just an example - you will need to pick a font that is available on your system and does
not suffer from the tab width issue.
This line will load ~treemacs-all-the-icons~ (*it must not have been loaded previously*) and enable the all-the-icons
theme. The given font argument will be used as the font for the alignment tabs used for the icons, hopefully alleviating
the indentation problem. In addition ~treemacs-indentation~ and ~treemacs-indentation-string~ will be set to 1 and a
(font-changed) TAB character respectively, so customizing them is (probably) not possible.
* Keymap
** Unbound functions
These functions are not bound to any keys by default. It's left up to users to find the most convenient key binds.
| Action | Description |
|------------------------------------------------------+your_sha256_hash------------|
| treemacs | Show/Hide/Initialize treemacs. |
| treemacs-bookmark | Find a bookmark in treemacs. |
| treemacs-find-file | Find and focus the current file in treemacs. |
| treemacs-find-tag | Find and focus the current tag in treemacs. |
| treemacs-select-window | Select the treemacs window if it is visible. Call ~treemacs~ if it is not. |
| treemacs-select-directory | Select a single directory |
| treemacs-delete-other-windows | Same as ~delete-other-windows~, but will not delete the treemacs window. |
| treemacs-show-changelog | Opens a buffer showing the changelog. |
| treemacs-load-theme | Load a different icon theme. |
| treemacs-icon-catalogue | Showcases all themes and their icons. |
| treemacs-narrow-to-current-file | Close everything except the view on the current file. |
| treemacs-create-workspace-from-project | Create a new workspace containing only the current project. |
|------------------------------------------------------+your_sha256_hash------------|
| treemacs-projectile | Add a project from projectile to treemacs. |
| treemacs-add-and-display-current-project | Add current project to treemacs and open it. |
| treemacs-add-and-display-current-project-exclusively | Add current project to treemacs and open it, deleting all others. |
| treemacs-select-scope-type | Select the scope of treemacs buffers in which they are unique |
** Default keymaps
Treemacs' keybindings are distributed to several keymaps, based on common keybindings:
*** Project Keybinds (Prefix ~C-c C-p~)
| Key | Action | Description |
|-------------------+----------------------------------------+--------------------------------------------------------|
| C-c C-p a | treemacs-add-project-to-workspace | Select a new project to add to the treemacs workspace. |
| C-c C-p p | treemacs-projectile | Select a projectile project to add to the workspace. |
| C-c C-p d | treemacs-remove-project-from-workspace | Remove project at point from the workspace. |
| C-c C-p r | treemacs-rename-project | Rename project at point. |
| C-c C-p c c | treemacs-collapse-project | Collapse project at point. |
| C-c C-p c o/S-TAB | treemacs-collapse-all-projects | Collapse all projects. |
| C-c C-p c o | treemacs-collapse-all-projects | Collapse all projects except the project at point. |
*** Workspaces Keybinds (Prefix ~C-c C-w~)
| Key | Action | Description |
|-----------+---------------------------------+----------------------------------------|
| C-c C-w r | treemacs-rename-workspace | Rename a workspace. |
| C-c C-w a | treemacs-create-workspace | Create a new workspace. |
| C-c C-w d | treemacs-remove-workspace | Delete a workspace. |
| C-c C-w s | treemacs-switch-workspace | Switch the current workspace. |
| C-c C-w e | treemacs-edit-workspaces | Edit workspace layout via org-mode. |
| C-c C-w n | treemacs-next-workspace | Switch to the next workspace. |
| C-c C-w f | treemacs-set-fallback-workspace | Select the default fallback workspace. |
*** Node Visit Keybinds (Prefix ~o~)
| Key | Action | Description |
|--------+--------------------------------------------------+your_sha256_hash------------------------------------------------|
| ov | treemacs-visit-node-vertical-split | Open current file or tag by vertically splitting ~next-window~. |
| oh | treemacs-visit-node-horizontal-split | Open current file or tag by horizontally splitting ~next-window~. |
| oo/RET | treemacs-visit-node-no-split | Open current file or tag, performing no split and using ~next-window~ directly. |
| oc | treemacs-visit-node-close-treemacs | Open current file or tag, performing no split and using ~next-window~ directly, and close treemacs. |
| oaa | treemacs-visit-node-ace | Open current file or tag, using ace-window to decide which window to open the file in. |
| oah | treemacs-visit-node-ace-horizontal-split | Open current file or tag by horizontally splitting a window selected by ace-window. |
| oav | treemacs-visit-node-ace-vertical-split | Open current file or tag by vertically splitting a window selected by ace-window. |
| or | treemacs-visit-node-in-most-recently-used-window | Open current file or tag in the most recently used window. |
| ox | treemacs-visit-node-in-external-application | Open current file according to its mime type in an external application. Linux, Windows and Mac are supported. |
*** Toggle Keybinds (Prefix ~t~)
| Key | Action | Description |
|-----+-------------------------------------+your_sha256_hash------------------------|
| th | treemacs-toggle-show-dotfiles | Toggle the hiding and displaying of dotfiles. |
| ti | treemacs-hide-gitignored-files-mode | Toggle the hiding and displaying of gitignored files. |
| tw | treemacs-toggle-fixed-width | Toggle whether the treemacs window should have a fixed width. See also treemacs-width. |
| tf | treemacs-follow-mode | Toggle ~treemacs-follow-mode~. |
| ta | treemacs-filewatch-mode | Toggle ~treemacs-filewatch-mode~. |
| tv | treemacs-fringe-indicator-mode | Toggle ~treemacs-fringe-indicator-mode~. |
| td | treemacs-git-commit-diff-mode | Toggle ~treemacs-git-commit-diff-mode~. |
*** Copy Keybinds (Prefix ~y~)
| Key | Action | Description |
|-----+--------------------------------------+your_sha256_hash---|
| ya | treemacs-copy-absolute-path-at-point | Copy the absolute path of the node at point. |
| yr | treemacs-copy-relative-path-at-point | Copy the path of the node at point relative to the project root. |
| yp | treemacs-copy-project-path-at-point | Copy the absolute path of the project root for the node at point. |
| yf | treemacs-copy-file | Copy the file at point. |
*** General Keybinds
| Key | Action | Description |
|----------+---------------------------------------------+your_sha256_hash----------------------------------------|
| ? | treemacs-common-helpful-hydra | Summon a helpful hydra to show you treemacs' most commonly used keybinds. |
| C-? | treemacs-advanced-helpful-hydra | Summon a helpful hydra to show you treemacs' rarely used, advanced keybinds. |
| j/n | treemacs-next-line | Go to the next line. |
| k/p | treemacs-previous-line | Go to the previous line. |
| M-J/N | treemacs-next-line-other-window | Go to the next line in ~next-window~. |
| M-K/P | treemacs-previous-line-other-window | Go to the previous line in ~next-window~.. |
| <PgUp> | treemacs-next-page-other-window | Go to the next page in ~next-window~. |
| <PgDn> | treemacs-previous-page-other-window | Go to the previous page in ~next-window~.. |
| M-j/M-n | treemacs-next-neighbour | Go to the next same-level neighbour of the current node. |
| M-k/M-p | treemacs-previous-neighbour | Go to the previous same-level neighbour of the current node. |
| u | treemacs-goto-parent-node | Go to parent of node at point, if possible. |
| <M-Up> | treemacs-move-project-up | Switch positions of project at point and the one above it. |
| <M-Down> | treemacs-move-project-down | Switch positions of project at point and the one below it. |
| w | treemacs-set-width | Set a new value for the width of the treemacs window. |
| < | treemacs-decrement-width | Decrease the width of the treemacs window. |
| > | treemacs-increment-width | Increase the width of the treemacs window. |
| RET | treemacs-RET-action | Run the action defined in ~treemacs-RET-actions-config~ for the current node. |
| TAB | treemacs-TAB-action | Run the action defined in ~treemacs-TAB-actions-config~ for the current node. |
| g/r/gr | treemacs-refresh | Refresh the project at point. |
| d | treemacs-delete-file | Delete node at point. |
| R | treemacs-rename-file | Rename node at point. |
| cf | treemacs-create-file | Create a file. |
| cd | treemacs-create-dir | Create a directory. |
| q | treemacs-quit | Hide the treemacs window. |
| Q | treemacs-kill-buffer | Delete the treemacs buffer. |
| P | treemacs-peek-mode | Peek at the files at point without fully opening them. |
| ya | treemacs-copy-absolute-path-at-point | Copy the absolute path of the node at point. |
| yr | treemacs-copy-relative-path-at-point | Copy the path of the node at point relative to the project root. |
| yp | treemacs-copy-project-path-at-point | Copy the absolute path of the project root for the node at point. |
| yf | treemacs-copy-file | Copy the file at point. |
| m | treemacs-move-file | Move the file at point. |
| s | treemacs-resort | Set a new value for ~treemacs-sorting~. |
| b | treemacs-add-bookmark | Bookmark the currently selected files's, dir's or tag's location. |
| h/M-h | treemacs-COLLAPSE-action | Run the action defined in ~treemacs-COLLAPSE-actions-config~ for the current node. |
| l/M-l | treemacs-RET-action | Run the action defined in ~treemacs-RET-actions-config~ for the current node. |
| M-H | treemacs-root-up | Move treemacs' root one level upward. Only works with a single project in the workspace. |
| M-L | treemacs-root-down | Move treemacs' root into the directory at point. Only works with a single project in the workspace. |
| H | treemacs-collapse-parent-node | Collapse the parent of the node at point. |
| \! | treemacs-run-shell-command-for-current-node | Run an asynchronous shell command on the current node, replacing "$path" with its path. |
| M-! | treemacs-run-shell-command-in-project-root | Run an asynchronous shell command in the root of the current project, replacing "$path" with its path. |
| C | treemacs-cleanup-litter | Close all directories matching any of ~treemacs-litter-directories~. |
| = | treemacs-fit-window-width | Adjust the width of the treemacs window to that of the longsest line. |
| W | treemacs-extra-wide-toggle | Toggle between normal and extra wide display for the treemacs window. |
* Compatibility
The correctness of treemacs' display behaviour is, to a large degree, ensured through window properties and reacting to
changes in the window configuration. The packages most likely to cause trouble for treemacs are therefore those that
interfere with Emacs' buffer spawning and window splitting behaviour. Treemacs is included in Spacemacs and I am a
Spacemacs user, therefore treemacs guarantees first-class support & compatibility for window-managing packages used in
Spacemacs, namely [[path_to_url [[path_to_url [[path_to_url and [[path_to_url as well as [[path_to_url For everything else there may be
issues and, depending on the complexity of the problem, I may decide it is not worth fixing.
Aside from this there are the following known incompatibilities:
* Any package invoking ~font-lock-ensure~ in the treemacs buffer. This will reset the faces of treemacs' buttons (once)
and is a known [[path_to_url bug]].
* A possible cause of this issue using an old version of swiper.
* Rainbow mode activated in treemacs will likewise produce this behaviour. Make sure not to include rainbow-mode as
part of ~special-mode-hook~, since this is the mode ~treemacs-mode~ is derived from.
* FAQ
- I don't need multiple projects, can treemacs just always show me the current project I'm in?
Yes, see the section about [[#navigation-without-projects-and-workspaces][Navigation without Projects and Workspace]].
- How do I hide files I don't want to see?
You need to define a predicate function and add it to ~treemacs-ignored-file-predicates~. This function accepts two
arguments, a file's name and its absolute path, and must return non-nil when treemacs should hide that file.
For example, the code to ignore files either called "foo" or located in "/x/y/z/" would look like this:
#+BEGIN_SRC emacs-lisp
(with-eval-after-load 'treemacs
(defun treemacs-ignore-example (filename absolute-path)
(or (string-equal filename "foo")
(string-prefix-p "/x/y/z/" absolute-path)))
(add-to-list 'treemacs-ignored-file-predicates #'treemacs-ignore-example))
#+END_SRC
- How do I keep treemacs from showing files that are ignored by git?
You can use ~treemacs-hide-gitignored-files-mode~ (bound to ~ti~) to switch between hiding and displaying of
gitignored files. Git-mode /must/ be enabled for this feature to work.
- Why am I seeing no file icons and only +/- for directories?
Treemacs will permanently fall back on its simple TUI icons if it detects that the emacs instance it is run in cannot
create images. You can test this by evaluating ~(create-image "" 'png)~. If this code returns an error like "Invalid
image type png" your emacs does not support images.
- How do I get treemacs to stop telling me when it's been refreshed, especially with filewatch-mode?
See ~treemacs-silent-refresh~ and ~treemacs-silent-filewatch~.
- ENOSPC / No space left on device / no file descriptor left
You may run into this error when you use filewatch-mode. The solution is to increase the number of allowed user
watches, as described [[path_to_url for Linux]] and [[path_to_url for Mac]].
You will also want to see what's responsible for setting all those file watches in the first place, since treemacs
only watches the expanded directories it is displaying and so won't produce more than a couple dozen watches at best.
- Why is treemacs warning me about not being able to find some background colors and falling back to something else?
Treemacs needs those colors to make sure that background colors of its icons correctly align with hl-line-mode. Png
images' backgrounds are not highlighted by hl-line-mode by default, treemacs is manually correcting this every time
hl-line's overlay is moved. To make that correction work it needs to know two colors: the current theme's ~default~
background, and its ~hl-line~ background color. If treemacs cannot find hl-lines's background color it falls back to
the default background color. If it cannot even find the default background it will fall back to #2d2d31. The
warnings serve to inform you of that fallback.
If your theme does not define a required color you can set it yourself before treemacs loads like this:
#+BEGIN_SRC emacs-lisp
(set-face-attribute 'hl-line nil :background "#333333")
#+END_SRC
If you just want to disable the warnings you can do so by defining the variable ~treemacs-no-load-time-warnings~. Its
exact value is irrelevant, all that matters is that it exists at all. Since the warnings are issues when treemacs is
first being loaded the variable must be defined *before* treemacs is initialized. This is best achieved by adding the
line ~(defvar treemacs-no-load-time-warnings t)~ to treemacs' use-package ~:init~ block.
- Can I expand *everything* under a node?
Yes, you just need to expand it with a [[path_to_url argument]]. Closing nodes with a prefix argument works as well. In this
case treemacs will forget about the nodes opened below the one that was closed and not reopen them automatically.
- Broken display of CJK characters
If you are seeing raw bytes like ~\316~ instead of proper CJK characters like [[path_to_url this issue]] you have to set the proper
language environment, e.g.:
#+BEGIN_SRC emacs-lisp
(set-language-environment 'Chinese-GB18030)
#+END_SRC
* Contributing
Contributions are very much welcome, but should fit the general scope and style of treemacs. The following is a list of
guidelines that should be met (exceptions confirm the rule):
- There should be one commit per feature.
- Commit messages should start with a note in brackets that roughly describes the area the commit relates to, for
example ~[Icons]~ if you add an icon.
- Code must be in the right place (what with the codebase being split in many small files). If there is no right place
it probably goes into treemacs-core-utils.el which is where all the general implementation details go.
- New features must be documented in the readme (for example mentioning new config options in the [[#variables][Config Table]]).
- There must not be any compiler warnings.
- The test suite must pass.
Treemacs uses cask to setup a local testing environment and a Makefile that simplifies compiling and testing the
codebase. First run ~cask install~ to locally pull treemacs' dependencies. Then you can use the following Makefile
targets:
- make prepare :: Downloads and updates Cask's dependencies. Is a dependency of the ~test~ and ~compile~ targets.
- make compile :: Compiles the code base (and treats compiler warnings as errors).
- make clean :: Removes the generated .elc files.
- make lint :: Runs first ~compile~ then ~clean~, even if the former fails.
- make test :: Runs the testsuite, once in a graphical environment and once in the terminal.
Finally if you want to just add an icon you can take [[path_to_url commit]] as an example (though the icons have since been moved
into their own module in ~treemacs-icons.el~).
* Working With The Code Base
If you want to delve into the treemacs' code base, check out [[path_to_url wiki]] for some general pointers.
* Dependencies
- emacs >= 26.1 (>= 27.1 for tab-bar)
- s
- dash
- cl-lib
- ace-window
- pfuture
- ht
- cfrs
- hydra
- (optionally) evil
- (optionally) projectile
- (optionally) winum
- (optionally) magit
- (optionally) perspective/persp
- (optionally) all-the-icons
- (optionally) python(3)
``` | /content/code_sandbox/README.org | org | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 16,578 |
```emacs lisp
;;; -*- lexical-binding: t -*-
;;; Based on path_to_url
(require 'bytecomp)
(require 'checkdoc)
(require 'dash)
(require 's)
(defconst all-el-files (append (directory-files "./src/elisp" :full ".el")
(directory-files "./src/extra" :full ".el")))
(defconst valid-doc-words
(append checkdoc-ispell-lisp-words
'("accessor"
"adoc"
"api"
"arg"
"args"
"async"
"baz"
"boolean"
"bool"
"btn"
"changelog"
"config"
"configs"
"cpp"
"customisations"
"debounce"
"debounced"
"dir"
"dired"
"dirs"
"dir's"
"dom"
"Dotfiles"
"dotfile"
"dotfiles"
"eieio"
"el"
"eldoc"
"elisp"
"elpa"
"filename"
"filesystem"
"filetree"
"FilePath"
"filepath"
"filepaths"
"filewatch"
"flycheck"
"fn"
"fontification"
"git"
"gitignore"
"goto"
"gui"
"HashMap"
"hoc"
"ImageMagick"
"imenu"
"init"
"initialiser"
"inlined"
"iter"
"keybind"
"keybinds"
"keybindings"
"kqueue"
"leftclick"
"linux"
"localized"
"macos"
"MacOS"
"magit"
"maildir"
"maildirs"
"makefile"
"metadata"
"minibuffer"
"modeline"
"org"
"org's"
"persp"
"Pfuture"
"pfuture"
"plist"
"png"
"plaintext"
"pos"
"programmatically"
"propertized"
"px"
"py"
"rebase"
"recentering"
"regex"
"resize"
"resized"
"resizing"
"sb"
"spaceline"
"splittable"
"struct"
"subdir"
"subdirs"
"subprocess"
"treemacs"
"tui"
"txt"
"unmark"
"untracked"
"variadic"
"wayland"
"whitespace"
"workspace"
"workspaces")))
(defun checkdoc-buffer (filename)
;; output only /src/elisp/filename.el as when compiling
(message "Checkdoc %s" (substring filename (1+ (s-index-of "/src" filename))))
(with-temp-buffer
;; Visit the file to make sure that the filename is set, as some checkdoc
;; lints only apply for buffers with filenames
(insert-file-contents filename :visit)
(set-buffer-modified-p nil)
(delay-mode-hooks (emacs-lisp-mode))
(setf delay-mode-hooks nil
ispell-dictionary "british")
(let ((checkdoc-autofix-flag 'never)
(checkdoc-force-docstrings-flag t)
(checkdoc-force-history-flag nil)
(checkdoc-permit-comma-termination-flag nil)
(checkdoc-spellcheck-documentation-flag t)
(checkdoc-ispell-lisp-words valid-doc-words)
(checkdoc-arguments-in-order-flag t)
(checkdoc-verb-check-experimental-flag t))
(checkdoc-current-buffer :take-notes))
(get-errors)))
(defun get-errors ()
(with-current-buffer checkdoc-diagnostic-buffer
(goto-char (point-min))
;; Skip over the checkdoc header
(re-search-forward (rx line-start "***" (1+ not-newline)
": checkdoc-current-buffer"))
(forward-line 1)
(prog1
(let ((text (buffer-substring-no-properties (point) (point-max))))
(and (not (s-blank-p text))
(split-string text "\n")))
(kill-buffer))))
(let ((errors (-mapcat #'checkdoc-buffer all-el-files)))
(-each errors #'message)
(kill-emacs (if errors 1 0)))
``` | /content/code_sandbox/test/checkdock.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 962 |
```emacs lisp
(defconst FOO)
(defun fn1 ())
(defun fn2 ())
``` | /content/code_sandbox/test/testdir1/testdir2/testdir3/testfile.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 15 |
```org
* Foo
** Foo2
*** Foo3
* Bar
``` | /content/code_sandbox/test/testdir1/testdir2/testdir3/testfile.org | org | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 15 |
```python
from subprocess import Popen, PIPE
import sys
STATUS_CMD = "git status -sb"
def main():
proc = Popen(STATUS_CMD, shell=True, stdout=PIPE, bufsize=100)
if (proc.wait() != 0):
sys.exit(2)
line = proc.stdout.readline()
i_open = line.find(b"[")
i_close = line.find(b"]")
if (i_open == -1):
print("nil")
sys.exit(0)
ahead = 0
ahead_len = 0
behind = 0
behind_len = 0
for inf in line[i_open+1 : i_close].split(b", "):
split = inf.split(b" ")
status = split[0]
text = split[1]
number = int(text)
if status == b"ahead":
ahead = number
ahead_len = len(text)
elif status == b"behind":
behind = number
behind_len = len(text)
if ahead == 0 and behind != 0:
face_len = 2 + behind_len
print('#(" {}" 0 {} (face treemacs-git-commit-diff-face))'.format(behind, face_len))
elif ahead != 0 and behind == 0:
face_len = 2 + ahead_len
print('#(" {}" 0 {} (face treemacs-git-commit-diff-face))'.format(ahead, face_len))
else:
face_len = 4 + ahead_len + behind_len
print('#(" {} {}" 0 {} (face treemacs-git-commit-diff-face))'.format(ahead, behind, face_len))
main()
``` | /content/code_sandbox/src/scripts/treemacs-git-commit-diff.py | python | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 365 |
```python
from subprocess import Popen, PIPE
from os.path import exists
import sys
GIT_CMD = "git clean -ndX"
STDOUT = sys.stdout.buffer
def quote(string):
return b'"' + string + b'"'
def process_git_output(root, proc):
root_bytes = bytes(root, "utf-8")
count = 0
for line in proc.stdout:
# output has the form 'Would remove /a/b/c'
# final newline and final slash also need to go
path = line.replace(b"Would remove ", b"")[:-1]
if path.endswith(b"/"):
path = path[:-1]
ignored_file = root_bytes + b"/" + path
ignored_file_parent = ignored_file[:ignored_file.rindex(b"/")]
STDOUT.write(quote(ignored_file_parent))
STDOUT.write(quote(ignored_file))
# arbitrary limit of no more than 100 files
count += 1
if count > 100:
break
def main():
roots = sys.argv[1:]
procs = []
for root in roots:
if exists(root + "/.git"):
proc = Popen(GIT_CMD, shell=True, stdout=PIPE, bufsize=100, cwd=root)
procs.append((root, proc))
STDOUT.write(b"(")
for (root, proc) in procs:
process_git_output(root, proc)
STDOUT.write(b")")
main()
``` | /content/code_sandbox/src/scripts/treemacs-find-ignored-files.py | python | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 313 |
```python
from subprocess import Popen, PIPE
import sys
# Command line arguments are a list of maildirs.
# The output is a list of items in the form '((P1 A1) (P2 A2))' where P is the node path for a maildir
# node, and A is the mail count annotation text
# Exmaple: '(((treemacs-mu4e "/web/") " (176)")((treemacs-mu4e "/web/" "/web/Inbox") " (161)"))'
UNREAD_CMD = "mu find maildir:'{}' --fields 'i' flag:'unread' 2> /dev/null | wc -l"
PATH_PREFIX = "treemacs-mu4e"
LOCAL_PREFIX = "/" + sys.argv[1]
def main():
maildirs = sys.argv[2:]
output = ["("]
for maildir in maildirs:
mu_dir = maildir
is_local = False
is_leaf = not maildir.endswith("/")
# "Local Folders" is an artificial maildir that is used to group
# otherwise free standing folders under a single header like
# in thunderbird
if mu_dir.startswith(LOCAL_PREFIX):
is_local = True
mu_dir = mu_dir.replace(LOCAL_PREFIX, "")
if mu_dir == "/":
continue
unread = Popen(UNREAD_CMD.format(mu_dir.replace(" ", "\ ")),
shell=True,
stdout=PIPE,
bufsize=100,
encoding='utf-8'
).communicate()[0][:-1]
if unread == "0":
continue
node_path = []
path_item = "/"
split_path = maildir.split("/")[1:] if is_leaf else maildir.split("/")[1:-1]
# it makes difference for mu whether a maildir ends in a slash or not
for i in range(0, len(split_path) - 1):
path_item = path_item + split_path[i] + "/"
node_path.append("\"" + path_item + "\"")
final_item = "" if is_leaf else "/"
node_path.append("\"" + path_item + split_path[-1] + final_item + "\"")
suffix = '" ({})"'.format(unread)
output.append('(({} {}) {})'.format(
PATH_PREFIX, " ".join(node_path), suffix
))
output.append(")")
print("".join(output))
main()
``` | /content/code_sandbox/src/scripts/treemacs-count-mail.py | python | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 522 |
```python
from os import listdir
from os.path import isdir
from posixpath import join
import sys
import os
LIMIT = int(sys.argv[1])
SHOW_ALL = sys.argv[2] == 't'
ROOTS = sys.argv[3:]
STDOUT = sys.stdout
# special workaround for windows platforms
# the default `join' implementation cannot quite deal with windows
# paths in the form of "C:/A/B" & "C:/A/B/C", joining them as
# "C:/A/B/C:/A/B/C"
# it can, however, be "tricked" into doing the right thing by adding
# a slash to the start of the paths
# go figure
if sys.platform == 'win32':
def join_dirs(d1, d2, full_path=False):
missing_slash = False
if not d1.startswith("/"):
missing_slash = True
d1 = "/" + d1
# full_path is only True when the second argument is
# another absolute path
if full_path and not d2.startswith("/"):
missing_slash = True
d2 = "/" + d2
joined = join(d1, d2)
if missing_slash:
# still need to return the joined path without the
# leading slash, the way it looked originally
return joined[1:]
else:
return joined
else:
def join_dirs(d1, d2, *_):
return join(d1, d2)
if LIMIT <= 0:
exit(0)
def dir_content(path):
"""
returns the content of given path, excluding unreadable files
and dotfiles (unless SHOW_ALL is True)
"""
ret = []
for item in listdir(path):
full_path = join_dirs(path, item)
if os.access(full_path, os.R_OK) and (SHOW_ALL or item[0] != '.'):
ret.append(full_path)
return ret
def main():
STDOUT.write("#s(hash-table size 10 test equal rehash-size 1.5 rehash-threshold 0.8125 data (")
for root in ROOTS:
STDOUT.write(f'"{root}"')
dirs = [d for d in dir_content(root) if isdir(d)]
STDOUT.write("(")
for current_dir in dirs:
content = dir_content(current_dir)
collapsed = current_dir
steps = []
depth = 0
while True:
if len(content) == 1 and isdir(content[0]):
single_path = content[0]
collapsed = join_dirs(collapsed, single_path, True)
content = dir_content(collapsed)
depth += 1
steps.append(single_path)
if depth >= LIMIT:
break
else:
break
if depth > 0 and not ('"' in collapsed or '\\' in collapsed):
final_dir = steps[-1]
display_suffix = final_dir[len(current_dir):]
STDOUT.write("(" + '"' + display_suffix + '" ' + '"' + current_dir + '" ' + '"' + '" "'.join(steps) + '")')
nothing_to_flatten = False
STDOUT.write(")")
# close hash table again
STDOUT.write("))")
main()
``` | /content/code_sandbox/src/scripts/treemacs-dirs-to-collapse.py | python | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 705 |
```python
from subprocess import run, Popen, PIPE, DEVNULL, check_output
import sys
import os
# There are 3+ command line arguments:
# 1) the file to update
# 2) the file's previous state, to check if things changed at all
# 3) the file's parents that need to be updated as well
FILE = sys.argv[1]
OLD_FACE = sys.argv[2]
PARENTS = [p for p in sys.argv[3:]]
FILE_STATE_CMD = "git status --porcelain --ignored=matching "
IS_IGNORED_CMD = "git check-ignore "
IS_TRACKED_CMD = "git ls-files --error-unmatch "
IS_CHANGED_CMD = "git ls-files --modified --others --exclude-standard "
def face_for_status(path, status):
if status == "M":
return "treemacs-git-modified-face"
elif status == "U":
return "treemacs-git-conflict-face"
elif status == "?":
return "treemacs-git-untracked-face"
elif status == "!":
return "treemacs-git-ignored-face"
elif status == "A":
return "treemacs-git-added-face"
elif status == "R":
return "treemacs-git-renamed-face"
elif os.path.isdir(path):
return "treemacs-directory-face"
else:
return "treemacs-git-unmodified-face"
def main():
if '"' in FILE or '\\' in FILE:
sys.exit(2)
new_state = determine_file_git_state()
old_state = face_for_status(FILE, OLD_FACE)
# nothing to do
if old_state == new_state:
sys.exit(2)
proc_list = []
# for every parent file start all necessary git processes immediately
# even if we don't need them later
for p in PARENTS:
add_git_processes(proc_list, p)
result_list = [(FILE, new_state)]
# iterate through the parents and propagate ignored and untracked states downwards
# the following states are possible for *directories*:
# 0 -> clean
# ! -> ignored
# ? -> untracked
# M -> modified
i = 0
l = len(proc_list)
propagate_state = None
while i < l:
path, ignore_proc, tracked_proc, changed_proc = proc_list[i]
if ignore_proc.communicate() and ignore_proc.returncode == 0:
propagate_state = "!"
result_list.append((path, propagate_state))
break
elif tracked_proc.communicate() and tracked_proc.returncode == 1:
propagate_state = "?"
result_list.append((path, propagate_state))
break
elif changed_proc.communicate() != b'' and changed_proc.returncode == 0:
result_list.append((path, "M"))
else:
result_list.append((path, "0"))
i += 1
if propagate_state:
i += 1
while i < l:
result_list.append((proc_list[i][0], propagate_state))
i += 1
elisp_conses = "".join(['("{}" . {})'.format(path, face_for_status(path, state)) for path, state in result_list])
elisp_alist = "({})".format(elisp_conses)
print(elisp_alist)
def add_git_processes(status_listings, path):
ignored_proc = Popen(IS_IGNORED_CMD + path, shell=True, stdout=DEVNULL, stderr=DEVNULL)
tracked_proc = Popen(IS_TRACKED_CMD + path, shell=True, stdout=DEVNULL, stderr=DEVNULL)
changed_proc = Popen(IS_CHANGED_CMD + path, shell=True, stdout=PIPE, stderr=DEVNULL)
status_listings.append((path, ignored_proc, tracked_proc, changed_proc))
def determine_file_git_state():
proc = Popen(FILE_STATE_CMD + FILE, shell=True, stdout=PIPE, stderr=DEVNULL)
line = proc.stdout.readline()
if line:
state = line.lstrip().split(b" ")[0]
return state.decode('utf-8').strip()[0]
else:
return "0"
main()
``` | /content/code_sandbox/src/scripts/treemacs-single-file-git-status.py | python | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 898 |
```python
from subprocess import Popen, PIPE
from os import listdir, environ
from os.path import isdir, islink
from posixpath import join
import sys
# The script is supplied with the followig command line arguments
# 1) the repository root - used only for file-joining to an absolute path
# the actual working directory is set in emacs
# 2) `treemacs-max-git-entries`
# 3) `treemacs-git-command-pipe`
# 4) a list of expanded directories the script may recurse into to collect
# an entry for every untracked/ignored file inside
# this list is turned into a set since it is possible that it contains duplicates
# when called for magit, see also `treemacs-magit--extended-git-mode-update`
GIT_ROOT = str.encode(sys.argv[1])
LIMIT = int(sys.argv[2])
GIT_CMD = "git status --porcelain --ignored=matching . " + sys.argv[3]
STDOUT = sys.stdout.buffer
RECURSE_DIRS = set([str.encode(it[(len(GIT_ROOT)):]) + b"/" for it in sys.argv[4:]]) if len(sys.argv) > 4 else []
QUOTE = b'"'
output = []
ht_size = 0
def face_for_status(status):
if status == b"M":
return b"treemacs-git-modified-face"
elif status == b"U":
return b"treemacs-git-conflict-face"
elif status == b"?":
return b"treemacs-git-untracked-face"
elif status == b"!":
return b"treemacs-git-ignored-face"
elif status == b"A":
return b"treemacs-git-added-face"
elif status == b"R":
return b"treemacs-git-renamed-face"
else:
return b"font-lock-keyword-face"
def find_recursive_entries(path, state):
global output, ht_size
for item in listdir(path):
full_path = join(path, item)
output.append(QUOTE + full_path + QUOTE + face_for_status(state))
ht_size += 1
if ht_size > LIMIT:
break
if isdir(full_path) and not islink(full_path):
find_recursive_entries(full_path, state)
def main():
global output, ht_size
# Don't lock Git when updating status.
environ["GIT_OPTIONAL_LOCKS"] = "0"
proc = Popen(GIT_CMD, shell=True, stdout=PIPE, bufsize=100)
dirs_added = {}
for item in proc.stdout:
# remove final newline
item = item[:-1]
# remove leading space if item was e.g. modified only in the worktree
if item.startswith(b' '):
item = item[1:]
state, filename = item.split(b' ', 1)
# reduce the state to a single-letter-string
state = state[0:1]
filename = filename.strip()
# sometimes git outputs quoted filesnames
if filename.startswith(b'"'):
filename = filename[1:-1]
# find the absolute path for the current item
# renames have the form STATE OLDNAME -> NEWNAME
abs_path = None
if state == b"R":
abs_path = join(GIT_ROOT, filename.split(b' -> ')[1])
else:
abs_path = join(GIT_ROOT, filename.lstrip())
# filename is a directory, final slash must be removed
if abs_path.endswith(b'/'):
abs_path = abs_path[:-1]
dirs_added[abs_path] = True
output.append(QUOTE + abs_path + QUOTE + face_for_status(state))
ht_size += 1
# for files deeper down in the file hierarchy also print all their directories
# if /A/B/C/x is changed then /A and /A/B and /A/B/C must be shown as changed as well
if b'/' in filename and state != b'!':
name_parts = filename.split(b'/')[:-1]
dirname = b''
for name_part in name_parts:
dirname = join(dirname, name_part)
full_dirname = join(GIT_ROOT, dirname.lstrip())
# directories should not be printed more than once, which would happen if
# e.g. both /A/B/C/x and /A/B/C/y have changes
if full_dirname not in dirs_added:
output.append(QUOTE + full_dirname + QUOTE + b"treemacs-git-modified-face")
ht_size += 1
dirs_added[full_dirname] = True
# for untracked and ignored directories we need to find an entry for every single file
# they contain
# however this applies only for directories that are expanded and whose content is visible
if state in [b'?', b'!'] and isdir(abs_path):
if filename in RECURSE_DIRS:
find_recursive_entries(abs_path, state)
if ht_size >= LIMIT:
break
STDOUT.write(
b"#s(hash-table size " + \
bytes(str(ht_size), 'utf-8') + \
b" test equal rehash-size 1.5 rehash-threshold 0.8125 data ("
)
if ht_size > 0:
STDOUT.write(b"".join(output))
STDOUT.write(b"))")
sys.exit(proc.poll())
main()
``` | /content/code_sandbox/src/scripts/treemacs-git-status.py | python | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,171 |
```emacs lisp
;;; treemacs-test.el --- Tests for treemacs -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;;; Code:
(require 'filenotify)
(require 'dash)
(require 'pfuture)
(require 'treemacs)
(require 'treemacs-macros)
(require 'treemacs-bookmarks)
(require 'treemacs-core-utils)
(require 'treemacs-tags)
(require 'treemacs-tag-follow-mode)
(require 'treemacs-mouse-interface)
(require 'treemacs-file-management)
(require 'org)
(require 'buttercup)
(defconst treemacs-should-run-file-notify-tests (not (null file-notify--library)))
(defmacro treemacs--with-project (pr &rest body)
"Set PR as the only project in current workspace and then run BODY."
(declare (indent 1))
`(let ((--original-- (treemacs-current-workspace))
(ws (treemacs-workspace->create! :name "FAKE" :projects ,(when pr `(list ,pr)))))
(unwind-protect
(progn
(setf (treemacs-current-workspace) ws)
,@body)
(progn
(setf (treemacs-current-workspace) --original--)))))
(defmacro treemacs--save-workspace (&rest body)
"Execute BODY saving the current workspace."
`(-let [ws (treemacs-current-workspace)]
(unwind-protect
,@body
(setf (treemacs-current-workspace) ws))))
(describe "treemacs-is-path"
(describe ":in matcher"
(it "identifies direct parent"
(let ((path "~/A/B/c")
(parent "~/A/B"))
(expect (treemacs-is-path path :in parent) :to-be-truthy)))
(it "identifies indirect parent"
(let ((path "~/A/B/C/D/e")
(parent "~/A/B"))
(expect (treemacs-is-path path :in parent) :to-be-truthy)))
(it "identifies non-parent"
(let ((path "~/A/B/C/D/e")
(parent "~/B"))
(expect (treemacs-is-path path :in parent) :not :to-be-truthy)))
(it "identifies non-parent with similar prefix"
(let ((path "~/A/prefix1")
(parent "~/A/prefix2"))
(expect (treemacs-is-path path :in parent) :not :to-be-truthy))))
(describe ":directly-in matcher"
(it "identifies direct parent"
(let ((path "~/A/B/c")
(parent "~/A/B"))
(expect (treemacs-is-path path :directly-in parent) :to-be-truthy)))
(it "rejects indirect parent"
(let ((path "~/A/B/c")
(parent "~/A"))
(expect (treemacs-is-path path :directly-in parent) :to-be nil)))
(it "rejects non-parent"
(let ((path "~/A/B/c")
(parent "x"))
(expect (treemacs-is-path path :directly-in parent) :to-be nil)))
(it "rejects non-parent with same length as parent"
(let ((path "~/A/B/c")
(parent "~/A/X"))
(expect (treemacs-is-path path :directly-in parent) :to-be nil)))
(it "rejects non-parent with similar preix"
(let ((path "~/A/prefix1")
(parent "~/A/prefix2"))
(expect (treemacs-is-path path :directly-in parent) :to-be nil)))
(it "rejects shorter path than parent"
(let ((path "~/A")
(parent "~/A/B/C"))
(expect (treemacs-is-path path :directly-in parent) :to-be nil))))
(describe ":in-project matcher"
(it "Identifies that a path is in a project"
(let ((path "~/P/A/B/C/D/E/F/file")
(project (treemacs-project->create! :name "P" :path "~/P/A/B/C" :path-status 'local-readable)))
(expect (treemacs-is-path path :in-project project) :to-be-truthy)))
(it "Identifies that a path is not in a project"
(let ((path "~/X/abc")
(project (treemacs-project->create! :name "P" :path "~/P" :path-status 'local-readable)))
(expect (treemacs-is-path path :in-project project) :not :to-be-truthy))))
(describe ":in-workspace matcher"
(it "Finds project of path in the workspace"
(let* ((path "~/C/abc")
(p1 (treemacs-project->create! :name "P1" :path "~/A" :path-status 'local-readable))
(p2 (treemacs-project->create! :name "P2" :path "~/B" :path-status 'local-readable))
(p3 (treemacs-project->create! :name "P3" :path "~/C" :path-status 'local-readable))
(ws (treemacs-workspace->create! :name "WS" :projects (list p1 p2 p3))))
(expect (treemacs-is-path path :in-workspace ws) :to-be p3)))
(it "Identifies path not in the workspace" ()
(let* ((path "~/D/abc")
(p1 (treemacs-project->create! :name "P1" :path "~/A" :path-status 'local-readable))
(p2 (treemacs-project->create! :name "P2" :path "~/B" :path-status 'local-readable))
(p3 (treemacs-project->create! :name "P3" :path "~/C" :path-status 'local-readable))
(ws (treemacs-workspace->create! :name "WS" :projects (list p1 p2 p3))))
(expect (treemacs-is-path path :in-workspace ws) :to-be nil)))))
(describe "treemacs--reject-ignored-files"
(let ((treemacs-ignored-file-predicates (default-value 'treemacs-ignored-file-predicates)))
(describe "Accepting"
(it "Accepts dot-file"
(expect (treemacs--reject-ignored-files "~/A/B/C/.foo.el") :to-be t))
(it "Accepts common absolute path"
(expect (treemacs--reject-ignored-files "~/A/B/C/foo.el") :to-be t))
(it "Accepts common filename"
(expect (treemacs--reject-ignored-files "foo.el") :to-be t))
(it "Accepts directory"
(expect (treemacs--reject-ignored-files "~/A/B/C/") :to-be t))
(it "Accepts .git when it is not hidden"
(-let [treemacs-hide-dot-git-directory nil]
(expect (treemacs--reject-ignored-files "~/A/B/C/.git") :to-be t))))
(describe "Rejecting"
(it "Fails on nil input"
(expect (treemacs--reject-ignored-files nil) :to-throw))
(it "Fails on empty name"
(expect (treemacs--reject-ignored-files "") :to-throw))
(it "Rejects Emacs lock file"
(expect (treemacs--reject-ignored-files "~/A/B/C/.#foo.el") :to-be nil))
(it "Rejects Emacs backup file"
(expect (treemacs--reject-ignored-files "~/A/B/C/foo.el~") :to-be nil))
(it "Rejects autosave file"
(expect (treemacs--reject-ignored-files "~/A/B/C/#foo.el#") :to-be nil))
(it "Rejects flycheck's temp file"
(expect (treemacs--reject-ignored-files "~/A/B/C/flycheck_foo.el") :to-be nil))
(it "Rejects dot"
(expect (treemacs--reject-ignored-files ".") :to-be nil))
(it "Rejects dot-dot"
(expect (treemacs--reject-ignored-files "..") :to-be nil)))))
(describe "treemacs--reject-ignored-and-dotfiles"
(let ((treemacs-ignored-file-predicates (default-value 'treemacs-ignored-file-predicates)))
(describe "Accepting"
(it "Accepts common absolute path"
(expect (treemacs--reject-ignored-and-dotfiles "~/A/B/C/foo.el") :to-be t))
(it "Accepts common filename"
(expect (treemacs--reject-ignored-and-dotfiles "foo.el") :to-be t))
(it "Accepts directory"
(expect (treemacs--reject-ignored-and-dotfiles "~/A/B/C/") :to-be t)))
(describe "Rejecting"
(it "Fails on nil input"
(expect (treemacs--reject-ignored-and-dotfiles nil) :to-throw))
(it "Fails on empty name"
(expect (treemacs--reject-ignored-and-dotfiles "") :to-throw))
(it "Rejects Emacs lock file"
(expect (treemacs--reject-ignored-and-dotfiles "~/A/B/C/.#foo.el") :to-be nil))
(it "Rejects Emacs backup file"
(expect (treemacs--reject-ignored-and-dotfiles "~/A/B/C/foo.el~") :to-be nil))
(it "Rejects autosave file"
(expect (treemacs--reject-ignored-and-dotfiles "~/A/B/C/#foo.el#") :to-be nil))
(it "Rejects flycheck's temp file"
(expect (treemacs--reject-ignored-and-dotfiles "~/A/B/C/flycheck_foo.el") :to-be nil))
(it "Rejects dot-file"
(expect (treemacs--reject-ignored-and-dotfiles "~/A/B/C/.foo.el") :to-be nil))
(it "Rejects .git"
(expect (treemacs--reject-ignored-and-dotfiles "~/A/B/C/.git") :to-be nil))
(it "Rejects dot"
(expect (treemacs--reject-ignored-and-dotfiles ".") :to-be nil))
(it "Rejects dot-dot"
(expect (treemacs--reject-ignored-and-dotfiles "..") :to-be nil)))))
(describe "treemacs--is-event-relevant?"
(-let [treemacs-ignored-file-predicates (default-value 'treemacs-ignored-file-predicates)]
(describe "accept"
(it "accepts change event when git-mode is enabled"
(let ((treemacs-git-mode t)
(event '(nil changed "~/A/a")))
(expect (treemacs--is-event-relevant? event) :to-be-truthy)))
(it "accepts create events"
(-let [event '(nil created "~/A/a")]
(expect (treemacs--is-event-relevant? event) :to-be-truthy)))
(it "accepts delete events"
(-let [event '(nil deleted "~/A/a")]
(expect (treemacs--is-event-relevant? event) :to-be-truthy))))
(describe "reject"
(it "rejects stop-watch event"
(-let [event '(nil stopped "~/A/a")]
(expect (treemacs--is-event-relevant? event) :not :to-be-truthy)))
(it "rejects change event when git-mode is disabled"
(let ((treemacs-git-mode nil)
(event '(nil changed "~/A/a")))
(expect (treemacs--is-event-relevant? event) :not :to-be-truthy)))
(it "rejects lockfile events"
(-let [event '(nil created "~/A/.#foo.el")]
(expect (treemacs--is-event-relevant? event) :not :to-be-truthy)))
(it "rejects flycheck file events"
(-let [event '(nil created "~/A/flycheck_foo.el")]
(expect (treemacs--is-event-relevant? event) :not :to-be-truthy))))))
(describe "treemacs--file-extension"
(it "Fails on nil input"
(expect (treemacs--file-extension nil) :to-throw))
(it "Returns empty string when input is empty string"
(expect (treemacs--file-extension "") :to-equal ""))
(it "Returns empty string when input is only period"
(expect (treemacs--file-extension ".") :to-equal ""))
(it "Returns empty string when input is many periods"
(expect (treemacs--file-extension ".......") :to-equal ""))
(it "Returns input for an absolute path without extension"
(expect (treemacs--file-extension "/A/B/C/D/foo") :to-equal "/A/B/C/D/foo"))
(it "Returns the filename of a filename without extension"
(expect (treemacs--file-extension "foo") :to-equal "foo"))
(it "Returns the extension of an absolute path"
(expect (treemacs--file-extension "~/A/B/C/D/foo.el") :to-equal "el"))
(it "Returns the extension of a filename"
(expect (treemacs--file-extension "foo.el") :to-equal "el"))
(it "Returns the extension of absolute path with periods"
(expect (treemacs--file-extension "~/A/foo.bar/baz.qux/foo.el") :to-equal "el")))
(describe "treemacs--partition-imenu-index"
(it "Returns nil on nil input"
(expect (treemacs--partition-imenu-index nil "A") :not :to-be-truthy))
(it "Returns index unchanged when input has no top level leaves"
(expect '(("A" ("a1" "a2")) ("B" ("b1" "b2")))
:to-equal
(treemacs--partition-imenu-index '(("A" ("a1" "a2")) ("B" ("b1" "b2"))) "Functions")))
(it "Partitions single top-level list into Functions"
(expect '(("Functions" ("x" "y" "z")))
:to-equal
(treemacs--partition-imenu-index '(("x" "y" "z")) "Functions")))
(it "Partitions top-level lists into Functions"
(expect '(("A" ("a1" "a2")) ("B" ("b1" "b2")) ("Functions" ("x" "y" "z")))
:to-equal
(treemacs--partition-imenu-index '(("A" ("a1" "a2")) ("B" ("b1" "b2")) ("x" "y" "z")) "Functions"))))
(describe "treemacs--should-reenter?"
(describe "Accepting"
(it "Accepts nil"
(expect (treemacs--should-reenter? nil)
:to-be t))
(it "Accepts custom nodes"
(expect (treemacs--should-reenter? '(:custom A B))
:to-be t))
(it "Accepts non-string/cons paths"
(expect (treemacs--should-reenter? 'X)
:to-be t))
(it "Accepts non-dotfiles"
(-let [treemacs-show-hidden-files nil]
(expect (treemacs--should-reenter? "/foo/bar")
:to-be t)))
(it "Accepts extensions under non-dotfiles"
(-let [treemacs-show-hidden-files nil]
(expect (treemacs--should-reenter? '("/foo/bar" A B))
:to-be t)))
(it "Accepts dotfiles when they are shown"
(-let [treemacs-show-hidden-files t]
(expect (treemacs--should-reenter? "/foo/.bar")
:to-be t)))
(it "Accepts extensions under dotfiles when they are shown"
(-let [treemacs-show-hidden-files t]
(expect (treemacs--should-reenter? '("/foo/.bar" A B))
:to-be t))))
(describe "Rejecting"
(it "Rejects dotfiles when they are hidden"
(-let [treemacs-show-hidden-files nil]
(expect (treemacs--should-reenter? "/foo/.bar")
:to-be nil)))
(it "Rejects extensions under dotfiles when they are hidden"
(-let [treemacs-show-hidden-files nil]
(expect (treemacs--should-reenter? '("/foo/.bar" A B))
:to-be nil)))))
(describe "treemacs--parent"
(it "Does not fail for nil input"
(expect (treemacs--parent nil) :to-be nil))
(it "Returns nil when input is empty"
(expect (treemacs--parent "") :to-be nil))
(it "Returns nil when input is not a valid path"
(expect (treemacs--parent "ABC") :to-be nil))
(it "Correctly identifies a parent path"
(expect (treemacs--parent "/home/A/B") :to-equal "/home/A"))
(it "Returns the system root when it's the input"
(expect (treemacs--parent "/") :to-equal "/"))
(it "Returns parent of root-level extension node."
(expect (treemacs--parent '(a b)) :to-equal '(a)))
(it "Returns parent of directory extension node."
(expect (treemacs--parent '("/test1" "a" "b")) :to-equal '("/test1" "a"))))
(describe "treemacs--get-or-parse-git-result"
(it "Returns an empty table when input is nil"
(-let [result (treemacs--get-or-parse-git-result nil)]
(expect result :to-be-truthy)
(expect (ht-empty? result) :to-be t)))
(it "Returns an already parsed table"
(let ((input (pfuture-new "echo"))
(result (ht)))
(process-put input 'git-table result)
(expect (treemacs--get-or-parse-git-result input) :to-be result)))
(it "Parses a process' git output"
(spy-on #'treemacs--git-status-parse-function
:and-return-value (ht ("A" 1) ("B" 2)))
(let* ((input (pfuture-new "echo"))
(result (treemacs--get-or-parse-git-result input)))
(expect (ht? result))
(expect (= 2 (ht-size result)))
(expect (= 1 (ht-get result "A")))
(expect (= 2 (ht-get result "B")))
(expect #'treemacs--git-status-parse-function :to-have-been-called))))
(describe "treemacs--on-rename"
(it "Does nothing when the dom is empty"
(with-temp-buffer
(-let [treemacs-dom (ht)]
(treemacs--on-rename "OLD" "NEW" nil)
(expect (ht-empty? treemacs-dom) :to-be t))))
(it "Does nothing when the old key is not in the dom"
(with-temp-buffer
(-let [treemacs-dom (ht ("A" (treemacs-dom-node->create! :key "A")))]
(treemacs--on-rename "OLD" "NEW" nil)
(expect (ht-size treemacs-dom) :to-equal 1)
(expect (ht-get treemacs-dom "A") :to-be-truthy))))
(it "Correctly renamed a full subtree"
(with-temp-buffer
(let* ((default-directory "/A")
(root (treemacs-dom-node->create! :key "/A"))
(node1 (treemacs-dom-node->create! :key "/A/OLD"))
(node2 (treemacs-dom-node->create! :key "/A/OLD/X"))
(node3 (treemacs-dom-node->create! :key "/A/OLD/X/Y"))
(node4 (treemacs-dom-node->create! :key (list "/A/OLD/X/Y" "Classes")))
(node5 (treemacs-dom-node->create! :key (list "/A/OLD/X/Y" "Classes" "Class Foo")))
(node6 (treemacs-dom-node->create! :key (list "/A/OLD/X/Y" "Classes" "Class Foo" "void bar()")))
(nodex (treemacs-dom-node->create! :key "/A/B"))
(nodey (treemacs-dom-node->create! :key "/A/B/C")))
(setf (treemacs-dom-node->parent nodex) root
(treemacs-dom-node->parent nodey) root
(treemacs-dom-node->parent node1) root
(treemacs-dom-node->parent node2) node1
(treemacs-dom-node->parent node3) node2
(treemacs-dom-node->parent node4) node3
(treemacs-dom-node->parent node5) node4
(treemacs-dom-node->parent node6) node5
(treemacs-dom-node->children root) (list node1 nodex nodey)
(treemacs-dom-node->children node1) (list node2)
(treemacs-dom-node->children node2) (list node3)
(treemacs-dom-node->children node3) (list node4)
(treemacs-dom-node->children node4) (list node5)
(treemacs-dom-node->children node5) (list node6))
(setq treemacs-dom
(ht ((treemacs-dom-node->key root) root)
((treemacs-dom-node->key nodex) nodex)
((treemacs-dom-node->key nodey) nodey)
((treemacs-dom-node->key node1) node1)
((treemacs-dom-node->key node2) node2)
((treemacs-dom-node->key node3) node3)
((treemacs-dom-node->key node4) node4)
((treemacs-dom-node->key node5) node5)
((treemacs-dom-node->key node6) node6)))
(treemacs--on-rename "/A/OLD" "/A/NEW" nil)
(dolist (key '("/A/OLD"
"/A/OLD/X"
"/A/OLD/X/Y"
("/A/OLD/X/Y" "Classes")
("/A/OLD/X/Y" "Classes" "Class Foo")
("/A/OLD/X/Y" "Classes" "Class Foo" "void bar()")))
(expect (ht-get treemacs-dom key) :to-be nil))
(dolist (key '("/A/NEW" "/A/NEW/X" "/A/NEW/X/Y"
("/A/NEW/X/Y" "Classes")
("/A/NEW/X/Y" "Classes" "Class Foo")
("/A/NEW/X/Y" "Classes" "Class Foo" "void bar()")))
(expect (ht-get treemacs-dom key) :to-be-truthy))
(expect (ht-size treemacs-dom) :to-equal 9))))
(it "Won't rename initial node when filewatch is enabled"
(with-temp-buffer
(let* ((default-directory "/A")
(root (treemacs-dom-node->create! :key "/A"))
(node1 (treemacs-dom-node->create! :key "/A/OLD"))
(node2 (treemacs-dom-node->create! :key "/A/OLD/X"))
(node3 (treemacs-dom-node->create! :key "/A/OLD/X/Y"))
(nodex (treemacs-dom-node->create! :key "/A/B"))
(nodey (treemacs-dom-node->create! :key "/A/B/C")))
(setf (treemacs-dom-node->parent nodex) root
(treemacs-dom-node->parent nodey) root
(treemacs-dom-node->parent node1) root
(treemacs-dom-node->parent node2) node1
(treemacs-dom-node->parent node3) node2
(treemacs-dom-node->children root) (list node1 nodex nodey)
(treemacs-dom-node->children node1) (list node2)
(treemacs-dom-node->children node2) (list node3))
(setf treemacs-dom
(ht ((treemacs-dom-node->key root) root)
((treemacs-dom-node->key nodex) nodex)
((treemacs-dom-node->key nodey) nodey)
((treemacs-dom-node->key node1) node1)
((treemacs-dom-node->key node2) node2)
((treemacs-dom-node->key node3) node3)))
(treemacs--on-rename "/A/OLD" "/A/NEW" t)
(dolist (key '("/A/OLD/X" "/A/OLD/X/Y"))
(expect (ht-get treemacs-dom key) :to-be nil))
(dolist (key '("/A/OLD" "/A/NEW/X" "/A/NEW/X/Y"))
(expect (ht-get treemacs-dom key) :to-be-truthy))
(expect (ht-size treemacs-dom) :to-equal 6)))))
(describe "treemacs-on-collapse"
(it "Fails when key is nil"
(with-temp-buffer
(-let [treemacs-dom (ht)]
(expect (treemacs-on-collapse nil) :to-throw))))
(it "Removes empty nodes from reentry"
(with-temp-buffer
(let* ((default-directory "/A")
(treemacs-dom (ht))
(root (progn
(ht-set! treemacs-dom default-directory
(treemacs-dom-node->create! :key default-directory))
(treemacs-find-in-dom default-directory)))
(node (progn
(ht-set! treemacs-dom "/A/B"
(treemacs-dom-node->create! :key "/A/B"))
(treemacs-find-in-dom "/A/B"))))
(setf (treemacs-dom-node->parent node) root
(treemacs-dom-node->children root) (list node)
(treemacs-dom-node->reentry-nodes root) (list node))
(treemacs-on-collapse "/A/B")
(expect (treemacs-dom-node->reentry-nodes root) :to-be nil))))
(it "Keeps node with children in reentry"
(with-temp-buffer
(let* ((default-directory "/A")
(treemacs-dom (ht))
(root (progn
(ht-set! treemacs-dom default-directory
(treemacs-dom-node->create! :key default-directory))
(treemacs-find-in-dom default-directory)))
(node1 (progn
(ht-set! treemacs-dom "/A/B"
(treemacs-dom-node->create! :key "/A/B"))
(treemacs-find-in-dom "/A/B")))
(node2 (progn
(ht-set! treemacs-dom "/A/B/C"
(treemacs-dom-node->create! :key "/A/B/C"))
(treemacs-find-in-dom "/A/B/C"))))
(setf (treemacs-dom-node->parent node1) root
(treemacs-dom-node->parent node2) node1
(treemacs-dom-node->children root) (list node1)
(treemacs-dom-node->children node1) (list node2)
(treemacs-dom-node->reentry-nodes root) (list node1)
(treemacs-dom-node->reentry-nodes node1) (list node2))
(treemacs-on-collapse "/A/B")
(expect (ht-size treemacs-dom)
:to-equal 2)
(expect (treemacs-dom-node->children root)
:to-equal (list node1))
(expect (treemacs-dom-node->children node1)
:to-be nil)
(expect (treemacs-find-in-dom "/A/B/C")
:to-be nil)
(expect (treemacs-dom-node->reentry-nodes root)
:to-be nil)
(expect (treemacs-dom-node->reentry-nodes node1)
:to-equal (list node2)))))
(it "Removes a subtree when purging"
(with-temp-buffer
(let* ((default-directory "/A")
(treemacs-dom (ht))
(root (progn
(ht-set! treemacs-dom default-directory
(treemacs-dom-node->create! :key default-directory))
(treemacs-find-in-dom default-directory)))
(node1 (progn
(ht-set! treemacs-dom "/A/B"
(treemacs-dom-node->create! :key "/A/B"))
(treemacs-find-in-dom "/A/B")))
(node2 (progn
(ht-set! treemacs-dom "/A/B/C" (treemacs-dom-node->create! :key "/A/B/C"))
(treemacs-find-in-dom "/A/B/C"))))
(setf (treemacs-dom-node->parent node1) root
(treemacs-dom-node->parent node2) node1
(treemacs-dom-node->children root) (list node1)
(treemacs-dom-node->children node1) (list node2)
(treemacs-dom-node->reentry-nodes root) (list node1)
(treemacs-dom-node->reentry-nodes node1) (list node2))
(treemacs-on-collapse "/A/B" :purge)
(expect (ht-size treemacs-dom)
:to-equal 2)
(expect (ht-get treemacs-dom "/A/B/C")
:to-be nil)
(expect (treemacs-dom-node->children node1)
:to-be nil)
(expect (treemacs-dom-node->reentry-nodes node1)
:to-be nil)))))
(describe "treemacs-on-expand"
(it "Fails when key is nil"
(with-temp-buffer
(-let [treemacs-dom (ht)]
(expect (treemacs-on-expand nil 1) :to-be nil))))
(it "Correctly expands root node"
(with-temp-buffer
(let* ((default-directory "/A")
(treemacs-dom (ht)))
(treemacs-on-expand "/A" 1)
(-let [root (treemacs-find-in-dom default-directory)]
(expect (ht-size treemacs-dom) :to-equal 1)
(expect (treemacs-dom-node->position root) :to-equal 1)
(expect (treemacs-dom-node->parent root) :to-be nil)))))
(it "Correctly expands child node"
(with-temp-buffer
(let* ((default-directory "/A")
(treemacs-dom (ht))
(root (progn
(ht-set! treemacs-dom default-directory
(treemacs-dom-node->create! :key default-directory))
(treemacs-find-in-dom default-directory)))
(node (progn
(ht-set! treemacs-dom "/A/B"
(treemacs-dom-node->create! :key "/A/B"))
(treemacs-find-in-dom "/A/B"))))
(setf (treemacs-dom-node->parent node) root
(treemacs-dom-node->children root) (list node))
(treemacs-on-expand "/A/B" 2)
(expect (treemacs-dom-node->position node) :to-equal 2)
(expect (treemacs-dom-node->reentry-nodes root) :to-equal (list node))))))
(when treemacs-should-run-file-notify-tests
(describe "treemacs--start-watching"
(before-each
(spy-on #'file-notify-add-watch :and-return-value 123456))
(it "Stars watching an unwatched file"
(let ((path "/A")
(treemacs-filewatch-mode t)
(treemacs--filewatch-index (make-hash-table :test #'equal))
(treemacs--collapsed-filewatch-index (make-hash-table :test #'equal)))
(treemacs--start-watching path t)
(expect (gethash path treemacs--filewatch-index)
:to-equal
(cons (list (current-buffer)) 123456))
(expect (gethash path treemacs--collapsed-filewatch-index) :to-be-truthy)
(expect #'file-notify-add-watch :to-have-been-called)))
(it "Keeps watching an already watched file"
(let ((path "/A")
(treemacs-filewatch-mode t)
(treemacs--filewatch-index (make-hash-table :test #'equal))
(treemacs--collapsed-filewatch-index (make-hash-table :test #'equal)))
(puthash path (cons '(x y) 123456) treemacs--filewatch-index)
(treemacs--start-watching path t)
(expect (gethash path treemacs--filewatch-index)
:to-equal
(cons (list (current-buffer) 'x 'y) 123456))
(expect (gethash path treemacs--collapsed-filewatch-index)
:to-be-truthy)
(expect #'file-notify-add-watch :not :to-have-been-called)))
(it "Adds a watching buffer only once"
(let ((path "/A")
(treemacs-filewatch-mode t)
(treemacs--filewatch-index (make-hash-table :test #'equal))
(treemacs--collapsed-filewatch-index (make-hash-table :test #'equal)))
(puthash path (cons '(x y) 123456) treemacs--filewatch-index)
(treemacs--start-watching path t)
(treemacs--start-watching path t)
(expect (gethash path treemacs--filewatch-index)
:to-equal
(cons (list (current-buffer) 'x 'y) 123456))
(expect (gethash path treemacs--collapsed-filewatch-index) :to-be-truthy)
(expect #'file-notify-add-watch :not :to-have-been-called)))))
(when treemacs-should-run-file-notify-tests
(describe "treemacs--stop-watching"
(it "Does nothing when path is not watched"
(let ((treemacs--filewatch-index (make-hash-table :test #'equal))
(treemacs--collapsed-filewatch-index (make-hash-table :test #'equal)))
(expect (treemacs--stop-watching "/A") :to-be nil)))
(it "Stops the watch of the only watching buffer"
(spy-on #'file-notify-rm-watch :and-return-value t)
(let ((path "/A")
(treemacs--filewatch-index (make-hash-table :test #'equal))
(treemacs--collapsed-filewatch-index (make-hash-table :test #'equal)))
(puthash path (cons (list (current-buffer)) 123456) treemacs--filewatch-index)
(puthash path t treemacs--collapsed-filewatch-index)
(treemacs--stop-watching path)
(expect (gethash path treemacs--filewatch-index) :to-be nil)
(expect (gethash path treemacs--collapsed-filewatch-index) :to-be nil)))
(it "Stops the watch of one of several buffers"
(spy-on #'file-notify-rm-watch)
(let ((path "/A")
(treemacs--filewatch-index (make-hash-table :test #'equal))
(treemacs--collapsed-filewatch-index (make-hash-table :test #'equal)))
(puthash path (cons (list 'x 'y (current-buffer)) 123456) treemacs--filewatch-index)
(puthash path t treemacs--collapsed-filewatch-index)
(treemacs--stop-watching path)
(expect (gethash path treemacs--filewatch-index)
:to-equal (cons '(x y) 123456))
(expect (gethash path treemacs--collapsed-filewatch-index) :to-be-truthy)
(expect #'file-notify-rm-watch :not :to-have-been-called)))
(it "Stops the watch of path below stopped path"
(spy-on #'file-notify-rm-watch :and-return-value t)
(let ((path "/A/B")
(treemacs--filewatch-index (make-hash-table :test #'equal))
(treemacs--collapsed-filewatch-index (make-hash-table :test #'equal)))
(puthash path (cons (list (current-buffer)) 123456) treemacs--filewatch-index)
(puthash path t treemacs--collapsed-filewatch-index)
(treemacs--stop-watching "/A")
(expect (gethash path treemacs--filewatch-index) :to-be nil)
(expect (gethash path treemacs--collapsed-filewatch-index) :to-be nil)))
(it "Stops the watch of all watching buffers"
(spy-on #'file-notify-rm-watch :and-return-value t)
(let ((path "/A")
(treemacs--filewatch-index (make-hash-table :test #'equal))
(treemacs--collapsed-filewatch-index (make-hash-table :test #'equal)))
(puthash path (cons '(x y z) 123456) treemacs--filewatch-index)
(puthash path t treemacs--collapsed-filewatch-index)
(treemacs--stop-watching path t)
(expect (gethash path treemacs--filewatch-index) :to-be nil)
(expect (gethash path treemacs--collapsed-filewatch-index) :to-be nil)))))
(describe "treemacs--flatten&sort-imenu-index"
(it "Correctly transforms an org-mode index"
(let ((org-imenu-depth 10)
(temp-file (make-temp-file "Treemacs Test")))
(ignore org-imenu-depth) ; for the compiler
(unwind-protect
(progn
(find-file-noselect temp-file)
(with-current-buffer (get-file-buffer temp-file)
(insert "* H1\n")
(insert "** H1.2\n")
(insert "*** H1.2.3\n")
(insert "* H2\n")
(org-mode)
(save-buffer)
(expect (treemacs--flatten&sort-imenu-index)
:to-equal
`((("H1" . ,(move-marker (make-marker) 1)))
(("H1.2" . ,(move-marker (make-marker) 6)) "H1")
(("H1.2.3" . ,(move-marker (make-marker) 14)) "H1" "H1.2")
(("H2" . ,(move-marker (make-marker) 25)))))))
(kill-buffer (get-file-buffer temp-file))
(delete-file temp-file)))))
(describe "treemacs--find-index-pos"
(it "Fails when point is nil"
(-let [pos nil]
(expect (treemacs--find-index-pos pos '((("A" . (make-marker))))) :to-throw)))
(it "Returns nil when index is nil"
(expect (treemacs--find-index-pos 1 nil) :to-be nil))
(it "Finds the correct position before the first marker"
(let ((input `((("A" . ,(move-marker (make-marker) 10)))
(("B" . ,(move-marker (make-marker) 20)))
(("C" . ,(move-marker (make-marker) 30))))))
(expect (treemacs--find-index-pos 1 input)
:to-equal (car input))))
(it "Finds the correct position after the last marker"
(let ((input `((("A" . ,(move-marker (make-marker) 10)))
(("B" . ,(move-marker (make-marker) 20)))
(("C" . ,(move-marker (make-marker) 30))))))
(expect (treemacs--find-index-pos 100 input)
:to-equal (-last-item input))))
(it "Finds an index using binary search"
(spy-on #'treemacs--binary-index-search :and-call-through)
(with-temp-buffer
;; make those markers viable
(dotimes (_ 10) (insert " \n"))
(let ((input `((("A" . ,(move-marker (make-marker) 10)))
(("B" . ,(move-marker (make-marker) 20)))
(("C" . ,(move-marker (make-marker) 30)))
(("D" . ,(move-marker (make-marker) 40)))
(("E" . ,(move-marker (make-marker) 50)))
(("F" . ,(move-marker (make-marker) 60)))
(("G" . ,(move-marker (make-marker) 70)))
(("H" . ,(move-marker (make-marker) 80)))
(("I" . ,(move-marker (make-marker) 90))))))
(expect (treemacs--find-index-pos 72 input)
:to-equal (nth 6 input))
(expect #'treemacs--binary-index-search :to-have-been-called)))))
(describe "treemacs--find-project-for-path"
(it "Returns nil when input is nil"
(treemacs--with-project (treemacs-project->create! :path "/A" :path-status 'local-readable)
(expect (treemacs--find-project-for-path nil) :to-be nil)))
(it "Returns nil when the workspace is empty"
(treemacs--with-project nil
(expect (treemacs--find-project-for-path "/A") :to-be nil)))
(it "Returns nil when path does not fit any project"
(treemacs--with-project (treemacs-project->create! :path "/A/B" :path-status 'local-readable)
(expect (treemacs--find-project-for-path "/A/C") :to-be nil)))
(it "Returns project when path fits"
(-let [project (treemacs-project->create! :path "/A/B" :path-status 'local-readable)]
(treemacs--with-project project
(expect (treemacs--find-project-for-path "/A/B/C")
:to-equal project)))))
(describe "treemacs--flatten-imenu-index"
(it "Does nothing when input is nil"
(expect (treemacs--flatten-imenu-index nil) :to-be nil))
(it "Does nothing when input is empty"
(expect (treemacs--flatten-imenu-index (list)) :to-be nil))
(it "Correctly parses a single item"
(expect (treemacs--flatten-imenu-index '("Functions")) :to-be nil))
(it "Correctly parses full index"
(-let [input `(("Functions" ("f1" . 1) ("f2" . 2))
("Types" ("t1" . 3) ("t2" . 4))
("Classes" ("c1" ("Members" ("m1" . 5) ("m2" . 6)))))]
(expect (treemacs--flatten-imenu-index input)
:to-equal
`((("f2" . 2) "Functions")
(("f1" . 1) "Functions")
(("t2" . 4) "Types")
(("t1" . 3) "Types")
(("m2" . 6) "Classes" "c1" "Members")
(("m1" . 5) "Classes" "c1" "Members"))))))
(describe "treemacs--flatten-org-mode-imenu-index"
(it "Does nothing when input is nil"
(expect (treemacs--flatten-org-mode-imenu-index nil) :to-be nil))
(it "Does nothing when input is empty"
(expect (treemacs--flatten-org-mode-imenu-index (list)) :to-be nil))
(it "Correctly parses a single item"
(expect (treemacs--flatten-org-mode-imenu-index '("Functions"))
:to-equal '(("Functions"))))
(it "Correctly parses full index"
(-let [input `(("Functions" ("f1" . 1) ("f2" . 2))
("Types" ("t1" . 3) ("t2" . 4))
("Classes" ("c1" ("Members" ("m1" . 5) ("m2" . 6)))))]
(expect (treemacs--flatten-org-mode-imenu-index input)
:to-equal
`(("Classes")
("Types")
("Functions")
(("f2" . 2) "Functions")
(("f1" . 1) "Functions")
(("t2" . 4) "Types")
(("t1" . 3) "Types")
("c1" "Classes")
("Members" "Classes" "c1")
(("m2" . 6) "Classes" "c1" "Members")
(("m1" . 5) "Classes" "c1" "Members"))))))
(describe "treemacs--next-non-child-button"
(it "Does nothing when input is nil"
(expect (treemacs--next-non-child-button nil) :to-be nil))
(it "Returns nil when there is only a single button"
(with-temp-buffer
(-let [b (insert-text-button "b")]
(expect (treemacs--next-non-child-button b) :to-be nil))))
(it "Directly returns the next button"
(with-temp-buffer
(let ((b1 (insert-text-button "b1"))
(b2 (insert-text-button "b2")))
(button-put b1 :depth 1)
(button-put b2 :depth 1)
(expect (marker-position (treemacs--next-non-child-button b1))
:to-equal b2))))
(it "Searches through higher-depth buttons"
(with-temp-buffer
(let ((b1 (insert-text-button "b1"))
(b2 (insert-text-button "b2"))
(b3 (insert-text-button "b3"))
(b4 (insert-text-button "b4"))
(b5 (insert-text-button "b5"))
(b6 (insert-text-button "b6")))
(button-put b1 :depth 1)
(button-put b2 :depth 2)
(button-put b3 :depth 3)
(button-put b4 :depth 4)
(button-put b5 :depth 5)
(button-put b6 :depth 1)
(expect (marker-position (treemacs--next-non-child-button b1))
:to-equal b6))))
(it "Returns nil when there is no next non-child button"
(with-temp-buffer
(let ((b1 (insert-text-button "b1"))
(b2 (insert-text-button "b2"))
(b3 (insert-text-button "b3"))
(b4 (insert-text-button "b4"))
(b5 (insert-text-button "b5"))
(b6 (insert-text-button "b6")))
(button-put b1 :depth 1)
(button-put b2 :depth 2)
(button-put b3 :depth 3)
(button-put b4 :depth 4)
(button-put b5 :depth 5)
(button-put b6 :depth 6)
(expect (treemacs--next-non-child-button b1) :to-be nil)))))
(describe "treemacs--validate-persist-lines"
(describe "Successes"
(it "Succeeds on correctly formed input"
(-let [lines '("* W1"
"** P1"
" - path :: a"
"** P2"
"- path :: b"
"* W2"
"** P3"
" - path :: c")]
(expect (treemacs--validate-persist-lines lines) :to-be 'success)))
(it "Succeeds with the same path in multiple workspaces"
(-let [lines '("* W1"
"** P1"
" - path :: /A/B"
"* W2"
"** P2"
" - path :: /A/B")]
(expect (treemacs--validate-persist-lines lines) :to-be 'success)))
(it "Succeeds with non-connectable remotes"
(let* ((treemacs--org-edit-buffer-name (buffer-name))
(lines '("* W1"
"** P1"
" - path :: /ftp:anonymous@ftp.invalid:/test-path")))
(expect (treemacs--validate-persist-lines lines) :to-be 'success)))
(it "Succeeds with disabled projects"
(-let [lines '("* W1"
"** COMMENT P1"
" - path :: a"
"** P2"
" - path :: b"
"** COMMENT P3"
" - path :: c")]
(expect (treemacs--validate-persist-lines lines) :to-be 'success)))
(it "Succeeds with disabled workspaces"
(-let [lines '("* COMMENT W1"
"** P1"
" - path :: a"
"* W2"
"** P2"
" - path :: b")]
(expect (treemacs--validate-persist-lines lines) :to-be 'success))))
(describe "Errors"
(it "Fails when first line is not a workspace name"
(-let [lines '("X")]
(expect (treemacs--validate-persist-lines lines)
:to-equal '(error "X" "First item must be a workspace name"))))
(it "Fails when line after workspace name is not a project name"
(-let [lines '("* X"
"Y")]
(expect (treemacs--validate-persist-lines lines)
:to-equal '(error "Y" "Workspace name must be followed by project name"))))
(it "Fails when line after project name is not a property"
(-let [lines '("* X"
"** Y"
"Z")]
(expect (treemacs--validate-persist-lines lines)
:to-equal '(error "** Y" "Project name must be followed by path declaration"))))
(it "Fails when line after path is not a project or workspace"
(-let [lines '("* X"
"** Y"
" - path :: Z"
"A")]
(expect (treemacs--validate-persist-lines lines)
:to-equal '(error " - path :: Z" "Path property must be followed by the next workspace or project"))))
(it "Fails when lines end at workspace name"
(-let [lines '("* X")]
(expect (treemacs--validate-persist-lines lines)
:to-equal '(error "* X" "Cannot end with a project or workspace name"))))
(it "Fails when lines end at project name"
(-let [lines '("* X"
"** X")]
(expect (treemacs--validate-persist-lines lines)
:to-equal '(error "** X" "Cannot end with a project or workspace name"))))
(it "Fails when input is empty"
(expect (treemacs--validate-persist-lines nil)
:to-equal '(error :start "Input is empty")))
(it "Fails when path appears more than once"
(-let [lines '("* W1"
"** P1"
" - path :: /A/B/C"
"** P2"
" - path :: /A/B/C/D")]
(expect (treemacs--validate-persist-lines lines)
:to-equal
'(error " - path :: /A/B/C/D" "Path '/A/B/C/D' appears in the workspace more than once."))))
(it "Fails when all projects are disabled"
(-let [lines '("* W1"
"** COMMENT P1"
" - path :: a"
"** COMMENT P2"
" - path :: b"
"** COMMENT P3"
" - path :: c")]
(expect (treemacs--validate-persist-lines lines)
:to-equal '(error " - path :: c" "Workspace must contain at least 1 project that is not disabled."))))
(it "Fails when all workspaces are disabled"
(-let [lines '("* COMMENT W1"
"** P1"
" - path :: a"
"* COMMENT W2"
"** P2"
" - path :: b")]
(expect (treemacs--validate-persist-lines lines)
:to-equal '(error " - path :: b" "There must be at least 1 worspace that is not disabled."))))))
(describe "treemacs--read-persist-lines"
(it "Ignores commentes"
(expect (treemacs--read-persist-lines "#\n#\n#") :to-be nil))
(it "Ignores blanks"
(expect (treemacs--read-persist-lines " \n \n \t \t ") :to-be nil))
(it "Reads everything else"
(expect (treemacs--read-persist-lines
(concat "#Foo: Bar\n" "\n" "* Workspace\n" "\t\n" "** Project\n" "#Comment\n" " - path :: /x\n"))
:to-equal
'("* Workspace" "** Project" " - path :: /x"))))
(describe "treemacs--read-workspaces"
(before-each
(spy-on #'treemacs--get-path-status :and-return-value 'local-readable))
(it "Reads workspaces correctly"
(let* ((list '("* WS 1"
"** P1"
" - path :: /a"
"** P2" " - path :: /b"
"* WS 2"
"** P3"
" - path :: /c"
"** P4"
" - path :: /d"))
(iter (treemacs-iter->create! :list list))
(result (treemacs--read-workspaces iter))
(disabled-workspaces (car result))
(workspaces (cadr result)))
(expect (length disabled-workspaces) :to-be 0)
(expect (length workspaces) :to-be 2)
(let* ((ws1 (car workspaces))
(ws2 (cadr workspaces))
(ws1-projects (treemacs-workspace->projects ws1))
(ws2-projects (treemacs-workspace->projects ws2)))
(expect (treemacs-workspace->name ws1) :to-equal "WS 1")
(expect (treemacs-workspace->name ws2) :to-equal "WS 2")
(expect (length ws1-projects) :to-be 2)
(expect (length ws2-projects) :to-be 2)
(let ((pr1 (car ws1-projects))
(pr2 (cadr ws1-projects))
(pr3 (car ws2-projects))
(pr4 (cadr ws2-projects)))
(expect (treemacs-project->name pr1) :to-equal "P1")
(expect (treemacs-project->name pr2) :to-equal "P2")
(expect (treemacs-project->name pr3) :to-equal "P3")
(expect (treemacs-project->name pr4) :to-equal "P4")
(expect (treemacs-project->path pr1) :to-equal "/a")
(expect (treemacs-project->path pr2) :to-equal "/b")
(expect (treemacs-project->path pr3) :to-equal "/c")
(expect (treemacs-project->path pr4) :to-equal "/d")))))
(it "Reads disbled workspaces correctly"
(let* ((list '("* COMMENT WS 1"
"** P1"
" - path :: /a"))
(iter (treemacs-iter->create! :list list))
(result (treemacs--read-workspaces iter))
(disabled-workspaces (car result))
(workspaces (cadr result)))
(expect (length disabled-workspaces) :to-be 1)
(expect (length workspaces) :to-be 0)
(let* ((ws1 (car disabled-workspaces))
(ws1-projects (treemacs-workspace->projects ws1)))
(expect (treemacs-workspace->name ws1) :to-equal "WS 1")
(expect (treemacs-workspace->is-disabled? ws1) :to-be t)
(expect (length ws1-projects) :to-be 1)
(let ((pr1 (car ws1-projects)))
(expect (treemacs-project->name pr1) :to-equal "P1")
(expect (treemacs-project->path pr1) :to-equal "/a")))))
(it "Reads disabled projects"
(let* ((list '("* WS 1"
"** COMMENT P1"
" - path :: /a"))
(iter (treemacs-iter->create! :list list))
(result (treemacs--read-workspaces iter))
(workspaces (cadr result))
(disabled-workspaces (car result)))
(expect (length workspaces) :to-be 1)
(expect (length disabled-workspaces) :to-be 0)
(-let [project (-> workspaces (car) (treemacs-workspace->projects) (car))]
(expect (treemacs-project->name project) :to-equal "P1")
(expect (treemacs-project->is-disabled? project) :to-be t)))))
(describe "treemacs--git-status-process"
(it "Does not call treemacs--git-status-process-function with non-local or unreadable paths"
(dolist (status '(local-unreadable remote-readable remote-unreadable remote-disconnected extension))
(spy-on 'treemacs--git-status-process-function)
(-> treemacs-dir
(treemacs-join-path "test")
(treemacs--git-status-process (treemacs-project->create! :name "P" :path treemacs-dir :path-status status)))
(expect 'treemacs--git-status-process-function
:not :to-have-been-called)))
(it "Calls treemacs--git-status-process-function with local readable path"
(spy-on 'treemacs--git-status-process-function)
(let ((path (treemacs-join-path treemacs-dir "test")))
(treemacs--git-status-process path (treemacs-project->create! :name "P" :path treemacs-dir :path-status 'local-readable))
(expect 'treemacs--git-status-process-function
:to-have-been-called-with path))))
(describe "treemacs--process-collapsed-dirs"
(it "Does nothing with non-local or unreadable paths"
(-let [treemacs-collapse-dirs 3]
(dolist (status '(local-unreadable remote-readable remote-unreadable remote-disconnected extension))
(expect (-> treemacs-dir
(treemacs-join-path "test")
(treemacs--flattened-dirs-process (treemacs-project->create! :name "P" :path treemacs-dir :path-status status)))
:to-equal
nil)))))
(describe "treemacs--remove-trailing-newline"
(it "Fails on nil input"
(expect (treemacs--remove-trailing-newline nil)
:to-throw))
(it "Fails on empty string"
(expect (treemacs--remove-trailing-newline "")
:to-throw))
(it "Does nothing when input does not need trimming"
(-let [input "abc"]
(expect (treemacs--remove-trailing-newline input) :to-equal input)))
(it "Removes the last newline"
(expect (treemacs--remove-trailing-newline "abc\n") :to-equal "abc"))
(it "Removes only the last newline"
(expect (treemacs--remove-trailing-newline "abc\n\n\n") :to-equal "abc\n\n")))
(describe "treemacs--add-trailing-slash"
(it "Fails on nil input"
(expect (treemacs--add-trailing-slash nil) :to-throw))
(it "Fails on blank input"
(expect (treemacs--add-trailing-slash "") :to-throw))
(it "Does not add slash if one is already present"
(expect (treemacs--add-trailing-slash "/ABC/") :to-equal "/ABC/"))
(it "Adds a slash when there isn't one"
(expect (treemacs--add-trailing-slash "/ABC") :to-equal "/ABC/")))
(describe "treemacs--is-name-invalid?"
(it "detects nil"
(expect (treemacs--is-name-invalid? nil) :to-be t))
(it "detects an empty string"
(expect (treemacs--is-name-invalid? "") :to-be t))
(it "detects a blank string"
(expect (treemacs--is-name-invalid? " ") :to-be t))
(it "detects a string with newlines"
(expect (treemacs--is-name-invalid? "a\nb") :to-be t)))
(describe "treemacs--find-workspace"
(it "Finds nothing when there are no workspaces"
(treemacs--save-workspace
(-let [treemacs--workspaces nil]
(treemacs--find-workspace)
(expect (treemacs-current-workspace) :to-be nil)))
(treemacs--save-workspace
(-let [treemacs--workspaces nil]
(treemacs--find-workspace "X")
(expect (treemacs-current-workspace) :to-be nil))))
(it "Finds the first workspace when there is no current file"
(treemacs--save-workspace
(let* ((ws1 (treemacs-workspace->create! :name "A"))
(ws2 (treemacs-workspace->create! :name "B"))
(treemacs--workspaces (list ws1 ws2)))
(treemacs--find-workspace)
(expect (treemacs-current-workspace) :to-be ws1))))
(it "Finds the first workspace when nothing fits the current file"
(treemacs--save-workspace
(let* ((p1 (treemacs-project->create! :name "P1" :path "P1"))
(p2 (treemacs-project->create! :name "P2" :path "P2"))
(ws1 (treemacs-workspace->create! :name "A" :projects (list p1)))
(ws2 (treemacs-workspace->create! :name "B" :projects (list p2)))
(treemacs--workspaces (list ws1 ws2)))
(treemacs--find-workspace "X")
(expect (treemacs-current-workspace) :to-be ws1))))
(it "Finds workspace which contains current file"
(treemacs--save-workspace
(let* ((p1 (treemacs-project->create! :name "P1" :path "P1"))
(p2 (treemacs-project->create! :name "P2" :path "/A"))
(ws1 (treemacs-workspace->create! :name "A" :projects (list p1)))
(ws2 (treemacs-workspace->create! :name "B" :projects (list p2)))
(treemacs--workspaces (list ws1 ws2)))
(treemacs--find-workspace "/A/B/C")
(expect (treemacs-current-workspace) :to-be ws2)))))
(defmacro test-treemacs--with-sample-buffer (&rest body)
"Evaluate BODY with some buttons defined.
In BODY, variable PROJECT is defined."
(declare (indent 0))
(let ((parent-marker (make-symbol "parent-marker")))
`(with-temp-buffer
(let ((project (treemacs-project->create! :name "Project" :path "/project"))
(,parent-marker nil))
(insert-text-button "Project"
:path "/project"
:state 'root-node-open
:depth 0
:project project)
(setq ,parent-marker (copy-marker (line-beginning-position)))
(insert "\n")
(insert-text-button "directory"
:path "/project/directory"
:key "/project/directory"
:state 'dir-node-open
:parent ,parent-marker
:depth 1)
(setq ,parent-marker (copy-marker (line-beginning-position)))
(insert "\n")
(insert-text-button "file.txt"
:path "/project/directory/file.txt"
:key "/project/directory/file.txt"
:state 'file-node-closed
:parent ,parent-marker
:depth 2)
(setq ,parent-marker (copy-marker (line-beginning-position)))
(insert "\n")
(goto-char 0)
,@body))))
(defun test-treemacs--format-pattern (template expected-1 expected-2 expected-3)
"Test that `treemacs--format-bookmark-title' expands TEMPLATE correctly.
EXPECTED-1 is the expected expansion of the \"Project\" button.
EXPECTED-2 is the expected expansion of the \"directory\" button.
EXPECTED-3 is the expected expansion of the \"file.txt\" button."
(test-treemacs--with-sample-buffer
(let ((treemacs-bookmark-title-template template))
(expect (treemacs--format-bookmark-title (treemacs-current-button)) :to-equal expected-1)
(forward-line 1)
(expect (treemacs--format-bookmark-title (treemacs-current-button)) :to-equal expected-2)
(forward-line 1)
(expect (treemacs--format-bookmark-title (treemacs-current-button)) :to-equal expected-3))))
(describe "treemacs-collect-child-nodes"
(it "Finds nothing for last node"
(with-temp-buffer
(insert (propertize "Root" 'button t :depth 1))
(insert "\n")
(goto-char 0)
(let* ((parent-btn (point-marker))
(result (treemacs-collect-child-nodes parent-btn)))
(expect result :to-be nil))))
(it "Finds nothing for node without direct children"
(with-temp-buffer
(let* ((root1 (progn
(insert (propertize "Root1" 'button t 'category 'treemacs-button :depth 1))
(beginning-of-line)
(point-marker)))
(input (progn
(end-of-line)
(insert "\n" (propertize " Input" 'button t 'category 'treemacs-button :depth 2 :parent root1))
(beginning-of-line)
(point-marker)))
(_root2 (progn
(end-of-line)
(insert "\n" (propertize "Root2" 'button t 'category 'treemacs-button :depth 1))
(beginning-of-line)
(point-marker))) )
(-let [result (treemacs-collect-child-nodes input)]
(expect result :to-be nil)))))
(it "Finds only direct children"
(with-temp-buffer
(let* ((root1 (progn
(insert (propertize "Root1" 'button t 'category 'treemacs-button :depth 1))
(beginning-of-line)
(point-marker)))
(input (progn
(end-of-line)
(insert "\n" (propertize " Input" 'button t 'category 'treemacs-button :depth 2 :parent root1))
(beginning-of-line)
(point-marker)))
(child1 (progn
(end-of-line)
(insert "\n" (propertize " Child1" 'button t 'category 'treemacs-button :depth 3 :parent input))
(beginning-of-line)
(point-marker)))
(_grand-child (progn
(end-of-line)
(insert "\n" (propertize " Grand Child" 'button t 'category 'treemacs-button :depth 4 :parent child1))
(beginning-of-line)
(point-marker)))
(_child2 (progn
(end-of-line)
(insert "\n" (propertize " Child2" 'button t 'category 'treemacs-button :depth 3 :parent input))
(beginning-of-line)
(point-marker))) )
(-let [result (-map #'treemacs--get-label-of (treemacs-collect-child-nodes input))]
(expect result :to-have-same-items-as '(" Child1" " Child2")))))))
(describe "treemacs--format-bookmark-title"
(it "Uses the configured pattern"
(test-treemacs--format-pattern "No replacements" "No replacements" "No replacements" "No replacements"))
(it "Formats the project name"
(test-treemacs--format-pattern "${project}" "Project" "Project" "Project"))
(it "Formats the label"
(test-treemacs--format-pattern "${label}" "Project" "directory" "file.txt"))
(it "Formats the parent label"
(test-treemacs--format-pattern "${label:1}" "" "Project" "directory"))
(it "Formats the grandparent label"
(test-treemacs--format-pattern "${label:2}" "" "" "Project"))
(it "Formats the label path"
(test-treemacs--format-pattern "${label-path}" "Project" "Project/directory" "Project/directory/file.txt"))
(it "Formats the limited label path"
(test-treemacs--format-pattern "${label-path:2}" "Project" "Project/directory" "directory/file.txt"))
(it "Does not hang with negatie label path limit"
(test-treemacs--format-pattern "${label-path:-2}" "Project" "Project/directory" "Project/directory/file.txt"))
(it "Formats the file path"
(test-treemacs--format-pattern "${file-path}" "/project" "/project/directory" "/project/directory/file.txt"))
(it "Formats the limited file path"
(test-treemacs--format-pattern "${file-path:2}" "/project" "/project/directory" "directory/file.txt"))
(it "Does not hang with negative file path"
(test-treemacs--format-pattern "${file-path:-1}" "" "" "")))
(describe "treemacs-dom-node->remove-collapse-keys!"
(it "Removes and deletes all collapse entries"
(with-temp-buffer
(let* ((dom-node (treemacs-dom-node->create!
:key "Main Key"
:collapse-keys '("Key 1" "Key 2" "Key 3")))
(treemacs-dom (ht ("Main Key" dom-node)
("Key 1" dom-node)
("Key 2" dom-node)
("Key 3" dom-node))))
(treemacs-dom-node->remove-collapse-keys! dom-node '("Key 1" "Key 3"))
(expect (treemacs-find-in-dom "Main Key") :to-be dom-node)
(expect (treemacs-find-in-dom "Key 2") :to-be dom-node)
(expect (treemacs-find-in-dom "Key 1") :to-be nil)
(expect (treemacs-find-in-dom "Key 3") :to-be nil)
(expect (treemacs-dom-node->collapse-keys dom-node) :to-equal '("Key 2"))))))
(describe "treemacs--maybe-clean-buffers-on-workspace-switch"
:var* ((tmp-file (make-temp-file "TESTFILE"))
(scratch (get-buffer-create "*scratch*"))
(file-buffer)
(non-file-buffer)
(fake-buffer-list))
(before-each
(setf file-buffer (find-file-noselect tmp-file)
non-file-buffer (get-buffer-create "TESTBUFFER")
fake-buffer-list (list file-buffer non-file-buffer scratch)))
(after-all
(when file-buffer (kill-buffer file-buffer))
(when non-file-buffer (kill-buffer non-file-buffer))
(delete-file tmp-file))
(it "Does nothing when cleanup is set to 'nil'"
(-let [treemacs-workspace-switch-cleanup nil]
(spy-on #'buffer-list :and-return-value fake-buffer-list)
(treemacs--maybe-clean-buffers-on-workspace-switch treemacs-workspace-switch-cleanup)
(expect (buffer-live-p scratch) :to-be t)
(expect (buffer-live-p file-buffer) :to-be t)
(expect (buffer-live-p non-file-buffer) :to-be t)))
(it "Kills file buffers when cleanup is set to 'files'"
(-let [treemacs-workspace-switch-cleanup 'files]
(spy-on #'buffer-list :and-return-value fake-buffer-list)
(treemacs--maybe-clean-buffers-on-workspace-switch treemacs-workspace-switch-cleanup)
(expect (buffer-live-p scratch) :to-be t)
(expect (buffer-live-p file-buffer) :to-be nil)
(expect (buffer-live-p non-file-buffer) :to-be t)))
(it "Kills all buffers when cleanup is set to 'all'"
(-let [treemacs-workspace-switch-cleanup 'all]
(spy-on #'buffer-list :and-return-value fake-buffer-list)
(treemacs--maybe-clean-buffers-on-workspace-switch treemacs-workspace-switch-cleanup)
(expect (buffer-live-p scratch) :to-be t)
(expect (buffer-live-p file-buffer) :to-be nil)
(expect (buffer-live-p non-file-buffer) :to-be nil))))
(describe "treemacs--find-repeated-file-name"
(before-each
(fset 'fake-file-exists
(lambda (p)
(pcase p
("/a/file.el" t)
("/c/file" t)
((guard (and (s-starts-with? "/b/" p)
(not (s-contains? "5" p))))
t)
((guard (and (s-starts-with? "/d/" p)
(not (s-contains? "5" p))))
t) )))
(spy-on 'file-exists-p :and-call-fake 'fake-file-exists))
(it "Returns input when it does not already exist"
(expect (treemacs--find-repeated-file-name "/X/Y/Z")
:to-equal "/X/Y/Z"))
(it "Find a (Copy 1) file with extension"
(expect (treemacs--find-repeated-file-name "/a/file.el")
:to-equal "/a/file (Copy 1).el"))
(it "Find a (Copy 5) file with extension"
(expect (treemacs--find-repeated-file-name "/b/file.el")
:to-equal "/b/file (Copy 5).el"))
(it "Find a (Copy 1) file without extension"
(expect (treemacs--find-repeated-file-name "/c/file")
:to-equal "/c/file (Copy 1)"))
(it "Find a (Copy 5) file without extension"
(expect (treemacs--find-repeated-file-name "/d/file")
:to-equal "/d/file (Copy 5)")))
(describe "treemacs--tokenize-path"
(it "Throws when path is nil"
(expect (treemacs--tokenize-path nil "/a")
:to-throw))
(it "Throws when exclude-prefix is longer than path"
(expect (treemacs--tokenize-path "/a" "/a/b")
:to-throw))
(it "Returns nothing when path and exclude-prefix are equally long"
(expect (treemacs--tokenize-path "/a/b" "/a/b")
:to-be nil))
(it "Tokenizes everything when exclude-prefix is nil"
(expect (treemacs--tokenize-path "/a/b/c/d" nil)
:to-equal '("a" "b" "c" "d")))
(it "Tokenizes everything when exclude-prefix is empty"
(expect (treemacs--tokenize-path "/a/b/c/d" "")
:to-equal '("a" "b" "c" "d")))
(it "Tokenizes everything past the exclude-prefix"
(expect (treemacs--tokenize-path "/a/b/c/d" "/a/b")
:to-equal '("c" "d"))))
(describe "Workspaces"
(describe "treemacs-find-workspace"
(describe "By Name"
(it "Finds the right workspace"
(let* ((ws1 (treemacs-workspace->create! :name "A"))
(ws2 (treemacs-workspace->create! :name "B"))
(ws3 (treemacs-workspace->create! :name "C"))
(treemacs--workspaces (list ws1 ws2 ws3)))
(expect (treemacs-find-workspace-by-name "B") :to-equal ws2)))
(it "Returns nil when no workspaceis found"
(let* ((ws1 (treemacs-workspace->create! :name "A"))
(ws2 (treemacs-workspace->create! :name "B"))
(ws3 (treemacs-workspace->create! :name "C"))
(treemacs--workspaces (list ws1 ws2 ws3)))
(expect (treemacs-find-workspace-by-name "X") :to-be nil))))
(describe "By Path"
(it "Finds the right workspace"
(let* ((ws1 (treemacs-workspace->create! :projects (list (treemacs-project->create! :path "A"))))
(ws2 (treemacs-workspace->create! :projects (list (treemacs-project->create! :path "B"))))
(ws3 (treemacs-workspace->create! :projects (list (treemacs-project->create! :path "C"))))
(treemacs--workspaces (list ws1 ws2 ws3)))
(expect (treemacs-find-workspace-by-path "B") :to-equal ws2)))
(it "Returns nil when no workspaceis found"
(let* ((ws1 (treemacs-workspace->create! :projects (list (treemacs-project->create! :path "A"))))
(ws2 (treemacs-workspace->create! :projects (list (treemacs-project->create! :path "B"))))
(ws3 (treemacs-workspace->create! :projects (list (treemacs-project->create! :path "C"))))
(treemacs--workspaces (list ws1 ws2 ws3)))
(expect (treemacs-find-workspace-by-path "X") :to-be nil))))
(describe "By Predicate"
(it "Finds the right workspace"
(let* ((ws1 (treemacs-workspace->create! :name "A"))
(ws2 (treemacs-workspace->create! :name "B" :projects (list (treemacs-project->create! :path "B"))))
(ws3 (treemacs-workspace->create! :name "B"))
(treemacs--workspaces (list ws1 ws2 ws3)))
(expect (treemacs-find-workspace-where (lambda (ws) (treemacs-workspace->projects ws)))
:to-equal ws2)))
(it "Returns nil when no workspaceis found"
(let* ((ws1 (treemacs-workspace->create! :name "A"))
(ws2 (treemacs-workspace->create! :name "B"))
(ws3 (treemacs-workspace->create! :name "C"))
(treemacs--workspaces (list ws1 ws2 ws3)))
(expect (treemacs-find-workspace-where (lambda (ws) (treemacs-workspace->projects ws)))
:to-be nil)))))
(describe "treemacs-create-workspace"
(describe "Failures"
(it "Fails when name is empty"
(expect (treemacs-do-create-workspace "")
:to-equal
'(invalid-name "")))
(it "Fails when name is blank"
(expect (treemacs-do-create-workspace " ")
:to-equal
'(invalid-name " ")))
(it "Fails when name contains newlines"
(expect (treemacs-do-create-workspace "a\nb")
:to-equal
'(invalid-name "a\nb")))
(it "Fails when name is a duplicate"
(let* ((ws (treemacs-workspace->create! :name "A"))
(treemacs--workspaces (list ws)))
(expect (treemacs-do-create-workspace "A")
:to-equal
`(duplicate-name ,ws)))))
(describe "Successes"
:var* ((treemacs--workspaces nil))
(before-each
(setf treemacs--workspaces nil)
(spy-on #'treemacs--persist nil))
(it "Adds the workspace"
(treemacs-do-create-workspace "Valid Name")
(expect (treemacs-find-workspace-by-name "Valid Name") :to-be-truthy))
(it "Persists the workspace"
(treemacs-do-create-workspace "Valid Name")
(expect #'treemacs--persist :to-have-been-called))
(it "Returns the created workspace"
(expect (car (treemacs-do-create-workspace "Valid Name"))
:to-equal
'success))))
(describe "treemacs-do-remove-workspace"
(describe "Failures"
(it "Cannot delete the last workspace"
(let* ((ws (treemacs-workspace->create!))
(treemacs--workspaces (list ws)))
(expect (treemacs-do-remove-workspace)
:to-equal
'only-one-workspace)))
(it "Can be canceled by the user"
(spy-on #'yes-or-no-p :and-return-value nil)
(let* ((ws1 (treemacs-workspace->create! :name "A"))
(ws2 (treemacs-workspace->create! :name "B"))
(treemacs--workspaces (list ws1 ws2)))
(expect (treemacs-do-remove-workspace "A" :ask-to-confirm)
:to-equal
'user-cancel)))
(it "Only deleted workspaces that exist"
(spy-on #'yes-or-no-p :and-return-value nil)
(let* ((ws1 (treemacs-workspace->create! :name "A"))
(ws2 (treemacs-workspace->create! :name "B"))
(treemacs--workspaces (list ws1 ws2)))
(expect (treemacs-do-remove-workspace "X")
:to-equal
'(workspace-not-found "X")))))
(describe "Successes"
(it "Deletes workspace that is given"
(let* ((ws1 (treemacs-workspace->create! :name "A"))
(ws2 (treemacs-workspace->create! :name "B"))
(treemacs--workspaces (list ws1 ws2)))
(expect (treemacs-do-remove-workspace "B")
:to-equal
`(success ,ws2 ,(list ws1)))))
(it "Deletes workspace that selected interactively"
(spy-on #'completing-read :and-return-value "B")
(let* ((ws1 (treemacs-workspace->create! :name "A"))
(ws2 (treemacs-workspace->create! :name "B"))
(treemacs--workspaces (list ws1 ws2)))
(expect (treemacs-do-remove-workspace)
:to-equal
`(success ,ws2 ,(list ws1)))))))
(describe "treemacs-do-switch-to-workspace"
(before-each
(spy-on #'treemacs--restore :and-return-value nil)
(spy-on #'treemacs--invalidate-buffer-project-cache :and-return-value nil)
(spy-on #'treemacs--rerender-after-workspace-change :and-return-value nil))
(describe "Failures"
(it "Fails when there is only 1 workspace"
(-let [treemacs--workspaces (list (treemacs-workspace->create! :name "A"))]
(expect (treemacs-do-switch-workspace)
:to-equal 'only-one-workspace)))
(it "Fails when workspace cannot be found"
(-let [treemacs--workspaces
(list (treemacs-workspace->create! :name "A")
(treemacs-workspace->create! :name "B"))]
(expect (treemacs-do-switch-workspace "X")
:to-equal '(workspace-not-found "X")))))
(describe "Successes"
(it "Succeeds when workspace is given by name"
(let* ((ws1 (treemacs-workspace->create! :name "A"))
(ws2 (treemacs-workspace->create! :name "B"))
(treemacs--workspaces (list ws1 ws2)))
(expect (treemacs-do-switch-workspace "B")
:to-equal `(success ,ws2))))
(it "Succeeds when workspace is given directly"
(let* ((ws1 (treemacs-workspace->create! :name "A"))
(ws2 (treemacs-workspace->create! :name "B"))
(treemacs--workspaces (list ws1 ws2)))
(expect (treemacs-do-switch-workspace ws2)
:to-equal `(success ,ws2)))))))
(describe "treemacs--select-file-from-current-btn"
:var (btn)
(before-each
(fset
'make-btn
(lambda (&rest props)
(insert "abc")
(goto-char 0)
(put-text-property 1 3 :path "/a/b/c")
(put-text-property 1 3 :button t)
(when props
(apply #'put-text-property 1 3 props))
(setf btn (point-marker))))
(spy-on #'treemacs-current-button :and-return-value btn)
(spy-on #'file-directory-p :and-return-value nil)
(spy-on #'file-regular-p :and-return-value nil))
(it "returns interactively chosen path for flattened nodes"
(with-temp-buffer
(with-no-warnings (make-btn :collapsed '(2 "/a" "/a/b" "/a/b/c")))
(spy-on #'completing-read :and-return-value "/a/b")
(expect (treemacs--select-file-from-btn btn "prompt")
:to-equal "/a/b")))
(it "returns path when it is a directory"
(with-temp-buffer
(with-no-warnings (make-btn))
(spy-on #'file-directory-p :and-return-value t)
(expect (treemacs--select-file-from-btn btn "prompt")
:to-equal "/a/b/c")))
(it "returns parent path when path is file and dir-only is set"
(with-temp-buffer
(with-no-warnings (make-btn))
(spy-on #'file-regular-p :and-return-value t)
(expect (treemacs--select-file-from-btn btn "prompt" :dir-only)
:to-equal "/a/b")))
(it "returns path when it is a file and dir-only is not set"
(with-temp-buffer
(with-no-warnings (make-btn))
(spy-on #'file-regular-p :and-return-value t)
(expect (treemacs--select-file-from-btn btn "prompt" nil)
:to-equal "/a/b/c")))
(it "returns HOME when path is not a string"
(with-temp-buffer
(with-no-warnings (make-btn :path '(a b c)))
(spy-on #'file-regular-p :and-return-value t)
(expect (treemacs--select-file-from-btn btn "prompt")
:to-equal (expand-file-name "~")))) )
(describe "treemacs--select-workspace-by-name"
(before-each
(spy-on #'treemacs--maybe-load-workspaces :and-return-value nil))
(it "returns match for only 1 workspace"
(spy-on #'completing-read :and-return-value "WS")
(let* ((ws (treemacs-workspace->create! :name "WS"))
(treemacs--workspaces (list ws)))
(expect (treemacs--select-workspace-by-name) :to-be ws)))
(it "returns match for more than 1 workspace"
(spy-on #'completing-read :and-return-value "WS2")
(let* ((ws1 (treemacs-workspace->create! :name "WS1"))
(ws2 (treemacs-workspace->create! :name "WS2"))
(treemacs--workspaces (list ws1 ws2)))
(expect (treemacs--select-workspace-by-name) :to-be ws2)))
(it "forces a name selection"
(spy-on #'completing-read :and-call-fake
(-let [c 0]
(lambda (&rest _)
(if (> c 3)
"WS2"
(cl-incf c)
""))))
(let* ((ws1 (treemacs-workspace->create! :name "WS1"))
(ws2 (treemacs-workspace->create! :name "WS2"))
(treemacs--workspaces (list ws1 ws2)))
(expect (treemacs--select-workspace-by-name) :to-be ws2))))
(describe "treemacs--find-workspace-by-name"
(before-each
(spy-on #'treemacs--maybe-load-workspaces :and-return-value nil))
(it "returns match for only 1 workspace"
(let* ((ws (treemacs-workspace->create! :name "WS1"))
(treemacs--workspaces (list ws)))
(expect (treemacs--find-workspace-by-name "WS1") :to-be ws)))
(it "returns match for more than 1 workspace"
(let* ((ws1 (treemacs-workspace->create! :name "WS1"))
(ws2 (treemacs-workspace->create! :name "WS2"))
(treemacs--workspaces (list ws1 ws2)))
(expect (treemacs--find-workspace-by-name "WS2") :to-be ws2)))
(it "returns nil when there is no match"
(let* ((ws1 (treemacs-workspace->create! :name "WS1"))
(ws2 (treemacs-workspace->create! :name "WS2"))
(treemacs--workspaces (list ws1 ws2)))
(expect (treemacs--find-workspace-by-name "X") :to-be nil))))
(describe "annotations"
(describe "cleanup"
(it "won't remove annotation if it has a face"
(-let [treemacs--annotation-store (make-hash-table :size 200 :test 'equal)]
(treemacs-set-annotation-face "Path" 'face "Source")
(-let [ann (treemacs-get-annotation "Path")]
(treemacs--remove-annotation-if-empty ann "Path")
(expect (treemacs-get-annotation "Path") :to-be ann))))
(it "won't remove annotation if it has a git face"
(let* ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal))
(ann (treemacs-annotation->create!)))
(ht-set! treemacs--annotation-store "Path" ann)
(setf (treemacs-annotation->git-face ann) 'face)
(treemacs--remove-annotation-if-empty ann "Path")
(expect (treemacs-get-annotation "Path") :to-be ann)))
(it "won't remove annotation if it has a suffix"
(-let [treemacs--annotation-store (make-hash-table :size 200 :test 'equal)]
(treemacs-set-annotation-suffix "Path" "Suffix" "Source")
(-let [ann (treemacs-get-annotation "Path")]
(treemacs--remove-annotation-if-empty ann "Path")
(expect (treemacs-get-annotation "Path") :to-be ann))))
(it "removes empty annotation"
(let* ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal))
(ann (treemacs-annotation->create!)))
(ht-set! treemacs--annotation-store "Path" ann)
(treemacs--remove-annotation-if-empty ann "Path")
(expect (treemacs-get-annotation "Path") :to-be nil))))
(describe "faces"
(describe "add"
(it "saves single value"
(-let [treemacs--annotation-store (make-hash-table :size 200 :test 'equal)]
(treemacs-set-annotation-face "Path" 'face "Source")
(-let [ann (treemacs-get-annotation "Path")]
(expect (treemacs-annotation->face ann)
:to-equal '(("Source" . face)))
(expect (treemacs-annotation->face-value ann)
:to-equal '(face)))))
(it "saves multiple values"
(-let [treemacs--annotation-store (make-hash-table :size 200 :test 'equal)]
(treemacs-set-annotation-face "Path" 'face1 "Source1")
(treemacs-set-annotation-face "Path" 'face2 "Source2")
(-let [ann (treemacs-get-annotation "Path")]
(expect (treemacs-annotation->face ann)
:to-equal '(("Source1" . face1) ("Source2" . face2)))
(expect (treemacs-annotation->face-value ann)
:to-equal '(face1 face2)))))
(it "updates face for same source"
(-let [treemacs--annotation-store (make-hash-table :size 200 :test 'equal)]
(treemacs-set-annotation-face "Path" 'face1 "Source1")
(treemacs-set-annotation-face "Path" 'face2 "Source1")
(-let [ann (treemacs-get-annotation "Path")]
(expect (treemacs-annotation->face ann)
:to-equal '(("Source1" . face2)))
(expect (treemacs-annotation->face-value ann)
:to-equal '(face2)))))
(it "includes git face as last value element"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal))
(ann (treemacs-annotation->create!)))
(ht-set! treemacs--annotation-store "Path" ann)
(setf (treemacs-annotation->git-face ann) 'git-face)
(treemacs-set-annotation-face "Path" 'face1 "Source1")
(treemacs-set-annotation-face "Path" 'face2 "Source2")
(-let [ann (treemacs-get-annotation "Path")]
(expect (treemacs-annotation->face ann)
:to-equal '(("Source1" . face1) ("Source2" . face2)))
(expect (treemacs-annotation->face-value ann)
:to-equal '(face1 face2 . git-face))))))
(describe "remove"
(it "does nothing when there is no face"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal)))
(treemacs-remove-annotation-face "Path" "Source")
(expect (ht-size treemacs--annotation-store) :to-equal 0)))
(it "removes the last face"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal))
(ann (treemacs-annotation->create!)))
(ht-set! treemacs--annotation-store "Path" ann)
(treemacs-set-annotation-face "Path" 'face "Source")
(treemacs-remove-annotation-face "Path" "Source")
(expect (ht-get treemacs--annotation-store "Path") :to-be ann)
(expect (treemacs-annotation->face ann) :to-be nil)
(expect (treemacs-annotation->face-value ann) :to-be nil)))
(it "sets face value to the git face after removing the last face"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal))
(ann (treemacs-annotation->create!)))
(ht-set! treemacs--annotation-store "Path" ann)
(setf (treemacs-annotation->git-face ann) 'git-face)
(treemacs-set-annotation-face "Path" 'face "Source")
(treemacs-remove-annotation-face "Path" "Source")
(expect (ht-get treemacs--annotation-store "Path") :to-be ann)
(expect (treemacs-annotation->face-value ann) :to-equal 'git-face)))
(it "leaves faces from other sources"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal))
(ann (treemacs-annotation->create!)))
(ht-set! treemacs--annotation-store "Path" ann)
(setf (treemacs-annotation->git-face ann) 'git-face)
(treemacs-set-annotation-face "Path" 'face1 "Source1")
(treemacs-set-annotation-face "Path" 'face2 "Source2")
(treemacs-remove-annotation-face "Path" "Source1")
(expect (ht-get treemacs--annotation-store "Path") :to-be ann)
(expect (treemacs-annotation->face ann) :to-equal '(("Source2" . face2)))
(expect (treemacs-annotation->face-value ann) :to-equal '(face2 . git-face)))))
(describe "clear"
(it "does nothing when there are no annotations"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal)))
(treemacs-clear-annotation-faces "Source")
(expect (ht-size treemacs--annotation-store) :to-be 0)))
(it "does not remove faces for a different source"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal)))
(treemacs-set-annotation-face "Path" 'face "Source1")
(treemacs-clear-annotation-faces "Source2")
(-let [ann (treemacs-get-annotation "Path")]
(expect ann :not :to-be nil)
(expect (treemacs-annotation->face ann) :to-equal '(("Source1" . face))))))
(it "removes empty annotations"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal)))
(treemacs-set-annotation-face "Path" 'face "Source")
(treemacs-clear-annotation-faces "Source")
(expect (treemacs-get-annotation "Path") :to-be nil)))
(it "removes all faces for the given source"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal)))
(treemacs-set-annotation-face "Path1" 'face1 "Source1")
(treemacs-set-annotation-face "Path1" 'face2 "Source2")
(treemacs-set-annotation-face "Path2" 'face1 "Source1")
(treemacs-set-annotation-face "Path2" 'face3 "Source3")
(treemacs-clear-annotation-faces "Source1")
(let ((ann1 (treemacs-get-annotation "Path1"))
(ann2 (treemacs-get-annotation "Path2")))
(expect ann1 :not :to-be nil)
(expect ann2 :not :to-be nil)
(expect (treemacs-annotation->face ann1) :to-equal '(("Source2" . face2)))
(expect (treemacs-annotation->face ann2) :to-equal '(("Source3" . face3))))))))
(describe "suffixes"
(describe "add"
(it "saves single value"
(-let [treemacs--annotation-store (make-hash-table :size 200 :test 'equal)]
(treemacs-set-annotation-suffix "Path" "Suffix" "Source")
(-let [ann (treemacs-get-annotation "Path")]
(expect (treemacs-annotation->suffix ann)
:to-equal '(("Source" . "Suffix")))
(expect (treemacs-annotation->suffix-value ann)
:to-equal "Suffix"))))
(it "saves multiple values"
(-let [treemacs--annotation-store (make-hash-table :size 200 :test 'equal)]
(treemacs-set-annotation-suffix "Path" "Suffix1" "Source1")
(treemacs-set-annotation-suffix "Path" "Suffix2" "Source2")
(-let [ann (treemacs-get-annotation "Path")]
(expect (treemacs-annotation->suffix ann)
:to-equal '(("Source1" . "Suffix1") ("Source2" . "Suffix2")))
(expect (substring-no-properties (treemacs-annotation->suffix-value ann))
:to-equal "Suffix1 Suffix2"))))
(it "updates suffix for same source"
(-let [treemacs--annotation-store (make-hash-table :size 200 :test 'equal)]
(treemacs-set-annotation-suffix "Path" "Suffix1" "Source1")
(treemacs-set-annotation-suffix "Path" "Suffix2" "Source1")
(-let [ann (treemacs-get-annotation "Path")]
(expect (treemacs-annotation->suffix ann)
:to-equal '(("Source1" . "Suffix2")))
(expect (substring-no-properties (treemacs-annotation->suffix-value ann))
:to-equal "Suffix2")))))
(describe "remove"
(it "does nothing when there is no suffix"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal)))
(treemacs-remove-annotation-suffix "Path" "Source")
(expect (ht-size treemacs--annotation-store) :to-equal 0)))
(it "leaves suffixes from other sources"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal))
(ann (treemacs-annotation->create!)))
(ht-set! treemacs--annotation-store "Path" ann)
(treemacs-set-annotation-suffix "Path" "Suffix1" "Source1")
(treemacs-set-annotation-suffix "Path" "Suffix2" "Source2")
(treemacs-remove-annotation-suffix "Path" "Source1")
(expect (ht-get treemacs--annotation-store "Path") :to-be ann)
(expect (treemacs-annotation->suffix ann) :to-equal '(("Source2" . "Suffix2")))
(expect (treemacs-annotation->suffix-value ann) :to-equal "Suffix2"))))
(describe "clear"
(it "does nothing when there are no annotations"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal)))
(treemacs-clear-annotation-faces "Source")
(expect (ht-size treemacs--annotation-store) :to-be 0)))
(it "does not remove suffixes for a different source"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal)))
(treemacs-set-annotation-suffix "Path" "Suffix" "Source1")
(treemacs-clear-annotation-suffixes "Source2")
(-let [ann (treemacs-get-annotation "Path")]
(expect ann :not :to-be nil)
(expect (treemacs-annotation->suffix ann) :to-equal '(("Source1" . "Suffix"))))))
(it "removes empty annotations"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal)))
(treemacs-set-annotation-suffix "Path" "Suffix" "Source")
(treemacs-clear-annotation-suffixes "Source")
(expect (treemacs-get-annotation "Path") :to-be nil)))
(it "removes all suffixes for the given source"
(let ((treemacs--annotation-store (make-hash-table :size 200 :test 'equal)))
(treemacs-set-annotation-suffix "Path1" "Suffix1" "Source1")
(treemacs-set-annotation-suffix "Path1" "Suffix2" "Source2")
(treemacs-set-annotation-suffix "Path2" "Suffix1" "Source1")
(treemacs-set-annotation-suffix "Path2" "Suffix3" "Source3")
(treemacs-clear-annotation-suffixes "Source1")
(let ((ann1 (treemacs-get-annotation "Path1"))
(ann2 (treemacs-get-annotation "Path2")))
(expect ann1 :not :to-be nil)
(expect ann2 :not :to-be nil)
(expect (treemacs-annotation->suffix ann1) :to-equal '(("Source2" . "Suffix2")))
(expect (treemacs-annotation->suffix ann2) :to-equal '(("Source3" . "Suffix3")))))))))
(describe "treemacs--prefix-arg-to-recurse-depth"
(it "translates numbers literally"
(dotimes (n 10)
(expect (treemacs--prefix-arg-to-recurse-depth n) :to-be n)))
(it "translates nil to 0"
(expect (treemacs--prefix-arg-to-recurse-depth nil) :to-be 0))
(it "translates everything else to 999"
(expect (treemacs--prefix-arg-to-recurse-depth '(4)) :to-be 999)
(expect (treemacs--prefix-arg-to-recurse-depth 1.0) :to-be 999)
(expect (treemacs--prefix-arg-to-recurse-depth "a") :to-be 999)
(expect (treemacs--prefix-arg-to-recurse-depth (treemacs-project->create!)) :to-be 999)))
(provide 'test-treemacs)
;;; treemacs-test.el ends here
``` | /content/code_sandbox/test/treemacs-test.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 23,644 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Functions relating to using the mouse in treemacs.
;; NOTE: This module is lazy-loaded.
;;; Code:
(require 'xref)
(require 'easymenu)
(require 'hl-line)
(require 'treemacs-core-utils)
(require 'treemacs-tags)
(require 'treemacs-scope)
(require 'treemacs-follow-mode)
(require 'treemacs-filewatch-mode)
(require 'treemacs-logging)
(eval-when-compile
(require 'cl-lib)
(require 'treemacs-macros))
(treemacs-import-functions-from "treemacs-interface"
treemacs-add-project-to-workspace)
(defvar treemacs--mouse-project-list-functions
'(("Add Project.el project" . treemacs--builtin-project-mouse-selection-menu)))
(defun treemacs--mouse-drag-advice (fn &rest args)
"Advice to wrap `adjust-window-trailing-edge' as FN and its ARGS.
Ensure that treemacs' window width can be changed with the mouse, even if it is
locked."
(with-selected-window (or (treemacs-get-local-window) (selected-window))
(let ((treemacs--width-is-locked)
(window-size-fixed))
(apply fn args))))
(advice-add #'adjust-window-trailing-edge :around #'treemacs--mouse-drag-advice)
(defun treemacs--builtin-project-mouse-selection-menu ()
"Build a mouse selection menu for project.el projects."
(pcase (if (fboundp 'project-known-project-roots)
(->> (project-known-project-roots)
(-map #'treemacs-canonical-path)
(-sort #'string<))
'unavailable)
(`unavailable
(list (vector "Project.el api is not available" #'ignore)))
(`nil
(list (vector "Project.el list is empty" #'ignore)))
(projects
(pcase (--reject (treemacs-is-path it :in-workspace) projects)
(`nil
(list (vector "All Project.el projects are alread in the workspace" #'ignore)))
(candidates
(--map (vector it (lambda () (interactive) (treemacs-add-project-to-workspace it))) candidates))))))
;;;###autoload
(defun treemacs-leftclick-action (event)
"Move focus to the clicked line.
Must be bound to a mouse click, or EVENT will not be supplied."
(interactive "e")
(when (eq 'down-mouse-1 (elt event 0))
(select-window (->> event (cadr) (nth 0)))
(goto-char (posn-point (cadr event)))
(when (region-active-p)
(keyboard-quit))
;; 7th element is the clicked image
(when (->> event (cadr) (nth 7))
(treemacs-do-for-button-state
:on-file-node-closed (treemacs--expand-file-node btn)
:on-file-node-open (treemacs--collapse-file-node btn)
:on-tag-node-closed (treemacs--expand-tag-node btn)
:on-tag-node-open (treemacs--collapse-tag-node btn)
:no-error t))
(treemacs--evade-image)))
;;;###autoload
(defun treemacs-doubleclick-action (event)
"Run the appropriate double-click action for the current node.
In the default configuration this means to expand/collapse directories and open
files and tags in the most recently used window.
This function's exact configuration is stored in
`treemacs-doubleclick-actions-config'.
Must be bound to a mouse double click to properly handle a click EVENT."
(interactive "e")
(when (eq 'double-mouse-1 (elt event 0))
(goto-char (posn-point (cadr event)))
(when (region-active-p)
(keyboard-quit))
(-when-let (state (treemacs--prop-at-point :state))
(--if-let (cdr (assq state treemacs-doubleclick-actions-config))
(progn
(funcall it)
(treemacs--evade-image))
(treemacs-pulse-on-failure "No double click action defined for node of type %s."
(propertize (format "%s" state) 'face 'font-lock-type-face))))))
;;;###autoload
(defun treemacs-single-click-expand-action (event)
"A modified single-leftclick action that expands the clicked nodes.
Can be bound to <mouse1> if you prefer to expand nodes with a single click
instead of a double click. Either way it must be bound to a mouse click, or
EVENT will not be supplied.
Clicking on icons will expand a file's tags, just like
`treemacs-leftclick-action'."
(interactive "e")
(when (eq 'mouse-1 (elt event 0))
(select-window (->> event (cadr) (nth 0)))
(goto-char (posn-point (cadr event)))
(when (region-active-p)
(keyboard-quit))
;; 7th element is the clicked image
(if (->> event (cadr) (nth 7))
(treemacs-do-for-button-state
:on-file-node-closed (treemacs--expand-file-node btn)
:on-file-node-open (treemacs--collapse-file-node btn)
:on-tag-node-closed (treemacs--expand-tag-node btn)
:on-tag-node-open (treemacs--collapse-tag-node btn)
:no-error t)
(-when-let (state (treemacs--prop-at-point :state))
(funcall (cdr (assoc state treemacs-doubleclick-actions-config)))))
(treemacs--evade-image)))
;;;###autoload
(defun treemacs-dragleftclick-action (event)
"Drag a file/dir node to be opened in a window.
Must be bound to a mouse click, or EVENT will not be supplied."
(interactive "e")
(when (eq 'drag-mouse-1 (elt event 0))
(let* ((info1 (elt (cdr event) 0))
(info2 (elt (cdr event) 1))
(source-window (elt info1 0))
(target-window (elt info2 0))
(source-pos (elt info1 1))
(target-pos (elt info2 1))
(treemacs-buffer (treemacs-get-local-buffer)))
(if (eq source-window target-window)
(treemacs--drag-move-files source-pos target-pos)
(let* ((node (with-current-buffer treemacs-buffer (treemacs-node-at-point)))
(path (-some-> node (treemacs-button-get :path))))
(treemacs-with-path path
:file-action (progn (select-window target-window)
(find-file path))
:no-match-action (ignore)))))))
(defun treemacs--drag-move-files (source-pos target-pos)
"Move files with a mouse-drag action.
SOURCE-POS: Start position of the mouse drag.
TARGET-POS: End position of the mouse drag."
(let* ((source-btn (treemacs--button-in-line source-pos))
(target-btn (treemacs--button-in-line target-pos))
(source-key (-some-> source-btn (treemacs-button-get :key)))
(target-key (-some-> target-btn (treemacs-button-get :key)))
(target-dir (and target-key
(if (file-directory-p target-key)
target-key
(treemacs--parent-dir target-key))))
(target-file (and source-key target-key
(treemacs-join-path target-dir (treemacs--filename source-key)))))
(when (and treemacs-move-files-by-mouse-dragging
source-key target-key
(not (string= source-key target-key))
(not (treemacs-is-path source-key :directly-in target-dir)))
(treemacs-do-delete-single-node source-key)
(treemacs--without-filewatch
(rename-file source-key target-file))
(run-hook-with-args 'treemacs-copy-file-functions source-key target-dir)
(treemacs-do-insert-single-node target-file target-dir)
(treemacs-update-single-file-git-state source-key)
(treemacs-update-single-file-git-state target-file)
(treemacs--on-file-deletion source-key)
(treemacs-goto-file-node target-file)
(treemacs-pulse-on-success "Moved %s to %s"
(propertize (treemacs--filename target-file) 'face 'font-lock-string-face)
(propertize target-dir 'face 'font-lock-string-face)))))
;;;###autoload
(defun treemacs-define-doubleclick-action (state action)
"Define the behaviour of `treemacs-doubleclick-action'.
Determines that a button with a given STATE should lead to the execution of
ACTION.
The list of possible states can be found in `treemacs-valid-button-states'.
ACTION should be one of the `treemacs-visit-node-*' commands."
(setf treemacs-doubleclick-actions-config (assq-delete-all state treemacs-doubleclick-actions-config))
(push (cons state action) treemacs-doubleclick-actions-config))
;;;###autoload
(defun treemacs-node-buffer-and-position (&optional _)
"Return source buffer or list of buffer and position for the current node.
This information can be used for future display. Stay in the selected window
and ignore any prefix argument."
(interactive "P")
(treemacs-without-messages
(treemacs--execute-button-action
:file-action (find-file-noselect (treemacs-safe-button-get btn :path))
:dir-action (find-file-noselect (treemacs-safe-button-get btn :path))
:tag-action (treemacs--tag-noselect btn)
:window (selected-window)
:window-arg '(4)
:ensure-window-split nil
:no-match-explanation "")))
(defun treemacs--imenu-tag-noselect (file tag-path)
"Return a list of the source buffer for FILE and the tag's from TAG-PATH."
(let ((tag (-last-item tag-path))
(path (-butlast tag-path)))
(condition-case e
(progn
(find-file-noselect file)
(let ((index (treemacs--get-imenu-index file)))
(dolist (path-item path)
(setq index (cdr (assoc path-item index))))
(-let [(buf . pos)
(treemacs--extract-position (cdr (--first (equal (car it) tag) index)) path)]
;; some imenu implementations, like markdown, will only provide
;; a raw buffer position (an int) to move to
(list (or buf (get-file-buffer file)) pos))))
(error
(treemacs-log-err "Something went wrong when finding tag '%s': %s"
(propertize tag 'face 'treemacs-tags-face)
e)))))
(defun treemacs--tag-noselect (btn)
"Return list of tag source buffer and position for BTN for future display."
(cl-flet ((xref-definition
(identifier)
"Return the first definition of string IDENTIFIER."
(car (xref-backend-definitions (xref-find-backend) identifier)))
(xref-item-buffer
(item)
"Return the buffer in which xref ITEM is defined."
(marker-buffer (save-excursion (xref-location-marker (xref-item-location item)))))
(xref-item-position
(item)
"Return the buffer position where xref ITEM is defined."
(marker-position (save-excursion (xref-location-marker (xref-item-location item))))))
(-let [(tag-buf . tag-pos)
(treemacs-with-button-buffer btn
(let ((marker (treemacs-button-get :marker btn))
(path (treemacs-button-get :path btn)))
(treemacs--extract-position marker path)))]
(if tag-buf
(list tag-buf tag-pos)
(pcase treemacs-goto-tag-strategy
('refetch-index
(let (file tag-path)
(with-current-buffer (marker-buffer btn)
(setq file (treemacs--nearest-path btn)
tag-path (treemacs-button-get btn :path)))
(treemacs--imenu-tag-noselect file tag-path)))
('call-xref
(let ((xref (xref-definition
(treemacs-with-button-buffer btn
(treemacs--get-label-of btn)))))
(when xref
(list (xref-item-buffer xref) (xref-item-position xref)))))
('issue-warning
(treemacs-log-failure "Tag '%s' is located in a buffer that does not exist."
(propertize (treemacs-with-button-buffer btn (treemacs--get-label-of btn)) 'face 'treemacs-tags-face)))
(_ (error "[Treemacs] '%s' is an invalid value for treemacs-goto-tag-strategy" treemacs-goto-tag-strategy)))))))
;;;###autoload
(defun treemacs-rightclick-menu (event)
"Show a contextual right click menu based on click EVENT."
(interactive "e")
(treemacs-without-following
(unless (eq major-mode 'treemacs-mode)
;; no when-let - the window must exist or this function would not be called
(select-window (treemacs-get-local-window)))
(goto-char (posn-point (cadr event)))
(hl-line-highlight)
;; need to redisplay manually so hl-line and point move correctly
;; and visibly
(redisplay)
(cl-labels ((check (value) (not (null value))))
(let* ((node (treemacs-node-at-point))
(state (-some-> node (treemacs-button-get :state)))
(project (treemacs-project-at-point))
(menu
(easy-menu-create-menu
nil
`(["Paste here"
treemacs-paste-dir-at-point-to-minibuffer
:visible ,(string-match-p "\\(\\(Move\\)\\|\\(Copy\\)\\) to: " (or (minibuffer-prompt) ""))]
("New"
["New File" treemacs-create-file]
["New Directory" treemacs-create-dir])
["Open" treemacs-visit-node-no-split :visible ,(check node)]
("Open With" :visible ,(not (null node))
["Open Directly" treemacs-visit-node-no-split]
["Open In External Application" treemacs-visit-node-in-external-application]
["Open With Vertical Split" treemacs-visit-node-vertical-split]
["Open With Horizontal Split" treemacs-visit-node-horizontal-split]
["Open With Ace" treemacs-visit-node-ace]
["Open With Ace & Vertical Split" treemacs-visit-node-ace-vertical-split]
["Open With Ace & Horizontal Split" treemacs-visit-node-ace-horizontal-split])
["Open Tags" treemacs-toggle-node :visible ,(check (memq state '(file-node-closed tag-node-closed)))]
["Close Tags" treemacs-toggle-node :visible ,(check (memq state '(file-node-open tag-node-open)))]
["--" #'ignore :visible ,(check node)]
["Rename" treemacs-rename-file :visible ,(check node)]
["Delete" treemacs-delete-file :visible ,(check node)]
["Move" treemacs-move-file :visible ,(check node)]
("Copy"
["Copy File" treemacs-copy-file :visible ,(check node)]
["Copy Absolute Path" treemacs-copy-absolute-path-at-point :visible ,(check node)]
["Copy Relative Path" treemacs-copy-relative-path-at-point :visible ,(check node)]
["Copy Project Path" treemacs-copy-project-path-at-point :visible ,(check node)])
["--" #'ignore t]
("Projects"
["Add Project" treemacs-add-project]
,@(--map `(,(car it) ,@(funcall (cdr it)))
treemacs--mouse-project-list-functions)
["Remove Project" treemacs-remove-project-from-workspace :visible ,(check project)]
["Rename Project" treemacs-rename-project :visible ,(check project)])
("Workspaces"
["Edit Workspaces" treemacs-edit-workspaces]
["Create Workspace" treemacs-create-workspace]
["Remove Workspace" treemacs-remove-workspace]
["Rename Workspace" treemacs-rename-workspace]
["Switch Workspace" treemacs-switch-workspace]
["Set Fallback Workspace" treemacs-set-fallback-workspace])
("Toggles"
[,(format "Dotfile Visibility (Currently %s)"
(if treemacs-show-hidden-files "Enabled" "Disabled"))
treemacs-toggle-show-dotfiles]
[,(format "Follow-Mode (Currently %s)"
(if treemacs-follow-mode "Enabled" "Disabled"))
treemacs-follow-mode]
[,(format "Filewatch-Mode (Currently %s)"
(if treemacs-filewatch-mode "Enabled" "Disabled"))
treemacs-filewatch-mode]
[,(format "Fringe-Indicator-Mode (Currently %s)"
(if treemacs-fringe-indicator-mode "Enabled" "Disabled"))
treemacs-fringe-indicator-mode])
("Help"
["Show Helpful Hydra" treemacs-helpful-hydra]
["Show Active Extensions" treemacs-show-extensions]
["Show Changelog" treemacs-show-changelog]))))
(choice (x-popup-menu event menu))
(cmd (lookup-key menu (apply 'vector choice))))
;; In the terminal clicking on a nested menu item does not expand it, but actually
;; selects it as the chosen use option. So as a workaround we need to manually go
;; through the menus until we land on an executable command.
(while (and (not (commandp cmd))
(not (eq cmd menu)))
(setf menu choice
choice (x-popup-menu event cmd)
cmd (lookup-key cmd (apply 'vector choice))))
(when (and cmd (commandp cmd))
(call-interactively cmd))
(hl-line-highlight)))))
(provide 'treemacs-mouse-interface)
;;; treemacs-mouse-interface.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-mouse-interface.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 4,061 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Not autoloaded, but user-facing functions.
;;; Code:
(require 'hl-line)
(require 'button)
(require 's)
(require 'dash)
(require 'treemacs-core-utils)
(require 'treemacs-filewatch-mode)
(require 'treemacs-rendering)
(require 'treemacs-scope)
(require 'treemacs-follow-mode)
(require 'treemacs-customization)
(require 'treemacs-workspaces)
(require 'treemacs-persistence)
(require 'treemacs-logging)
(eval-when-compile
(require 'cl-lib)
(require 'treemacs-macros))
(autoload 'ansi-color-apply-on-region "ansi-color")
(treemacs-import-functions-from "ace-window"
ace-select-window)
(treemacs-import-functions-from "cfrs"
cfrs-read)
(treemacs-import-functions-from "treemacs"
treemacs-find-file
treemacs-select-window)
(treemacs-import-functions-from "treemacs-tags"
treemacs--expand-file-node
treemacs--collapse-file-node
treemacs--expand-tag-node
treemacs--collapse-tag-node
treemacs--goto-tag
treemacs--visit-or-expand/collapse-tag-node)
(defvar treemacs-valid-button-states
'(root-node-open
root-node-closed
dir-node-open
dir-node-closed
file-node-open
file-node-closed
tag-node-open
tag-node-closed
tag-node)
"List of all valid values for treemacs buttons' :state property.")
(defun treemacs-next-line (&optional count)
"Go to next line.
A COUNT argument, moves COUNT lines down."
(interactive "p")
;; Move to EOL - if point is in the middle of a button, forward-button
;; just moves to the end of the current button.
(goto-char (line-end-position))
;; Don't show the "No more buttons" message.
(ignore-errors
(forward-button count treemacs-wrap-around))
;; Move to BOL, since the button might not start at BOL, but parts
;; of Treemacs might expect that the point is always at BOL.
(forward-line 0)
(treemacs--evade-image))
(defun treemacs-previous-line (&optional count)
"Go to previous line.
A COUNT argument, moves COUNT lines up."
(interactive "p")
;; Move to the start of line - if point is in the middle of a button,
;; backward-button just moves to the start of the current button.
(forward-line 0)
;; Don't show the "No more buttons" message.
(ignore-errors
(backward-button count treemacs-wrap-around))
;; Move to BOL, since backward-button moves to the end of the button,
;; and the button might not start at BOL, but parts of Treemacs might
;; expect that the point is always at BOL.
(forward-line 0)
(treemacs--evade-image))
(defun treemacs-toggle-node (&optional arg)
"Expand or close the current node.
If a prefix ARG is provided the open/close process is done recursively. When
opening directories that means that all sub-directories are opened as well.
When opening files all their tag sections will be opened.
Recursively closing any kind of node means that treemacs will forget about
everything that was expanded below that node.
Since tags cannot be opened or closed a goto definition action will called on
them instead."
(interactive "P")
(treemacs-do-for-button-state
:on-root-node-open (treemacs--collapse-root-node btn arg)
:on-root-node-closed (treemacs--expand-root-node btn arg)
:on-dir-node-open (treemacs--collapse-dir-node btn arg)
:on-dir-node-closed (treemacs--expand-dir-node btn :recursive arg)
:on-file-node-open (treemacs--collapse-file-node btn arg)
:on-file-node-closed (treemacs--expand-file-node btn arg)
:on-tag-node-open (treemacs--collapse-tag-node btn arg)
:on-tag-node-closed (treemacs--expand-tag-node btn arg)
:on-tag-node-leaf (progn (other-window 1) (treemacs--goto-tag btn))
:on-nil (treemacs-pulse-on-failure "There is nothing to do here.")
:fallback (treemacs-TAB-action)))
(defun treemacs-toggle-node-prefer-tag-visit (&optional arg)
"Same as `treemacs-toggle-node' but will visit a tag node in some conditions.
Tag nodes, despite being expandable sections, will be visited in the following
conditions:
* Tags belong to a .py file and the tag section's first child element's label
ends in \" definition*\". This indicates the section is the parent element in
a nested class/function definition and can be moved to.
* Tags belong to a .org file and the tag section element possesses a
\\='org-imenu-marker text property. This indicates that the section is a
headline with further org elements below it.
The prefix argument ARG is treated the same way as with `treemacs-toggle-node'."
(interactive)
(run-hook-with-args
'treemacs-after-visit-functions
(treemacs-do-for-button-state
:on-root-node-open (treemacs--collapse-root-node btn arg)
:on-root-node-closed (treemacs--expand-root-node btn)
:on-dir-node-open (treemacs--collapse-dir-node btn arg)
:on-dir-node-closed (treemacs--expand-dir-node btn :recursive arg)
:on-file-node-open (treemacs--collapse-file-node btn arg)
:on-file-node-closed (treemacs--expand-file-node btn arg)
:on-tag-node-open (treemacs--visit-or-expand/collapse-tag-node btn arg t)
:on-tag-node-closed (treemacs--visit-or-expand/collapse-tag-node btn arg t)
:on-tag-node-leaf (progn (other-window 1) (treemacs--goto-tag btn))
:on-nil (treemacs-pulse-on-failure "There is nothing to do here."))))
(defun treemacs-TAB-action (&optional arg)
"Run the appropriate TAB action for the current node.
In the default configuration this usually means to expand or close the content
of the currently selected node. A potential prefix ARG is passed on to the
executed action, if possible.
This function's exact configuration is stored in `treemacs-TAB-actions-config'."
(interactive "P")
(-when-let (state (treemacs--prop-at-point :state))
(--if-let (cdr (assq state treemacs-TAB-actions-config))
(progn
(funcall it arg)
(treemacs--evade-image))
(treemacs-pulse-on-failure "No TAB action defined for node of type %s."
(propertize (format "%s" state) 'face 'font-lock-type-face)))))
(defun treemacs-goto-parent-node (&optional _arg)
"Select parent of selected node, if possible.
ARG is optional and only available so this function can be used as an action."
(interactive)
(--if-let (-some-> (treemacs-current-button) (treemacs-button-get :parent))
(goto-char it)
(treemacs-pulse-on-failure "There is no parent to move up to.")))
(defun treemacs-next-neighbour ()
"Select next node at the same depth as currently selected node, if possible."
(interactive)
(or (-some-> (treemacs-current-button)
(treemacs--next-neighbour-of)
(goto-char))
(treemacs-pulse-on-failure)))
(defun treemacs-previous-neighbour ()
"Select previous node at the same depth as currently selected node, if possible."
(interactive)
(or (-some-> (treemacs-current-button)
(treemacs--prev-non-child-button)
(goto-char))
(treemacs-pulse-on-failure)))
(defun treemacs-visit-node-vertical-split (&optional arg)
"Open current file or tag by vertically splitting `next-window'.
Stay in the current window with a single prefix argument ARG, or close the
treemacs window with a double prefix argument."
(interactive "P")
(run-hook-with-args
'treemacs-after-visit-functions
(treemacs--execute-button-action
:split-function #'split-window-vertically
:file-action (find-file (treemacs-safe-button-get btn :path))
:dir-action (dired (treemacs-safe-button-get btn :path))
:tag-section-action (treemacs--visit-or-expand/collapse-tag-node btn arg nil)
:tag-action (treemacs--goto-tag btn)
:window-arg arg
:no-match-explanation "Node is neither a file, a directory or a tag - nothing to do here.")))
(defun treemacs-visit-node-horizontal-split (&optional arg)
"Open current file or tag by horizontally splitting `next-window'.
Stay in the current window with a single prefix argument ARG, or close the
treemacs window with a double prefix argument."
(interactive "P")
(run-hook-with-args
'treemacs-after-visit-functions
(treemacs--execute-button-action
:split-function #'split-window-horizontally
:file-action (find-file (treemacs-safe-button-get btn :path))
:dir-action (dired (treemacs-safe-button-get btn :path))
:tag-section-action (treemacs--visit-or-expand/collapse-tag-node btn arg nil)
:tag-action (treemacs--goto-tag btn)
:window-arg arg
:no-match-explanation "Node is neither a file, a directory or a tag - nothing to do here.")))
(defun treemacs-visit-node-close-treemacs (&optional _)
"Open current node without and close treemacs.
Works just like calling `treemacs-visit-node-no-split' with a double prefix
arg."
(interactive "P")
(treemacs-visit-node-no-split '(16)))
(defun treemacs-visit-node-no-split (&optional arg)
"Open current node without performing any window split or window selection.
The node will be displayed in the window next to treemacs, the exact selection
is determined by `next-window'. If the node is already opened in some other
window then that window will be selected instead.
Stay in the current window with a single prefix argument ARG, or close the
treemacs window with a double prefix argument."
(interactive "P")
(run-hook-with-args
'treemacs-after-visit-functions
(treemacs--execute-button-action
:file-action (find-file (treemacs-safe-button-get btn :path))
:dir-action (dired (treemacs-safe-button-get btn :path))
:tag-section-action (treemacs--visit-or-expand/collapse-tag-node btn arg nil)
:tag-action (treemacs--goto-tag btn)
:window-arg arg
:ensure-window-split t
:window (-some-> btn (treemacs--nearest-path) (get-file-buffer) (get-buffer-window))
:no-match-explanation "Node is neither a file, a directory or a tag - nothing to do here.")))
(defun treemacs-visit-node-ace (&optional arg)
"Open current file or tag in window selected by `ace-window'.
Stay in the current window with a single prefix argument ARG, or close the
treemacs window with a double prefix argument."
(interactive "P")
(run-hook-with-args
'treemacs-after-visit-functions
(treemacs--execute-button-action
:window (ace-select-window)
:file-action (find-file (treemacs-safe-button-get btn :path))
:dir-action (dired (treemacs-safe-button-get btn :path))
:tag-section-action (treemacs--visit-or-expand/collapse-tag-node btn arg nil)
:tag-action (treemacs--goto-tag btn)
:window-arg arg
:ensure-window-split t
:no-match-explanation "Node is neither a file, a directory or a tag - nothing to do here.")))
(defun treemacs-visit-node-in-most-recently-used-window (&optional arg)
"Open current file or tag in window selected by `get-mru-window'.
Stay in the current window with a single prefix argument ARG, or close the
treemacs window with a double prefix argument."
(interactive "P")
(run-hook-with-args
'treemacs-after-visit-functions
(treemacs--execute-button-action
:window (get-mru-window (selected-frame) nil :not-selected)
:file-action (find-file (treemacs-safe-button-get btn :path))
:dir-action (dired (treemacs-safe-button-get btn :path))
:tag-section-action (treemacs--visit-or-expand/collapse-tag-node btn arg nil)
:tag-action (treemacs--goto-tag btn)
:window-arg arg
:ensure-window-split t
:no-match-explanation "Node is neither a file, a directory or a tag - nothing to do here.")))
(defun treemacs-visit-node-ace-horizontal-split (&optional arg)
"Open current file by horizontally splitting window selected by `ace-window'.
Stay in the current window with a single prefix argument ARG, or close the
treemacs window with a double prefix argument."
(interactive "P")
(run-hook-with-args
'treemacs-after-visit-functions
(treemacs--execute-button-action
:split-function #'split-window-horizontally
:window (ace-select-window)
:file-action (find-file (treemacs-safe-button-get btn :path))
:dir-action (dired (treemacs-safe-button-get btn :path))
:tag-section-action (treemacs--visit-or-expand/collapse-tag-node btn arg nil)
:tag-action (treemacs--goto-tag btn)
:window-arg arg
:no-match-explanation "Node is neither a file, a directory or a tag - nothing to do here.")))
(defun treemacs-visit-node-ace-vertical-split (&optional arg)
"Open current file by vertically splitting window selected by `ace-window'.
Stay in the current window with a single prefix argument ARG, or close the
treemacs window with a double prefix argument."
(interactive "P")
(run-hook-with-args
'treemacs-after-visit-functions
(treemacs--execute-button-action
:split-function #'split-window-vertically
:window (ace-select-window)
:file-action (find-file (treemacs-safe-button-get btn :path))
:dir-action (dired (treemacs-safe-button-get btn :path))
:tag-section-action (treemacs--visit-or-expand/collapse-tag-node btn arg nil)
:tag-action (treemacs--goto-tag btn)
:window-arg arg
:no-match-explanation "Node is neither a file, a directory or a tag - nothing to do here.")))
(defun treemacs-visit-node-default (&optional arg)
"Run `treemacs-default-visit-action' for the current button.
A potential prefix ARG is passed on to the executed action, if possible."
(interactive "P")
(funcall-interactively treemacs-default-visit-action arg))
(defun treemacs-RET-action (&optional arg)
"Run the appropriate RET action for the current button.
In the default configuration this usually means to open the content of the
currently selected node. A potential prefix ARG is passed on to the executed
action, if possible.
This function's exact configuration is stored in `treemacs-RET-actions-config'."
(interactive "P")
(-when-let (state (treemacs--prop-at-point :state))
(--if-let (cdr (assq state treemacs-RET-actions-config))
(progn
(funcall it arg)
(treemacs--evade-image))
(treemacs-pulse-on-failure "No RET action defined for node of type %s."
(propertize (format "%s" state) 'face 'font-lock-type-face)))))
(defun treemacs-define-RET-action (state action)
"Define the behaviour of `treemacs-RET-action'.
Determines that a button with a given STATE should lead to the execution of
ACTION.
The list of possible states can be found in `treemacs-valid-button-states'.
ACTION should be one of the `treemacs-visit-node-*' commands."
(setf treemacs-RET-actions-config (assq-delete-all state treemacs-RET-actions-config))
(push (cons state action) treemacs-RET-actions-config))
(defun treemacs-define-TAB-action (state action)
"Define the behaviour of `treemacs-TAB-action'.
Determines that a button with a given STATE should lead to the execution of
ACTION.
The list of possible states can be found in `treemacs-valid-button-states'.
ACTION should be one of the `treemacs-visit-node-*' commands."
(setf treemacs-TAB-actions-config (assq-delete-all state treemacs-TAB-actions-config))
(push (cons state action) treemacs-TAB-actions-config))
(defun treemacs-COLLAPSE-action (&optional arg)
"Run the appropriate COLLAPSE action for the current button.
In the default configuration this usually means to close the content of the
currently selected node. A potential prefix ARG is passed on to the executed
action, if possible.
This function's exact configuration is stored in
`treemacs-COLLAPSE-actions-config'."
(interactive "P")
(-when-let (state (treemacs--prop-at-point :state))
(--if-let (cdr (assq state treemacs-COLLAPSE-actions-config))
(progn
(funcall it arg)
(treemacs--evade-image))
(treemacs-pulse-on-failure "No COLLAPSE action defined for node of type %s."
(propertize (format "%s" state) 'face 'font-lock-type-face)))))
(defun treemacs-define-COLLAPSE-action (state action)
"Define the behaviour of `treemacs-COLLAPSE-action'.
Determines that a button with a given STATE should lead to the execution of
ACTION.
The list of possible states can be found in `treemacs-valid-button-states'.
ACTION should be one of the `treemacs-visit-node-*' commands."
(setf treemacs-COLLAPSE-actions-config (assq-delete-all state treemacs-COLLAPSE-actions-config))
(push (cons state action) treemacs-COLLAPSE-actions-config))
(defun treemacs-visit-node-in-external-application ()
"Open current file according to its mime type in an external application.
Treemacs knows how to open files on linux, windows and macos."
(interactive)
;; code adapted from ranger.el
(-if-let (path (treemacs--prop-at-point :path))
(pcase system-type
('windows-nt
(declare-function w32-shell-execute "w32fns.c")
(w32-shell-execute "open" (replace-regexp-in-string "/" "\\" path t t)))
('darwin
(shell-command (format "open \"%s\"" path)))
('gnu/linux
(let (process-connection-type)
(start-process
"" nil "sh" "-c"
;; XXX workaround for #633
(format "xdg-open %s; sleep 1"
(shell-quote-argument path)))))
(_ (treemacs-pulse-on-failure "Don't know how to open files on %s."
(propertize (symbol-name system-type) 'face 'font-lock-string-face))))
(treemacs-pulse-on-failure "Nothing to open here.")))
(defun treemacs-quit (&optional arg)
"Quit treemacs with `bury-buffer'.
With a prefix ARG call `treemacs-kill-buffer' instead."
(interactive "P")
(if arg
(treemacs-kill-buffer)
(bury-buffer)
(run-hooks 'treemacs-quit-hook)))
(defun treemacs-kill-buffer ()
"Kill the treemacs buffer."
(interactive)
(when treemacs--in-this-buffer
;; teardown logic handled in kill hook
(if (one-window-p)
(kill-this-buffer)
(kill-buffer-and-window))
(run-hooks 'treemacs-kill-hook)))
(defun treemacs-toggle-show-dotfiles ()
"Toggle the hiding and displaying of dotfiles.
For toggling the display of git-ignored files see
`treemacs-hide-gitignored-files-mode'."
(interactive)
(setq treemacs-show-hidden-files (not treemacs-show-hidden-files))
(treemacs-run-in-every-buffer
(treemacs--do-refresh (current-buffer) 'all))
(treemacs-log "Dotfiles will now be %s"
(if treemacs-show-hidden-files "displayed." "hidden.")))
(defun treemacs-toggle-fixed-width ()
"Toggle whether the local treemacs buffer should have a fixed width.
See also `treemacs-width.'"
(interactive)
(-if-let (buffer (treemacs-get-local-buffer))
(with-current-buffer buffer
(setq treemacs--width-is-locked (not treemacs--width-is-locked)
window-size-fixed (when treemacs--width-is-locked 'width))
(treemacs-log "Window width has been %s."
(propertize (if treemacs--width-is-locked "locked" "unlocked")
'face 'font-lock-string-face)))
(treemacs-log-failure "There is no treemacs buffer in the current scope.")))
(defun treemacs-set-width (&optional arg)
"Select a new value for `treemacs-width'.
With a prefix ARG simply reset the width of the treemacs window."
(interactive "P")
(unless arg
(setq treemacs-width
(->> treemacs-width
(format "New Width (current = %s): ")
(read-number))))
(treemacs--set-width treemacs-width))
(defun treemacs-increase-width (&optional arg)
"Increase the value for `treemacs-width' with `treemacs-width-increment'.
With a prefix ARG add the increment value multiple times."
(interactive "P")
(let* ((treemacs-window (treemacs-get-local-window))
(multiplier (if (numberp arg) arg 1))
(old-width (window-body-width treemacs-window))
(new-width (+ old-width (* multiplier treemacs-width-increment))))
(setq treemacs-width new-width)
(treemacs--set-width new-width)
(let ((current-size (window-body-width treemacs-window)))
(when (not (eq current-size new-width))
(setq treemacs-width old-width)
(treemacs--set-width old-width)
(treemacs-pulse-on-failure "Could not increase window width!")))))
(defun treemacs-decrease-width (&optional arg)
"Decrease the value for `treemacs-width' with `treemacs-width-increment'.
With a prefix ARG substract the increment value multiple times."
(interactive "P")
(let* ((treemacs-window (treemacs-get-local-window))
(multiplier (if (numberp arg) arg 1))
(old-width (window-body-width treemacs-window))
(new-width (- old-width (* multiplier treemacs-width-increment))))
(setq treemacs-width new-width)
(treemacs--set-width new-width)
(let ((current-size (window-body-width treemacs-window)))
(when (not (eq current-size new-width))
(setq treemacs-width old-width)
(treemacs--set-width old-width)
(treemacs-pulse-on-failure "Could not decrease window width!")))))
(defun treemacs-copy-absolute-path-at-point ()
"Copy the absolute path of the node at point."
(interactive)
(treemacs-block
(-let [path (treemacs--prop-at-point :path)]
(treemacs-error-return-if (null path)
"There is nothing to copy here")
(treemacs-error-return-if (not (stringp path))
"Path at point is not a file.")
(when (file-directory-p path)
(setf path (treemacs--add-trailing-slash path)))
(kill-new path)
(treemacs-pulse-on-success "Copied absolute path: %s" (propertize path 'face 'font-lock-string-face)))))
(defun treemacs-copy-relative-path-at-point ()
"Copy the path of the node at point relative to the project root."
(interactive)
(treemacs-block
(let ((path (treemacs--prop-at-point :path))
(project (treemacs-project-at-point)))
(treemacs-error-return-if (null path)
"There is nothing to copy here")
(treemacs-error-return-if (not (stringp path))
"Path at point is not a file.")
(when (file-directory-p path)
(setf path (treemacs--add-trailing-slash path)))
(-let [copied (-> path (file-relative-name (treemacs-project->path project)))]
(kill-new copied)
(treemacs-pulse-on-success "Copied relative path: %s" (propertize copied 'face 'font-lock-string-face))))))
(defun treemacs-copy-project-path-at-point ()
"Copy the absolute path of the current treemacs root."
(interactive)
(treemacs-block
(-let [project (treemacs-project-at-point)]
(treemacs-error-return-if (null project)
"There is nothing to copy here")
(treemacs-error-return-if (not (stringp (treemacs-project->path project)))
"Project at point is not a file.")
(-let [copied (-> project (treemacs-project->path))]
(kill-new copied)
(treemacs-pulse-on-success "Copied project path: %s" (propertize copied 'face 'font-lock-string-face))))))
(defun treemacs-paste-dir-at-point-to-minibuffer ()
"Paste the directory at point into the minibuffer.
This is used by the \"Paste here\" mouse menu button, which assumes that we are
running `treemacs--copy-or-move', so that pasting this path into the minibuffer
allows us to copy/move the previously-selected file into the path at point."
(interactive)
(treemacs-block
(treemacs-error-return-if (not (active-minibuffer-window))
"Minibuffer is not active")
(let* ((path-at-point (treemacs--prop-at-point :path))
(dir (if (file-directory-p path-at-point)
path-at-point
(file-name-directory path-at-point))))
(select-window (active-minibuffer-window))
(delete-region (minibuffer-prompt-end) (point-max))
(insert dir))
(message "Copied from treemacs")))
(defun treemacs-delete-other-windows ()
"Same as `delete-other-windows', but will not delete the treemacs window.
If this command is run when the treemacs window is selected `next-window' will
also not be deleted."
(interactive)
(save-selected-window
(-let [w (treemacs-get-local-window)]
(when (eq w (selected-window))
(select-window (next-window)))
(delete-other-windows)
;; we still want to call `delete-other-windows' since it contains plenty of nontrivial code
;; that we shouldn't prevent from running, so we just restore treemacs instead of preventing
;; it from being deleted
;; 'no-delete-other-windows could be used instead, but it's only available for emacs 26
(when (and w (not (equal 'visible (treemacs-current-visibility))))
(treemacs--select-not-visible-window)))))
(defun treemacs-temp-resort-root (&optional sort-method)
"Temporarily resort the entire treemacs buffer.
SORT-METHOD is a cons of a string describing the method and the actual sort
value, as returned by `treemacs--sort-value-selection'. SORT-METHOD will be
provided when this function is called from `treemacs-resort' and will be
interactively read otherwise. This way this function can be bound directly,
without the need to call `treemacs-resort' with a prefix arg."
(interactive)
(-let* (((sort-name . sort-method) (or sort-method (treemacs--sort-value-selection)))
(treemacs-sorting sort-method))
(treemacs-without-messages (treemacs-refresh))
(treemacs-log "Temporarily resorted everything with sort method '%s.'"
(propertize sort-name 'face 'font-lock-type-face))))
(defun treemacs-temp-resort-current-dir (&optional sort-method)
"Temporarily resort the current directory.
SORT-METHOD is a cons of a string describing the method and the actual sort
value, as returned by `treemacs--sort-value-selection'. SORT-METHOD will be
provided when this function is called from `treemacs-resort' and will be
interactively read otherwise. This way this function can be bound directly,
without the need to call `treemacs-resort' with a prefix arg."
(interactive)
(-let* (((sort-name . sort-method) (or sort-method (treemacs--sort-value-selection)))
(treemacs-sorting sort-method))
(-if-let (btn (treemacs-current-button))
(pcase (treemacs-button-get btn :state)
('dir-node-closed
(treemacs--expand-dir-node btn)
(treemacs-log "Resorted %s with sort method '%s'."
(propertize (treemacs--get-label-of btn) 'face 'font-lock-string-face)
(propertize sort-name 'face 'font-lock-type-face)))
('dir-node-open
(treemacs--collapse-dir-node btn)
(goto-char (treemacs-button-start btn))
(treemacs--expand-dir-node btn)
(treemacs-log "Resorted %s with sort method '%s'."
(propertize (treemacs--get-label-of btn) 'face 'font-lock-string-face)
(propertize sort-name 'face 'font-lock-type-face)))
((or 'file-node-open 'file-node-closed 'tag-node-open 'tag-node-closed 'tag-node)
(let* ((parent (treemacs-button-get btn :parent)))
(while (and parent
(not (-some-> parent (treemacs-button-get :path) (file-directory-p))))
(setq parent (treemacs-button-get parent :parent)))
(if parent
(let ((line (line-number-at-pos))
(window-point (window-point)))
(goto-char (treemacs-button-start parent))
(treemacs--collapse-dir-node parent)
(goto-char (treemacs-button-start btn))
(treemacs--expand-dir-node parent)
(set-window-point (selected-window) window-point)
(with-no-warnings (goto-line line))
(treemacs-log "Resorted %s with sort method '%s'."
(propertize (treemacs--get-label-of parent) 'face 'font-lock-string-face)
(propertize sort-name 'face 'font-lock-type-face)))
;; a top level file's containing dir is root
(treemacs-without-messages (treemacs-refresh))
(treemacs-log "Resorted root directory with sort method '%s'."
(propertize sort-name 'face 'font-lock-type-face)))))))))
(defun treemacs-resort (&optional arg)
"Select a new permanent value for `treemacs-sorting' and refresh.
With a single prefix ARG use the new sort value to *temporarily* resort the
\(closest\) directory at point.
With a double prefix ARG use the new sort value to *temporarily* resort the
entire treemacs view.
Temporary sorting will only stick around until the next refresh, either manual
or automatic via `treemacs-filewatch-mode'.
Instead of calling this with a prefix arg you can also directly call
`treemacs-temp-resort-current-dir' and `treemacs-temp-resort-root'."
(interactive "P")
(pcase arg
;; Resort current dir only
(`(4)
(treemacs-temp-resort-current-dir))
;; Temporarily resort everything
(`(16)
(treemacs-temp-resort-root))
;; Set new permanent value
(_
(-let (((sort-name . sort-value) (treemacs--sort-value-selection)))
(setq treemacs-sorting sort-value)
(treemacs-without-messages (treemacs-refresh))
(treemacs-log "Sorting method changed to '%s'."
(propertize sort-name 'face 'font-lock-type-face)))))
(treemacs--evade-image))
(defun treemacs-next-line-other-window (&optional count)
"Scroll forward COUNT lines in `next-window'."
(interactive "p")
(treemacs-without-following
(with-selected-window (next-window)
(scroll-up-line count))))
(defun treemacs-previous-line-other-window (&optional count)
"Scroll backward COUNT lines in `next-window'."
(interactive "p")
(treemacs-without-following
(with-selected-window (next-window)
(scroll-down-line count))))
(defun treemacs-next-page-other-window (&optional count)
"Scroll forward COUNT pages in `next-window'.
For slower scrolling see `treemacs-next-line-other-window'"
(interactive "p")
(treemacs-without-following
(with-selected-window (next-window)
(condition-case _
(dotimes (_ (or count 1))
(scroll-up nil))
(end-of-buffer (goto-char (point-max)))))))
(defun treemacs-previous-page-other-window (&optional count)
"Scroll backward COUNT pages in `next-window'.
For slower scrolling see `treemacs-previous-line-other-window'"
(interactive "p")
(treemacs-without-following
(with-selected-window (next-window)
(condition-case _
(dotimes (_ (or count 1))
(scroll-down nil))
(beginning-of-buffer (goto-char (point-min)))))))
(defun treemacs-next-project ()
"Move to the next project root node."
(interactive)
(-let [pos (treemacs--next-project-pos)]
(if (or (= pos (point))
(= pos (point-max)))
(treemacs-pulse-on-failure "There is no next project to move to.")
(goto-char pos)
(treemacs--maybe-recenter treemacs-recenter-after-project-jump))))
(defun treemacs-previous-project ()
"Move to the next project root node."
(interactive)
(-let [pos (treemacs--prev-project-pos)]
(if (or (= pos (point))
(= pos (point-min)))
(treemacs-pulse-on-failure "There is no previous project to move to.")
(goto-char pos)
(treemacs--maybe-recenter treemacs-recenter-after-project-jump))))
(defun treemacs-rename-project ()
"Give the project at point a new name."
(interactive)
(treemacs-with-writable-buffer
(treemacs-block
(treemacs-unless-let (project (treemacs-project-at-point))
(treemacs-pulse-on-failure "There is no project here.")
(let* ((old-name (treemacs-project->name project))
(project-btn (treemacs-project->position project))
(state (treemacs-button-get project-btn :state))
(new-name (treemacs--read-string "New name: " (treemacs-project->name project))))
(treemacs-save-position
(progn
(treemacs-return-if (treemacs--is-name-invalid? new-name)
(treemacs-pulse-on-failure "'%s' is an invalid name."
(propertize new-name 'face 'font-lock-type-face)))
(treemacs-return-if (string-equal old-name new-name)
(treemacs-pulse-on-failure "The new name is the same as the old name."))
(setf (treemacs-project->name project) new-name)
;; after renaming, delete and redisplay the project
(goto-char (treemacs-button-end project-btn))
(delete-region (line-beginning-position) (line-end-position))
(treemacs--add-root-element project)
(when (eq state 'root-node-open)
(treemacs--collapse-root-node (treemacs-project->position project))
(treemacs--expand-root-node (treemacs-project->position project))))
(run-hook-with-args 'treemacs-rename-project-functions project old-name)
(treemacs-pulse-on-success "Renamed project %s to %s."
(propertize old-name 'face 'font-lock-type-face)
(propertize new-name 'face 'font-lock-type-face)))))))
(treemacs--evade-image))
(defun treemacs-add-project-to-workspace (path &optional name)
"Add a project at given PATH to the current workspace.
The PATH's directory name will be used as a NAME for a project. The NAME can
\(or must) be entered manually with either a prefix arg or if a project with the
auto-selected name already exists."
(interactive "DProject root: ")
(let* ((default-name (treemacs--filename path))
(double-name (--first (string= default-name (treemacs-project->name it))
(treemacs-workspace->projects (treemacs-current-workspace)))))
(if (or current-prefix-arg double-name)
(setf name (treemacs--read-string "Project Name: " (unless double-name (treemacs--filename path))))
(setf name default-name)))
(pcase (treemacs-do-add-project-to-workspace path name)
(`(success ,project)
(treemacs-pulse-on-success "Added project '%s' to the workspace."
(propertize (treemacs-project->name project) 'face 'font-lock-type-face)))
(`(invalid-path ,reason)
(treemacs-pulse-on-failure (concat "Path '%s' is invalid: %s")
(propertize path 'face 'font-lock-string-face)
reason))
(`(invalid-name ,name)
(treemacs-pulse-on-failure "Name '%s' is invalid."
(propertize name 'face 'font-lock-string-face)))
(`(duplicate-project ,duplicate)
(goto-char (treemacs-project->position duplicate))
(treemacs-pulse-on-failure "A project for '%s' already exists. Projects may not overlap."
(propertize (treemacs-project->path duplicate) 'face 'font-lock-string-face)))
(`(includes-project ,project)
(goto-char (treemacs-project->position project))
(treemacs-pulse-on-failure "Project '%s' is included in '%s'. Projects may not overlap."
(propertize (treemacs-project->name project) 'face 'font-lock-type-face)
(propertize path 'face 'font-lock-string-face)))
(`(duplicate-name ,duplicate)
(goto-char (treemacs-project->position duplicate))
(treemacs-pulse-on-failure "A project with the name %s already exists."
(propertize (treemacs-project->name duplicate) 'face 'font-lock-type-face))))
nil)
(defalias 'treemacs-add-project #'treemacs-add-project-to-workspace)
(with-no-warnings
(make-obsolete #'treemacs-add-project #'treemacs-add-project-to-workspace "v2.2.1"))
(defun treemacs-remove-project-from-workspace (&optional arg)
"Remove the project at point from the current workspace.
With a prefix ARG select project to remove by name."
(interactive "P")
(let ((project (treemacs-project-at-point))
(save-pos))
(when (or arg (null project))
(setf project (treemacs--select-project-by-name)
save-pos (not (equal project (treemacs-project-at-point)))))
(pcase (if save-pos
(treemacs-save-position
(treemacs-do-remove-project-from-workspace project nil :ask))
(treemacs-do-remove-project-from-workspace project nil :ask))
(`success
(whitespace-cleanup)
(treemacs-pulse-on-success "Removed project %s from the workspace."
(propertize (treemacs-project->name project) 'face 'font-lock-type-face)))
(`user-cancel
(ignore))
(`cannot-delete-last-project
(treemacs-pulse-on-failure "Cannot delete the last project."))
(`(invalid-project ,reason)
(treemacs-pulse-on-failure "Cannot delete project: %s"
(propertize reason 'face 'font-lock-string-face))))))
(defun treemacs-create-workspace ()
"Create a new workspace."
(interactive)
(pcase (treemacs-do-create-workspace)
(`(success ,workspace)
(treemacs-pulse-on-success "Workspace %s successfully created."
(propertize (treemacs-workspace->name workspace) 'face 'font-lock-type-face)))
(`(invalid-name ,name)
(treemacs-pulse-on-failure "Name '%s' is invalid."
(propertize name 'face 'font-lock-string-face)))
(`(duplicate-name ,duplicate)
(treemacs-pulse-on-failure "A workspace with the name %s already exists."
(propertize (treemacs-workspace->name duplicate) 'face 'font-lock-string-face)))))
(defun treemacs-remove-workspace ()
"Delete a workspace."
(interactive)
(pcase (treemacs-do-remove-workspace nil :ask-to-confirm)
('only-one-workspace
(treemacs-pulse-on-failure "You cannot delete the last workspace."))
(`(workspace-not-found ,name)
(treemacs-pulse-on-failure "Workspace with name '%s' does not exist"
(propertize name 'face 'font-lock-type-face)))
('user-cancel
(ignore))
(`(success ,deleted ,_)
(treemacs-pulse-on-success "Workspace %s was deleted."
(propertize (treemacs-workspace->name deleted) 'face 'font-lock-type-face)))))
(defun treemacs-switch-workspace (arg)
"Select a different workspace for treemacs.
With a prefix ARG clean up buffers after the switch. A single prefix argument
will delete all file visiting buffers, 2 prefix arguments will clean up all open
buffers (except for treemacs itself and the scratch and messages buffers).
Without a prefix argument `treemacs-workspace-switch-cleanup' will
be followed instead."
(interactive "P")
(pcase (treemacs-do-switch-workspace)
('only-one-workspace
(treemacs-pulse-on-failure "There are no other workspaces to select."))
(`(success ,workspace)
(treemacs--maybe-clean-buffers-on-workspace-switch
(pcase arg
(`(4) 'files)
(`(16) 'all)
(_ treemacs-workspace-switch-cleanup)))
(treemacs-pulse-on-success "Selected workspace %s."
(propertize (treemacs-workspace->name workspace))))))
(defun treemacs-set-fallback-workspace (&optional arg)
"Set the current workspace as the default fallback.
With a non-nil prefix ARG choose the fallback instead.
The fallback workspace is the one treemacs will select when it is opened for the
first time and the current file at the time is not part of any of treemacs'
workspaces."
(interactive "P")
(treemacs-block
(-let [fallback (if arg (treemacs--select-workspace-by-name) (treemacs-current-workspace))]
(treemacs-error-return-if (null fallback)
"There is no workspace with that name.")
(setf treemacs--workspaces
(sort treemacs--workspaces
(lambda (ws _) (equal ws fallback))))
(treemacs--persist)
(treemacs-pulse-on-success "Selected workspace %s as fallback."
(propertize (treemacs-workspace->name fallback) 'face 'font-lock-type-face)))))
(defun treemacs-rename-workspace ()
"Select a workspace to rename."
(interactive)
(pcase (treemacs-do-rename-workspace)
(`(success ,old-name ,workspace)
(treemacs-pulse-on-success "Workspace %s successfully renamed to %s."
(propertize old-name 'face 'font-lock-type-face)
(propertize (treemacs-workspace->name workspace) 'face 'font-lock-type-face)))
(`(invalid-name ,name)
(treemacs-pulse-on-failure "Name '%s' is invalid."
(propertize name 'face 'font-lock-string-face)))))
(defun treemacs-refresh ()
"Refresh the project at point."
(interactive)
(treemacs-unless-let (btn (treemacs-current-button))
(treemacs-log-failure "There is nothing to refresh.")
(-let [project (treemacs-project-of-node btn)]
(treemacs-without-recenter
(treemacs--do-refresh (current-buffer) project))
(run-hook-with-args 'treemacs-post-project-refresh-functions project))))
(defun treemacs-collapse-project (&optional arg)
"Close the project at point.
With a prefix ARG also forget about all the nodes opened in the project."
(interactive "P")
(treemacs-unless-let (project (treemacs-project-at-point))
(treemacs-pulse-on-failure "There is nothing to close here.")
(-let [btn (treemacs-project->position project)]
(when (treemacs-is-node-expanded? btn)
(goto-char btn)
(treemacs--collapse-root-node btn arg)
(treemacs--maybe-recenter 'on-distance)))
(treemacs-pulse-on-success "Collapsed current project")))
(defun treemacs-collapse-all-projects (&optional arg)
"Collapses all projects.
With a prefix ARG remember which nodes were expanded."
(interactive "P")
(-when-let (buffer (treemacs-get-local-buffer))
(with-current-buffer buffer
(save-excursion
(dolist (project (treemacs-workspace->projects (treemacs-current-workspace)))
(-when-let (pos (treemacs-project->position project))
(when (eq 'root-node-open (treemacs-button-get pos :state))
(goto-char pos)
(treemacs--collapse-root-node pos (not arg))))))
(treemacs--maybe-recenter 'on-distance)
(treemacs-pulse-on-success "Collapsed all projects"))))
(defun treemacs-collapse-other-projects (&optional arg)
"Collapses all projects except the project at point.
With a prefix ARG also forget about all the nodes opened in the projects."
(interactive "P")
(save-excursion
(-let [curr-project (treemacs-project-at-point)]
(dolist (project (treemacs-workspace->projects (treemacs-current-workspace)))
(unless (eq project curr-project)
(-when-let (pos (treemacs-project->position project))
(when (eq 'root-node-open (treemacs-button-get pos :state))
(goto-char pos)
(treemacs--collapse-root-node pos arg)))))))
(treemacs--maybe-recenter 'on-distance)
(treemacs-pulse-on-success "Collapsed all other projects"))
(defun treemacs-root-up (&optional _)
"Move treemacs' root one level upward.
Only works with a single project in the workspace."
(interactive "P")
(treemacs-block
(unless (= 1 (length (treemacs-workspace->projects (treemacs-current-workspace))))
(treemacs-error-return
"Ad-hoc navigation is only possible when there is but a single project in the workspace."))
(-let [btn (treemacs-current-button)]
(unless btn
(setq btn (previous-button (point))))
(let* ((project (-> btn (treemacs--nearest-path) (treemacs--find-project-for-path)))
(old-root (treemacs-project->path project))
(new-root (treemacs--parent old-root))
(new-name (pcase new-root
("/" new-root)
(_ (file-name-nondirectory new-root))))
(treemacs--no-messages t)
(treemacs-pulse-on-success nil))
(unless (treemacs-is-path old-root :same-as new-root)
(treemacs-do-remove-project-from-workspace project :ignore-last-project-restriction)
(treemacs--reset-dom) ;; remove also the previous root's dom entry
(treemacs-do-add-project-to-workspace new-root new-name)
(treemacs-goto-file-node old-root))))))
(defun treemacs-root-down (&optional _)
"Move treemacs' root into the directory at point.
Only works with a single project in the workspace."
(interactive "P")
(treemacs-block
(treemacs-error-return-if (/= 1 (length (treemacs-workspace->projects (treemacs-current-workspace))))
"Free navigation is only possible when there is but a single project in the workspace.")
(treemacs-unless-let (btn (treemacs-current-button))
(treemacs-pulse-on-failure
"There is no directory to move into here.")
(pcase (treemacs-button-get btn :state)
((or 'dir-node-open 'dir-node-closed)
(let ((new-root (treemacs-button-get btn :path))
(treemacs--no-messages t)
(treemacs-pulse-on-success nil))
(treemacs-do-remove-project-from-workspace (treemacs-project-at-point) :ignore-last-project-restriction)
(treemacs--reset-dom) ;; remove also the previous root's dom entry
(treemacs-do-add-project-to-workspace new-root (file-name-nondirectory new-root))
(treemacs-goto-file-node new-root)))
(_
(treemacs-pulse-on-failure "Button at point is not a directory."))))))
(defun treemacs-show-extensions ()
"Display a list of all active extensions."
(interactive)
(-let [txt (list "#+TITLE: Treemacs Active Extensions\n")]
(cl-flet ((with-face (txt face) (propertize txt 'font-lock-face face)))
(pcase-dolist
(`(,headline . ,name)
'(("* Directory Extensions" . directory)
("* Project Extensions" . project)
("* Root Extetensions" . root)) )
(let ((top-name (symbol-value (intern (format "treemacs--%s-top-extensions" name))))
(bottom-name (symbol-value (intern (format "treemacs--%s-bottom-extensions" name)))))
(push headline txt)
(pcase-dolist
(`(,pos-txt . ,pos-val)
`(("** Top" . ,top-name)
("** Bottom" . ,bottom-name)))
(push pos-txt txt)
(if pos-val
(dolist (ext pos-val)
(push (format " - %s\n with predicate %s\n defined in %s"
(with-face (symbol-name (car ext)) 'font-lock-keyword-face)
(with-face (--if-let (cdr ext) (symbol-name it) "None") 'font-lock-function-name-face)
(with-face (get (car ext) :defined-in) 'font-lock-string-face))
txt))
(push (with-face " - None" 'font-lock-comment-face) txt))))))
(-let [buf (get-buffer-create "*Treemacs Extension Overview*")]
(switch-to-buffer buf)
(org-mode)
(erase-buffer)
(->> txt (nreverse) (--map (concat it "\n")) (apply #'concat) (insert))
(with-no-warnings (org-reveal))
(goto-char 0)
(forward-line))))
(defun treemacs-move-project-up ()
"Switch position of the project at point and the one above it."
(interactive)
(treemacs-block
(let* ((workspace (treemacs-current-workspace))
(projects (treemacs-workspace->projects workspace))
(project1 (treemacs-project-at-point))
(index1 (or (treemacs-error-return-if (null project1)
"There is nothing to move here.")
(-elem-index project1 projects)))
(index2 (1- index1))
(project2 (or (treemacs-error-return-if (> 0 index2)
"There is no project to switch places with above.")
(nth index2 projects)))
(bounds1 (treemacs--get-bounds-of-project project1))
(bounds2 (treemacs--get-bounds-of-project project2)))
(treemacs-with-writable-buffer
(transpose-regions
(car bounds1) (cdr bounds1)
(car bounds2) (cdr bounds2)))
(setf (nth index1 projects) project2
(nth index2 projects) project1)
(treemacs--persist)
(recenter))))
(defun treemacs-move-project-down ()
"Switch position of the project at point and the one below it."
(interactive)
(treemacs-block
(let* ((workspace (treemacs-current-workspace))
(projects (treemacs-workspace->projects workspace))
(project1 (treemacs-project-at-point))
(index1 (or (treemacs-error-return-if (null project1)
"There is nothing to move here.")
(-elem-index project1 projects)))
(index2 (1+ index1))
(project2 (or (treemacs-error-return-if (>= index2 (length projects))
"There is no project to switch places with below.")
(nth index2 projects)))
(bounds1 (treemacs--get-bounds-of-project project1))
(bounds2 (treemacs--get-bounds-of-project project2)))
(treemacs-with-writable-buffer
(transpose-regions
(car bounds1) (cdr bounds1)
(car bounds2) (cdr bounds2)))
(setf (nth index1 projects) project2
(nth index2 projects) project1)
(treemacs--persist)
(recenter))))
(defun treemacs-finish-edit ()
"Finish editing your workspaces and apply the change."
(interactive)
(treemacs-block
(treemacs-error-return-if (not (equal (buffer-name) treemacs--org-edit-buffer-name))
"This is not a valid treemacs workspace edit buffer")
(treemacs--org-edit-remove-validation-msg)
(widen)
(whitespace-cleanup)
(-let [lines (treemacs--read-persist-lines (buffer-string))]
(treemacs-error-return-if (null (buffer-string))
"The buffer is empty, there is nothing here to save.")
(pcase (treemacs--validate-persist-lines lines)
(`(error ,err-line ,err-msg)
(treemacs--org-edit-display-validation-msg err-msg err-line))
('success
(treemacs--invalidate-buffer-project-cache)
(write-region
(apply #'concat (--map (concat it "\n") lines))
nil
treemacs-persist-file
nil :silent)
(treemacs--restore)
(-if-let (ws (treemacs--find-workspace-by-name
(treemacs-workspace->name (treemacs-current-workspace))))
(setf (treemacs-current-workspace) ws)
(treemacs--find-workspace))
(treemacs--consolidate-projects)
(if (and (treemacs-get-local-window)
(= 2 (length (window-list))))
(kill-buffer)
(quit-window)
(kill-buffer-and-window))
(run-hooks 'treemacs-workspace-edit-hook)
(when treemacs-hide-gitignored-files-mode
(treemacs--prefetch-gitignore-cache 'all))
(treemacs-log "Edit completed successfully."))))))
(defun treemacs-collapse-parent-node (arg)
"Close the parent of the node at point.
Prefix ARG will be passed on to the closing function
\(see `treemacs-toggle-node'.\)"
(interactive "P")
(-if-let* ((btn (treemacs-current-button))
(parent (button-get btn :parent)))
(progn
(goto-char parent)
(treemacs-toggle-node arg)
(treemacs--evade-image))
(treemacs-pulse-on-failure
(if btn "Already at root." "There is nothing to close here."))))
(defun treemacs-run-shell-command-in-project-root (&optional arg)
"Run an asynchronous shell command in the root of the current project.
Output will only be saved and displayed if prefix ARG is non-nil.
Every instance of the string `$path' will be replaced with the (properly quoted)
absolute path of the project root."
(interactive "P")
(let* ((cmd (read-shell-command "Command: "))
(name "*Treemacs Shell Command*")
(node (treemacs-node-at-point))
(buffer (progn (--when-let (get-buffer name)
(kill-buffer it))
(get-buffer-create name)))
(working-dir nil))
(treemacs-block
(treemacs-error-return-if (null node)
(treemacs-pulse-on-failure "There is no project here."))
(-let [project (treemacs-project-of-node node)]
(treemacs-error-return-if (treemacs-project->is-unreadable? project)
(treemacs-pulse-on-failure "Project path is not readable."))
(setf working-dir (treemacs-project->path project)
cmd (s-replace "$path" (shell-quote-argument working-dir) cmd))
(pfuture-callback `(,shell-file-name ,shell-command-switch ,cmd)
:name name
:buffer buffer
:directory working-dir
:on-success
(if arg
(progn
(pop-to-buffer pfuture-buffer)
(require 'ansi-color)
(ansi-color-apply-on-region (point-min) (point-max)))
(treemacs-log "Shell command completed successfully.")
(kill-buffer buffer))
:on-error
(progn
(treemacs-log-failure "Shell command failed with exit code %s and output:" (process-exit-status process))
(message "%s" (pfuture-callback-output))
(kill-buffer buffer)))))))
(defun treemacs-run-shell-command-for-current-node (&optional arg)
"Run a shell command on the current node.
Output will only be saved and displayed if prefix ARG is non-nil.
Will use the location of the current node as working directory. If the current
node is not a file/dir, then the next-closest file node will be used. If all
nodes are non-files, or if there is no node at point, $HOME will be set as the
working directory.
Every instance of the string `$path' will be replaced with the (properly quoted)
absolute path of the node (if it is present)."
(interactive "P")
(let* ((cmd (read-shell-command "Command: "))
(name "*Treemacs Shell Command*")
(node (treemacs-node-at-point))
(buffer (progn (--when-let (get-buffer name)
(kill-buffer it))
(get-buffer-create name)))
(working-dir (-some-> node (treemacs-button-get :path))))
(cond
((null node)
(setf working-dir "~/"))
((or (null working-dir) (not (file-exists-p working-dir)))
(setf working-dir (treemacs--nearest-path node))
(when (or (null working-dir)
(not (file-exists-p working-dir)))
(setf working-dir "~/")))
(t
(setf working-dir (treemacs--parent working-dir))))
(when (and node (treemacs-is-node-file-or-dir? node))
(setf cmd (s-replace "$path" (shell-quote-argument (treemacs-button-get node :path)) cmd)))
(pfuture-callback `(,shell-file-name ,shell-command-switch ,cmd)
:name name
:buffer buffer
:directory working-dir
:on-success
(if arg
(progn
(pop-to-buffer pfuture-buffer)
(require 'ansi-color)
(autoload 'ansi-color-apply-on-region "ansi-color")
(ansi-color-apply-on-region (point-min) (point-max)))
(treemacs-log "Shell command completed successfully.")
(kill-buffer buffer))
:on-error
(progn
(treemacs-log-failure "Shell command failed with exit code %s and output:" (process-exit-status process))
(message "%s" (pfuture-callback-output))
(kill-buffer buffer)))))
(defun treemacs-narrow-to-current-file ()
"Close everything except the view on the current file.
This command is best understood as a combination of
`treemacs-collapse-all-projects' followed by `treemacs-find-file'."
(interactive)
(treemacs-unless-let (buffer (treemacs-get-local-buffer))
(treemacs-log-failure "There is no treemacs buffer")
(let* ((treemacs-pulse-on-success nil)
(treemacs-pulse-on-failure nil)
(treemacs--no-messages t))
(with-current-buffer buffer
(treemacs-collapse-all-projects :forget-all))
(treemacs-find-file))))
(defun treemacs-select-scope-type ()
"Select the scope for treemacs buffers.
The default (and only) option is scoping by frame, which means that every Emacs
frame (and only an Emacs frame) will have its own unique treemacs buffer.
Additional scope types can be enabled by installing the appropriate package.
The following packages offer additional scope types:
* treemacs-persp
* treemacs-perspective
To programmatically set the scope type see `treemacs-set-scope-type'."
(interactive)
(let* ((selection (completing-read "Select Treemacs Scope: " treemacs-scope-types))
(new-scope-type (-> selection (intern) (assoc treemacs-scope-types) (cdr))))
(cond
((null new-scope-type)
(treemacs-log "Nothing selected, type %s remains in effect."
(propertize selection 'face 'font-lock-type-face)))
((eq new-scope-type treemacs--current-scope-type)
(treemacs-log "New scope type is same as old, nothing has changed."))
(t
(treemacs--do-set-scope-type new-scope-type)
(treemacs-log "Scope of type %s is now in effect."
(propertize selection 'face 'font-lock-type-face))))))
(defun treemacs-cleanup-litter ()
"Collapse all nodes matching any of `treemacs-litter-directories'."
(interactive)
(-let [litter-list (-map #'regexp-quote treemacs-litter-directories)]
(treemacs-run-in-every-buffer
(treemacs-save-position
(dolist (project (treemacs-workspace->projects workspace))
(treemacs-walk-reentry-dom (-> project treemacs-project->path treemacs-find-in-dom)
(lambda (dom-node)
(-let [path (treemacs-dom-node->key dom-node)]
(when (and (stringp path)
(--any? (string-match-p it path) litter-list))
(--when-let (treemacs-find-node path project)
(goto-char it)
(treemacs-toggle-node :purge)))))))))
(treemacs-pulse-on-success "Cleanup complete.")))
(defun treemacs-fit-window-width ()
"Make treemacs wide enough to display its entire content.
Specifically this will increase (or reduce) the width of the treemacs window to
that of the longest line, counting all lines, not just the ones that are
visible."
(interactive)
(let ((longest 0)
(depth 0))
(save-excursion
(goto-char (point-min))
(while (= 0 (forward-line 1))
(-let [new-len (- (line-end-position) (line-beginning-position))]
(when (> new-len longest)
(setf longest new-len
depth (treemacs--prop-at-point :depth))))))
(let* ((icon-px-diff (* depth (- treemacs--icon-size (frame-char-width))))
(icon-offset (% icon-px-diff (frame-char-width)))
(new-width (+ longest icon-offset)))
(setf treemacs-width new-width)
(treemacs--set-width new-width)
(treemacs-pulse-on-success "Width set to %s"
(propertize (format "%s" new-width) 'face 'font-lock-string-face)))))
(defun treemacs-extra-wide-toggle ()
"Expand the treemacs window to an extr-wide state (or turn it back).
Specifically this will toggle treemacs' width between
`treemacs-wide-toggle-width' and the normal `treemacs-width'."
(interactive)
(if (get 'treemacs-extra-wide-toggle :toggle-on)
(progn
(treemacs--set-width treemacs-width)
(put 'treemacs-extra-wide-toggle :toggle-on nil)
(treemacs-log "Switched to normal width display"))
(treemacs--set-width treemacs-wide-toggle-width)
(put 'treemacs-extra-wide-toggle :toggle-on t)
(treemacs-log "Switched to extra width display")))
(defun treemacs-next-workspace (&optional arg)
"Switch to the next workspace.
With a prefix ARG switch to the previous workspace instead."
(interactive)
(treemacs-block
(treemacs-error-return-if (= 1 (length treemacs--workspaces))
"There is only 1 workspace.")
(let* ((ws (treemacs-current-workspace))
(ws-count (length treemacs--workspaces))
(idx (--find-index (eq it ws) treemacs--workspaces))
(new-idx (% (+ ws-count (if arg (1- idx) (1+ idx))) ws-count))
(new-ws (nth new-idx treemacs--workspaces)))
(treemacs-do-switch-workspace new-ws)
(treemacs-pulse-on-success "Switched to workspace '%s'"
(propertize (treemacs-workspace->name new-ws)
'face 'font-lock-string-face)))))
(defun treemacs-create-workspace-from-project (&optional arg)
"Create (and switch to) a workspace containing only the current project.
By default uses the project at point in the treemacs buffer. If there is no
treemacs buffer, then the project of the current file is used instead. With a
prefix ARG it is also possible to interactively select the project."
(interactive "P")
(treemacs-block
(-let [project nil]
(if (eq t treemacs--in-this-buffer)
(setf project (treemacs-project-of-node (treemacs-current-button)))
(setf project (treemacs--find-project-for-buffer (buffer-file-name (current-buffer))))
(treemacs-select-window))
(when (or arg (null project))
(setf project (treemacs--select-project-by-name))
(treemacs-return-if (null project)))
(let* ((ws-name (treemacs-project->name project))
(new-ws (treemacs--find-workspace-by-name ws-name)))
(if new-ws
(setf (treemacs-workspace->projects new-ws) (list project))
(-let [ws-create-result (treemacs-do-create-workspace ws-name)]
(treemacs-error-return-if (not (equal 'success (car ws-create-result)))
"Something went wrong when creating a new workspace: %s" ws-create-result)
(setf new-ws (cdr ws-create-result))
(setf (treemacs-workspace->projects new-ws) (list project))
(treemacs--persist)))
(treemacs-do-switch-workspace new-ws)
(treemacs-pulse-on-success "Switched to project workspace '%s'"
(propertize ws-name 'face 'font-lock-type-face))))))
(defun treemacs-icon-catalogue ()
"Showcase a catalogue of all treemacs themes and their icons."
(interactive)
(switch-to-buffer (get-buffer-create "*Treemacs Icons*"))
(erase-buffer)
(dolist (theme (nreverse treemacs--themes))
(insert (format "* Theme %s\n\n" (treemacs-theme->name theme)))
(insert " |------+------------|\n")
(insert " | Icon | Extensions |\n")
(insert " |------+------------|\n")
(let* ((icons (treemacs-theme->gui-icons theme))
(rev-icons (make-hash-table :size (ht-size icons) :test 'equal))
(txt))
(treemacs--maphash icons (ext icon)
(let* ((display (get-text-property 0 'display icon))
(saved-exts (ht-get rev-icons display)))
(if saved-exts
(cl-pushnew ext saved-exts)
(setf saved-exts (list ext)))
(ht-set! rev-icons display saved-exts)))
(treemacs--maphash rev-icons (display exts)
(push
(format " | %s | %s |\n"
(propertize "x" 'display display)
(s-join " " (-map #'prin1-to-string exts)))
txt))
(insert (apply #'concat (nreverse txt)))
(with-no-warnings
(org-mode)
(org-table-align))))
(goto-char 0))
(provide 'treemacs-interface)
;;; treemacs-interface.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-interface.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 15,335 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;;; API required for writing extensions for/with treemacs.
;;; Code:
(require 's)
(require 'dash)
(require 'treemacs)
(eval-when-compile
(require 'treemacs-macros)
(require 'cl-lib))
(eval-when-compile
(cl-declaim (optimize (speed 3) (safety 0))))
(defconst treemacs-treelib-version "1.1")
(defconst treemacs--treelib-async-load-string
(propertize " Loading "
'face 'treemacs-async-loading-face
'treemacs-async-string t))
(defvar treemacs--extension-registry nil
"Alist storage of extension instances.
The car is a symbol of an extension node's state, the cdr the instance of the
`treemacs-extension' type.")
(defvar treemacs--async-update-count (make-hash-table :size 5 :test 'equal)
"Holds the count of nodes an async update needs to process.
The count is used as finish condition in `treemacs--async-update-part-complete'.")
(defvar treemacs--async-update-cache (make-hash-table :size 20 :test 'equal)
"Holds to pre-computed cache for async updates.
Set by `treemacs--async-update-part-complete'.")
(cl-defstruct (treemacs-extension
(:conc-name treemacs-extension->)
(:constructor treemacs-extension->create!))
;; only for comparisons
name
;; open/close
closed-state
open-state
closed-icon
open-icon
;; produces full list of child items to render
children
;; produces a key for one item returned by children
key
;; produces a text label for one item returned by children
label
;; plist of additional text properties for on item returned by children
more-properties
;; Struct instance of child nodes returned by children
child-type
;; used for entry-point render method selection
variadic?
;; special treatment for asynchronous behavior
async?
;; used as a check when the extension is enabled
entry-point?
;; callback to run when a node is expanded
on-expand
;; callback to run when a node is collapsed
on-collapse)
(define-inline treemacs--ext-symbol-to-instance (symbol)
"Derive an extension instance from the given SYMBOL."
(declare (side-effect-free t))
(inline-letevals (symbol)
(inline-quote
(symbol-value (intern (format "treemacs-%s-extension-instance" ,symbol))))))
(defun treemacs--compare-extensions-by-name (e1 e2)
"Compare E1 and E2 by their names."
(declare (side-effect-free t))
;; take into account cells used by functions like `tremacs-define-project-extension'
(let ((e1 (if (consp e1) (car e1) e1))
(e2 (if (consp e2) (car e2) e2)))
(equal (treemacs-extension->name e1)
(treemacs-extension->name e2))))
(defmacro treemacs-extension->get (self field &rest args)
"Access helper for the lambda fields of `treemacs-extension' instances.
Takes SELF's given FIELD and `funcall's it with ARGS."
(let* ((field-name (substring (symbol-name field) 1))
(fn (intern (s-lex-format "treemacs-extension->${field-name}"))))
`(funcall (,fn ,self) ,@args)))
(cl-macrolet
((build-extension-addition
(name)
(let ((define-function-name (intern (s-lex-format "treemacs-enable-${name}-extension")))
(top-extension-point (intern (s-lex-format "treemacs--${name}-top-extensions")))
(bottom-extension-point (intern (s-lex-format "treemacs--${name}-bottom-extensions"))))
`(progn
(defvar ,top-extension-point nil)
(defvar ,bottom-extension-point nil)
(cl-defun ,define-function-name (&key extension predicate position)
,(s-lex-format
"Enable a `${name}' level EXTENSION for treemacs to use.
EXTENSION is a `treemacs-extension' instance as created by
`treemacs-define-entry-node-type'
PREDICATE is a function that will be called to determine whether the extension
should be displayed. It is invoked with a single argument, which is the
project struct or directory that is being expanded.
POSITION is either `top' or `bottom', indicating whether the extension should be
rendered as the first or last element.
See also `treemacs-disable-${name}-extension'.")
(let* ((ext-instance (treemacs--ext-symbol-to-instance extension))
(cell (cons ext-instance predicate)))
(treemacs-static-assert (treemacs-extension-p ext-instance)
"Given argument is not a valid `treemacs-extension': %s" extension)
(treemacs-static-assert (treemacs-extension->entry-point? ext-instance)
"The given extension '%s' is not an entry point" extension)
(pcase position
('top (add-to-list ',top-extension-point cell nil #'treemacs--compare-extensions-by-name))
('bottom (add-to-list ',bottom-extension-point cell nil #'treemacs--compare-extensions-by-name))
(other (error "Invalid extension position value `%s'" other)))
t)))))
(build-extension-removal
(name)
(let ((remove-function-name (intern (s-lex-format "treemacs-disable-${name}-extension")))
(top-extension-point (intern (s-lex-format "treemacs--${name}-top-extensions")))
(bottom-extension-point (intern (s-lex-format "treemacs--${name}-bottom-extensions"))))
`(progn
(cl-defun ,remove-function-name (&key extension position)
,(s-lex-format
"Remove a `${name}' EXTENSION at the given POSITION.
See also `treemacs-enable-${name}-extension'.")
(-let [ext-instance (treemacs--ext-symbol-to-instance extension)]
(treemacs-static-assert (treemacs-extension-p ext-instance)
"Given argument is not a valid `treemacs-extension': %s" extension)
(pcase position
('top
(setf ,top-extension-point
(--remove-first (treemacs--compare-extensions-by-name it ext-instance)
,top-extension-point)))
('bottom
(setf ,bottom-extension-point
(--remove-first (treemacs--compare-extensions-by-name it ext-instance)
,bottom-extension-point)))
(other
(error "Invalid extension position value `%s'" other))))
t))))
(build-extension-application
(name)
(let ((apply-top-name (intern (s-lex-format "treemacs--apply-${name}-top-extensions")))
(apply-bottom-name (intern (s-lex-format "treemacs--apply-${name}-bottom-extensions")))
(top-extension-point (intern (s-lex-format "treemacs--${name}-top-extensions")))
(bottom-extension-point (intern (s-lex-format "treemacs--${name}-bottom-extensions"))))
`(progn
(defun ,apply-top-name (node data)
,(s-lex-format
"Apply the top `${name}' extensions for NODE.
Also pass additional DATA to predicate function.")
(dolist (cell ,top-extension-point)
(let ((extension (car cell))
(predicate (cdr cell)))
(when (or (null predicate) (funcall predicate data))
(if (functionp extension)
;; TODO(2020/05/30): old-school extensions
;; to be removed eventually
(funcall extension node)
(treemacs--extension-entry-render extension node))))))
(defun ,apply-bottom-name (node data)
,(s-lex-format
"Apply the `${name}' bottom extensions for NODE.
Also pass additional DATA to predicate function.")
(dolist (cell ,bottom-extension-point)
(let ((extension (car cell))
(predicate (cdr cell)))
(when (or (null predicate) (funcall predicate data))
(if (functionp extension)
;; TODO(2020/05/30): old-school extensions
;; to be removed eventually
(funcall extension node)
(treemacs--extension-entry-render extension node)))))))))
(build-top-level-extension-application
(pos)
(let ((name (intern (s-lex-format "treemacs--apply-root-${pos}-extensions")))
(variable (intern (s-lex-format "treemacs--top-level-${pos}-extensions"))))
`(defun ,name (workspace &optional has-previous)
,(s-lex-format
"Apply the ${pos} `top-level' extensions for the current WORKSPACE.
Also pass additional DATA to predicate function.")
(let ((is-first (not has-previous)))
(--each ,variable
(let ((extension (car it))
(predicate (cdr it)))
(when (or (null predicate) (funcall predicate workspace))
(unless is-first
(treemacs--insert-root-separator))
;; TODO(2020/05/30): old-school extensions
;; to be removed eventually
(setf is-first (if (functionp extension)
(funcall extension)
(treemacs--render-extension extension))))))
(not is-first))))))
(build-extension-addition "project")
(build-extension-removal "project")
(build-extension-application "project")
(build-extension-addition "directory")
(build-extension-removal "directory")
(build-extension-application "directory")
(build-extension-addition "top-level")
(build-extension-removal "top-level")
(build-top-level-extension-application "top")
(build-top-level-extension-application "bottom"))
(cl-defmacro treemacs-do-define-extension-type
(name &key
children
more-properties
key
label
open-icon
closed-icon
child-type
ret-action
visit-action
double-click-action
no-tab?
variadic?
async?
entry-point?
on-expand
on-collapse)
"Base building block for extension node setup.
Not meant for direct use. Instead one of the following macros should be
employed:
- `treemacs-define-leaf-node-type'
- `treemacs-define-expandable-node-type'
- `treemacs-define-entry-node-type'
- `treemacs-define-variadic-entry-node-type'
NAME of this node type is a symbol. After an extension is defined the NAME
symbol can be passed to a function like `treemacs-initialize' or
`treemacs-enable-top-level-extension' to make start using it.
CHILDREN is a form to query a list of items to be rendered as children when a
node is expanded. The node being expanded is available as a variable under the
name `btn'. It is a `button' in the sense of the built-in button.el library
\(really just a marker to a buffer position), so its text-properties can be
extracted via `(treemacs-button-get btn :property)' (see also MORE-PROPERTIES).
In addition the item (as produced by the form passed here) that was used to
create the node will also be available under the name `item'.
KEY, LABEL, OPEN-ICON, CLOSE-ICON and MORE-PROPERTIES all act on one of the
items produced by CHILDREN. The node and the item that produced it will be
bound under the names `btn' and `item' respectively.
KEY is a form to generate a semi-unique key for a given node for one of the
items produced by CHILDREN. Semi-unique means that nodes' keys don't all have
to be unique on their own, it is only necessary that a node's path - the list of
all node keys starting from the top level root leading to a specific node - must
be un-ambiguous.
LABEL is a form to query a node's text label (the text after the icon) for one
of the items produced by CHILDREN. The return value should be a string.
OPEN-ICON and CLOSED-ICON are forms to determine the icons used for the node's
open and closed states. The return value should be a string.
MORE-PROPERTIES is a form to produce a plist that will be saved as additional
text-properties in a given node. These properties can later be accessed when
querying the node's CHILDREN (see above).
CHILD-TYPE is, unlike all the other arguments, not a form, but a quoted symbol.
It must refer to the NAME argument of a another (or the same) extension type and
determines the behaviours (LABEL etc.) used to create the children of the node
type being defined here.
RET-ACTION is the function that is called when RET is pressed on a node of this
be able to handle both a closed and open state. If no explicit RET-ACTION type
argument is given RET will do the same as TAB. The function is called with a
single argument - the prefix arg - and must be able to handle both a closed and
and expanded node state.
VISIT-ACTION is a function that is called when a node is to be opened with a
command like `treemacs-visit-node-ace'. It is called with the current `btn' and
must be able to handle both an open and a closed state. It will most likely be
called in a window that is not the one where the button resides, so if you need
to extract text properties from the button you to must use
`treemacs-safe-button-get', e.g. \(treemacs-safe-button-get btn :path\).
DOUBLE-CLICK-ACTION is similar to RET-ACTION, but will be called without any
arguments. There is no default click behaviour, if no DOUBLE-CLICK-ACTION is
given then treemacs will do nothing for double-clicks.
NO-TAB indicates that pressing TAB on this node type should do nothing. It will
be set by `treemacs-define-leaf-node'.
VARIADIC is only relevant for entry-point nodes and indicates that the extension
will produces multiple nodes when first rendered.
ASYNC will enable an asynchronous, callback-based fetching of CHILDREN. When it
is non-nil the function passed to children will be called with the 3rd argument
`callback'. It should be invoked via `funcall' with the items that were
produced asynchronously.
If the asynchronous execution fails the `callback' should be called with a list
in the form \(`:async-error' error-message\). Treemacs will take care of
cleanup and logging the error.
ENTRY-POINT indicates that the node type defined here is an entry-point for an
extension, it will be used as a type-check when enabling an extension with e.g.
`treemacs-enable-top-level-extension'.
ON-EXPAND and ON-COLLAPSE are forms to be invoked at the very end of the
expand/collapse process. They are invoked with the current `btn' as their sole
argument."
(declare (indent 1))
(let* ((child-type (cadr child-type))
(child-name (intern (s-lex-format "treemacs-${child-type}-extension-instance")))
(struct-name (intern (s-lex-format "treemacs-${name}-extension-instance")))
(open-state (intern (s-lex-format "treemacs-${name}-open")))
(closed-state (intern (s-lex-format "treemacs-${name}-closed")))
(children-fn (if async?
`(lambda (&optional btn item callback) (ignore btn item callback) ,children)
`(lambda (&optional btn item) (ignore btn item) ,children))))
`(progn
(defconst ,struct-name
(treemacs-extension->create!
:name ',name
:variadic? ,variadic?
:async? ,async?
:children ,children-fn
:entry-point? ,entry-point?
:label (lambda (&optional btn item) "" (ignore item) (ignore btn) ,label)
:key (lambda (&optional btn item) "" (ignore item) (ignore btn) ,key)
:open-icon (lambda (&optional btn item) "" (ignore item) (ignore btn) ,open-icon)
:closed-icon (lambda (&optional btn item) "" (ignore item) (ignore btn) ,closed-icon)
:more-properties (lambda (&optional btn item) "" (ignore item) (ignore btn) ,more-properties)
:child-type (lambda () "" (symbol-value ',child-name))
:open-state (lambda () "" ',open-state)
:closed-state (lambda () "" ',closed-state)
:on-expand (lambda (&optional btn ) "" (ignore btn) ,on-expand)
:on-collapse (lambda (&optional btn ) "" (ignore btn) ,on-collapse)))
(with-eval-after-load 'treemacs-mouse-interface
(treemacs-define-doubleclick-action ',closed-state ,(or double-click-action '#'ignore))
(treemacs-define-doubleclick-action ',open-state ,(or double-click-action '#'ignore)))
(treemacs-define-TAB-action
',closed-state
,(cond
(no-tab? '#'ignore)
(variadic? '#'treemacs--expand-variadic-parent)
(t '#'treemacs-expand-extension-node)))
(treemacs-define-TAB-action ',open-state ,(if no-tab? '#'ignore '#'treemacs-collapse-extension-node))
(treemacs-define-RET-action ',closed-state ,(or ret-action (if no-tab? '#'ignore '#'treemacs-expand-extension-node)))
(treemacs-define-RET-action ',open-state ,(or ret-action (if no-tab? '#'ignore '#'treemacs-collapse-extension-node)))
(when ,visit-action
(put ',open-state :treemacs-visit-action ,visit-action)
(put ',closed-state :treemacs-visit-action ,visit-action))
(add-to-list 'treemacs--extension-registry (cons ',closed-state ,struct-name))
(add-to-list 'treemacs--extension-registry (cons ',open-state ,struct-name))
(add-to-list 'treemacs--closed-node-states ',closed-state)
(add-to-list 'treemacs--open-node-states ',open-state)
(add-to-list 'treemacs-valid-button-states ',closed-state)
(add-to-list 'treemacs-valid-button-states ',open-state)
',struct-name)))
(cl-defmacro treemacs-define-leaf-node-type
(name &key
icon
label
key
more-properties
ret-action
visit-action
double-click-action)
"Define a type of node that is a leaf and cannot be further expanded.
The NAME, ICON, LABEL and KEY arguments are mandatory.
MORE-PROPERTIES, RET-ACTION, VISIT-ACTION and DOUBLE-CLICK-ACTION are optional.
For a detailed description of all arguments see
`treemacs-do-define-extension-type'."
(declare (indent 1))
(treemacs-static-assert icon ":icon parameter is mandatory")
(treemacs-static-assert label ":label parameter is mandatory")
(treemacs-static-assert key ":key parameter is mandatory")
`(treemacs-do-define-extension-type ,name
:key ,key
:label ,label
:more-properties (append '(:leaf t) ,more-properties)
:closed-icon ,icon
:ret-action ,ret-action
:visit-action ,visit-action
:double-click-action ,double-click-action
:no-tab? t
:children (lambda () (error "Called :children of leaf node"))
:child-type (lambda () (error "Called :child-type of leaf node"))))
(cl-defmacro treemacs-define-expandable-node-type
(name &key
closed-icon
open-icon
label
key
children
child-type
more-properties
ret-action
double-click-action
on-expand
on-collapse
async?)
"Define a general-purpose expandable node-type.
The NAME, CLOSED-ICON, OPEN-ICON LABEL, KEY, CHILDREN and CHILD-TYPE arguments
are mandatory.
MORE-PROPERTIES, RET-ACTION, DOUBLE-CLICK-ACTION, ON-EXPAND, ON-COLLAPSE and
ASYNC are optional.
For a detailed description of all arguments see
`treemacs-do-define-extension-type'."
(declare (indent 1))
(treemacs-static-assert closed-icon ":closed-icon parameter is mandatory")
(treemacs-static-assert open-icon ":open-icon parameter is mandatory")
(treemacs-static-assert label ":label parameter is mandatory")
(treemacs-static-assert key ":key parameter is mandatory")
(treemacs-static-assert children ":children parameter is mandatory")
(treemacs-static-assert child-type ":child-type parameter is mandatory")
`(treemacs-do-define-extension-type ,name
:closed-icon ,closed-icon
:open-icon ,open-icon
:label ,label
:key ,key
:children ,children
:child-type ,child-type
:more-properties ,more-properties
:ret-action ,ret-action
:double-click-action ,double-click-action
:async? ,async?
:on-expand ,on-expand
:on-collapse ,on-collapse))
(cl-defmacro treemacs-define-entry-node-type
(name &key
key
label
open-icon
closed-icon
children
child-type
more-properties
ret-action
double-click-action
on-expand
on-collapse
async?)
"Define a node type with NAME that serves as an entry-point for an extension.
The KEY, LABEL, OPEN-ICON CLOSED-ICON, CHILDREN and CHILD-TYPE arguments are
mandatory.
MORE-PROPERTIES, RET-ACTION, DOUBLE-CLICK-ACTION, ON-EXPAND, ON-COLLAPSE and
ASYNC are optional.
For a detailed description of all arguments see
`treemacs-do-define-extension-type'."
(declare (indent 1))
(treemacs-static-assert key ":key parameter is mandatory")
(treemacs-static-assert label ":label parameter is mandatory")
(treemacs-static-assert open-icon ":open-icon parameter is mandatory")
(treemacs-static-assert closed-icon ":closed-icon parameter is mandatory")
(treemacs-static-assert children ":childen parameter is mandatory")
(treemacs-static-assert child-type ":child-type parameter is mandatory")
`(treemacs-do-define-extension-type ,name
:key ,key
:label ,label
:open-icon ,open-icon
:closed-icon ,closed-icon
:children ,children
:child-type ,child-type
:more-properties ,more-properties
:async? ,async?
:ret-action ,ret-action
:double-click-action ,double-click-action
:on-expand ,on-expand
:on-collapse ,on-collapse
:entry-point? t))
(cl-defmacro treemacs-define-variadic-entry-node-type
(name &key
key
children
child-type)
"Define a node type that serves as an entry-point for a variadic extension.
'Variadic' means that the extension will produce multiple nodes when it is first
rendered instead of just one (e.g. a single 'Buffer List' node vs multiple nodes
each grouping buffers by major mode).
The NAME symbol can be passed to `treemacs-initialize' to render this extension
in a buffer.
The KEY, CHILDREN and CHILD-TYPE arguments are mandatory.
For a detailed description of all arguments see
`treemacs-do-define-extension-type'."
(declare (indent 1))
(treemacs-static-assert key ":key parameter is mandatory")
(treemacs-static-assert children ":childen parameter is mandatory")
(treemacs-static-assert child-type ":child-type parameter is mandatory")
`(treemacs-do-define-extension-type ,name
:open-icon ""
:key ,key
:closed-icon ""
:children ,children
:child-type ,child-type
:variadic? t
:entry-point? t))
(defun treemacs--render-extension (ext &optional expand-depth)
"Render the entry point of the given extension EXT.
Also serves as an entry point to render an extension in an independent buffer
outside of treemacs proper.
EXPAND-DEPTH indicates the additional recursion depth.
EXT: `treemacs-extension' instance
EXPAND-DEPTH: Int"
(when (symbolp ext)
(setf ext (treemacs--ext-symbol-to-instance ext)))
(if (treemacs-extension->variadic? ext)
(treemacs--variadic-extension-entry-render ext expand-depth)
(treemacs--singular-extension-entry-render ext)))
(defun treemacs--singular-extension-entry-render (ext)
"Render the entry point of the given singular top level extension EXT.
Will create and insert the required strings and make a new dom entry.
EXT: `treemacs-extension' instance"
(treemacs-with-writable-buffer
(let* ((label (treemacs-extension->get ext :label))
(key (treemacs-extension->get ext :key))
(project (treemacs-project->create!
:name label
:path key
:path-status 'extension))
(dom-node (treemacs-dom-node->create!
:key key
:position (point-marker))))
(treemacs-dom-node->insert-into-dom! dom-node)
(insert (treemacs-extension->get ext :closed-icon))
(setf (treemacs-dom-node->position dom-node) (point-marker))
(insert (propertize
label
'button '(t)
'category 'treemacs-button
:custom t
:key key
:path key
:depth 0
:project project
:state (treemacs-extension->get ext :closed-state)))))
nil)
(defun treemacs--variadic-extension-entry-render (ext &optional expand-depth)
"Render the entry point of the given variadic top level extension EXT.
Will create and insert the required strings and make a new dom entry.
EXPAND-DEPTH indicates the additional recursion depth.
EXT: `treemacs-extension' instance
EXPAND-DEPTH: Int"
(save-excursion
(treemacs-with-writable-buffer
;; When the extension is variadic it will be managed by a hidden top-level
;; node. Its depth is -1 and it is not visible, but can still be used to update
;; the entire extension without explicitly worrying about complex dom changes.
(let* ((key (treemacs-extension->get ext :key nil nil))
(path (list key))
(pr (treemacs-project->create!
:name (treemacs-extension->get ext :label nil nil)
:path path
:path-status 'extension))
(button-start (point-marker))
(dom-node (treemacs-dom-node->create!
:key path
:position (point-marker))))
(treemacs-dom-node->insert-into-dom! dom-node)
(insert (propertize "Hidden node"
'button '(t)
'category 'treemacs-button
'invisible t
'skip t
:custom t
:key key
:path path
:depth -1
:project pr
:state (treemacs-extension->get ext :closed-state)))
(let ((marker (copy-marker (point) t)))
(treemacs--do-expand-variadic-parent button-start ext expand-depth)
(goto-char marker)))))
t)
(cl-defmacro treemacs--create-node-strings
(&key parent
parent-path
parent-dom-node
more-properties
icon
state
key
depth
label)
"Create the strings needed to render an extension node.
PARENT: Button
PARENT-PATH: List<?>
PARENT-DOM-NODE: Dom Node Struct
MORE-PROPERTIES: Plist
ICON: String
STATE: Symbol
KEY: Any
DEPTH: Int
LABEL: String"
(macroexp-let2* nil
((key key))
`(let* ((path (append ,parent-path (list ,key)))
(dom-node (treemacs-dom-node->create! :key path :parent parent-dom-node))
(props ,more-properties)
(ann (treemacs-get-annotation path)))
(treemacs-dom-node->insert-into-dom! dom-node)
(when ,parent-dom-node
(treemacs-dom-node->add-child! parent-dom-node dom-node))
(list (unless (zerop depth) prefix)
,icon
(apply
#'propertize ,label
'button '(t)
'category 'treemacs-button
:custom t
:state ,state
:parent ,parent
:depth ,depth
:path path
:key ,key
:no-git t
props)
(and ann (treemacs-annotation->suffix-value ann))
(when (zerop depth) (if treemacs-space-between-root-nodes "\n\n" "\n"))))))
;; render method for extensions by the old version of the api
(defun treemacs--extension-entry-render (ext parent)
"Render the entry point of the given extension EXT under PARENT.
Will create and insert the required strings and make a new dom entry.
EXT: `treemacs-extension' instance
PARENT: Button"
(let* ((key (treemacs-extension->get ext :key))
(depth (1+ (treemacs-button-get parent :depth)))
(path (list (treemacs-button-get parent :path) key))
(parent-dom-node (treemacs-find-in-dom (treemacs-button-get parent :path)))
(new-dom-node (treemacs-dom-node->create! :key path :parent parent-dom-node)))
(treemacs-dom-node->insert-into-dom! new-dom-node)
(when parent-dom-node
(treemacs-dom-node->add-child! parent-dom-node new-dom-node))
(insert "\n")
(insert
(treemacs--get-indentation depth)
(treemacs-extension->get ext :closed-icon)
(propertize (treemacs-extension->get ext :label)
'button '(t)
'category 'treemacs-button
:custom t
:key key
:path path
:depth depth
:no-git t
:parent parent
:state (treemacs-extension->get ext :closed-state))))
nil)
(defun treemacs-expand-extension-node (&optional arg)
"Expand a node created with the extension api.
If a prefix ARG is provided expand recursively."
(interactive "P")
(let* ((btn (treemacs-node-at-point))
(state (treemacs-button-get btn :state))
(path (treemacs-button-get btn :path))
(ext (alist-get state treemacs--extension-registry))
(eol (line-end-position))
(already-loading
(/= eol
(next-single-property-change
(line-beginning-position) 'treemacs-async-string nil eol))))
(when (null ext)
(error "No extension is registered for state '%s'" state))
(unless (or (treemacs-button-get btn :leaf) already-loading)
(-let [async-cache (ht-get treemacs--async-update-cache path)]
(treemacs-with-writable-buffer
(cond
(async-cache
;; IMPORTANT
;; Asynchronous updates must be directed *very* carefully.
;; If there is no pre-computed cache the expand happens normally with
;; a "Loading..." string and normal async delay.
;; If the cache already exists then we at first open the async nodes
;; as if they were normal nodes, using the cache as their items.
;; Then, in the background, we start an asynchronous update via
;; `treemacs-update-async-node'.
;; However this first mundane node expansion will trigger re-entry, so
;; every child that is re-entered might trigger its own async update,
;; which is bad for 2 reasons:
;; 1. `treemacs-update-async-node' already updates a full path
;; including all its children
;; 2. At the end of every update is a call to `treemacs-update-node'
;; with a new async cache, causing another round of re-entry and
;; potential async updates.
;; In short: there is strong potential for an infinite loop!
;;
;; To keep this from happening the async background update must be
;; suppressed for all nodes but the very first, both for re-entry and
;; the final update.
;; This is achieved by setting the `busy' flag at the first async
;; node, and only starting the second update if, and only if, neither
;; the current node, nor any of its parents, are marked as busy.
(let* ((busy? (treemacs-button-get btn :busy))
(parent btn))
(unless busy?
(while (and (not busy?)
(setf parent (treemacs-button-get parent :parent)))
(setf busy? (treemacs-button-get parent :busy))))
(unless busy?
(treemacs-button-put btn :busy t))
(treemacs--do-expand-extension-node
btn ext async-cache arg)
(unless busy?
(treemacs-update-async-node path (marker-buffer btn)))))
((treemacs-extension->async? ext)
(treemacs--do-expand-async-extension-node btn ext arg))
(t
(treemacs--do-expand-extension-node btn ext nil arg)))
(treemacs-extension->get ext :on-expand btn))))))
(defun treemacs-collapse-extension-node (&optional arg)
"Collapse a node created with the extension api.
If a prefix ARG is provided expand recursively."
(interactive "P")
(let* ((btn (treemacs-node-at-point))
(state (treemacs-button-get btn :state))
(ext (alist-get state treemacs--extension-registry)))
(when (null ext)
(error "No extension is registered for state '%s'" state))
(treemacs--do-collapse-extension-node btn ext arg)
(treemacs-extension->get ext :on-collapse btn)))
(defun treemacs--do-expand-async-extension-node (btn ext &optional arg)
"Expand an async extension node BTN for the given extension EXT.
Prefix ARG is used to set expand recursion depth.
BTN: Button
EXT: `treemacs-extension' instance
ARG: Prefix Arg"
(interactive)
(treemacs-block
(treemacs-error-return-if (not (eq (treemacs-extension->get ext :closed-state)
(treemacs-button-get btn :state)))
"This function cannot expand a node of type '%s'."
(propertize (format "%s" (treemacs-button-get btn :state))
'face 'font-lock-type-face))
(save-excursion
(treemacs-with-writable-buffer
(goto-char (line-end-position))
(insert treemacs--treelib-async-load-string)))
(funcall
(treemacs-extension->children ext)
btn
(treemacs-button-get btn :item)
(lambda (items)
(ht-set! treemacs--async-update-cache (treemacs-button-get btn :path)
(or items 'nothing))
(treemacs--complete-async-expand-callback btn items ext arg)))))
(defun treemacs--complete-async-expand-callback (btn items ext arg)
"Properly expand an async node at BTN after its child ITEMS were computed.
BTN: Button
ITEMS: List<Any>
EXT: `treemacs-extension' instance
ARG: Prefix Arg"
(treemacs-with-button-buffer btn
(save-excursion
(goto-char btn)
(treemacs-with-writable-buffer
(delete-region
(next-single-char-property-change (point) 'treemacs-async-string)
(line-end-position)))
(if (eq :async-error (car items))
(treemacs-log-err "Something went wrong in an asynchronous context: %s" (cadr items))
(treemacs--do-expand-extension-node btn ext (or items 'nothing) arg)))
(hl-line-highlight)))
(defun treemacs--do-expand-extension-node (btn ext &optional items arg)
"Expand an extension node BTN for the given extension EXT.
ITEMS will override the node's normal `children' function. This is only used
when the node is asynchronous and this call is used to complete the async
computation.
Prefix ARG is used to set expand recursion depth.
BTN: Button
EXT: `treemacs-extension' instance
ARG: Prefix Arg
ITEMS: List<Any>"
(treemacs-block
(treemacs-error-return-if (not (eq (treemacs-extension->get ext :closed-state)
(treemacs-button-get btn :state)))
"This function cannot expand a node of type '%s'. Current node type is %s"
(propertize (format "%s" (treemacs-button-get btn :state))
'face 'font-lock-type-face)
(propertize (format "%s" (treemacs-extension->get ext :closed-state))
'face 'font-lock-type-face))
(let* ((items (pcase items
(`nil
(treemacs-extension->get
ext :children btn (treemacs-button-get btn :item)))
(`nothing nil)
(_ items)))
(depth (1+ (treemacs-button-get btn :depth)))
(btn-path (treemacs-button-get btn :path))
(parent-path (if (listp btn-path) btn-path (list btn-path)))
(parent-dom-node (treemacs-find-in-dom btn-path))
(child-ext (treemacs-extension->get ext :child-type))
(child-state (treemacs-extension->get child-ext :closed-state))
(closed-icon-fn (treemacs-extension->closed-icon child-ext))
(label-fn (treemacs-extension->label child-ext))
(properties-fn (treemacs-extension->more-properties child-ext))
(key-fn (treemacs-extension->key child-ext))
(recursive (treemacs--prefix-arg-to-recurse-depth arg)))
(treemacs--button-open
:button btn
:new-state (treemacs-extension->get ext :open-state)
:new-icon (treemacs-extension->get
ext :open-icon btn (treemacs-button-get btn :item))
:immediate-insert t
:open-action
(treemacs--create-buttons
:nodes items
:depth depth
:node-name item
:node-action
(treemacs--create-node-strings
:parent btn
:parent-path parent-path
:parent-dom-node parent-dom-node
:more-properties (append `(:item ,item) (funcall properties-fn btn item))
:icon (funcall closed-icon-fn btn item)
:state child-state
:key (funcall key-fn btn item)
:depth depth
:label (funcall label-fn btn item)))
:post-open-action
(progn
(treemacs-on-expand btn-path btn)
(treemacs--reentry btn-path)
(when (> recursive 0)
(cl-decf recursive)
(--each (treemacs-collect-child-nodes btn)
(when (treemacs-is-node-collapsed? it)
(goto-char (treemacs-button-start it))
(treemacs-expand-extension-node recursive)))))))))
(defun treemacs--expand-variadic-parent (&optional arg)
"Interactive command to expand a variadic parent.
Only required to set up `treemacs-TAB-actions-config'.
ARG: Prefix Arg"
(interactive "P")
(let* ((btn (treemacs-node-at-point))
(state (treemacs-button-get btn :state))
(ext (alist-get state treemacs--extension-registry)))
(when (null ext)
(error "No extension is registered for state '%s'" state))
(treemacs-with-writable-buffer
(treemacs--do-expand-variadic-parent btn ext arg))))
(defun treemacs--do-expand-variadic-parent (btn ext &optional expand-depth)
"Expand the hidden parent BTN of a variadic extension instance EXT.
EXPAND-DEPTH indicates the additional recursion depth.
BTN: Button
EXT: `treemacs-extension' instance
EXPAND-DEPTH: Int"
(let* ((items (treemacs-extension->get ext :children))
(parent-path (treemacs-button-get btn :path))
(parent-dom-node (treemacs-find-in-dom parent-path))
(child-ext (treemacs-extension->get ext :child-type))
(child-state (treemacs-extension->get child-ext :closed-state))
(closed-icon-fn (treemacs-extension->closed-icon child-ext))
(label-fn (treemacs-extension->label child-ext))
(properties-fn (treemacs-extension->more-properties child-ext))
(key-fn (treemacs-extension->key child-ext))
(expand-depth (treemacs--prefix-arg-to-recurse-depth expand-depth)))
(goto-char (button-end btn))
(insert (apply #'propertize "\n" (text-properties-at btn)))
(treemacs--button-open
:button btn
:new-state (treemacs-extension->get ext :open-state)
:immediate-insert t
:open-action
(treemacs--create-buttons
:nodes items
:depth 0
:node-name item
:node-action
(treemacs--create-node-strings
:parent nil
:parent-path parent-path
:parent-dom-node parent-dom-node
:more-properties
(append `(:item ,item)
`(:project ,(treemacs-project->create!
:name (funcall label-fn btn item)
:path path
:path-status 'extension))
(funcall properties-fn btn item))
:icon (funcall closed-icon-fn btn item)
:state child-state
:key (funcall key-fn btn item)
:depth depth
:label (funcall label-fn btn item)))
:post-open-action
(progn
;; projects' positions must always be known, so in this one
;; case they have to be collected very manually
(save-excursion
(goto-char (point-min))
(-let [btn (point)]
(while (setf btn (next-button btn))
(let* ((path (treemacs-button-get btn :path))
(dom-node (treemacs-find-in-dom path)))
(setf (treemacs-dom-node->position dom-node) btn)))))
(treemacs-on-expand (treemacs-button-get btn :path) btn)
(treemacs--reentry (treemacs-button-get btn :path))
(when (> expand-depth 0)
(cl-decf expand-depth)
(--each (treemacs--all-buttons-with-depth 0)
(when (treemacs-is-node-collapsed? it)
(goto-char (treemacs-button-start it))
(treemacs-expand-extension-node expand-depth))))))))
(defun treemacs-update-async-node (path buffer)
"Update an asynchronous node at PATH in the given BUFFER.
The update process will asynchronously pre-compute the children for every node
currently expanded under PATH. The results of this computation will be cached
and then used to update the UI in one go."
(-let [items-to-update (treemacs--get-async-update-items path)]
(ht-set! treemacs--async-update-count path (length items-to-update))
(dolist (item items-to-update)
(let* ((item-path (car item))
(ext (cdr item))
(btn (treemacs-find-node item-path))
(item (treemacs-button-get btn :item))
(children-fn (treemacs-extension->children ext)))
(funcall
children-fn btn item
(lambda (items)
(treemacs--async-update-part-complete
path item-path items buffer)))))))
(defun treemacs--get-async-update-items (path)
"Get the items needed for an async update at the given PATH.
Every item in the returned list will consist of the node's key and its
extensions instance."
(-let [items nil]
(treemacs-walk-reentry-dom (treemacs-find-in-dom path)
(lambda (dom-node)
(let* ((key (treemacs-dom-node->key dom-node))
(state (treemacs-button-get (treemacs-find-node key) :state))
(ext (alist-get state treemacs--extension-registry)))
(push (cons key ext) items))))
items))
(defun treemacs--async-update-part-complete (top-path updated-path items buffer)
"Partial completion for an asynchronous update.
TOP-PATH is the path of the node the update was called for.
UPDATED-PATH is the path of one of top node's children (may also be TOP-PATH)
whose content has just been computed.
ITEMS are the new items for the UPDATED-PATH that will be cached for the next
update.
BUFFER is the buffer where the node is located."
(ht-set! treemacs--async-update-cache updated-path (or items 'nothing))
(-let [count (cl-decf (ht-get treemacs--async-update-count top-path))]
(when (= 0 count)
(--when-let (buffer-live-p buffer)
(with-current-buffer buffer
(treemacs-with-writable-buffer
(treemacs-update-node top-path)
(treemacs-button-put (treemacs-find-node updated-path) :busy nil)))))))
(defun treemacs--do-collapse-extension-node (btn ext &optional __arg)
"Collapse an extension button BTN for the given EXT.
BTN: Button
EXT: `treemacs-extensions' instance
ARG: Prefix Arg"
(treemacs--button-close
:button btn
:new-state (treemacs-extension->get ext :closed-state)
:new-icon
(treemacs-extension->get ext :closed-icon btn (treemacs-button-get btn :item))
:post-close-action
(treemacs-on-collapse (treemacs-button-get btn :path))))
(cl-defmacro treemacs-initialize
(extension
&key
(with-expand-depth 0)
and-do)
"Initialise an external buffer for use with the given EXTENSION.
EXTENSION is the same symbol that was passed as a `:key' argument
to `treemacs-define-variadic-entry-node-type'.
WITH-EXPAND-DEPTH indicates the number of nodes that should be expanded *in
addition* to the default. If a value is given that is not a number then
treemacs will assume that *all* possible nodes should be expanded.
AND-DO can be used to set up buffer-local variables after the buffer has
switched over to `treemacs-mode'."
(declare (indent 1))
`(progn
(treemacs--disable-fringe-indicator)
(treemacs-with-writable-buffer
(erase-buffer))
;; make sure the fringe indicator is enabled later, otherwise treemacs
;; attempts to move it right after the `treemacs-mode' call the indicator
;; cannot be created before either since the major-mode activation wipes
;; out buffer-local variables' values
(let ((treemacs-fringe-indicator-mode nil)
(treemacs--in-this-buffer t))
(treemacs-mode))
(setq-local treemacs-space-between-root-nodes nil)
(setq-local treemacs--in-this-buffer :extension)
,and-do
(treemacs--render-extension
(let ((instance (treemacs--ext-symbol-to-instance ',extension)))
(treemacs-static-assert
(and instance (treemacs-extension->variadic? instance))
"%s is not a variadic extension" ',extension)
instance)
(if (numberp ,with-expand-depth) ,with-expand-depth 999))
(goto-char 1)
(treemacs--evade-image)))
(provide 'treemacs-treelib)
;;; treemacs-treelib.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-treelib.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 10,693 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Code in this file is considered performance critical. The usual
;; restrictions w.r.t quality, readability and maintainability are
;; lifted here.
;;; Code:
(require 's)
(require 'ht)
(require 'treemacs-core-utils)
(require 'treemacs-icons)
(require 'treemacs-async)
(require 'treemacs-customization)
(require 'treemacs-dom)
(require 'treemacs-workspaces)
(require 'treemacs-visuals)
(require 'treemacs-logging)
(require 'treemacs-annotations)
(eval-when-compile
(require 'cl-lib)
(require 'treemacs-macros)
(require 'inline))
(treemacs-import-functions-from "treemacs"
treemacs-select-window)
(treemacs-import-functions-from "treemacs-filewatch-mode"
treemacs--start-watching
treemacs--stop-watching)
(treemacs-import-functions-from "treemacs-visuals"
treemacs--get-indentation)
(treemacs-import-functions-from "treemacs-interface"
treemacs-add-project-to-workspace
treemacs-TAB-action)
(treemacs-import-functions-from "treemacs-tags"
treemacs--expand-file-node
treemacs--expand-tag-node)
;; Ensure mouse cursor turns into a hand over treemacs' buttons
(put 'treemacs-button 'mouse-face 'highlight)
(defvar-local treemacs--projects-end nil
"Marker pointing to position at the end of the last project.
If there are no projects, points to the position at the end of any top level
extensions positioned to `TOP'. This can always be used as the insertion point
for new projects.")
(defvar treemacs--file-name-handler-alist nil
"Value of `file-name-handler-alist' when treemacs loads a directory's content.")
(defvar treemacs--no-recenter nil
"Set for non-interactive updates.
When non-nil `treemacs--maybe-recenter' will have no effect.")
(define-inline treemacs--projects-end ()
"Importable accessor for `treemacs--projects-end'."
(declare (side-effect-free t))
(inline-quote treemacs--projects-end))
(define-inline treemacs--button-at (pos)
"Return the button at position POS in the current buffer, or nil.
If the button at POS is a text property button, the return value
is a marker pointing to POS."
(declare (side-effect-free t))
(inline-letevals (pos)
(inline-quote (copy-marker ,pos t))))
(define-inline treemacs--button-in-line (pos)
"Return the button in the line at POS in the current buffer, or nil.
If the button at POS is a text property button, the return value
is a marker pointing to POS."
(inline-letevals (pos)
(inline-quote
(save-excursion
(goto-char ,pos)
(copy-marker
(next-single-property-change
(line-beginning-position) 'button nil (line-end-position))
t)))))
(define-inline treemacs--current-screen-line ()
"Get the current screen line in the selected window."
(declare (side-effect-free t))
(inline-quote
(max 1 (count-screen-lines (window-start) (line-end-position)))))
(define-inline treemacs--lines-in-window ()
"Determine the number of lines visible in the current (treemacs) window.
A simple call to something like `window-screen-lines' is insufficient because
the height of treemacs' icons must be taken into account."
(declare (side-effect-free t))
(inline-quote
(/ (- (window-pixel-height) (window-mode-line-height))
(max treemacs--icon-size (frame-char-height)))))
(define-inline treemacs--sort-alphabetic-asc (f1 f2)
"Sort F1 and F2 alphabetically ascending."
(declare (pure t) (side-effect-free t))
(inline-letevals (f1 f2)
(inline-quote (string-lessp ,f1 ,f2))))
(define-inline treemacs--sort-alphabetic-desc (f1 f2)
"Sort F1 and F2 alphabetically descending."
(declare (pure t) (side-effect-free t))
(inline-letevals (f1 f2)
(inline-quote (string-lessp ,f2 ,f1))))
(define-inline treemacs--sort-alphabetic-numeric-asc (f1 f2)
"Sort F1 and F2 alphabetically and numerically ascending."
(declare (pure t) (side-effect-free t))
(inline-letevals (f1 f2)
(inline-quote (string-version-lessp ,f1 ,f2))))
(define-inline treemacs--sort-alphabetic-numeric-desc (f1 f2)
"Sort F1 and F2 alphabetically and numerically descending."
(declare (pure t) (side-effect-free t))
(inline-letevals (f1 f2)
(inline-quote (string-version-lessp ,f2 ,f1))))
(define-inline treemacs--sort-alphabetic-case-insensitive-asc (f1 f2)
"Sort F1 and F2 case insensitive alphabetically ascending."
(declare (pure t) (side-effect-free t))
(inline-letevals (f1 f2)
(inline-quote (string-lessp (downcase ,f1) (downcase ,f2)))))
(define-inline treemacs--sort-alphabetic-case-insensitive-desc (f1 f2)
"Sort F1 and F2 case insensitive alphabetically descending."
(declare (pure t) (side-effect-free t))
(inline-letevals (f1 f2)
(inline-quote (string-lessp (downcase ,f2) (downcase ,f1)))))
(define-inline treemacs--sort-alphabetic-numeric-case-insensitive-asc (f1 f2)
"Sort F1 and F2 case insensitive alphabetically and numerically ascending."
(declare (pure t) (side-effect-free t))
(inline-letevals (f1 f2)
(inline-quote (string-version-lessp (downcase ,f1) (downcase ,f2)))))
(define-inline treemacs--sort-alphabetic-numeric-case-insensitive-desc (f1 f2)
"Sort F1 and F2 case insensitive alphabetically and numerically descending."
(declare (pure t) (side-effect-free t))
(inline-letevals (f1 f2)
(inline-quote (string-version-lessp (downcase ,f2) (downcase ,f1)))))
(define-inline treemacs--sort-size-asc (f1 f2)
"Sort F1 and F2 by size ascending."
(declare (side-effect-free t))
(inline-letevals (f1 f2)
(inline-quote
(< (nth 7 (file-attributes ,f1))
(nth 7 (file-attributes ,f2))))))
(define-inline treemacs--sort-size-desc (f1 f2)
"Sort F1 and F2 by size descending."
(declare (side-effect-free t))
(inline-letevals (f1 f2)
(inline-quote
(>= (nth 7 (file-attributes ,f1))
(nth 7 (file-attributes ,f2))))))
(define-inline treemacs--sort-mod-time-asc (f1 f2)
"Sort F1 and F2 by modification time ascending."
(declare (side-effect-free t))
(inline-letevals (f1 f2)
(inline-quote (file-newer-than-file-p ,f2 ,f1))))
(define-inline treemacs--sort-mod-time-desc (f1 f2)
"Sort F1 and F2 by modification time descending."
(declare (side-effect-free t))
(inline-letevals (f1 f2)
(inline-quote (file-newer-than-file-p ,f1 ,f2))))
(define-inline treemacs--insert-root-separator ()
"Insert a root-level separator at point, moving point after the separator."
(inline-quote
(insert (if treemacs-space-between-root-nodes "\n\n" "\n"))))
(define-inline treemacs--get-sort-fuction ()
(declare (side-effect-free t))
(inline-quote
(pcase treemacs-sorting
('alphabetic-asc #'treemacs--sort-alphabetic-asc)
('alphabetic-desc #'treemacs--sort-alphabetic-desc)
('alphabetic-numeric-asc #'treemacs--sort-alphabetic-numeric-asc)
('alphabetic-numeric-desc #'treemacs--sort-alphabetic-numeric-desc)
('alphabetic-case-insensitive-asc #'treemacs--sort-alphabetic-case-insensitive-asc)
('alphabetic-case-insensitive-desc #'treemacs--sort-alphabetic-case-insensitive-desc)
('alphabetic-numeric-case-insensitive-asc #'treemacs--sort-alphabetic-numeric-case-insensitive-asc)
('alphabetic-numeric-case-insensitive-desc #'treemacs--sort-alphabetic-numeric-case-insensitive-desc)
('size-asc #'treemacs--sort-size-asc)
('size-desc #'treemacs--sort-size-desc)
('mod-time-asc #'treemacs--sort-mod-time-asc)
('mod-time-desc #'treemacs--sort-mod-time-desc)
(other other))))
(define-inline treemacs--get-dir-content (dir)
"Get the content of DIR, separated into sub-lists of first dirs, then files."
(inline-letevals (dir)
(inline-quote
;; `directory-files' is much faster in a temp buffer for whatever reason
(with-temp-buffer
(let* ((file-name-handler-alist treemacs--file-name-handler-alist)
(sort-func (treemacs--get-sort-fuction))
(entries (-> ,dir (directory-files :absolute-names nil :no-sort) (treemacs--filter-files-to-be-shown)))
(dirs-files (-separate #'file-directory-p entries)))
(list (sort (car dirs-files) sort-func)
(sort (cadr dirs-files) sort-func)))))))
(define-inline treemacs--create-dir-button-strings (path prefix parent depth)
"Return the text to insert for a directory button for PATH.
PREFIX is a string inserted as indentation.
PARENT is the (optional) button under which this one is inserted.
DEPTH indicates how deep in the filetree the current button is."
(inline-letevals (path prefix parent depth)
(inline-quote
(let ((dir-name (file-name-nondirectory ,path)))
(list
,prefix
(treemacs-icon-for-dir dir-name 'closed)
(propertize (->> dir-name (funcall treemacs-directory-name-transformer))
'button '(t)
'category 'treemacs-button
'help-echo nil
'keymap nil
:default-face 'treemacs-directory-face
:state 'dir-node-closed
:path ,path
:key ,path
:symlink (file-symlink-p ,path)
:parent ,parent
:depth ,depth))))))
(define-inline treemacs--create-file-button-strings (path prefix parent depth)
"Return the text to insert for a file button for PATH.
PREFIX is a string inserted as indentation.
PARENT is the (optional) button under which this one is inserted.
DEPTH indicates how deep in the filetree the current button is."
(inline-letevals (path prefix parent depth)
(inline-quote
(list
,prefix
(treemacs-icon-for-file ,path)
(propertize (->> ,path file-name-nondirectory (funcall treemacs-file-name-transformer))
'button '(t)
'category 'treemacs-button
'help-echo nil
'keymap nil
:default-face 'treemacs-git-unmodified-face
:state 'file-node-closed
:path ,path
:key ,path
:parent ,parent
:depth ,depth)))))
;; TODO document open-action return strings
(cl-defmacro treemacs--button-open (&key button new-state new-icon open-action post-open-action immediate-insert)
"Building block macro to open a BUTTON.
Gives the button a NEW-STATE, and, optionally, a NEW-ICON. Performs OPEN-ACTION
and, optionally, POST-OPEN-ACTION. If IMMEDIATE-INSERT is non-nil it will
concat and apply `insert' on the items returned from OPEN-ACTION. If it is nil
either OPEN-ACTION or POST-OPEN-ACTION are expected to take over insertion."
`(prog1
(save-excursion
(let ((p (point))
lines)
(treemacs-with-writable-buffer
(treemacs-button-put ,button :state ,new-state)
,@(when new-icon
`((beginning-of-line)
(treemacs--button-symbol-switch ,new-icon)))
(goto-char (line-end-position))
,@(if immediate-insert
`((progn
(insert (apply #'concat ,open-action))))
`(,open-action))
(setf lines (count-lines p (point)))
,post-open-action
lines)))
(when treemacs-move-forward-on-expand
(let* ((parent (treemacs-current-button))
(child (next-button parent)))
(when (equal parent (treemacs-button-get child :parent))
(forward-line 1))))))
(cl-defmacro treemacs--create-buttons (&key nodes node-action depth extra-vars node-name)
"Building block macro for creating buttons from a list of NODES.
Will not making any insertions, but instead return a list of strings created by
NODE-ACTION, so that the list can be further manipulated and efficiently
inserted in one go.
NODES is the list to create buttons from.
DEPTH is the indentation level buttons will be created on.
EXTRA-VARS are additional var bindings inserted into the initial let block.
NODE-ACTION is the button creating form inserted for every NODE.
NODE-NAME is the variable individual nodes are bound to in NODE-ACTION."
`(let* ((depth ,depth)
(prefix (concat "\n" (treemacs--get-indentation depth)))
(,node-name (car ,nodes))
(strings)
,@extra-vars)
;; extensions only implicitly use the prefix by calling into `treemacs-render-node'
;; (ignore prefix)
(when ,node-name
(dolist (,node-name ,nodes)
(--each ,node-action
(push it strings))))
(nreverse strings)))
(defun treemacs--flatten-dirs (dirs)
"Display DIRS as flattened.
Go to each dir button, expand its label with the collapsed dirs, set its new
path and give it a special parent-path property so opening it will add the
correct cache entries.
DIRS: List of Collapse Paths. Each Collapse Path is a list of
1) the extra text that must be appended in the view,
2) The original full and un-collapsed path,
3) a series of intermediate steps which are the result of appending the
collapsed path elements onto the original, ending in
4) the full path to the
directory that the collapsing leads to. For Example:
(\"/26.0/elpa\"
\"/home/a/Documents/git/treemacs/.cask\"
\"/home/a/Documents/git/treemacs/.cask/26.0\"
\"/home/a/Documents/git/treemacs/.cask/26.0/elpa\")"
(when dirs
(-let [project (-> dirs (car) (cadr) (treemacs--find-project-for-path))]
(dolist (it dirs)
(let* ((label-to-add (car it))
(original-path (cadr it))
(extra-steps (cddr it))
(new-path (-last-item extra-steps))
(coll-count (length extra-steps)))
;; use when-let because the operation may fail when we try to move to a node
;; that us not visible because treemacs ignores it
(-when-let (b (treemacs-find-file-node original-path project))
;; no warning since filewatch mode is known to be defined
(when (with-no-warnings treemacs-filewatch-mode)
(treemacs--start-watching original-path)
(dolist (step extra-steps)
(treemacs--start-watching step t)))
;; make extra dom entries for the flattened steps
(-let [dom-node (treemacs-find-in-dom original-path)]
(dolist (step extra-steps)
(ht-set! treemacs-dom step dom-node))
(setf (treemacs-dom-node->collapse-keys dom-node) extra-steps))
(-let [props (text-properties-at (treemacs-button-start b))]
(treemacs-button-put b :path new-path)
;; if the collapsed path leads to a symlinked directory the button needs to be marked as a symlink
;; so `treemacs--expand-dir-node' will know to start a new git future under its true-name
(treemacs-button-put b :symlink (or (treemacs-button-get b :symlink)
(--first (file-symlink-p it) extra-steps)))
;; number of directories that have been appended to the original path plus all extra steps
;; to use as dom keys when the node is expanded
(treemacs-button-put b :collapsed (cons coll-count (cons original-path extra-steps)))
(end-of-line)
(-let [beg (point)]
(insert label-to-add)
(add-text-properties beg (point) props)
(unless (treemacs--non-simple-git-mode-enabled)
(add-text-properties
beg (point)
'(face treemacs-directory-collapsed-face)))
(-when-let* ((ann (treemacs-get-annotation new-path))
(git-cache
(->> original-path
(treemacs--parent-dir)
(ht-get treemacs--git-cache))))
(treemacs-button-put
b 'face
(treemacs-annotation->face-value ann)))))))))))
(defmacro treemacs--inplace-map-when-unrolled (items interval &rest mapper)
"Unrolled in-place mapping operation.
Maps ITEMS at given index INTERVAL using MAPPER function."
(declare (indent 2))
(let ((l (make-symbol "list"))
(tail-op (cl-case interval
(2 'cdr)
(3 'cddr)
(4 'cdddr)
(_ (error "Interval %s is not handled yet" interval)))))
`(let ((,l ,items))
(while ,l
(setq ,l (,tail-op ,l))
(let ((it (car ,l)))
(setf (car ,l) ,@mapper)
(pop ,l)))
,items)))
(define-inline treemacs--create-branch (root depth git-future flatten-future &optional parent)
"Create a new treemacs branch under ROOT.
The branch is indented at DEPTH and uses the eventual outputs of
GIT-FUTURE to decide on file buttons' faces and FLATTEN-FUTURE to determine
which directories should be displayed as one. The buttons' parent property is
set to PARENT."
(inline-letevals (root depth git-future flatten-future parent)
(inline-quote
(save-excursion
(let* ((dirs-and-files (treemacs--get-dir-content ,root))
(dirs (car dirs-and-files))
(files (cadr dirs-and-files))
(parent-node (treemacs-find-in-dom ,root))
(dir-dom-nodes)
(file-dom-nodes)
(git-info)
(file-strings)
(dir-strings))
(setq dir-strings
(treemacs--create-buttons
:nodes dirs
:depth ,depth
:node-name node
:node-action (treemacs--create-dir-button-strings node prefix ,parent ,depth)))
(setq file-strings
(treemacs--create-buttons
:nodes files
:depth ,depth
:node-name node
:node-action (treemacs--create-file-button-strings node prefix ,parent ,depth)))
(end-of-line)
;; the files list contains 3 item tuples: the prefix the icon and the filename
;; direcories are different, since dirs do not have different icons the icon is part if the prefix
;; therefore when filtering or propertizing the files and dirs only every 3rd or 2nd item must be looked at
;; as reopening is done recursively the parsed git status is passed down to subsequent calls
;; so there are two possibilities: either the future given to this function is a pfuture object
;; that needs to complete and be parsed or it's an already finished git status hash table
;; additionally when git mode is deferred we don't parse the git output right here, it is instead done later
;; by means of an idle timer. The git info used is instead fetched from `treemacs--git-cache', which is
;; based on previous invocations
;; if git-mode is disabled there is nothing to do - in this case the git status parse function will always
;; produce an empty hash table
(pcase treemacs--git-mode
((or 'simple 'extended)
(setf git-info (treemacs--get-or-parse-git-result ,git-future))
(ht-set! treemacs--git-cache ,root git-info))
('deferred
(setf git-info (or (ht-get treemacs--git-cache ,root) treemacs--empty-table)))
(_
(setf git-info treemacs--empty-table)))
(run-with-timer
0.5 nil
#'treemacs--apply-annotations-deferred
,parent ,root (current-buffer) ,git-future)
(if treemacs-pre-file-insert-predicates
(progn
(-let [result nil]
(while file-strings
(let* ((prefix (car file-strings))
(icon (cadr file-strings))
(filename (caddr file-strings))
(filepath (concat ,root "/" filename)))
(unless (--any? (funcall it filepath git-info) treemacs-pre-file-insert-predicates)
(setq result (cons filename (cons icon (cons prefix result))))
(push (treemacs-dom-node->create! :parent parent-node :key filepath)
file-dom-nodes)))
(setq file-strings (cdddr file-strings)))
(setq file-strings (nreverse result)))
(-let [result nil]
(while dir-strings
(let* ((prefix (car dir-strings))
(icon (cadr dir-strings))
(dirname (caddr dir-strings))
(dirpath (concat ,root "/" dirname)))
(unless (--any? (funcall it dirpath git-info) treemacs-pre-file-insert-predicates)
(setq result (cons dirname (cons icon (cons prefix result))))
(push (treemacs-dom-node->create! :parent parent-node :key dirpath)
dir-dom-nodes)))
(setq dir-strings (cdddr dir-strings)))
(setq dir-strings (nreverse result))))
(setf
file-dom-nodes
(--map (treemacs-dom-node->create! :parent parent-node :key it) files)
dir-dom-nodes
(--map (treemacs-dom-node->create! :parent parent-node :key it) dirs)))
;; do nodes can only be created *after* any potential fitering has taken place,
;; otherwise we end up with dom entries for files that are not rendered
(setf (treemacs-dom-node->children parent-node)
(nconc dir-dom-nodes file-dom-nodes (treemacs-dom-node->children parent-node)))
(dolist (it (treemacs-dom-node->children parent-node))
(treemacs-dom-node->insert-into-dom! it))
(setf dir-strings
(treemacs--inplace-map-when-unrolled dir-strings 3
(-if-let* ((ann (treemacs-get-annotation (concat ,root "/" it)))
(face (treemacs-annotation->face-value ann)))
(progn
(put-text-property
0
(length it)
'face
face
it)
(concat it (treemacs-annotation->suffix-value ann)))
(put-text-property
0
(length it)
'face
'treemacs-directory-face
it)
it)))
(insert (apply #'concat dir-strings))
(end-of-line)
(setf file-strings
(treemacs--inplace-map-when-unrolled file-strings 3
(-if-let* ((ann (treemacs-get-annotation (concat ,root "/" it)))
(face (treemacs-annotation->face-value ann)))
(progn
(put-text-property
0
(length it)
'face
face
it)
(concat it (treemacs-annotation->suffix-value ann)))
(put-text-property
0
(length it)
'face
'treemacs-git-unmodified-face
it)
it)))
(insert (apply #'concat file-strings))
(save-excursion
(treemacs--flatten-dirs
(treemacs--parse-flattened-dirs ,root ,flatten-future))
(treemacs--reentry ,root ,git-future ,flatten-future))
(with-no-warnings
(line-end-position)))))))
(cl-defmacro treemacs--button-close (&key button new-icon new-state post-close-action)
"Close node given by BUTTON, use NEW-ICON and BUTTON's state to NEW-STATE.
Run POST-CLOSE-ACTION after everything else is done."
`(save-excursion
(treemacs-with-writable-buffer
,@(when new-icon
`((treemacs--button-symbol-switch ,new-icon)))
(treemacs-button-put ,button :state ,new-state)
(-let [next (next-button (button-end ,button))]
(if (or (null next)
(/= (1+ (treemacs-button-get ,button :depth))
(treemacs-button-get (copy-marker next t) :depth)))
(delete-trailing-whitespace)
;; Delete from end of the current button to end of the last sub-button.
;; This will make the EOL of the last button become the EOL of the
;; current button, making the treemacs--projects-end marker track
;; properly when collapsing the last project or a last directory of the
;; last project.
(let* ((pos-start (line-end-position))
(next (treemacs--next-non-child-button ,button))
(pos-end (if next
(-> next (treemacs-button-start) (previous-button) (treemacs-button-end))
(point-max))))
(delete-region pos-start pos-end))))
,post-close-action)))
(defun treemacs--expand-root-node (btn &optional recursive)
"Expand the given root BTN.
Open every child-directory as well when RECURSIVE is non-nil.
BTN: Button
RECURSIVE: Bool"
(let ((project (treemacs-button-get btn :project)))
(treemacs-with-writable-buffer
(treemacs-project->refresh-path-status! project))
(if (treemacs-project->is-unreadable? project)
(treemacs-pulse-on-failure
(format "%s is not readable."
(propertize (treemacs-project->path project) 'face 'font-lock-string-face)))
(let* ((path (treemacs-button-get btn :path))
(git-path (if (treemacs-button-get btn :symlink) (file-truename path) path))
(git-future (treemacs--git-status-process git-path project))
(flatten-future (treemacs--flattened-dirs-process path project))
(recursive (treemacs--prefix-arg-to-recurse-depth recursive)) )
(treemacs--maybe-recenter treemacs-recenter-after-project-expand
(treemacs--button-open
:immediate-insert nil
:button btn
:new-state 'root-node-open
:new-icon treemacs-icon-root-open
:open-action
(progn
;; TODO(2019/10/14): go back to post open
;; expand first because it creates a dom node entry
(treemacs-on-expand path btn)
(when (fboundp 'treemacs--apply-project-top-extensions)
(treemacs--apply-project-top-extensions btn project))
(when (fboundp 'treemacs--apply-project-bottom-extensions)
(save-excursion
(treemacs--apply-project-bottom-extensions btn project)))
(treemacs--create-branch
path
(1+ (treemacs-button-get btn :depth))
git-future
flatten-future
btn)
(treemacs--start-watching path)
;; Performing FS ops on a disconnected Tramp project
;; might have changed the state to connected.
(treemacs-with-writable-buffer
(treemacs-project->refresh-path-status! project))
(when (and (> recursive 0) (treemacs-project->is-readable? project))
(cl-decf recursive)
(--each (treemacs-collect-child-nodes btn)
(when (eq 'dir-node-closed (treemacs-button-get it :state))
(goto-char (treemacs-button-start it))
(treemacs--expand-dir-node it :git-future git-future :recursive recursive)))))))))))
(defun treemacs--collapse-root-node (btn &optional recursive)
"Collapse the given root BTN.
Remove all open entries below BTN when RECURSIVE is non-nil."
(treemacs--button-close
:button btn
:new-state 'root-node-closed
:new-icon treemacs-icon-root-closed
:post-close-action
(-let [path (treemacs-button-get btn :path)]
(treemacs--stop-watching path)
(treemacs-on-collapse path recursive))))
(cl-defun treemacs--expand-dir-node
(btn
&key
git-future
flatten-future
recursive)
"Open the node given by BTN.
BTN: Button
GIT-FUTURE: Pfuture|HashMap
FLATTEN-FUTURE: Pfuture|HashMap
RECURSIVE: Bool"
(-let [path (treemacs-button-get btn :path)]
(if (not (file-readable-p path))
(treemacs-pulse-on-failure "Directory %s is not readable."
(propertize path 'face 'font-lock-string-face))
(let* ((project (treemacs-project-of-node btn))
(git-future (if (treemacs-button-get btn :symlink)
(treemacs--git-status-process (file-truename path) project)
(or git-future (treemacs--git-status-process path project))))
(flatten-future (or flatten-future
(treemacs--flattened-dirs-process path project)))
(recursive (treemacs--prefix-arg-to-recurse-depth recursive))
(base-dir-name (treemacs--filename (treemacs-button-get btn :key))))
(treemacs--button-open
:immediate-insert nil
:button btn
:new-state 'dir-node-open
:new-icon (treemacs-icon-for-dir base-dir-name 'open)
:open-action
(progn
;; do on-expand first so buttons that need collapsing can quickly find their parent
(treemacs-on-expand path btn)
(when (fboundp 'treemacs--apply-directory-top-extensions)
(treemacs--apply-directory-top-extensions btn path))
(goto-char
(treemacs--create-branch
path (1+ (treemacs-button-get btn :depth))
git-future flatten-future btn))
(when (fboundp 'treemacs--apply-directory-bottom-extensions)
(treemacs--apply-directory-bottom-extensions btn path))
(treemacs--start-watching path)
(when (> recursive 0)
(cl-decf recursive)
(--each (treemacs-collect-child-nodes btn)
(when (eq 'dir-node-closed (treemacs-button-get it :state))
(goto-char (treemacs-button-start it))
(treemacs--expand-dir-node it :git-future git-future :recursive recursive))))))))))
(defun treemacs--collapse-dir-node (btn &optional recursive)
"Close node given by BTN.
Remove all open dir and tag entries under BTN when RECURSIVE."
(let ((path (treemacs-button-get btn :path))
(base-dir-name (treemacs--filename (treemacs-button-get btn :key))))
(treemacs--button-close
:button btn
:new-state 'dir-node-closed
:new-icon (treemacs-icon-for-dir base-dir-name 'closed)
:post-close-action
(progn
(treemacs--stop-watching path)
(treemacs-on-collapse path recursive)))))
(defun treemacs--root-face (project)
"Get the face to be used for PROJECT."
(cl-case (treemacs-project->path-status project)
(local-unreadable 'treemacs-root-unreadable-face)
(remote-readable 'treemacs-root-remote-face)
(remote-disconnected 'treemacs-root-remote-disconnected-face)
(remote-unreadable 'treemacs-root-remote-unreadable-face)
(otherwise 'treemacs-root-face)))
(defun treemacs--add-root-element (project)
"Insert a new root node for the given PROJECT node.
PROJECT: Project Struct"
(insert treemacs-icon-root-closed)
(let* ((pos (point-marker))
(path (treemacs-project->path project))
(dom-node (treemacs-dom-node->create! :key path :position pos)))
(treemacs-dom-node->insert-into-dom! dom-node)
(insert
(propertize (treemacs-project->name project)
'button '(t)
'category 'treemacs-button
'face (treemacs--root-face project)
:project project
:default-face 'treemacs-root-face
:key path
:symlink (when (treemacs-project->is-readable? project)
(file-symlink-p path))
:state 'root-node-closed
:path path
:depth 0))))
(defun treemacs--render-projects (projects)
"Actually render the given PROJECTS in the current buffer."
(treemacs-with-writable-buffer
(unless treemacs--projects-end
(setq treemacs--projects-end (make-marker)))
(let* ((projects (-reject #'treemacs-project->is-disabled? projects))
(current-workspace (treemacs-current-workspace))
(has-previous (when (fboundp 'treemacs--apply-root-top-extensions)
(treemacs--apply-root-top-extensions current-workspace))))
(--each projects
(when has-previous (treemacs--insert-root-separator))
(setq has-previous t)
(treemacs--add-root-element it))
;; Set the end marker after inserting the extensions. Otherwise, the
;; extensions would move the marker.
(let ((projects-end-point (point)))
(when (fboundp 'treemacs--apply-root-bottom-extensions)
(treemacs--apply-root-bottom-extensions current-workspace has-previous))
;; If the marker lies at the start of the buffer, expanding extensions would
;; move the marker. Make sure that the marker does not move when doing so.
(set-marker-insertion-type treemacs--projects-end has-previous)
(set-marker treemacs--projects-end projects-end-point)))))
(define-inline treemacs-do-update-node (path &optional force-expand)
"Update the node identified by its PATH.
Throws an error when the node cannot be found. Does nothing if the node is not
expanded, unless FORCE-EXPAND is non-nil, in which case the node will be
expanded.
Same as `treemacs-update-node', but does not take care to either save
position or assure hl-line highlighting, so it should be used when making
multiple updates.
PATH: Node Path
FORCE-EXPAND: Boolean"
(inline-letevals (path force-expand)
(inline-quote
(treemacs-without-recenter
(-if-let (btn (if ,force-expand
(treemacs-goto-node ,path)
(-some-> (treemacs-find-visible-node ,path)
(goto-char))))
(if (treemacs-is-node-expanded? btn)
(-let [close-func (alist-get (treemacs-button-get btn :state) treemacs-TAB-actions-config)]
(funcall close-func)
;; close node again if no new lines were rendered
(when (eq 1 (funcall (alist-get (treemacs-button-get btn :state) treemacs-TAB-actions-config)))
(funcall close-func)))
(when ,force-expand
(funcall (alist-get (treemacs-button-get btn :state) treemacs-TAB-actions-config))))
(-when-let (dom-node (treemacs-find-in-dom ,path))
(setf (treemacs-dom-node->refresh-flag dom-node) t)))))))
(defun treemacs-update-node (path &optional force-expand)
"Update the node identified by its PATH.
Same as `treemacs-do-update-node', but wraps the call in
`treemacs-save-position'.
PATH: Node Path
FORCE-EXPAND: Boolean"
(treemacs-save-position
(treemacs-do-update-node path force-expand)))
(defun treemacs-delete-single-node (path &optional project)
"Delete single node at given PATH and PROJECT.
Does nothing when the given node is not visible. Must be run in a treemacs
buffer.
This will also take care of all the necessary house-keeping like making sure
child nodes are deleted as well and everything is removed from the dom.
If multiple nodes are to be deleted it is more efficient to make multiple calls
to `treemacs-do-delete-single-node' wrapped in `treemacs-save-position' instead.
PATH: Node Path
Project: Project Struct"
(treemacs-save-position
(treemacs-do-delete-single-node path project)
(hl-line-highlight)))
(defun treemacs-do-delete-single-node (path &optional project)
"Actual implementation of single node deletion.
Will delete node at given PATH and PROJECT. See also
`treemacs-delete-single-node'.
PATH: Node Path
Project: Project Struct"
(-when-let (dom-node (treemacs-find-in-dom path))
(-let [btn (or (treemacs-dom-node->position dom-node)
(treemacs-goto-node path project :ignore-file-exists))]
(goto-char btn)
(when (treemacs-is-node-expanded? btn)
(treemacs-TAB-action :purge))
(treemacs-with-writable-buffer
(if (treemacs-button-get btn :collapsed)
(treemacs--delete-at-flattened-path btn path dom-node)
(treemacs--delete-line)
(treemacs-dom-node->remove-from-dom! dom-node))))))
(defun treemacs--delete-at-flattened-path (btn deleted-path dom-node)
"Handle a delete for a flattened path BTN for given DELETED-PATH.
Remove DOM-NODE from the dom if the entire line was deleted.
Btn: Button
DELETED-PATH: File Path
DOM-NODE: Dom Node"
(let* ((key (treemacs-button-get btn :key))
(coll-status (treemacs-button-get btn :collapsed))
(curr-collapse-steps (cdr coll-status)))
(if (string= deleted-path key)
(progn
;; remove full dom entry if entire line was deleted
(treemacs--delete-line)
(treemacs-dom-node->remove-from-dom! dom-node))
;; otherwise change the current line and update its properties
(let* ((path (treemacs-button-get btn :path))
(new-path (treemacs--parent deleted-path))
(delete-offset (- (length path) (length new-path)))
(new-label (substring new-path (length key)))
(old-coll-count (car coll-status))
(new-coll-count (length (treemacs-split-path new-label))))
(treemacs-button-put btn :path new-path)
(end-of-line)
;; delete just enough to get rid of the deleted dirs
(delete-region (- (point) delete-offset) (point))
;; then remove the deleted directories from the dom
(-let [removed-collapse-keys (last curr-collapse-steps (- old-coll-count new-coll-count))]
(treemacs-dom-node->remove-collapse-keys! dom-node removed-collapse-keys)
(-each removed-collapse-keys #'treemacs--stop-watching))
;; and update inline collpase info
(if (= 0 new-coll-count)
(treemacs-button-put btn :collapsed nil)
(treemacs-button-put
btn :collapsed
(cons new-coll-count (-take (1+ new-coll-count) curr-collapse-steps))))))))
(defun treemacs--determine-insert-position (path parent-btn sort-function)
"Determine the insert location for PATH under PARENT-BTN.
Specifically this will return the node *after* which to make the new insert.
Mostly this means the position before the first node for whose path returns
SORT-FUNCTION returns non-nil, but files and directories must be handled
properly,and edge cases for inserting at the end of the project and buffer must
be taken into account.
PATH: File Path
PARENT-BTN: Button
SORT-FUNCTION: Button -> Boolean."
(let* ((parent-dom-node (treemacs-find-in-dom (treemacs-button-get parent-btn :path)))
(children (treemacs-dom-node->children parent-dom-node))
(dirs-files (--separate (-let [path (treemacs-dom-node->key it)]
(and (stringp path) (file-directory-p path)))
children))
(dirs (sort (car dirs-files) (lambda (d1 d2)
(funcall sort-function
(treemacs-dom-node->key d1)
(treemacs-dom-node->key d2)))))
(files (sort (cadr dirs-files) (lambda (f1 f2)
(funcall sort-function
(treemacs-dom-node->key f1)
(treemacs-dom-node->key f2))))))
(if (file-directory-p path)
;; insert directory ...
(or
;; at first dir that fits sort order
(--when-let (--first (funcall sort-function path (treemacs-dom-node->key it)) dirs)
(previous-button (or (treemacs-dom-node->position it)
(treemacs-find-file-node (treemacs-dom-node->key it)))))
;; after last dir
(--when-let (-last-item dirs)
(or (treemacs-dom-node->position it)
(treemacs-find-file-node (treemacs-dom-node->key it))))
;; before first file
(--when-let (car files)
(previous-button (or (treemacs-dom-node->position it)
(treemacs-find-file-node (treemacs-dom-node->key it)))))
;; after parent
parent-btn)
;; insert file ...
(or
;; at first file that fits sort order
(--when-let (--first (funcall sort-function path (treemacs-dom-node->key it)) files)
(previous-button (or (treemacs-dom-node->position it)
(treemacs-find-file-node (treemacs-dom-node->key it)))) )
;; after last file
(--when-let (-last-item files)
(or (treemacs-dom-node->position it)
(treemacs-find-file-node (treemacs-dom-node->key it))) )
;; after last dir
(--when-let (-last-item dirs)
(or (treemacs-dom-node->position it)
(treemacs-find-file-node (treemacs-dom-node->key it))))
;; after parent
parent-btn))))
(defun treemacs-do-insert-single-node (path parent-path)
"Insert single file node at given PATH and below PARENT-PATH.
PATH: File Path
PARENT-PATH: File Path"
(-when-let (parent-dom-node (treemacs-find-in-dom parent-path))
(if (treemacs-find-in-dom path)
;; "creating" a file that is already present may happen due to an interaction in magit
;; in that case we need to checkthe file's git status
(treemacs-update-single-file-git-state path)
(let* ((parent-btn (treemacs-dom-node->position parent-dom-node))
(parent-flatten-info (treemacs-button-get parent-btn :collapsed)))
(treemacs-with-writable-buffer
(if parent-flatten-info
(treemacs--insert-node-in-flattened-directory
path parent-btn parent-dom-node parent-flatten-info)
(treemacs--insert-single-node
path parent-btn parent-dom-node)))))))
(defun treemacs--insert-single-node (created-path parent-btn parent-dom-node)
"Insert new CREATED-PATH below non-flattened directory at PARENT-BTN.
Will find the correct insert location, insert the necessary strings, and make
the necessary dom entries and adjust PARENT-DOM-NODE."
(let* ((sort-function (treemacs--get-sort-fuction))
(insert-after (treemacs--determine-insert-position created-path parent-btn sort-function)))
(goto-char insert-after)
(end-of-line)
(insert "\n" (treemacs--create-string-for-single-insert
created-path parent-btn (1+ (button-get parent-btn :depth))))
(-let [new-dom-node (treemacs-dom-node->create! :key created-path :parent parent-dom-node)]
(treemacs-dom-node->insert-into-dom! new-dom-node)
(treemacs-dom-node->add-child! parent-dom-node new-dom-node))
(when treemacs-git-mode
(treemacs-do-update-single-file-git-state created-path :exclude-parents :override-status))))
(defun treemacs--insert-node-in-flattened-directory (created-path parent-btn parent-dom-node flatten-info)
"Insert new CREATED-PATH below flattened directory at PARENT-BTN.
Will take care of every part necessary for adding a new node under a flattened
directory - adjusting the label, the state PARENT-DOM-NODE, the FLATTEN-INFO and
path text properties, the filewatch entries. It will also differentiate between
creating new files and new directories and re-open the node accordingly.
PATH: File Path
PARENT-BTN: Button
PARENT-DOM-NODE: Dom Node Struct
FLATTEN-INFO [Int File Path...]"
(treemacs-block
(let ((is-file? (file-regular-p created-path))
(insert-at-end? (treemacs-is-path created-path :in (-last-item flatten-info)))
(is-expanded? (treemacs-is-node-expanded? parent-btn)))
;; Simple addition of a file
(treemacs-return-if (and is-file? insert-at-end? is-expanded?)
(treemacs--insert-single-node created-path parent-btn parent-dom-node))
;; Simple file addition at the end, but the node is collapsed so we do nothing
(treemacs-return-if (and is-file? insert-at-end? (not is-expanded?))
t)
(let* ((properties (text-properties-at parent-btn))
(current-base-path (treemacs-button-get parent-btn :key))
;; In case we either add a new file or a directory somewhere in the middle of the flattened paths
;; we move the `created-path' up a step because that means we do not simple add another directory to
;; the flattened path. Instead we remove everything *up to* the directory the new item was created in.
;; Pretending the `created-path' has moved up like is an easy way to make sure the new button label
;; and properties are determined correctly.
(created-path (if (or is-file? (not insert-at-end?))
(treemacs--parent-dir created-path)
created-path))
(new-path-tokens (treemacs--tokenize-path created-path current-base-path))
(new-button-label (substring created-path (1+ (length (treemacs--parent-dir current-base-path)))))
;; TODO(2020/10/02): Check again when exactly this count is actually used
;; maybe it can be removed by now
(new-flatten-info-count 0)
(new-flatten-info (list current-base-path))
(new-flatten-info-item current-base-path))
;; Do nothing if we add a new directory and we have already reached maximum length
(unless (and insert-at-end?
(>= (car flatten-info) treemacs-collapse-dirs)
(not is-file?))
;; Create the path items of the new `:collapsed' property
(dolist (token new-path-tokens)
(cl-incf new-flatten-info-count)
(setf new-flatten-info-item (treemacs-join-path new-flatten-info-item token))
(push new-flatten-info-item new-flatten-info))
(setf new-flatten-info (nreverse new-flatten-info))
;; Take care of filewatch and dom entries for all paths added and removed
(let* ((old-flatten-paths (-difference (cdr flatten-info) new-flatten-info))
(new-flatten-paths (-difference new-flatten-info (cdr flatten-info))))
(dolist (old-flatten-path old-flatten-paths)
(treemacs--stop-watching old-flatten-path)
(ht-set! treemacs-dom old-flatten-path nil))
(dolist (new-flatten-path new-flatten-paths)
(treemacs--start-watching new-flatten-path :flatten)
(ht-set! treemacs-dom new-flatten-path parent-dom-node))
(setf (treemacs-dom-node->collapse-keys parent-dom-node) (copy-sequence (cdr new-flatten-info))))
;; Update text properties with new state
(setf new-flatten-info (when (> new-flatten-info-count 0)
(cons new-flatten-info-count new-flatten-info)))
(plist-put properties :collapsed new-flatten-info)
(plist-put properties :path created-path)
;; Insert new label
(goto-char parent-btn)
(delete-region (point) (line-end-position))
(insert (apply #'propertize new-button-label properties))
;; Fixing marker probably necessary since it's also in the dom
(goto-char (- (point) (length new-button-label)))
(set-marker parent-btn (point))
(if (and insert-at-end? is-file?)
;; TODO(2020/10/01): this reopening is used multiple tims like this
;; it should be abstracted properly
(funcall (alist-get (treemacs-button-get parent-btn :state) treemacs-TAB-actions-config))
(funcall (alist-get (treemacs-button-get parent-btn :state) treemacs-TAB-actions-config))
(setf (treemacs-dom-node->refresh-flag parent-dom-node) nil)))))))
(define-inline treemacs--create-string-for-single-insert (path parent depth)
"Create the necessary strings to insert a new file node.
Creates the required indent prefix and file icon based on the given file PATH,
PARENT node and node DEPTH.
PATH: File Path
PARENT: Button
DEPTH: Int"
(declare (side-effect-free t))
(inline-letevals (path depth parent)
(inline-quote
(let ((prefix (treemacs--get-indentation ,depth)))
(apply
#'concat
(let* ((strs)
(face))
(if (file-directory-p ,path)
(setf
strs (treemacs--create-dir-button-strings
,path prefix ,parent ,depth)
face 'treemacs-directory-face)
(setf strs (treemacs--create-file-button-strings
,path prefix ,parent ,depth)
face 'treemacs-file-face))
(-let [last (-last-item strs)]
(put-text-property 0 (length last) 'face face last))
strs))))) )
(defun treemacs--maybe-recenter (when &optional new-lines)
"Potentially recenter based on value of WHEN.
WHEN can take the following values:
* always: Recenter indiscriminately,
* on-distance: Recentering depends on the distance between `point' and the
window top/bottom being smaller than `treemacs-recenter-distance'.
* on-visibility: Special case for projects: recentering depends on whether the
newly rendered number of NEW-LINES fits the view."
(declare (indent 1))
(when (and (null treemacs--no-recenter)
(treemacs-is-treemacs-window? (selected-window)))
(let* ((current-line (float (treemacs--current-screen-line)))
(all-lines (float (treemacs--lines-in-window))))
(pcase when
('always (recenter))
('on-visibility
(-let [lines-left (- all-lines current-line)]
(when (> new-lines lines-left)
;; if possible recenter only as much as is needed to bring all new lines
;; into view
(recenter (max 0 (round (- current-line (- new-lines lines-left))))))))
('on-distance
(let* ((distance-from-top (/ current-line all-lines))
(distance-from-bottom (- 1.0 distance-from-top)))
(when (or (> treemacs-recenter-distance distance-from-top)
(> treemacs-recenter-distance distance-from-bottom))
(recenter))))))))
;; TODO(201/10/30): update of parents
(defun treemacs--recursive-refresh-descent (node project)
"Recursively refresh by descending the dom starting from NODE.
If NODE under PROJECT is marked for refresh and in an open state (since it could
have been collapsed in the meantime) it will simply be collapsed and
re-expanded. If NODE is node marked its children will be recursively
investigated instead.
Additionally all the refreshed nodes are collected and returned so their
parents' git status can be updated."
(let ((recurse t)
(refreshed-nodes nil))
(-when-let (change-list (treemacs-dom-node->refresh-flag node))
(setf (treemacs-dom-node->refresh-flag node) nil)
(push node refreshed-nodes)
(if (> (length change-list) 8)
(progn
(setf recurse nil)
(if (null (treemacs-dom-node->parent node))
(treemacs-project->refresh! project)
(treemacs--refresh-dir (treemacs-dom-node->key node) project)))
(dolist (change change-list)
(-let [(path . type) change]
(pcase type
('deleted
(treemacs-do-delete-single-node path project))
('changed
(treemacs-do-update-node path)
(treemacs-update-single-file-git-state path))
('created
(treemacs-do-insert-single-node path (treemacs-dom-node->key node)))
('force-refresh
(setf recurse nil)
(if (null (treemacs-dom-node->parent node))
(treemacs-project->refresh! project)
(treemacs--refresh-dir (treemacs-dom-node->key node) project)))
(_
;; Renaming is handled as a combination of delete+create, so
;; this case should never be taken
(treemacs-log-failure "Unknown change event: %s" change)
(setf recurse nil)
(if (null (treemacs-dom-node->parent node))
(treemacs-project->refresh! project)
(treemacs--refresh-dir (treemacs-dom-node->key node) project))))))))
(when recurse
(dolist (child (treemacs-dom-node->children node))
(setq refreshed-nodes
(nconc refreshed-nodes
(treemacs--recursive-refresh-descent child project)))))
;; TODO(2019/07/30): add as little as possible
refreshed-nodes))
(define-inline treemacs--should-reenter? (path)
"Check if PATH should not be reentered.
Returns nil if PATH is either not a file or it should be hidden on account of
`treemacs-show-hidden-files' being non-nil.
PATH: Node Path"
(declare (side-effect-free t))
(inline-letevals (path)
(inline-quote
(let ((path (cond
((stringp ,path)
,path)
;; tags should be reopened also
((and (consp ,path)
(stringp (car ,path)))
(car ,path)))))
(if path
(or treemacs-show-hidden-files
(not (s-matches? treemacs-dotfiles-regex
(treemacs--filename path))))
t)))))
(defun treemacs--reentry (path &optional git-future flatten-future)
"Reopen dirs below PATH.
GIT-FUTURE and FLATTEN-FUTURE are passed through from the previous branch build.
PATH: Node Path
GIT-INFO: Pfuture | Map<String, String>"
(-when-let* ((dom-node (treemacs-find-in-dom path))
(reopen-list (treemacs-dom-node->reentry-nodes dom-node)))
;; get rid of the reentry-remnant so it wont pollute the actual dom
(setf (treemacs-dom-node->reentry-nodes dom-node) nil)
(dolist (to-reopen-dom-node reopen-list)
;; the dom-node in the reentry-remnant and the one currently in the dom
;; are different, we need to make sure the latter is present, otherwise
;; the file has since been deleted
(let* ((reopen-path (treemacs-dom-node->key to-reopen-dom-node))
(actual-dom-node (treemacs-find-in-dom reopen-path)))
(when (and actual-dom-node
(treemacs--should-reenter? reopen-path))
;; move the next level of the reentry-remnant to the new reopened dom
;; so the process can continue
(setf (treemacs-dom-node->reentry-nodes actual-dom-node)
(treemacs-dom-node->reentry-nodes to-reopen-dom-node))
(treemacs--reopen-node
(treemacs-goto-node reopen-path)
git-future
flatten-future))))))
(defun treemacs--reopen-node (btn &optional git-future flatten-future)
"Reopen file BTN.
GIT-FUTURE and FLATTEN-FUTURE are passed through from the previous branch build."
(pcase (treemacs-button-get btn :state)
('dir-node-closed (treemacs--expand-dir-node
btn
:git-future git-future
:flatten-future flatten-future))
('file-node-closed (treemacs--expand-file-node btn))
('tag-node-closed (treemacs--expand-tag-node btn))
('root-node-closed (treemacs--expand-root-node btn))
(other (funcall (alist-get other treemacs-TAB-actions-config)))))
(defun treemacs--show-single-project (path name)
"Show only a project for the given PATH and NAME in the current workspace."
(let* ((ws (treemacs-current-workspace)))
(setf (treemacs-workspace->projects ws)
(list (treemacs-project->create!
:name name
:path path
:path-status (treemacs--get-path-status path))))
(--when-let (treemacs-get-local-buffer)
(with-current-buffer it
(treemacs--consolidate-projects)))
(-let [treemacs-select-when-already-in-treemacs 'stay]
(treemacs-select-window))
(goto-char (point-min))
(-if-let (btn (treemacs-current-button))
(unless (treemacs-is-node-expanded? btn)
(treemacs--expand-root-node btn)))
(treemacs--evade-image)))
(provide 'treemacs-rendering)
;;; treemacs-rendering.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-rendering.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 13,299 |
```emacs lisp
;;; treemacs.el --- A tree style file explorer package -*- lexical-binding: t -*-
;; Author: Alexander Miller <alexanderm@web.de>
;; Package-Requires: ((emacs "26.1") (cl-lib "0.5") (dash "2.11.0") (s "1.12.0") (ace-window "0.9.0") (pfuture "1.7") (hydra "0.13.2") (ht "2.2") (cfrs "1.3.2"))
;; Homepage: path_to_url
;; Version: 3.1
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; A powerful and flexible file tree project explorer.
;;; Code:
(require 'dash)
(require 'treemacs-macros)
(require 'treemacs-customization)
(require 'treemacs-logging)
(require 'treemacs-themes)
(require 'treemacs-icons)
(require 'treemacs-faces)
(require 'treemacs-visuals)
(require 'treemacs-rendering)
(require 'treemacs-core-utils)
(require 'treemacs-scope)
(require 'treemacs-follow-mode)
(require 'treemacs-filewatch-mode)
(require 'treemacs-mode)
(require 'treemacs-interface)
(require 'treemacs-persistence)
(require 'treemacs-async)
(require 'treemacs-compatibility)
(require 'treemacs-workspaces)
(require 'treemacs-fringe-indicator)
(require 'treemacs-header-line)
(require 'treemacs-annotations)
(defconst treemacs-version
(eval-when-compile
(format "v3.1 (installed %s) @ Emacs %s"
(format-time-string "%Y.%m.%d" (current-time))
emacs-version)))
(treemacs-import-functions-from "treemacs-tag-follow-mode"
treemacs--flatten&sort-imenu-index
treemacs--do-follow-tag)
;;;###autoload
(defun treemacs-version ()
"Return the `treemacs-version'."
(interactive)
(when (called-interactively-p 'interactive)
(treemacs-log "%s" treemacs-version))
treemacs-version)
;;;###autoload
(defun treemacs (&optional arg)
"Initialise or toggle treemacs.
- If the treemacs window is visible hide it.
- If a treemacs buffer exists, but is not visible show it.
- If no treemacs buffer exists for the current frame create and show it.
- If the workspace is empty additionally ask for the root path of the first
project to add.
- With a prefix ARG launch treemacs and force it to select a workspace"
(interactive "P")
(pcase (treemacs-current-visibility)
((guard arg)
(treemacs-do-switch-workspace (treemacs--select-workspace-by-name))
(treemacs-select-window))
('visible (delete-window (treemacs-get-local-window)))
('exists (treemacs-select-window))
('none (treemacs--init))))
;;;###autoload
(defun treemacs-select-directory ()
"Select a directory to open in treemacs.
This command will open *just* the selected directory in treemacs. If there are
other projects in the workspace they will be removed.
To *add* a project to the current workspace use
`treemacs-add-project-to-workspace' or
`treemacs-add-and-display-current-project' instead."
(interactive)
(treemacs-block
(let* ((path (-> "Directory: "
(read-directory-name)
(treemacs-canonical-path)))
(name (treemacs--filename path))
(ws (treemacs-current-workspace)))
(treemacs-return-if
(and (= 1 (length (treemacs-workspace->projects ws)))
(string= path (-> ws
(treemacs-workspace->projects)
(car)
(treemacs-project->path))))
(treemacs-select-window))
(treemacs--show-single-project path name)
(treemacs-pulse-on-success "Now showing %s"
(propertize path 'face 'font-lock-string-face)))))
;;;###autoload
(defun treemacs-find-file (&optional arg)
"Find and focus the current file in the treemacs window.
If the current buffer has visits no file or with a prefix ARG ask for the
file instead.
Will show/create a treemacs buffers if it is not visible/does not exist.
For the most part only useful when `treemacs-follow-mode' is not active."
(interactive "P")
(-let ((path (unless arg (buffer-file-name (current-buffer))))
(manually-entered nil))
(unless path
(setq manually-entered t
path (->> (--if-let (treemacs-current-button) (treemacs--nearest-path it))
(read-file-name "File to find: ")
(treemacs-canonical-path))))
(treemacs-unless-let (project (treemacs--find-project-for-path path))
(treemacs-pulse-on-failure (format "%s does not fall under any project in the workspace."
(propertize path 'face 'font-lock-string-face)))
(save-selected-window
(pcase (treemacs-current-visibility)
('visible (treemacs--select-visible-window))
('exists (treemacs--select-not-visible-window))
('none (treemacs--init)))
(treemacs-goto-file-node path project)
(when manually-entered (treemacs-pulse-on-success))))))
;;;###autoload
(defun treemacs-find-tag ()
"Find and move point to the tag at point in the treemacs view.
Most likely to be useful when `treemacs-tag-follow-mode' is not active.
Will ask to change the treemacs root if the file to find is not under the
root. If no treemacs buffer exists it will be created with the current file's
containing directory as root. Will do nothing if the current buffer is not
visiting a file or Emacs cannot find any tags for the current file."
(interactive)
(treemacs-block
(let* ((buffer (current-buffer))
(buffer-file (when buffer (buffer-file-name buffer)))
(project (treemacs--find-project-for-buffer))
(index (when buffer-file (treemacs--flatten&sort-imenu-index)))
(treemacs-window nil))
(treemacs-error-return-if (null buffer-file)
"Current buffer is not visiting a file.")
(treemacs-error-return-if (null index)
"Current buffer has no tags.")
(treemacs-error-return-if (eq index 'unsupported)
"Treemacs does not support following tags in this major mode.")
(treemacs-error-return-if (null project)
"%s does not fall under any project in the workspace."
(propertize buffer-file 'face 'font-lock-string-face))
(save-selected-window
(pcase (treemacs-current-visibility)
('visible (treemacs--select-visible-window))
('exists (treemacs--select-not-visible-window))
('none (treemacs--init)))
(setq treemacs-window (selected-window)))
(treemacs--do-follow-tag index treemacs-window buffer-file project))))
;;;###autoload
(defun treemacs-start-on-boot (&optional focus-treemacs)
"Initialiser specifically to start treemacs as part of your init file.
Ensures that all visual elements are present which might otherwise be missing
because their setup requires an interactive command or a post-command hook.
FOCUS-TREEMACS indicates whether the treemacs window should be selected."
(-let [initial-window (selected-window)]
(treemacs)
(hl-line-highlight)
(redisplay)
(unless focus-treemacs (select-window initial-window))))
;;;###autoload
(defun treemacs-select-window (&optional arg)
"Select the treemacs window if it is visible.
Bring it to the foreground if it is not visible.
Initialise a new treemacs buffer as calling `treemacs' would if there is no
treemacs buffer for this frame.
In case treemacs is already selected behaviour will depend on
`treemacs-select-when-already-in-treemacs'.
A non-nil prefix ARG will also force a workspace switch."
(interactive "P")
(pcase (treemacs-current-visibility)
((guard arg)
(treemacs-do-switch-workspace (treemacs--select-workspace-by-name))
(treemacs-select-window))
('exists (treemacs--select-not-visible-window))
('none (treemacs--init))
('visible
(if (not (eq treemacs--in-this-buffer t))
(treemacs--select-visible-window)
(pcase-exhaustive treemacs-select-when-already-in-treemacs
('stay
(ignore))
('close
(treemacs-quit))
('goto-next
(treemacs--jump-to-next-treemacs-window))
('next-or-back
(or
(treemacs--jump-to-next-treemacs-window)
(select-window (get-mru-window (selected-frame) nil :not-selected))))
('move-back
(select-window (get-mru-window (selected-frame) nil :not-selected))))))))
(setf treemacs-select-when-already-in-treemacs 'next-or-back)
;;;###autoload
(defun treemacs-show-changelog ()
"Show the changelog of treemacs."
(interactive)
(-> "Changelog.org"
(locate-file (list treemacs-dir))
(find-file-existing)))
;;;###autoload
(defun treemacs-edit-workspaces ()
"Edit your treemacs workspaces and projects as an `org-mode' file."
(interactive)
(require 'org)
(require 'outline)
(treemacs--persist)
(switch-to-buffer (get-buffer-create treemacs--org-edit-buffer-name))
(erase-buffer)
(org-mode)
(use-local-map (copy-keymap (with-no-warnings org-mode-map)))
(local-set-key (kbd "C-c C-c") #'treemacs-finish-edit)
(insert "#+TITLE: Edit Treemacs Workspaces & Projects\n")
(when treemacs-show-edit-workspace-help
(insert "# Call ~treemacs-finish-edit~ or press ~C-c C-c~ when done.\n")
(insert "# [[path_to_url#conveniently-editing-your-projects-and-workspaces][Click here for detailed documentation.]]\n")
(insert "# To cancel you can simply kill this buffer.\n\n"))
(insert-file-contents treemacs-persist-file)
(with-no-warnings
(outline-show-all))
(goto-char 0))
;;;###autoload
(defun treemacs-add-and-display-current-project-exclusively ()
"Display the current project, and *only* the current project.
Like `treemacs-add-and-display-current-project' this will add the current
project to treemacs based on either projectile, the built-in project.el, or the
current working directory.
However the \\='exclusive\\=' part means that it will make the current project
the only project, all other projects *will be removed* from the current
workspace."
(interactive)
(treemacs-block
(treemacs-unless-let (root (treemacs--find-current-user-project))
(treemacs-error-return-if (null root)
"Not in a project.")
(let* ((path (treemacs-canonical-path root))
(name (treemacs--filename path))
(ws (treemacs-current-workspace)))
(treemacs-return-if
(-let [projects (treemacs-workspace->projects ws)]
(and (= 1 (length projects))
(string=
path
(treemacs-project->path (car projects)))))
(treemacs-select-window))
(treemacs--show-single-project path name)
(treemacs-pulse-on-success "Now showing %s"
(propertize path 'face 'font-lock-string-face))))))
(define-obsolete-function-alias
'treemacs-display-current-project-exclusively
#'treemacs-add-and-display-current-project-exclusively
"v2.9")
;;;###autoload
(defun treemacs-add-and-display-current-project ()
"Open treemacs and add the current project root to the workspace.
The project is determined first by projectile (if treemacs-projectile is
installed), then by project.el, then by the current working directory.
If the project is already registered with treemacs just move point to its root.
An error message is displayed if the current buffer is not part of any project."
(interactive)
(treemacs-block
(treemacs-unless-let (root (treemacs--find-current-user-project))
(treemacs-error-return-if (null root)
"Not in a project.")
(let* ((path (treemacs-canonical-path root))
(name (treemacs--filename path)))
(unless (treemacs-current-workspace)
(treemacs--find-workspace))
(if (treemacs-workspace->is-empty?)
(progn
(treemacs-do-add-project-to-workspace path name)
(treemacs-select-window)
(treemacs-pulse-on-success))
(treemacs-select-window)
(if (treemacs-is-path path :in-workspace)
(treemacs-goto-file-node path)
(treemacs-add-project-to-workspace path name)))))))
(provide 'treemacs)
;;; treemacs.el ends here
``` | /content/code_sandbox/src/elisp/treemacs.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 2,952 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Everything related to file management.
;; NOTE: This module is lazy-loaded.
;;; Code:
(require 'dash)
(require 'hydra)
(require 'treemacs-core-utils)
(require 'treemacs-visuals)
(require 'treemacs-filewatch-mode)
(require 'treemacs-logging)
(require 'treemacs-rendering)
(require 'treemacs-annotations)
(require 'treemacs-async)
(eval-when-compile
(require 'inline)
(require 'treemacs-macros))
(declare-function string-join "subr-x.el")
(defconst treemacs--mark-annotation-source "treemacs-marked-paths")
(defvar-local treemacs--marked-paths nil)
(with-eval-after-load 'recentf
(declare-function recentf-remove-if-non-kept "recentf")
(declare-function treemacs--remove-from-recentf-after-move/rename "treemacs-file-management")
(defun treemacs--remove-from-recentf-after-move/rename (path _)
"Remove PATH from recentf after the file was moved or renamed."
(recentf-remove-if-non-kept path))
(add-hook 'treemacs-rename-file-functions #'treemacs--remove-from-recentf-after-move/rename)
(add-hook 'treemacs-move-file-functions #'treemacs--remove-from-recentf-after-move/rename)
(add-hook 'treemacs-delete-file-functions #'recentf-remove-if-non-kept))
(defconst treemacs--file-node-states
'(file-node-open file-node-closed dir-node-open dir-node-closed)
"List of node states treemacs is able to rename/delete etc.")
(define-inline treemacs--is-node-file-manageable? (btn)
"Determines whether BTN is a file node treemacs can rename/delete."
(declare (side-effect-free t))
(inline-letevals (btn)
(inline-quote
(memq (treemacs-button-get ,btn :state)
treemacs--file-node-states))))
;;;###autoload
(defun treemacs-delete-file (&optional arg)
"Delete node at point.
A delete action must always be confirmed. Directories are deleted recursively.
By default files are deleted by moving them to the trash. With a prefix ARG
they will instead be wiped irreversibly."
(interactive "P")
(treemacs-block
(treemacs-unless-let (btn (treemacs-current-button))
(treemacs-pulse-on-failure "Nothing to delete here.")
(treemacs-error-return-if (not (memq (treemacs-button-get btn :state)
'(file-node-open file-node-closed dir-node-open dir-node-closed)))
"Only files and directories can be deleted.")
(treemacs--without-filewatch
(let* ((delete-by-moving-to-trash (not arg))
(path (treemacs--select-file-from-btn btn "Delete: "))
(file-name (propertize (treemacs--filename path) 'face 'font-lock-string-face)))
(cond
((file-symlink-p path)
(if (yes-or-no-p (format "Remove link '%s -> %s' ? "
file-name
(propertize (file-symlink-p path) 'face 'font-lock-face)))
(delete-file path delete-by-moving-to-trash)
(treemacs-return (treemacs-log "Cancelled."))))
((file-regular-p path)
(if (yes-or-no-p (format "Delete '%s' ? " file-name))
(delete-file path delete-by-moving-to-trash)
(treemacs-return (treemacs-log "Cancelled."))))
((file-directory-p path)
(if (yes-or-no-p (format "Recursively delete '%s' ? " file-name))
(delete-directory path t delete-by-moving-to-trash)
(treemacs-return (treemacs-log "Cancelled."))))
(t
(treemacs-error-return
(treemacs-pulse-on-failure
"Item is neither a file, a link or a directory - treemacs does not know how to delete it. (Maybe it no longer exists?)"))))
(treemacs--on-file-deletion path)
(treemacs-without-messages
(treemacs-run-in-every-buffer
(treemacs-delete-single-node path)))
(run-hook-with-args 'treemacs-delete-file-functions path)
(treemacs-log "Deleted %s."
(propertize path 'face 'font-lock-string-face))))
(treemacs--evade-image))))
(defalias 'treemacs-delete #'treemacs-delete-file)
(make-obsolete #'treemacs-delete #'treemacs-delete-file "v2.9.3")
;;;###autoload
(defun treemacs-delete-marked-files (&optional arg)
"Delete all marked files.
A delete action must always be confirmed. Directories are deleted recursively.
By default files are deleted by moving them to the trash. With a prefix ARG
they will instead be wiped irreversibly.
For marking files see `treemacs-bulk-file-actions'."
(interactive "P")
(treemacs-block
(let ((delete-by-moving-to-trash (not arg))
(to-delete (-filter #'file-exists-p treemacs--marked-paths)))
(treemacs-error-return-if (null treemacs--marked-paths)
"There are no marked files")
(unless (yes-or-no-p (format "Really delete %s marked files?"
(length to-delete)))
(treemacs-return (treemacs-log "Cancelled.")))
(treemacs--without-filewatch
(dolist (path to-delete)
;; 2nd check in case of recursive deletes
(when (file-exists-p path)
(cond
((or (file-symlink-p path) (file-regular-p path))
(delete-file path delete-by-moving-to-trash))
((file-directory-p path)
(delete-directory path t delete-by-moving-to-trash))))
(treemacs--on-file-deletion path)
(treemacs-without-messages
(treemacs-run-in-every-buffer
(treemacs-delete-single-node path)))
(run-hook-with-args 'treemacs-delete-file-functions path))
(treemacs--evade-image)
(setf treemacs--marked-paths (-difference treemacs--marked-paths to-delete))
(treemacs-log "Deleted %s files." (length to-delete))))))
;;;###autoload
(defun treemacs-move-file ()
"Move file (or directory) at point.
If the selected target is an existing directory the source file will be directly
moved into this directory. If the given target instead does not exist then it
will be treated as the moved file's new name, meaning the original source file
will be both moved and renamed."
(interactive)
(treemacs--copy-or-move
:action 'move
:no-node-msg "There is nothing to move here."
:wrong-type-msg "Only files and directories can be moved."
:action-fn #'rename-file
:prompt "Move to: "
:flat-prompt "File to copy: "
:finish-verb "Moved"))
;;;###autoload
(defun treemacs-copy-file ()
"Copy file (or directory) at point.
If the selected target is an existing directory the source file will be directly
copied into this directory. If the given target instead does not exist then it
will be treated as the copied file's new name, meaning the original source file
will be both copied and renamed."
(interactive)
(treemacs--copy-or-move
:action 'copy
:no-node-msg "There is nothing to move here."
:wrong-type-msg "Only files and directories can be copied."
:action-fn (lambda (from to)
(if (file-directory-p from)
(copy-directory from to)
(copy-file from to)))
:prompt "Copy to: "
:flat-prompt "File to copy: "
:finish-verb "Copied"))
(cl-defun treemacs--copy-or-move
(&key
action
no-node-msg
wrong-type-msg
action-fn
prompt
flat-prompt
finish-verb)
"Internal implementation for copying and moving files.
ACTION: either `copy' or `move'
NO-NODE-MSG: error message in case there is no node in the current line
WRONG-TYPE-MSG: error message in case current node is not a file
ACTION-FN: function to actually copy or move a file
PROMPT: prompt to read the target directory
FLAT-PROMPT: prompt to select source file when node is flattened
FINISH-VERB: finisher for the success message."
(treemacs-block
(let ((btn (treemacs-current-button)))
(treemacs-error-return-if (null btn)
no-node-msg)
(treemacs-error-return-if
(not (memq (treemacs-button-get btn :state)
'(file-node-open file-node-closed dir-node-open dir-node-closed)))
wrong-type-msg)
(let* ((source (treemacs--select-file-from-btn btn flat-prompt))
(destination (treemacs--canonical-path
(read-directory-name prompt nil default-directory)))
(destination-dir (if (file-directory-p destination)
destination
(treemacs--parent-dir destination)))
(target-name (treemacs--filename
(if (file-directory-p destination)
source
destination)))
(target (->> target-name
(treemacs-join-path destination-dir)
(treemacs--find-repeated-file-name))))
(unless (file-exists-p destination-dir)
(make-directory destination-dir :parents))
(when (eq action 'move)
;; do the deletion *before* moving the file, otherwise it will
;; no longer exist and treemacs will not recognize it as a file path
(treemacs-do-delete-single-node source))
(treemacs--without-filewatch
(funcall action-fn source target))
(pcase action
('move
(run-hook-with-args 'treemacs-copy-file-functions source target)
(treemacs--on-file-deletion source))
('copy
(run-hook-with-args 'treemacs-move-file-functions source target)
(treemacs-remove-annotation-face source "treemacs-marked-paths")))
(treemacs-update-node destination-dir)
(when (treemacs-is-path target :in-workspace)
(treemacs-goto-file-node target))
(treemacs-pulse-on-success "%s %s to %s"
finish-verb
(propertize (treemacs--filename target) 'face 'font-lock-string-face)
(propertize destination-dir 'face 'font-lock-string-face))))))
;;;###autoload
(defun treemacs-move-marked-files ()
"Move all marked files.
For marking files see `treemacs-bulk-file-actions'."
(interactive)
(treemacs--bulk-copy-or-move
:action 'move
:action-fn #'rename-file
:prompt "Move to: "
:finish-verb "Moved"))
;;;###autoload
(defun treemacs-copy-marked-files ()
"Copy all marked files.
For marking files see `treemacs-bulk-file-actions'."
(interactive)
(treemacs--bulk-copy-or-move
:action 'copy
:action-fn (lambda (from to)
(if (file-directory-p from)
(copy-directory from to)
(copy-file from to)))
:prompt "Copy to: "
:finish-verb "Copied"))
(cl-defun treemacs--bulk-copy-or-move
(&key
action
action-fn
prompt
finish-verb)
"Internal implementation for bulk-copying and -moving files.
ACTION: either `copy' or `move'
ACTION-FN: function to actually copy or move a file
PROMPT: prompt to read the target directory
FINISH-VERB: finisher for the success message."
(treemacs-block
(let* ((to-move (-filter #'file-exists-p treemacs--marked-paths))
(destination-dir (treemacs--canonical-path
(read-directory-name prompt nil default-directory)))
(projects (->> to-move
(-map #'treemacs--find-project-for-path)
(cl-remove-duplicates)
(-filter #'identity))))
(treemacs-save-position
(dolist (source to-move)
(let ((target (->> source
(treemacs--filename)
(treemacs-join-path destination-dir)
(treemacs--find-repeated-file-name))))
(unless (string= source target)
(unless (file-exists-p destination-dir)
(make-directory destination-dir :parents))
(when (eq action 'move)
;; do the deletion *before* moving the file, otherwise it will
;; no longer exist and treemacs will not recognize it as a file path
(treemacs-do-delete-single-node source))
(treemacs--without-filewatch
(funcall action-fn source target))
(pcase action
('move
(run-hook-with-args 'treemacs-copy-file-functions source target)
(treemacs--on-file-deletion source))
('copy
(run-hook-with-args 'treemacs-move-file-functions source target)
(treemacs-remove-annotation-face source "treemacs-marked-paths"))))))
(dolist (project projects)
(treemacs-project->refresh! project)))
(when (treemacs-is-path destination-dir :in-workspace)
(treemacs-goto-file-node destination-dir))
(setf treemacs--marked-paths (-difference treemacs--marked-paths to-move))
(treemacs-pulse-on-success "%s %s files to %s"
finish-verb
(propertize (number-to-string (length to-move)) 'face 'font-lock-constant-face)
(propertize destination-dir 'face 'font-lock-string-face)))))
;;;###autoload
(cl-defun treemacs-rename-file ()
"Rename the file/directory at point.
Buffers visiting the renamed file or visiting a file inside the renamed
directory and windows showing them will be reloaded. The list of recent files
will likewise be updated."
(interactive)
(treemacs-block
(treemacs-unless-let (btn (treemacs-current-button))
(treemacs-pulse-on-failure "Nothing to rename here.")
(-let [old-path (treemacs--select-file-from-btn btn "Rename: ")]
(treemacs-error-return-if (null old-path)
"Found nothing to rename here.")
(treemacs-error-return-if (not (treemacs--is-node-file-manageable? btn))
"Only files and directories can be deleted.")
(treemacs-error-return-if (not (file-exists-p old-path))
"The file to be renamed does not exist.")
(let* ((old-name (treemacs--filename old-path))
(new-name (treemacs--read-string
"New name: " (file-name-nondirectory old-path)))
(dir (treemacs--parent-dir old-path))
(new-path (treemacs-join-path dir new-name))
(parent (treemacs-button-get btn :parent)))
(treemacs-error-return-if
(and (file-exists-p new-path)
(or (not (eq 'darwin system-type))
(not (string= old-name new-name))))
"A file named %s already exists."
(propertize new-name 'face font-lock-string-face))
(treemacs--without-filewatch
(rename-file old-path new-path)
(treemacs--replace-recentf-entry old-path new-path)
(-let [treemacs-silent-refresh t]
(treemacs-run-in-every-buffer
(treemacs--on-rename old-path new-path treemacs-filewatch-mode)
;; save-excursion does not work for whatever reason
(-let [p (point)]
(treemacs-do-update-node (treemacs-button-get parent :path))
(goto-char p)))))
(treemacs--reload-buffers-after-rename old-path new-path)
(run-hook-with-args
'treemacs-rename-file-functions
old-path new-path)
(treemacs-pulse-on-success "Renamed %s to %s."
(propertize (treemacs--filename old-path) 'face font-lock-string-face)
(propertize new-name 'face font-lock-string-face)))))))
(defalias 'treemacs-rename #'treemacs-rename-file)
(make-obsolete #'treemacs-rename #'treemacs-rename-file "v2.9.3")
;;; Bulk Actions
;;;###autoload
(defun treemacs-show-marked-files ()
"Print a list of all files marked by treemacs."
(interactive)
(let* ((len (length treemacs--marked-paths))
(message
(pcase len
(0 "There are currently no marked files.")
(1 (format "There is currently 1 marked file:\n%s"
(car treemacs--marked-paths)))
(_ (format "There are currently %s marked files:\n%s"
len
(string-join treemacs--marked-paths "\n"))))))
(treemacs-log message)))
;;;###autoload
(defun treemacs-mark-or-unmark-path-at-point ()
"Mark or unmark the absolute path of the node at point."
(interactive)
(treemacs-block
(-let [path (treemacs--prop-at-point :path)]
(treemacs-error-return-if (null path)
"There is nothing to mark here")
(treemacs-error-return-if
(or (not (stringp path)) (not (file-exists-p path)))
"Path at point is not a file or directory.")
(if (member path treemacs--marked-paths)
(progn
(setq treemacs--marked-paths
(remove path treemacs--marked-paths))
(treemacs-log "Unmarked path: %s" (propertize path 'face 'font-lock-string-face))
(treemacs-remove-annotation-face path "treemacs-marked-paths"))
(progn
(setq treemacs--marked-paths
(append treemacs--marked-paths (list path)))
(treemacs-log "Marked path: %s" (propertize path 'face 'font-lock-string-face))
(treemacs-set-annotation-face path 'treemacs-marked-file-face "treemacs-marked-paths")))
(treemacs-apply-annotations (treemacs--parent-dir path)))))
;;;###autoload
(defun treemacs-reset-marks ()
"Unmark all previously marked files in the current buffer."
(interactive)
(let ((count (length treemacs--marked-paths))
(projects))
(dolist (path treemacs--marked-paths)
(treemacs-remove-annotation-face path treemacs--mark-annotation-source)
(push (treemacs--find-project-for-path path) projects))
(setf treemacs--marked-paths nil)
(dolist (project (-uniq projects))
(treemacs-apply-annotations (treemacs-project->path project)))
(treemacs-pulse-on-success "Unmarked %s file(s)." count)))
;;;###autoload
(defun treemacs-delete-marked-paths ()
"Delete all previously marked files."
(interactive)
(treemacs-save-position
(when (yes-or-no-p
(format "Really delete %s marked file(s)?"
(length treemacs--marked-paths)))
(-let [count (length treemacs--marked-paths)]
(dolist (path treemacs--marked-paths)
(if (file-directory-p path)
(delete-directory path t)
(delete-file path))
(treemacs-do-delete-single-node path)
(treemacs-remove-annotation-face path treemacs--mark-annotation-source))
(setf treemacs--marked-paths nil)
(hl-line-highlight)
(treemacs-log "Deleted %s files." count)))))
;; shut down docstring width warnings
(with-no-warnings
(defhydra treemacs-bulk-file-actions-hydra (:exit t :hint nil)
("m" #'treemacs-mark-or-unmark-path-at-point "(un)mark")
("u" #'treemacs-reset-marks "unmark all")
("s" #'treemacs-show-marked-files "show")
("d" #'treemacs-delete-marked-files "delete")
("c" #'treemacs-copy-marked-files "copy")
("o" #'treemacs-move-marked-files "move")
("q" nil "cancel")))
;;;###autoload
(defun treemacs-bulk-file-actions ()
"Activate the bulk file actions hydra.
This interface allows to quickly (unmark) files, so as to copy, move or delete
them in bulk.
Note that marking files is *permanent*, files will stay marked until they are
either manually unmarked or deleted. You can show a list of all currently
marked files with `treemacs-show-marked-files' or `s' in the hydra."
(interactive)
(treemacs-bulk-file-actions-hydra/body))
;;;###autoload
(defun treemacs-create-file ()
"Create a new file.
Enter first the directory to create the new file in, then the new file's name.
The pre-selection for what directory to create in is based on the \"nearest\"
path to point - the containing directory for tags and files or the directory
itself, using $HOME when there is no path at or near point to grab."
(interactive)
(treemacs--create-file/dir t))
;;;###autoload
(defun treemacs-create-dir ()
"Create a new directory.
Enter first the directory to create the new dir in, then the new dir's name.
The pre-selection for what directory to create in is based on the \"nearest\"
path to point - the containing directory for tags and files or the directory
itself, using $HOME when there is no path at or near point to grab."
(interactive)
(treemacs--create-file/dir nil))
(defun treemacs--create-file/dir (is-file?)
"Interactively create either a file or directory, depending on IS-FILE.
IS-FILE?: Bool"
(interactive)
(let* ((curr-path (treemacs--select-file-from-btn
(treemacs-current-button)
"Create in: " :dir-only))
(path-to-create (treemacs-canonical-path
(read-file-name
(if is-file? "Create File: " "Create Directory: ")
(treemacs--add-trailing-slash
(if (file-directory-p curr-path)
curr-path
(treemacs--parent-dir curr-path)))))))
(treemacs-block
(treemacs-error-return-if (file-exists-p path-to-create)
"%s already exists." (propertize path-to-create 'face 'font-lock-string-face))
(treemacs--without-filewatch
(if is-file?
(-let [dir (treemacs--parent-dir path-to-create)]
(unless (file-exists-p dir)
(make-directory dir t))
(write-region "" nil path-to-create nil 0))
(make-directory path-to-create t))
(run-hook-with-args 'treemacs-create-file-functions path-to-create))
(-when-let (project (treemacs--find-project-for-path path-to-create))
(-when-let* ((created-under (treemacs--parent path-to-create))
(created-under-btn (treemacs-find-visible-node created-under)))
;; update only the part that changed to keep things smooth
;; for files that's just their parent, for directories we have to take
;; flattening into account
(-let [path-to-update
(if (treemacs-button-get created-under-btn :collapsed)
(treemacs-button-get (treemacs-button-get created-under-btn :parent) :path)
(treemacs-button-get created-under-btn :path))]
(treemacs-update-node path-to-update)
(when (treemacs--non-simple-git-mode-enabled)
(treemacs-update-single-file-git-state path-to-update))))
(treemacs-goto-file-node path-to-create project)
(recenter))
(treemacs-pulse-on-success
"Created %s." (propertize path-to-create 'face 'font-lock-string-face)))))
(defun treemacs--select-file-from-btn (btn prompt &optional dir-only)
"Select the file at BTN for file management.
Offer a specifying dialogue with PROMPT when the button is flattened.
Pick only directories when DIR-ONLY is non-nil."
(declare (side-effect-free t))
(let* ((path (and btn (treemacs-button-get btn :path)))
(collapse-info (and btn (treemacs-button-get btn :collapsed)))
(is-str (and path (stringp path)))
(is-dir (and is-str (file-directory-p path)))
(is-file (and is-str (file-regular-p path))))
(cond
(collapse-info
(completing-read prompt collapse-info nil :require-match))
(is-dir
path)
((and is-file dir-only)
(treemacs--parent-dir path))
(is-file
path)
(t
(expand-file-name "~")))))
(provide 'treemacs-file-management)
;;; treemacs-file-management.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-file-management.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 5,633 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Module that handles uniquely associating treemacs buffers with a
;; certain scope, like the selected frame, or (to be implemented
;; later) the active eyebrowse or persp desktop.
;; This is implemented using a (somewhat) OOP style with eieio and
;; static functions, where each scope type is expected to know how to
;; query the current scope (e.g. the selected frame) and how to set up
;; and tear down itself (e.g. deleting a frames associated buffer when
;; the frame is deleted)
;;; Code:
(require 'dash)
(require 'eieio)
(require 'treemacs-core-utils)
(require 's)
(require 'inline)
(eval-when-compile
(require 'treemacs-macros)
(require 'cl-lib))
(eval-when-compile
(cl-declaim (optimize (speed 3) (safety 0))))
(treemacs-import-functions-from "treemacs-filewatch-mode"
treemacs--stop-filewatch-for-current-buffer)
(treemacs-import-functions-from "treemacs-interface"
treemacs-quit
treemacs-select-window)
(treemacs-import-functions-from "treemacs-workspaces"
treemacs--find-workspace)
(cl-defstruct (treemacs-scope-shelf
(:conc-name treemacs-scope-shelf->)
(:constructor treemacs-scope-shelf->create!))
buffer
workspace)
(defvar treemacs-scope-types (list (cons 'Frames 'treemacs-frame-scope))
"List of all known scope types.
The car is the name seen in interactive selection. The cdr is the eieio class
name.")
(defvar treemacs--current-scope-type 'treemacs-frame-scope
"The general type of objects/items treemacs is currently scoped to.")
(defvar treemacs--scope-storage nil
"Alist of all active scopes mapped to their buffers & workspaces.
The car is the scope, the cdr is a `treemacs-scope-shelf'.")
(define-inline treemacs-scope-shelf->kill-buffer (self)
"Kill the buffer stored in SELF."
(inline-letevals (self)
(inline-quote
(progn
(let ((buffer (treemacs-scope-shelf->buffer ,self)))
(when (buffer-live-p buffer) (kill-buffer buffer)))
(setf (treemacs-scope-shelf->buffer ,self) nil)))))
(define-inline treemacs--scope-store ()
"Return `treemacs--scope-storage'."
(inline-quote treemacs--scope-storage))
(define-inline treemacs-current-scope-type ()
"Return the current scope type."
(declare (side-effect-free t))
(inline-quote treemacs--current-scope-type))
(define-inline treemacs-current-scope ()
"Return the current scope."
(declare (side-effect-free t))
(inline-quote
(treemacs-scope->current-scope (treemacs-current-scope-type))))
(define-inline treemacs-current-scope-shelf (&optional scope)
"Return the current scope shelf, containing the active workspace and buffer.
Use either the given SCOPE or `treemacs-current-scope' otherwise.
Can be used with `setf'."
(declare (side-effect-free t))
(inline-letevals (scope)
(inline-quote
(cdr (assoc (or ,scope (treemacs-current-scope)) treemacs--scope-storage)))))
(gv-define-setter treemacs-current-scope-shelf (val)
`(let* ((current-scope (treemacs-current-scope))
(shelf-mapping (assoc current-scope treemacs--scope-storage)))
(if (cdr shelf-mapping)
(setf (cdr shelf-mapping) ,val)
(push (cons current-scope ,val) treemacs--scope-storage))))
(defclass treemacs-scope () () :abstract t)
(cl-defmethod treemacs-scope->current-scope ((_ (subclass treemacs-scope)))
"Get the current scope."
(error "Default `current-scope' implementation was called"))
(cl-defmethod treemacs-scope->current-scope-name ((_ (subclass treemacs-scope)) scope)
"Get the name of the given SCOPE."
(ignore scope)
nil)
(cl-defmethod treemacs-scope->setup ((_ (subclass treemacs-scope)))
"Setup for a scope type."
nil)
(cl-defmethod treemacs-scope->cleanup ((_ (subclass treemacs-scope)))
"Tear-down for a scope type."
nil)
(defclass treemacs-frame-scope (treemacs-scope) () :abstract t)
(cl-defmethod treemacs-scope->current-scope ((_ (subclass treemacs-frame-scope)))
"Get the current scope."
(selected-frame))
(cl-defmethod treemacs-scope->current-scope-name ((_ (subclass treemacs-frame-scope)) frame)
"Prints the given FRAME."
(prin1-to-string frame))
(cl-defmethod treemacs-scope->setup ((_ (subclass treemacs-frame-scope)))
"Frame-scope setup."
(add-hook 'delete-frame-functions #'treemacs--on-scope-kill))
(cl-defmethod treemacs-scope->cleanup ((_ (subclass treemacs-frame-scope)))
"Frame-scope tear-down."
(remove-hook 'delete-frame-functions #'treemacs--on-scope-kill))
(defun treemacs-set-scope-type (new-scope-type)
"Set a NEW-SCOPE-TYPE for treemacs buffers.
Valid values for TYPE are the `car's of the elements of `treemacs-scope-types'.
This is meant for programmatic use. For an interactive selection see
`treemacs-select-buffer-scope-type'."
(-let [class (alist-get new-scope-type treemacs-scope-types)]
(unless class (user-error "'%s' is not a valid scope new-scope-type. Valid types are: %s"
new-scope-type
(-map #'car treemacs-scope-types)))
(treemacs--do-set-scope-type class)))
(defun treemacs--do-set-scope-type (new-scope-type)
"Set NEW-SCOPE-TYPE as the scope managing class.
Kill all treemacs buffers and windows and reset the buffer store.
NEW-SCOPE-TYPE: T: treemacs-scope"
(treemacs-scope->cleanup treemacs--current-scope-type)
(setf treemacs--current-scope-type new-scope-type)
(dolist (frame (frame-list))
(dolist (window (window-list frame))
(when (treemacs-is-treemacs-window? window)
(delete-window window))))
(dolist (it treemacs--scope-storage)
(treemacs-scope-shelf->kill-buffer (cdr it)))
(setf treemacs--scope-storage nil)
(treemacs-scope->setup new-scope-type))
(defun treemacs--on-buffer-kill ()
"Cleanup to run when a treemacs buffer is killed."
(when (eq t treemacs--in-this-buffer)
;; stop watch must come first since we need a reference to the killed buffer
;; to remove it from the filewatch list
(treemacs--stop-filewatch-for-current-buffer)
;; not present for extension buffers
(-when-let (shelf (treemacs-current-scope-shelf))
(setf (treemacs-scope-shelf->buffer shelf) nil))))
(defun treemacs--on-scope-kill (scope)
"Kill and remove the buffer assigned to the given SCOPE."
(-when-let (shelf (treemacs-current-scope-shelf scope))
(treemacs-scope-shelf->kill-buffer shelf)
(setf treemacs--scope-storage (--reject-first (equal (car it) scope) treemacs--scope-storage))))
(defun treemacs--create-buffer-for-scope (scope)
"Create and store a new buffer for the given SCOPE."
(-let [shelf (treemacs-current-scope-shelf scope)]
(unless shelf
(setf shelf (treemacs-scope-shelf->create!))
(push (cons scope shelf) treemacs--scope-storage)
(treemacs--find-workspace (buffer-file-name)))
(treemacs-scope-shelf->kill-buffer shelf)
(let* ((name-suffix (or (treemacs-scope->current-scope-name treemacs--current-scope-type scope)
(prin1-to-string scope)))
(name (format "%sScoped-Buffer-%s*" treemacs--buffer-name-prefix name-suffix))
(buffer (get-buffer-create name)))
(setf (treemacs-scope-shelf->buffer shelf) buffer)
buffer)))
(defun treemacs--change-buffer-on-scope-change (&rest _)
"Switch the treemacs buffer after the current scope was changed."
(--when-let (treemacs-get-local-window)
(save-selected-window
(with-selected-window it
(treemacs-quit))
(treemacs-select-window))))
(defun treemacs--select-visible-window ()
"Switch to treemacs buffer, given that it is currently visible."
(-some->> treemacs--scope-storage
(assoc (treemacs-scope->current-scope treemacs--current-scope-type))
(cdr)
(treemacs-scope-shelf->buffer)
(get-buffer-window)
(select-window))
(run-hook-with-args 'treemacs-select-functions 'visible))
(defun treemacs-get-local-buffer ()
"Return the treemacs buffer local to the current scope-type.
Returns nil if no such buffer exists.."
(declare (side-effect-free t))
(let* ((scope (treemacs-scope->current-scope treemacs--current-scope-type))
(buffer (-some->> treemacs--scope-storage
(assoc scope)
(cdr)
(treemacs-scope-shelf->buffer))))
(and (buffer-live-p buffer) buffer)))
(defun treemacs-get-local-buffer-create ()
"Get the buffer for the current scope, creating a new one if needed."
(or (treemacs-get-local-buffer)
(treemacs--create-buffer-for-scope (treemacs-scope->current-scope treemacs--current-scope-type))))
(defun treemacs-get-local-window ()
"Return the window displaying the treemacs buffer in the current frame.
Returns nil if no treemacs buffer is visible."
(declare (side-effect-free error-free))
(->> (window-list (selected-frame))
(--first (->> it
(window-buffer)
(buffer-name)
(s-starts-with? treemacs--buffer-name-prefix)))))
(define-inline treemacs-current-visibility ()
"Return whether the current visibility state of the treemacs buffer.
Valid states are \\='visible, \\='exists and \\='none."
(declare (side-effect-free t))
(inline-quote
(cond
((treemacs-get-local-window) 'visible)
((treemacs-get-local-buffer) 'exists)
(t 'none))))
(treemacs-only-during-init
(setf treemacs--current-scope-type 'treemacs-frame-scope)
(treemacs-scope->setup 'treemacs-frame-scope))
(provide 'treemacs-scope)
;;; treemacs-scope.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-scope.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 2,518 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Basically this: path_to_url
;;; Code:
(require 'ht)
(require 'dash)
(require 's)
(eval-when-compile
(require 'cl-lib)
(require 'inline)
(require 'treemacs-macros))
(eval-when-compile
(cl-declaim (optimize (speed 3) (safety 0))))
(defvar-local treemacs-dom nil)
(cl-defstruct (treemacs-dom-node
(:conc-name treemacs-dom-node->)
(:constructor treemacs-dom-node->create!))
key
parent
children
reentry-nodes
position
refresh-flag
collapse-keys)
;; needed because simple declare-function for pos slot in core-utils wont properly expand via setf
(define-inline treemacs-dom-node->set-position! (self value)
"Set `position' field of SELF to VALUE.
SELF: Dom Node Struct
VALUE: Marker"
(inline-letevals (self value)
(inline-quote
(setf (treemacs-dom-node->position ,self) ,value))))
(defun treemacs--reset-dom ()
"Reset the dom."
(setf treemacs-dom (make-hash-table :size 1000 :test 'equal)))
(define-inline treemacs-find-in-dom (key)
"Get node with KEY, if any.
KEY: Node Path"
(declare (side-effect-free t))
(inline-letevals (key)
(inline-quote
(ht-get treemacs-dom ,key))))
(define-inline treemacs-dom-node->insert-into-dom! (self)
"Insert SELF into the dom.
SELF: Dom Node Struct"
(inline-letevals (self)
(inline-quote
(ht-set! treemacs-dom (treemacs-dom-node->key ,self) ,self))))
(define-inline treemacs-dom-node->add-child! (self child)
"Add CHILD to to the children of SELF."
(inline-letevals (self child)
(inline-quote
(setf (treemacs-dom-node->children ,self)
(cons ,child (treemacs-dom-node->children ,self))))))
(define-inline treemacs-dom-node->remove-from-dom! (self)
"Remove SELF from the dom.
SELF: Dom Node Struct"
(inline-letevals (self)
(inline-quote
(progn
(ht-remove! treemacs-dom (treemacs-dom-node->key ,self))
(let ((parent (treemacs-dom-node->parent ,self)))
(setf (treemacs-dom-node->children parent)
(delete ,self (treemacs-dom-node->children parent))))
(dolist (key (treemacs-dom-node->collapse-keys ,self))
(ht-remove! treemacs-dom key))))))
(define-inline treemacs-dom-node->remove-collapse-keys! (self keys)
"Remove the given collapse KEYS from both SELF and the dom."
(inline-letevals (self keys)
(inline-quote
(progn
(dolist (key ,keys)
(ht-remove! treemacs-dom key))
(setf (treemacs-dom-node->collapse-keys ,self)
(--reject (member it ,keys) (treemacs-dom-node->collapse-keys ,self)))))))
(define-inline treemacs-dom-node->all-parents (self)
"Get all parent nodes of SELF.
List will be sorted top to bottom.
SELF: Dom Node Struct"
(declare (side-effect-free t))
(inline-letevals (self)
(inline-quote
(let ((parent (treemacs-dom-node->parent ,self))
(ret))
(while parent
(push parent ret)
(setf parent (treemacs-dom-node->parent parent)))
ret))))
(define-inline treemacs-on-expand (key pos)
"Re-arrange the dom when node at KEY with POS is expanded.
KEY: Node Path
POS: Marker"
(inline-letevals (key pos)
(inline-quote
(-if-let (dom-node (treemacs-find-in-dom ,key))
(progn
(setf (treemacs-dom-node->position dom-node) ,pos)
(dolist (collapse-key (treemacs-dom-node->collapse-keys dom-node))
(setf (treemacs-dom-node->position (treemacs-find-in-dom collapse-key)) ,pos))
(-when-let (parent-dom-node (treemacs-dom-node->parent dom-node))
(setf (treemacs-dom-node->reentry-nodes parent-dom-node)
(cons dom-node (treemacs-dom-node->reentry-nodes parent-dom-node)))))
;; expansion of root
(setf dom-node (treemacs-dom-node->create! :key ,key :position ,pos))
(treemacs-dom-node->insert-into-dom! dom-node)))))
(define-inline treemacs-on-collapse (key &optional purge)
"Re-arrange the dom when node at KEY was collapsed.
Will remove NODE's parent/child link and invalidate the position and refresh
data of NODE and all its children. When PURGE is non-nil will instead remove
NODE and its children from the dom.
KEY: Node Path
Purge: Boolean"
(inline-letevals (key purge)
(inline-quote
(let* ((dom-node (treemacs-find-in-dom ,key))
(children (treemacs-dom-node->children dom-node)))
(-when-let (parent-dom-node (treemacs-dom-node->parent dom-node))
(setf (treemacs-dom-node->reentry-nodes parent-dom-node)
(delete dom-node (treemacs-dom-node->reentry-nodes parent-dom-node))))
(cond
(,purge
(treemacs--on-purged-collapse dom-node))
(children
(treemacs--on-collapse-of-node-with-children dom-node))
(t
(treemacs--on-collapse-of-node-without-children dom-node)))))))
(define-inline treemacs--on-purged-collapse (dom-node)
"Run when a DOM-NODE is collapsed with a purge (prefix) argument.
Will remove all the children of DOM-NODE from the dom.
DOM-NODE: Dom Node Struct"
(inline-letevals (dom-node)
(inline-quote
(progn
(treemacs-walk-dom-exclusive ,dom-node
(lambda (it) (treemacs-dom-node->remove-from-dom! it)))
(setf (treemacs-dom-node->children ,dom-node) nil
(treemacs-dom-node->reentry-nodes ,dom-node) nil)))))
(define-inline treemacs--on-collapse-of-node-without-children (dom-node)
"Run when a DOM-NODE without any children is collapsed.
Will remove DOm-NODE from its parent's reentry list.
DOM-NODE: Dom Node Struct"
(inline-letevals (dom-node)
(inline-quote
(let ((parent-dom-node (treemacs-dom-node->parent ,dom-node)))
(when parent-dom-node
(setf (treemacs-dom-node->reentry-nodes parent-dom-node)
(delete ,dom-node (treemacs-dom-node->reentry-nodes parent-dom-node))))))))
(define-inline treemacs--on-collapse-of-node-with-children (dom-node)
"Run when a DOM-NODE with children is collapsed.
Will remove all entries below the one collapsed from the dom.
DOM-NODE: Dom Node Struct"
(inline-letevals (dom-node)
(inline-quote
(progn
(treemacs-walk-dom-exclusive ,dom-node
(lambda (it)
(treemacs-dom-node->remove-from-dom! it)
(setf (treemacs-dom-node->children it) nil)))
(setf (treemacs-dom-node->children ,dom-node) nil)))))
(defun treemacs--on-rename (old-name new-name dont-rename-initial)
"Renames dom entries after a file was renamed from OLD-NAME to NEW-NAME.
Renames the initial dom entry (the one backing the file that was actually
renamed) only if DONT-RENAME-INITIAL is nil in case the entry is required for
filewatch-mode to work.
OLD-NAME: File Path | Tag Path
NEW-NAME: File Path | Tag Path
DONT-RENAME-INITIAL: Boolean"
(-when-let (dom-node (treemacs-find-in-dom old-name))
(-let [migrate-keys
(lambda (it)
(let* ((old-key (treemacs-dom-node->key it))
(new-key (cond
((stringp old-key)
(s-replace old-name new-name old-key))
((and (consp old-key) (stringp (car old-key)))
(cons (s-replace old-name new-name (car old-key)) (cdr old-key))))))
(when new-key
(ht-remove! treemacs-dom old-key)
(ht-set! treemacs-dom new-key it)
(setf (treemacs-dom-node->key it) new-key))))]
;; when filewatch is enabled the acutally renamed file needs to keep
;; its dom entry until refresh actually runs so it can be deleted properly
(if dont-rename-initial
(progn
(treemacs-walk-reentry-dom-exclusive dom-node migrate-keys)
(treemacs-walk-dom-exclusive dom-node migrate-keys))
(treemacs-walk-dom dom-node migrate-keys)
(treemacs-walk-reentry-dom dom-node migrate-keys)))))
(defun treemacs-walk-dom (node fn)
"Recursively walk the dom starting at NODE.
Calls FN on every node encountered in a depth-first pattern, starting with the
deepest. This assures that FN may destructively modify the dom, at least on
levels the one currently visiting.
NODE: Dom Node Struct
FN: (Dom Node) -> Any"
(declare (indent 1))
(-let [children (treemacs-dom-node->children node)]
(funcall fn node)
(dolist (it children)
(treemacs-walk-dom it fn))))
(defun treemacs-walk-dom-exclusive (node fn)
"Same as `treemacs-walk-dom', but start NODE will not be passed to FN.
NODE: Dom Node Struct
FN: (Dom Node) -> Any"
(declare (indent 1))
(dolist (it (treemacs-dom-node->children node))
(treemacs-walk-dom it fn)))
(defun treemacs-walk-reentry-dom (node fn)
"Recursively walk the dom starting at NODE.
Unlike `treemacs-walk-dom' only expanded nodes are selected.
Calls FN on every node encountered in a depth-first pattern, starting with the
deepest. This assures that FN may destructively modify the dom, at least on
levels the one currently visiting.
NODE: Dom Node Struct
FN: (Dom Node) -> Any"
(declare (indent 1))
(funcall fn node)
(dolist (it (treemacs-dom-node->reentry-nodes node))
(treemacs-walk-reentry-dom it fn)))
(defun treemacs-walk-reentry-dom-exclusive (node fn)
"Same as `treemacs-walk-reentry-dom', but start NODE will not be passed to FN.
NODE: Dom Node Struct
FN: (Dom Node) -> Any"
(declare (indent 1))
(dolist (it (treemacs-dom-node->reentry-nodes node))
(treemacs-walk-reentry-dom it fn)))
(provide 'treemacs-dom)
;;; treemacs-dom.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-dom.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 2,596 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Minor mode to follow the tag at point in the treemacs view on an idle timer
;; Finding the current tag is a fairly involved process:
;; * Grab current buffer's imenu output
;; * Flatten the list to create full tag paths
;; * Sort according to tag position
;; * Beware of edge cases: org-mode headlines are containers, but also hold a position, hidden as a text property and
;; semantic-mode parsed buffers use overlays instead of markers
;; * Find the last tag whose position begins before point
;; * Jump to that tag path
;; * No jump when there's no buffer file, or no imenu, or buffer file is not seen in treemacs etc.
;; NOTE: This module is lazy-loaded.
;;; Code:
(require 'imenu)
(require 'hl-line)
(require 'treemacs-customization)
(require 'treemacs-core-utils)
(require 'treemacs-tags)
(require 'treemacs-scope)
(require 'treemacs-follow-mode)
(require 'treemacs-logging)
(eval-when-compile
(require 'inline)
(require 'cl-lib)
(require 'treemacs-macros))
(defvar treemacs--tag-follow-timer nil
"The idle timer object for `treemacs-tag-follow-mode'.
Active while tag follow mode is enabled and nil/cancelled otherwise.")
(defvar-local treemacs--previously-followed-tag-position nil
"Records the last node and path whose tags were expanded by tag follow mode.
Is made up of a cons of the last expanded node and its path. Both are kept to
make sure that the position has not become invalidated in the meantime.
When `treemacs-tag-follow-cleanup' it t this button's tags will be closed up
again when tag follow mode moves to another button.")
(defvar-local treemacs--imenu-cache nil
"Cache for the current buffer's flattened and sorted imenu index.
Is reset in `first-change-hook' will only be set again after the buffer has been
saved.")
(define-inline treemacs--reset-imenu-cache ()
"Reset `treemacs--imenu-cache'."
(inline-quote (setq-local treemacs--imenu-cache nil)))
(define-inline treemacs--forget-previously-follow-tag-btn ()
"Forget the previously followed button when treemacs is killed or rebuilt."
(inline-quote (setq treemacs--previously-followed-tag-position nil)))
;;;###autoload
(defun treemacs--flatten&sort-imenu-index ()
"Flatten current file's imenu index and sort it by tag position.
The tags are sorted into the order in which they appear, regardless of section
or nesting depth."
(if (eq major-mode 'pdf-view-mode)
'unsupported
(let* ((imenu-auto-rescan t)
(org? (eq major-mode 'org-mode))
(index (-> (buffer-file-name) (treemacs--get-imenu-index)))
(flat-index (if org?
(treemacs--flatten-org-mode-imenu-index index)
(treemacs--flatten-imenu-index index)))
(first (caar flat-index))
;; in org mode buffers the first item may not be a cons since its position
;; is still stored as a text property
(semantic? (and (consp first) (overlayp (cdr first))))
(compare-func (if (memq major-mode '(markdown-mode adoc-mode))
#'treemacs--compare-markdown-tag-paths
#'treemacs--compare-tag-paths)))
(cond
(semantic?
;; go ahead and just transform semantic overlays into markers so we dont
;; have trouble with comparisons when searching a position
(dolist (tag-path flat-index)
(let ((leaf (car tag-path))
(marker (make-marker)))
(setcdr leaf (move-marker marker (overlay-start (cdr leaf)))))))
;; same goes for an org index, since headlines with children store their
;; positions as text properties
(org?
(dolist (tag-path flat-index)
(let ((leaf (car tag-path)))
(when (stringp leaf)
(setcar tag-path (cons leaf (get-text-property 0 'org-imenu-marker leaf))))))))
(sort flat-index compare-func))))
(defun treemacs--flatten-imenu-index (index &optional path)
"Flatten a nested imenu INDEX to a flat list of tag paths.
The function works recursively with PATH being the already collected tag path in
each iteration.
INDEX: Imenu Tag Index
PATH: String List"
(declare (pure t) (side-effect-free t))
(let (result)
(--each index
(cond
((imenu--subalist-p it)
(setq result
(append result (treemacs--flatten-imenu-index (cdr it) (cons (car it) path)))))
;; make sure our leaf elements have a cdr where a location should be stored, it looks like there are cases,
;; at least on emacs 25, where we only get what amounts to an empty section
;; path_to_url#issuecomment-427281977
((and (consp it) (cdr it))
(setq result (cons (cons it (nreverse (copy-sequence path))) result)))))
result))
(defun treemacs--flatten-org-mode-imenu-index (index &optional path)
"Specialisation of `treemacs--flatten-imenu-index' for org mode.
An index produced in an `org-mode' buffer is special in that tag sections act
not just as a means of grouping tags (being bags of functions, classes etc).
Each tag section is instead also a headline which can be moved to. The
flattening algorithm must therefore be slightly adjusted.
INDEX: Org Imenu Tag Index
PATH: String List"
(declare (pure t) (side-effect-free t))
(let (result)
(--each index
(let ((is-subalist? (imenu--subalist-p it)))
(setq result (cons (cons (if is-subalist? (car it) it) (nreverse (copy-sequence path))) result))
(when is-subalist?
(setq result (append result (treemacs--flatten-org-mode-imenu-index (cdr it) (cons (car it) path)))))))
result))
(define-inline treemacs--compare-tag-paths (p1 p2)
"Compare two tag paths P1 & P2 by the position of the tags they lead to.
Used to sort tag paths according to the order their tags appear in.
P1: Tag-Path
P2: Tag-Path"
(declare (pure t) (side-effect-free t))
(inline-letevals (p1 p2)
(inline-quote
(< (-> ,p1 (cdar) (marker-position))
(-> ,p2 (cdar) (marker-position))))))
(define-inline treemacs--compare-markdown-tag-paths (p1 p2)
"Specialised version of `treemacs--compare-tag-paths' for markdown and adoc.
P1: Tag-Path
P2: Tag-Path"
(declare (pure t) (side-effect-free t))
(inline-letevals (p1 p2)
(inline-quote
(< (cdar ,p1) (cdar ,p2)))))
(defun treemacs--find-index-pos (point list)
"Find the tag at POINT within a flat tag-path LIST.
Returns the tag-path whose tag is the last to be situated before POINT (meaning
that the next tag is after POINT and thus too far). Accounts for POINT being
located either before the first or after the last tag.
POINT: Int
LIST: Sorted Tag Path List"
(declare (pure t) (side-effect-free t))
(when list
(let ((first (car list))
(last (nth (1- (length list)) list)))
(cond
((<= point (-> first car cdr))
first)
((>= point (-> last car cdr))
last)
(t (treemacs--binary-index-search point list))))))
(cl-defun treemacs--binary-index-search (point list &optional (start 0) (end (1- (length list))))
"Find the position of POINT in LIST using a binary search.
Continuation of `treemacs--find-index-pos'. Search LIST between START & END.
POINT: Integer
LIST: Sorted Tag Path List
START: Integer
END: Integer"
(declare (pure t) (side-effect-free t))
(let* ((index (+ start (/ (- end start) 2)))
(elem1 (nth index list))
(elem2 (nth (1+ index) list))
(pos1 (-> elem1 car cdr))
(pos2 (-> elem2 car cdr)))
(cond
((and (> point pos1)
(<= point pos2))
elem1)
((> pos2 point)
(treemacs--binary-index-search point list 0 index))
((< pos2 point)
(treemacs--binary-index-search point list index end)))))
(defun treemacs--do-follow-tag (flat-index treemacs-window buffer-file project)
"Actual tag-follow implementation, run once the necessary data is gathered.
FLAT-INDEX: Sorted list of tag paths
TREEMACS-WINDOW: Window
BUFFER-FILE: Filepath
PROJECT: Project Struct"
(let* ((tag-path (treemacs--find-index-pos (point) flat-index))
(file-states '(file-node-open file-node-closed root-node-open root-node-closed))
(btn))
(when tag-path
(treemacs-without-following
(with-selected-window treemacs-window
(setq btn (treemacs-current-button))
(if btn
;; first move to the nearest file when we're on a tag
(if (memq (treemacs-button-get btn :state) '(tag-node-open tag-node-closed tag-node))
(while (not (memq (treemacs-button-get btn :state) file-states))
(setq btn (treemacs-button-get btn :parent)))
;; when that doesnt work move manually to the correct file
(-let [btn-path (treemacs-button-get btn :path)]
(unless (and (stringp btn-path) (treemacs-is-path buffer-file :same-as btn-path))
(treemacs-goto-file-node buffer-file project)
(setq btn (treemacs-current-button)))))
;; also move manually when there is no button at point
(treemacs-goto-file-node buffer-file project)
(setq btn (treemacs-current-button)))
;; close the button that was opened on the previous follow
(goto-char (treemacs-button-start btn))
;; imenu already rescanned when fetching the tag path
(let ((imenu-auto-rescan nil)
(new-file-btn))
;; make a copy since this tag-path will be saved as cache, and the two modifications made here
;; make it impossible to find the current position in `treemacs--find-index-pos'
(let* ((tag-path (copy-sequence tag-path))
(target-tag (list (car (car tag-path)))))
;; remove position marker from target tag and move it
;; to the end of the tag path
(setf tag-path (nconc (cdr tag-path) target-tag))
;; the tag path also needs its file
(setf tag-path (cons buffer-file tag-path))
;; workaround: goto routines assume that at least the very first element of the followed
;; path has a dom entry with a valid position, but this is not the case when moving to tags
;; in a previously never-expanded file node, so we first find the file to make sure its
;; position is known
(setf new-file-btn (treemacs-find-file-node buffer-file))
(treemacs-goto-node tag-path)
(when (and treemacs--previously-followed-tag-position
(not (equal (car treemacs--previously-followed-tag-position) new-file-btn)))
(-let [(prev-followed-pos . _) treemacs--previously-followed-tag-position]
(save-excursion
(when (eq 'file-node-open (treemacs-button-get prev-followed-pos :state))
(goto-char prev-followed-pos)
(treemacs--collapse-file-node prev-followed-pos)))))
(setf treemacs--previously-followed-tag-position
(cons new-file-btn (treemacs-button-get new-file-btn :path)))))
(hl-line-highlight)
(treemacs--evade-image)
(when treemacs-recenter-after-tag-follow
(treemacs--maybe-recenter treemacs-recenter-after-tag-follow)))))))
(defun treemacs--follow-tag-at-point ()
"Follow the tag at point in the treemacs view."
(interactive)
(let* ((treemacs-window (treemacs-get-local-window))
(buffer (current-buffer))
(buffer-file (when buffer (buffer-file-name)))
(project (treemacs--find-project-for-buffer)))
(when (and treemacs-window buffer-file project)
(condition-case e
(-when-let (index (or treemacs--imenu-cache
(treemacs--flatten&sort-imenu-index)))
(unless (eq index 'unsupported)
(unless (buffer-modified-p)
(setq-local treemacs--imenu-cache (copy-sequence index)))
(treemacs--do-follow-tag index treemacs-window buffer-file project)))
(imenu-unavailable (ignore e))
(error (treemacs-log-err "Encountered error while following tag at point: %s" e))))))
(defun treemacs--setup-tag-follow-mode ()
"Setup tag follow mode."
(treemacs-follow-mode -1)
(--each (buffer-list)
(with-current-buffer it
(treemacs--reset-imenu-cache)))
(add-hook 'first-change-hook #'treemacs--reset-imenu-cache)
(setq treemacs--tag-follow-timer
(run-with-idle-timer treemacs-tag-follow-delay t #'treemacs--follow-tag-at-point)))
(defun treemacs--tear-down-tag-follow-mode ()
"Tear down tag follow mode."
(remove-hook 'first-change-hook #'treemacs--reset-imenu-cache)
(when treemacs--tag-follow-timer
(cancel-timer treemacs--tag-follow-timer)))
;;;###autoload
(define-minor-mode treemacs-tag-follow-mode
"Toggle `treemacs-tag-follow-mode'.
This acts as more fine-grained alternative to `treemacs-follow-mode' and will
thus disable `treemacs-follow-mode' on activation. When enabled treemacs will
focus not only the file of the current buffer, but also the tag at point.
The follow action is attached to Emacs' idle timer and will run
`treemacs-tag-follow-delay' seconds of idle time. The delay value is not an
integer, meaning it accepts floating point values like 1.5.
Every time a tag is followed a re--scan of the imenu index is forced by
temporarily setting `imenu-auto-rescan' to t (though a cache is applied as long
as the buffer is unmodified). This is necessary to assure that creation or
deletion of tags does not lead to errors and guarantees an always up-to-date tag
view.
Note that in order to move to a tag in treemacs the treemacs buffer's window
needs to be temporarily selected, which will reset blink-cursor-mode's timer if
it is enabled. This will result in the cursor blinking seemingly pausing for a
short time and giving the appearance of the tag follow action lasting much
longer than it really does."
:init-value nil
:global t
:lighter nil
:group 'treemacs
(if treemacs-tag-follow-mode
(treemacs--setup-tag-follow-mode)
(treemacs--tear-down-tag-follow-mode)))
(provide 'treemacs-tag-follow-mode)
;;; treemacs-tag-follow-mode.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-tag-follow-mode.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 3,563 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Tags display functionality.
;; Need to be very careful here - many of the functions in this module
;; need to be run inside the treemacs buffer, while the
;; `treemacs--execute-button-action' macro that runs them will switch
;; windows before doing so. Heavy use of `treemacs-safe-button-get'
;; or `treemacs-with-button-buffer' is necessary.
;; NOTE: This module is lazy-loaded.
;;; Code:
(require 'xref)
(require 'imenu)
(require 'dash)
(require 'treemacs-core-utils)
(require 'treemacs-rendering)
(require 'treemacs-customization)
(require 'treemacs-faces)
(require 'treemacs-visuals)
(require 'treemacs-dom)
(require 'treemacs-icons)
(require 'treemacs-logging)
(eval-when-compile
(require 'inline)
(require 'cl-lib)
(require 'treemacs-macros))
(treemacs-import-functions-from "treemacs"
treemacs-select-window)
(treemacs-import-functions-from "org-comat"
org-imenu-get-tree)
;; TODO(2019/10/17): rebuild this module using the extension api
;; TODO(2020/12/14): Improve special-casing of org-mode & especially pdf-tools
(defun treemacs--partition-imenu-index (index default-name)
"Put top level leaf nodes in INDEX under DEFAULT-NAME."
(declare (pure t) (side-effect-free t))
(let ((ret)
(rest index))
(while rest
(let ((item (car rest)))
(if (imenu--subalist-p item)
(progn
(setq ret (cons item ret))
(setq rest (cdr rest)))
(progn
(setq ret (cons (cons default-name rest) ret)
rest nil)))))
(nreverse ret)))
;; this function was recently added in emacs 26 (as of august 2017)
;; code copied here for earler releases
(defun treemacs--provided-mode-derived-p (mode &rest modes)
"Non-nil if MODE is derived from one of MODES.
Uses the `derived-mode-parent' property of the symbol to trace backwards.
If you just want to check `major-mode', use `derived-mode-p'."
(while (and (not (memq mode modes))
(setq mode (get mode 'derived-mode-parent))))
mode)
(defun treemacs--post-process-index (index index-mode)
"Post process a tags INDEX for the major INDEX-MODE the tags were gathered in.
As of now this only decides which (if any) section name the top level leaves
should be placed under."
(declare (pure t) (side-effect-free t))
(pcase index-mode
((or 'markdown-mode 'org-mode 'python-mode)
index)
((guard (treemacs--provided-mode-derived-p index-mode 'conf-mode))
(treemacs--partition-imenu-index index "Sections"))
(_
(treemacs--partition-imenu-index index "Functions"))))
(defun treemacs--get-imenu-index (file)
"Fetch imenu index of FILE."
(let ((buff)
(result)
(mode)
(existing-buffer (get-file-buffer
(or (file-symlink-p file) file)))
(org-imenu-depth (max 10 (or 0 (and (boundp 'org-imenu-depth) org-imenu-depth)))))
(ignore org-imenu-depth)
(if existing-buffer
(setq buff existing-buffer)
(cl-letf (((symbol-function 'run-mode-hooks) (symbol-function 'ignore)))
(setq buff (find-file-noselect file))))
(condition-case e
(when (buffer-live-p buff)
(with-current-buffer buff
(let ((imenu-generic-expression
(if (eq major-mode 'emacs-lisp-mode)
(or treemacs-elisp-imenu-expression
imenu-generic-expression)
imenu-generic-expression))
(imenu-create-index-function
(if (eq major-mode 'org-mode)
#'org-imenu-get-tree
imenu-create-index-function)))
(setf result (and (or imenu-generic-expression imenu-create-index-function)
(imenu--make-index-alist t))
mode major-mode)))
(unless existing-buffer (kill-buffer buff))
(when result
(when (string= "*Rescan*" (caar result))
(setf result (cdr result)))
(unless (equal result '(nil))
(treemacs--post-process-index result mode))))
(imenu-unavailable (ignore e))
(error (prog1 nil (treemacs-log-err "Encountered error while following tag at point: %s" e))))))
(define-inline treemacs--insert-tag-leaf (item path prefix parent depth)
"Return the text to insert for a tag leaf ITEM with given PATH.
Use PREFIX for indentation.
Set PARENT and DEPTH button properties.
ITEM: String . Marker
PREFIX: String
PARENT: Button
DEPTH: Int"
(inline-letevals (item prefix parent depth)
(inline-quote
(list
,prefix
(propertize (car ,item)
'button '(t)
'category 'treemacs-button
'face 'treemacs-tags-face
'help-echo nil
:path ,path
:key (car ,item)
:state 'tag-node
:parent ,parent
:depth ,depth
:marker (cdr ,item))))))
(define-inline treemacs--insert-tag-node (node path prefix parent depth)
"Return the text to insert for a tag NODE with given tag PATH.
Use PREFIX for indentation.
Set PARENT and DEPTH button properties.
NODE: String & List of (String . Marker)
PATH: Tag Path
PREFIX: String
PARENT: Button
DEPTH: Int"
(inline-letevals (node prefix parent depth)
(inline-quote
(list
,prefix
(propertize (car ,node)
'button '(t)
'category 'treemacs-button
'face 'treemacs-tags-face
'help-echo nil
:path ,path
:key (car ,node)
:state 'tag-node-closed
:parent ,parent
:depth ,depth
:index (cdr ,node))))))
;;;###autoload
(defun treemacs--expand-file-node (btn &optional recursive)
"Open tag items for file BTN.
Recursively open all tags below BTN when RECURSIVE is non-nil."
(let* ((path (treemacs-button-get btn :path))
(parent-dom-node (treemacs-find-in-dom path))
(recursive (treemacs--prefix-arg-to-recurse-depth recursive)))
(-if-let (index (treemacs--get-imenu-index path))
(treemacs--button-open
:button btn
:immediate-insert t
:new-state 'file-node-open
:open-action
(treemacs--create-buttons
:nodes index
:extra-vars
((node-prefix (concat prefix treemacs-icon-tag-closed))
(leaf-prefix (concat prefix treemacs-icon-tag-leaf)))
:depth (1+ (treemacs-button-get btn :depth))
:node-name item
:node-action (if (imenu--subalist-p item)
(treemacs--insert-tag-node item (list path (car item)) node-prefix btn depth)
(treemacs--insert-tag-leaf item (list path (car item)) leaf-prefix btn depth)))
:post-open-action
(progn
(-let [dom-nodes
(--map (treemacs-dom-node->create!
:key (list path (car it))
:parent parent-dom-node)
index)]
(-each dom-nodes #'treemacs-dom-node->insert-into-dom!)
(setf (treemacs-dom-node->children parent-dom-node)
(nconc dom-nodes (treemacs-dom-node->children parent-dom-node))))
(treemacs-on-expand path btn)
(treemacs--reentry path)
(end-of-line)
(when (> recursive 0)
(cl-decf recursive)
(--each (treemacs-collect-child-nodes btn)
(when (eq 'tag-node-closed (treemacs-button-get it :state))
(goto-char (treemacs-button-start it))
(treemacs--expand-tag-node it t))))))
(treemacs-pulse-on-failure "No tags found for %s" (propertize path 'face 'font-lock-string-face)))))
;;;###autoload
(defun treemacs--collapse-file-node (btn &optional recursive)
"Close node given by BTN.
Remove all open tag entries under BTN when RECURSIVE."
(treemacs--button-close
:button btn
:new-state 'file-node-closed
:post-close-action (treemacs-on-collapse (treemacs-button-get btn :path) recursive)))
;;;###autoload
(defun treemacs--visit-or-expand/collapse-tag-node (btn arg find-window)
"Visit tag section BTN if possible, expand or collapse it otherwise.
Pass prefix ARG on to either visit or toggle action.
FIND-WINDOW is a special provision depending on this function's invocation
context and decides whether to find the window to display in (if the tag is
visited instead of the node being expanded).
On the one hand it can be called based on `treemacs-RET-actions-config' (or
TAB). The functions in these configs are expected to find the windows they need
to display in themselves, so FIND-WINDOW must be t. On the other hand this
function is also called from the top level vist-node functions like
`treemacs-visit-node-vertical-split' which delegates to the
`treemacs--execute-button-action' macro which includes the determination of
the display window."
(let* ((path (treemacs--nearest-path btn))
(extension (file-name-extension path)))
(pcase extension
("py"
(let* ((first-child (car (treemacs-button-get btn :index)))
(name (car first-child))
(marker (cdr first-child)))
;; name of first subelement of a section node ends in "definition" means we have a function
;; nested inside a function, so we move to the definition here instead of expanding
(if (not (s-ends-with? " definition*" name))
(treemacs--expand-tag-node btn arg)
;; select the window as visit-no-split would
(when find-window
(--if-let (-some-> path (get-file-buffer) (get-buffer-window))
(select-window it)
(other-window 1)))
(find-file path)
(if (buffer-live-p (marker-buffer marker))
(goto-char marker)
;; marker is stale and we need a live child button to grab its tag path to re-call imenu, but the
;; child button may not be there so we briefly expand the button to grab the first child to whose
;; position we need to move
(-let [need-to-close-section nil]
(treemacs-with-button-buffer btn
(when (eq 'tag-node-closed (treemacs-button-get btn :state))
(setq need-to-close-section t)
(treemacs--expand-tag-node btn)))
(treemacs--call-imenu-and-goto-tag
(treemacs-with-button-buffer btn (treemacs-button-get (next-button (treemacs-button-end btn)) :path)))
(when need-to-close-section
(treemacs-with-button-buffer btn
(treemacs--collapse-tag-node btn))))
(when arg (treemacs-select-window))))))
("org"
(treemacs-unless-let (pos (treemacs-button-get btn 'org-imenu-marker))
(treemacs--expand-tag-node btn arg)
;; select the window as visit-no-split would
(when find-window
(--if-let (-some-> path (get-file-buffer) (get-buffer-window))
(select-window it)
(other-window 1)))
(find-file path)
(if (marker-position pos)
(goto-char pos)
(treemacs--call-imenu-and-goto-tag (treemacs-with-button-buffer btn (treemacs-button-get btn :path)) t))))
(_ (pcase (treemacs-button-get btn :state)
('tag-node-open (treemacs--collapse-tag-node btn arg))
('tag-node-closed (treemacs--expand-tag-node btn arg)))))))
;;;###autoload
(defun treemacs--expand-tag-node (btn &optional recursive)
"Open tags node items for BTN.
Open all tag section under BTN when call is RECURSIVE."
(let* ((index (treemacs-button-get btn :index))
(tag-path (treemacs-button-get btn :path))
(parent-dom-node (treemacs-find-in-dom tag-path))
(recursive (treemacs--prefix-arg-to-recurse-depth recursive)))
(treemacs--button-open
:button btn
:immediate-insert t
:new-state 'tag-node-open
:new-icon treemacs-icon-tag-open
:open-action (treemacs--create-buttons
:nodes index
:depth (1+ (treemacs-button-get btn :depth))
:node-name item
:extra-vars ((leaf-prefix (concat prefix treemacs-icon-tag-leaf))
(node-prefix (concat prefix treemacs-icon-tag-closed)))
:node-action (if (imenu--subalist-p item)
(treemacs--insert-tag-node
item (append tag-path (list (car item))) node-prefix btn depth)
(treemacs--insert-tag-leaf
item (append tag-path (list (car item))) leaf-prefix btn depth)))
:post-open-action
(progn
(-let [dom-nodes
(--map (treemacs-dom-node->create!
:key (append tag-path (list (car it)))
:parent parent-dom-node)
index)]
(-each dom-nodes #'treemacs-dom-node->insert-into-dom!)
(setf (treemacs-dom-node->children parent-dom-node)
(nconc dom-nodes (treemacs-dom-node->children parent-dom-node))))
(treemacs-on-expand tag-path btn)
(if (> recursive 0)
(progn
(cl-decf recursive)
(--each (treemacs-collect-child-nodes btn)
(when (eq 'tag-node-closed (treemacs-button-get it :state))
(goto-char (treemacs-button-start it))
(treemacs--expand-tag-node it t))))
(treemacs--reentry tag-path))))))
(defun treemacs--collapse-tag-node-recursive (btn)
"Recursively close tag section BTN.
Workaround for tag section having no easy way to purge all open tags below a
button from cache. Easiest way is to just do it manually here."
(--each (treemacs-collect-child-nodes btn)
(when (eq 'tag-node-open (treemacs-button-get it :state))
(treemacs--collapse-tag-node-recursive it)
(goto-char (treemacs-button-start it))
(treemacs--collapse-tag-node it)))
(goto-char (treemacs-button-start btn))
(treemacs--collapse-tag-node btn))
;;;###autoload
(defun treemacs--collapse-tag-node (btn &optional recursive)
"Close tags node at BTN.
Remove all open tag entries under BTN when RECURSIVE."
(if recursive
(treemacs--collapse-tag-node-recursive btn)
(treemacs--button-close
:button btn
:new-state 'tag-node-closed
:new-icon treemacs-icon-tag-closed
:post-close-action
(treemacs-on-collapse (treemacs-button-get btn :path)))))
(defun treemacs--extract-position (item file)
"Extract a tag's position stored in ITEM and FILE.
The position can be stored in the following ways:
* ITEM is a marker pointing to a tag provided by imenu.
* ITEM is an overlay pointing to a tag provided by imenu with semantic mode.
* ITEM is a raw number pointing to a buffer position.
* ITEM is a cons: special case for imenu elements of an `org-mode' buffer.
ITEM is an imenu sub-tree and the position is stored as a marker in the first
element's \\='org-imenu-marker text property.
* ITEM is a cons: special case for imenu elements of an `pdfview-mode' buffer.
In this case no position is stored directly, navigation to the tag must happen
via callback
FILE is the path the tag is in, so far it is only relevant for `pdfview-mode'
tags."
(declare (side-effect-free t))
(pcase (type-of item)
('marker
(cons (marker-buffer item) (marker-position item)))
('overlay
(cons (overlay-buffer item) (overlay-start item)))
('integer
(cons nil item))
('cons
(cond
((eq 'pdf-outline-imenu-activate-link (cadr item))
(with-no-warnings
(cons (find-buffer-visiting file) (lambda () (apply #'pdf-outline-imenu-activate-link item)))))
((get-text-property 0 'org-imenu-marker (car item))
(-let [org-marker (get-text-property 0 'org-imenu-marker (car item))]
(cons (marker-buffer org-marker) (marker-position org-marker))))))))
(defun treemacs--call-imenu-and-goto-tag (tag-path &optional org?)
"Call the imenu index of the tag at TAG-PATH and go to its position.
ORG? should be t when this function is called for an org buffer and index since
org requires a slightly different position extraction because the position of a
headline with sub-elements is saved in an `org-imenu-marker' text property."
(let* ((file (car tag-path))
(path (-butlast (cdr tag-path)))
(tag (-last-item tag-path)))
(condition-case e
(progn
(find-file-noselect file)
(let ((index (treemacs--get-imenu-index file)))
(dolist (path-item path)
(setq index (cdr (assoc path-item index))))
(-let [(buf . pos) (treemacs--extract-position
(-let [item (--first
(equal (car it) tag)
index)]
(if org? item (cdr item)))
(car tag-path))]
;; some imenu implementations, like markdown, will only provide
;; a raw buffer position (an int) to move to
(switch-to-buffer (or buf (get-file-buffer file)))
(if (functionp pos)
(funcall pos)
(goto-char pos))
;; a little bit of convenience - reveal those nested headlines
(when (and (eq major-mode 'org-mode)
(fboundp 'org-reveal))
(org-reveal)))))
(error
(treemacs-log-err "Something went wrong when finding tag '%s': %s"
(propertize tag 'face 'treemacs-tags-face)
e)))))
;;;###autoload
(defun treemacs--goto-tag (btn)
"Go to the tag at BTN."
;; The only code currently calling this is run through `treemacs--execute-button-action' which always
;; switches windows before running it, so we need to be really careful here when querying any button
;; properties.
(let* ((tag-buffer) (tag-pos))
(treemacs-with-button-buffer btn
(-let [info (treemacs--extract-position
(treemacs-button-get btn :marker)
(car (treemacs-button-get btn :path)))]
(setf tag-buffer (car info)
tag-pos (cdr info))))
(if (not (buffer-live-p tag-buffer))
(pcase treemacs-goto-tag-strategy
('refetch-index
(treemacs--call-imenu-and-goto-tag
(treemacs-safe-button-get btn :path)))
('call-xref
(xref-find-definitions
(treemacs-with-button-buffer btn
(treemacs--get-label-of btn))))
('issue-warning
(treemacs-pulse-on-failure
"Tag '%s' is located in a buffer that does not exist."
(propertize (treemacs-with-button-buffer btn (treemacs--get-label-of btn)) 'face 'treemacs-tags-face)))
(_ (error "[Treemacs] '%s' is an invalid value for treemacs-goto-tag-strategy" treemacs-goto-tag-strategy)))
(progn
(switch-to-buffer tag-buffer nil t)
;; special case for pdf mode buffers - their imenu tags do not store a marker
;; movement must happen via a special callback
(cond
((numberp tag-pos)
(goto-char tag-pos))
((functionp tag-pos)
(funcall tag-pos)))
;; a little bit of convenience - reveal those nested headlines
(when (and (eq major-mode 'org-mode) (fboundp 'org-reveal))
(org-reveal))))))
;;;###autoload
(defun treemacs--create-imenu-index-function ()
"The `imenu-create-index-function' for treemacs buffers."
(declare (side-effect-free t))
(let (index)
(pcase treemacs-imenu-scope
('everything
(dolist (project (treemacs-workspace->projects (treemacs-current-workspace)))
(let ((project-name (treemacs-project->name project))
(root-dom-node (treemacs-find-in-dom (treemacs-project->path project))))
(-when-let (index-items (treemacs--get-imenu-index-items root-dom-node))
(push (cons project-name index-items) index)))))
('current-project
(treemacs-unless-let (project (treemacs-project-at-point))
(treemacs-pulse-on-failure "Cannot create imenu index because there is no project at point")
(let ((project-name (treemacs-project->name project))
(root-dom-node (treemacs-find-in-dom (treemacs-project->path project))))
(-when-let (index-items (treemacs--get-imenu-index-items root-dom-node))
(push (cons project-name index-items) index)))))
(other (error "Invalid imenu scope value `%s'" other)))
(nreverse index)))
(defun treemacs--get-imenu-index-items (project-dom-node)
"Collects the imenu index items for the given PROJECT-DOM-NODE."
(declare (side-effect-free t))
(let (result)
(treemacs-walk-dom project-dom-node
(lambda (node)
(-let [node-btn (or (treemacs-dom-node->position node)
(treemacs-find-node (treemacs-dom-node->key node)))]
(push (list (if (treemacs-button-get node-btn :custom)
(treemacs--get-label-of node-btn)
(file-relative-name (treemacs-dom-node->key node) (treemacs-dom-node->key project-dom-node)))
(or node-btn -1)
#'treemacs--imenu-goto-node-wrapper
(treemacs-dom-node->key node))
result))))
(nreverse result)))
(define-inline treemacs--imenu-goto-node-wrapper (_name _pos key)
"Thin wrapper around `treemacs-goto-node'.
Used by imenu to move to the node with the given KEY."
(inline-letevals (key)
(inline-quote
(treemacs-goto-node ,key))))
(provide 'treemacs-tags)
;;; treemacs-tags.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-tags.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 5,261 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; General purpose macros, and those used in, but defined outside of
;; treemacs-core-utils.el are put here, to prevent using them before
;; their definition, hopefully preventing issues like #97.
;;; Code:
(require 'dash)
(require 's)
(require 'pcase)
(eval-when-compile
(require 'cl-lib)
(require 'gv))
(declare-function treemacs--scope-store "treemacs-scope")
(defmacro treemacs-import-functions-from (file &rest functions)
"Import FILE's FUNCTIONS.
Creates a list of `declare-function' statements."
(declare (indent 1))
(let ((imports (--map (list 'declare-function it file) functions)))
`(progn ,@imports)))
(defmacro treemacs-static-assert (predicate error-msg &rest error-args)
"Assert for macros that triggers at expansion time.
Tests PREDICATE and, if it evaluates to nil, throws an error with ERROR-MSG and
ERROR-ARGS. Basically the same thing as `cl-assert', but does not (seem to)
interfere with auto-completion."
(declare (indent 1))
`(unless ,predicate
(error (apply #'format
(concat "[Treemacs] " ,error-msg)
(list ,@error-args)))))
(defmacro treemacs-with-writable-buffer (&rest body)
"Temporarily turn off read-only mode to execute BODY."
(declare (debug t))
`(let (buffer-read-only)
,@body))
(defmacro treemacs-safe-button-get (button &rest properties)
"Safely extract BUTTON's PROPERTIES.
Using `button-get' on a button located in a buffer that is not the current
buffer does not work, so this function will run the property extraction from
inside BUTTON's buffer."
`(with-current-buffer (marker-buffer ,button)
,(if (= 1 (length properties))
`(treemacs-button-get ,button ,(car properties))
`(--map (treemacs-button-get ,button it) ,properties))))
(defmacro treemacs-with-button-buffer (btn &rest body)
"Use BTN's buffer to execute BODY.
Required for button interactions (like `treemacs-button-get') that do not work
when called from another buffer than the one the button resides in and
`treemacs-safe-button-get' is not enough."
(declare (indent 1)
(debug (form body)))
`(with-current-buffer (marker-buffer ,btn)
,@body))
(defmacro treemacs-unless-let (var-val &rest forms)
"Same as `-if-let-', but the negative case is handled in the first form.
Delegates VAR-VAL and the given FORMS to `-if-let-'."
(declare (debug ((sexp form) body))
(indent 2))
(let ((then (cdr forms))
(else (car forms)))
`(-if-let ,var-val (progn ,@then) ,else)))
(defmacro treemacs-with-current-button (error-msg &rest body)
"Execute an action with the current button bound to \\='current-btn'.
Log ERROR-MSG if no button is selected, otherwise run BODY."
(declare (debug (form body)))
`(-if-let (current-btn (treemacs-current-button))
(progn ,@body)
(treemacs-pulse-on-failure ,error-msg)))
(defmacro treemacs-without-following (&rest body)
"Execute BODY with `treemacs--ready-to-follow' set to nil."
(declare (debug t))
`(let ((treemacs--ready-to-follow nil))
;; ignore because not every module using this macro requires follow-mode.el
(ignore treemacs--ready-to-follow)
,@body))
(cl-defmacro treemacs-do-for-button-state
(&key no-error
fallback
on-root-node-open
on-root-node-closed
on-file-node-open
on-file-node-closed
on-dir-node-open
on-dir-node-closed
on-tag-node-open
on-tag-node-closed
on-tag-node-leaf
on-nil)
"Building block macro to execute a form based on the current node state.
Will bind to current button to \\='btn' for the execution of the action forms.
When NO-ERROR is non-nil no error will be thrown if no match for the button
state is achieved. A general FALLBACK can also be used instead of NO-ERROR. In
that case the unknown state will be bound as `state' in the FALLBACK form.
Otherwise either one of ON-ROOT-NODE-OPEN, ON-ROOT-NODE-CLOSED,
ON-FILE-NODE-OPEN, ON-FILE-NODE-CLOSED, ON-DIR-NODE-OPEN, ON-DIR-NODE-CLOSED,
ON-TAG-NODE-OPEN, ON-TAG-NODE-CLOSED, ON-TAG-NODE-LEAF or ON-NIL will be
executed."
(declare (debug (&rest [sexp form])))
(treemacs-static-assert (or (null no-error) (null fallback))
"no-error and fallback arguments are mutually exclusive.")
`(-if-let (btn (treemacs-current-button))
(pcase (treemacs-button-get btn :state)
,@(when on-root-node-open
`((`root-node-open
,on-root-node-open)))
,@(when on-root-node-closed
`((`root-node-closed
,on-root-node-closed)))
,@(when on-file-node-open
`((`file-node-open
,on-file-node-open)))
,@(when on-file-node-closed
`((`file-node-closed
,on-file-node-closed)))
,@(when on-dir-node-open
`((`dir-node-open
,on-dir-node-open)))
,@(when on-dir-node-closed
`((`dir-node-closed
,on-dir-node-closed)))
,@(when on-tag-node-open
`((`tag-node-open
,on-tag-node-open)))
,@(when on-tag-node-closed
`((`tag-node-closed
,on-tag-node-closed)))
,@(when on-tag-node-leaf
`((`tag-node
,on-tag-node-leaf)))
,@(when fallback
`((state
(ignore state)
,fallback)))
,@(unless (or fallback no-error)
`((state (error "[Treemacs] Unexpected button state %s" state)))))
,on-nil))
(cl-defmacro treemacs--execute-button-action
(&key no-match-explanation
window
split-function
ensure-window-split
dir-action
file-action
tag-section-action
tag-action
window-arg)
"Infrastructure macro for setting up actions on different button states.
Fetches the currently selected button and verifies it's in the correct state
based on the given state actions.
If it isn't it will log NO-MATCH-EXPLANATION, if it is it selects WINDOW (or
`next-window' if none is given) and splits it with SPLIT-FUNCTION if given.
If ENSURE-WINDOW-SPLIT is non-nil treemacs will vertically split the window if
treemacs is the only window to make sure a buffer is opened next to it, not
under or below it.
DIR-ACTION, FILE-ACTION, TAG-SECTION-ACTION and TAG-ACTION are inserted into a
`pcase' statement matching the buttons state. Project root nodes are treated
the same common directory nodes.
WINDOW-ARG determines whether the treemacs windows should remain selected,
\(single prefix arg), or deleted (double prefix arg)."
(declare (debug (&rest [sexp form])))
(let ((valid-states (list)))
(when dir-action
(push 'root-node-open valid-states)
(push 'root-node-closed valid-states)
(push 'dir-node-open valid-states)
(push 'dir-node-closed valid-states))
(when file-action
(push 'file-node-open valid-states)
(push 'file-node-closed valid-states))
(when tag-section-action
(push 'tag-node-open valid-states)
(push 'tag-node-closed valid-states))
(when tag-action
(push 'tag-node valid-states))
`(-when-let (btn (treemacs-current-button))
(treemacs-without-following
(let* ((state (treemacs-button-get btn :state))
(current-window (selected-window)))
(if (and (not (memq state ',valid-states))
(not (get state :treemacs-visit-action)))
(treemacs-pulse-on-failure "%s" ,no-match-explanation)
(progn
,@(if ensure-window-split
`((when (one-window-p)
(save-selected-window
(split-window nil nil (if (eq 'left treemacs-position) 'right 'left))))))
(select-window (or ,window (next-window (selected-window) nil nil)))
,@(if split-function
`((funcall ,split-function)
(other-window 1)))
;; Return the result of the action
(prog1 (pcase state
,@(when dir-action
`(((or `dir-node-open `dir-node-closed `root-node-open `root-node-closed)
,dir-action)))
,@(when file-action
`(((or `file-node-open `file-node-closed)
,file-action)))
,@(when tag-section-action
`(((or `tag-node-open `tag-node-closed)
,tag-section-action)))
,@(when tag-action
`((`tag-node
,tag-action)))
(_
(-if-let (visit-action (get state :treemacs-visit-action))
(funcall visit-action btn)
(error "No match achieved even though button's state %s was part of the set of valid states %s"
state ',valid-states))))
(pcase ,window-arg
('(4) (select-window current-window))
('(16) (delete-window current-window)))))))))))
;; TODO(2021/08/28): RM
(defmacro treemacs--without-filewatch (&rest body)
"Run BODY without triggering the filewatch callback.
Required for manual interactions with the file system (like deletion), otherwise
the on-delete code will run twice."
(declare (debug t))
`(cl-flet (((symbol-function 'treemacs--filewatch-callback) (symbol-function 'ignore)))
,@body))
(defmacro treemacs-save-position (main-form &rest final-form)
"Execute MAIN-FORM without switching position.
Finally execute FINAL-FORM after the code to restore the position has run.
This macro is meant for cases where a simple `save-excursion' will not do, like
a refresh, which can potentially change the entire buffer layout. In practice
this means attempt first to keep point on the same file/tag, and if that does
not work keep it on the same line."
(declare (debug (form body)))
`(treemacs-without-following
(declare-function treemacs--current-screen-line "treemacs-rendering")
(let* ((curr-btn (treemacs-current-button))
(curr-point (point-marker))
(next-path (-some-> curr-btn (treemacs--next-non-child-button) (button-get :path)))
(prev-path (-some-> curr-btn (treemacs--prev-non-child-button) (button-get :path)))
(curr-node-path (-some-> curr-btn (treemacs-button-get :path)))
(curr-state (-some-> curr-btn (treemacs-button-get :state)))
(collapse (-some-> curr-btn (treemacs-button-get :collapsed)))
(curr-file (if collapse (treemacs-button-get curr-btn :key) (-some-> curr-btn (treemacs--nearest-path))))
(curr-window (get-buffer-window (current-buffer)))
(curr-win-line (when curr-window
(with-selected-window curr-window
(treemacs--current-screen-line)))))
,main-form
;; try to stay at the same file/tag
;; if the tag no longer exists move to the tag's owning file node
(pcase curr-state
((or 'root-node-open 'root-node-closed)
;; root nodes are always visible even if deleted.
(treemacs-goto-file-node curr-file))
((or 'dir-node-open 'dir-node-closed 'file-node-open 'file-node-closed)
;; stay on the same file
(if (and (treemacs-is-path-visible? curr-file)
(or treemacs-show-hidden-files
(not (s-matches? treemacs-dotfiles-regex (treemacs--filename curr-file)))))
(treemacs-goto-file-node curr-file)
;; file we were on is no longer visible
;; try dodging to our immediate neighbours, if they are no longer visible either
;; keep going up
(cl-labels
((can-move-to (it) (and (treemacs-is-path-visible? it)
(or treemacs-show-hidden-files
(not (s-matches? treemacs-dotfiles-regex (treemacs--filename it)))))))
(cond
((and next-path (can-move-to next-path))
(treemacs-goto-file-node next-path))
((and prev-path (can-move-to prev-path))
(treemacs-goto-file-node prev-path))
(t
(-let [detour (treemacs--parent curr-file)]
(while (not (can-move-to detour))
(setf detour (treemacs--parent detour)))
(treemacs-goto-file-node detour)))))))
((or 'tag-node-open 'tag-node-closed 'tag-node)
(treemacs-goto-node curr-node-path))
((pred null)
(goto-char curr-point))
(_
;; point is on a custom node
;; TODO(2018/10/30): custom node exists predicate?
(condition-case _
(treemacs-goto-node curr-node-path)
(error (ignore)))))
(treemacs--evade-image)
(when (get-text-property (point) 'invisible)
(goto-char (or
(next-single-property-change (point) 'invisible)
(point-min))))
(when curr-win-line
(-let [buffer-point (point)]
(with-selected-window curr-window
;; recenter starts counting at 0
(-let [scroll-margin 0]
(recenter (1- curr-win-line)))
(set-window-point (selected-window) buffer-point))))
,@final-form)))
(defmacro treemacs-with-workspace (workspace &rest body)
"Use WORKSPACE as the current workspace when running BODY.
Specifically this means that calls to `treemacs-current-workspace' will return
WORKSPACE and if no workspace has been set for the current scope yet it will not
be set either."
(declare (indent 1) (debug (form body)))
`(let ((treemacs-override-workspace ,workspace))
(ignore treemacs-override-workspace)
,@body))
(defmacro treemacs-run-in-every-buffer (&rest body)
"Run BODY once locally in every treemacs buffer.
Only includes treemacs file tree buffers, not extensions.
Sets `treemacs-override-workspace' so calls to `treemacs-current-workspace'
return the workspace of the active treemacs buffer."
(declare (debug t))
`(pcase-dolist (`(,_ . ,shelf) (treemacs--scope-store))
(let ((buffer (treemacs-scope-shelf->buffer shelf))
(workspace (treemacs-scope-shelf->workspace shelf)))
(when (buffer-live-p buffer)
(treemacs-with-workspace workspace
(with-current-buffer buffer
,@body))))))
(defmacro treemacs-run-in-all-derived-buffers (&rest body)
"Run BODY once locally in every treemacs buffer.
Includes *all* treemacs-mode-derived buffers, including extensions."
(declare (debug t))
`(dolist (buffer (buffer-list))
(when (buffer-local-value 'treemacs--in-this-buffer buffer)
(with-current-buffer buffer
,@body))))
(defmacro treemacs-only-during-init (&rest body)
"Run BODY only when treemacs has not yet been loaded.
Specifically only run it when (featurep \\='treemacs) returns nil."
(declare (debug t))
`(unless (featurep 'treemacs)
,@body))
(defmacro treemacs--maphash (table names &rest body)
"Iterate over entries of TABLE with NAMES in BODY.
Entry variables will bound based on NAMES which is a list of two elements."
(declare (debug (sexp sexp body))
(indent 2))
(let ((key-name (car names))
(val-name (cadr names)))
`(maphash
(lambda (,key-name ,val-name) ,@body)
,table)))
(defmacro treemacs-error-return (error-msg &rest msg-args)
"Interactive early return failure from `treemacs-block'.
Will also pass ERROR-MSG and MSG-ARGS to `treemacs-pulse-on-failure'."
(declare (indent 1) (debug (form body)))
`(cl-return-from __body__
(treemacs-pulse-on-failure ,error-msg ,@msg-args)))
(defmacro treemacs-error-return-if (predicate error-msg &rest msg-args)
"Interactive early return from `treemacs-block'.
Checks if PREDICATE returns a non-nil value, and will pass also ERROR-MSG and
MSG-ARGS to `treemacs-pulse-on-failure'."
(declare (indent 1) (debug (form sexp body)))
`(when ,predicate
(cl-return-from __body__
(treemacs-pulse-on-failure ,error-msg ,@msg-args))))
(defmacro treemacs-return (ret)
"Early return from `treemacs-block', returning RET."
(declare (debug t))
`(cl-return-from __body__ ,ret))
(defmacro treemacs-return-if (predicate &optional ret)
"Early return from `treemacs-block'.
When PREDICATE returns non-nil RET will be returned."
(declare (indent 1) (debug (form sexp)))
`(when ,predicate
(cl-return-from __body__ ,ret)))
(cl-defmacro treemacs-first-child-node-where (btn &rest predicate)
"Among the *direct* children of BTN find the first child matching PREDICATE.
For the PREDICATE call the button being checked is bound as \\='child-btn'."
(declare (indent 1) (debug (sexp body)))
`(cl-block __search__
(let* ((child-btn (next-button (treemacs-button-end ,btn) t))
(depth (when child-btn (treemacs-button-get child-btn :depth))))
(when (and child-btn
(equal (treemacs-button-get child-btn :parent) ,btn))
(if (progn ,@predicate)
(cl-return-from __search__ child-btn)
(while child-btn
(setq child-btn (next-button (treemacs-button-end child-btn)))
(when child-btn
(-let [child-depth (treemacs-button-get child-btn :depth)]
(cond
((= depth child-depth)
(when (progn ,@predicate) (cl-return-from __search__ child-btn)) )
((> depth child-depth)
(cl-return-from __search__ nil)))))))))))
(defmacro treemacs-block (&rest forms)
"Put FORMS in a `cl-block' named '__body__'.
This pattern is oftentimes used in treemacs, see also `treemacs-return-if',
`treemacs-return', `treemacs-error-return' and `treemacs-error-return-if'"
(declare (debug t))
`(cl-block __body__ ,@forms))
(defmacro treemacs-is-path (left op &optional right)
"Readable utility macro for various path predicates.
LEFT is a file path, OP is the operator and RIGHT is either a path, project, or
workspace. OP can be one of the following:
* `:same-as' will check for string equality.
* `:in' will check will check whether LEFT is a child or the same as RIGHT.
* `:directly-in' will check will check whether LEFT is *direct* child of RIGHT.
* `:parent-of' will check whether LEFT is a parent of, and not equal to, RIGHT.
* `:in-project' will check whether LEFT is part of the project RIGHT.
* `:in-workspace' will check whether LEFT is part of the workspace RIGHT and
return the appropriate project when it is. If RIGHT is not given it will
default to calling `treemacs-current-workspace'.
LEFT and RIGHT are expected to be in treemacs canonical file path format (see
also `treemacs-canonical-path').
Even if LEFT or RIGHT should be a form and not a variable it is guaranteed that
they will be evaluated only once."
(declare (debug (&rest form)))
(treemacs-static-assert (memq op '(:same-as :in :directly-in :parent-of :in-project :in-workspace))
"Invalid treemacs-is-path operator: `%s'" op)
(treemacs-static-assert (or (eq op :in-workspace) right)
"Right-side argument is required")
(macroexp-let2* nil
((left left)
(right right))
(pcase op
(:same-as
`(string= ,left ,right))
(:in
`(or (string= ,left ,right)
(s-starts-with? (treemacs--add-trailing-slash ,right) ,left)))
(:directly-in
`(let ((l (length ,right)))
(and (> (length ,left) l)
(string= (treemacs--filename ,left) (substring ,left (1+ l)))
(string-prefix-p ,right ,left))))
(:parent-of
`(and (s-starts-with? (treemacs--add-trailing-slash ,left) ,right)
(not (string= ,left ,right))))
(:in-project
`(treemacs-is-path ,left :in (treemacs-project->path ,right)))
(:in-workspace
(-let [ws (or right '(treemacs-current-workspace))]
`(--first (treemacs-is-path ,left :in-project it)
(treemacs-workspace->projects ,ws)))))))
(cl-defmacro treemacs-with-path (path &key file-action extension-action no-match-action)
"Execute an action depending on the type of PATH.
FILE-ACTION is the action to perform when PATH is a regular file node.
EXTENSION-ACTION is performed on extension-created nodes.
If none of the path types matches, NO-MATCH-ACTION is executed."
(declare (indent 1))
(let ((path-symbol (make-symbol "path")))
`(let ((,path-symbol ,path))
(cond
,@(when file-action
`(((stringp ,path-symbol) ,file-action)))
,@(when extension-action
`(((or (symbolp ,path)
(symbolp (car ,path))
(stringp (car ,path)))
,extension-action)))
(t
,(if no-match-action
no-match-action
`(error "Path type did not match: %S" ,path-symbol)))))))
(defmacro treemacs-with-toggle (&rest body)
"Building block helper macro.
If treemacs is currently visible it will be hidden, if it is not visible, or no
treemacs buffer exists at all, BODY will be executed."
`(--if-let (treemacs-get-local-window)
(delete-window it)
,@body))
(defmacro treemacs-with-ignored-errors (ignored-errors &rest body)
"Given list of specifically IGNORED-ERRORS evaluate BODY.
IGNORED-ERRORS is a list of errors to ignore. Each element is a list whose car
is the error's type, and second item is a regex to match against error messages.
If any of the IGNORED-ERRORS matches, the error is suppressed and nil returned."
(let ((err (make-symbol "err")))
`(condition-case-unless-debug ,err
,(macroexp-progn body)
,@(mapcar
(lambda (ignore-spec)
`(,(car ignore-spec)
(unless (string-match-p ,(nth 1 ignore-spec) (error-message-string ,err))
(signal (car ,err) (cdr ,err)))))
ignored-errors))))
(defmacro treemacs-debounce (guard delay &rest body)
"Debounce a function call.
Based on a timer GUARD variable run function with the given DELAY and BODY."
(declare (indent 2))
`(unless ,guard
(setf ,guard
(run-with-idle-timer
,delay nil
(lambda ()
(unwind-protect
(progn ,@body)
(setf ,guard nil)))))))
(defmacro treemacs-without-recenter (&rest body)
"Run BODY without the usual recentering for expanded nodes.
Specifically `treemacs--no-recenter' will be set to \\='t' so that
`treemacs--maybe-recenter' will have no effect during non-interactive updates
triggered by e.g. filewatch-mode."
(declare (debug t))
`(let ((treemacs--no-recenter t))
,@body))
(provide 'treemacs-macros)
;;; treemacs-macros.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-macros.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 5,699 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Implementation for logging messages.
;;; Code:
(require 'treemacs-customization)
(defvar treemacs--saved-eldoc-display nil
"Stores the value of `treemacs-eldoc-display'.
The value is set to nil and stashed here with every log statement to prevent the
logged message being almost immediately overridden by the eldoc output.
The value is also stashed as a single-item-list which serves as a check make
sure it isn't stashed twice (thus stashing the already disabled nil value).")
(defvar treemacs--no-messages nil
"When set to t `treemacs-log' will produce no output.
Not used directly, but as part of `treemacs-without-messages'.")
(defun treemacs--restore-eldoc-after-log ()
"Restore the stashed value of `treemacs-eldoc-display'."
(remove-hook 'pre-command-hook #'treemacs--restore-eldoc-after-log)
(setf treemacs-eldoc-display (car treemacs--saved-eldoc-display)
treemacs--saved-eldoc-display nil))
(defmacro treemacs-without-messages (&rest body)
"Temporarily turn off messages to execute BODY."
(declare (debug t))
`(let ((treemacs--no-messages t))
,@body))
(defmacro treemacs--do-log (prefix msg &rest args)
"Print a log statement with the given PREFIX and MSG and format ARGS."
`(progn
(unless (consp treemacs--saved-eldoc-display)
(setf treemacs--saved-eldoc-display (list treemacs-eldoc-display)))
(setf treemacs-eldoc-display nil)
(unless treemacs--no-messages
(message "%s %s" ,prefix (format ,msg ,@args)))
(add-hook 'pre-command-hook #'treemacs--restore-eldoc-after-log)))
(defmacro treemacs-log (msg &rest args)
"Write an info/success log statement given format string MSG and ARGS."
(declare (indent 1))
`(treemacs--do-log
(propertize "[Treemacs]" 'face 'font-lock-keyword-face)
,msg ,@args))
(defmacro treemacs-log-failure (msg &rest args)
"Write a warning/failure log statement given format string MSG and ARGS."
(declare (indent 1))
`(treemacs--do-log
(propertize "[Treemacs]" 'face '((:inherit warning :weight bold)))
,msg ,@args))
(defmacro treemacs-log-err (msg &rest args)
"Write an error log statement given format string MSG and ARGS."
(declare (indent 1))
`(treemacs--do-log
(propertize "[Treemacs]" 'face '((:inherit error :weight bold)))
,msg ,@args))
(provide 'treemacs-logging)
;;; treemacs-logging.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-logging.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 728 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; General implementation details.
;;; Code:
(require 'hl-line)
(require 'dash)
(require 's)
(require 'ht)
(require 'pfuture)
(require 'treemacs-customization)
(require 'treemacs-logging)
(eval-when-compile
(require 'inline)
(require 'cl-lib)
(require 'treemacs-macros))
(treemacs-import-functions-from "cfrs"
cfrs-read)
(treemacs-import-functions-from "treemacs-interface"
treemacs-toggle-node)
(treemacs-import-functions-from "treemacs-tags"
treemacs--expand-file-node
treemacs--collapse-file-node
treemacs--expand-tag-node
treemacs--collapse-tag-node
treemacs--extract-position
treemacs--goto-tag)
(treemacs-import-functions-from "treemacs"
treemacs-refresh)
(treemacs-import-functions-from "treemacs-scope"
treemacs-get-local-window
treemacs-get-local-buffer
treemacs-get-local-buffer-create
treemacs-scope-shelf->buffer
treemacs-scope-shelf->workspace
treemacs-current-visibility
treemacs--select-visible-window
treemacs--remove-buffer-after-kill
treemacs--scope-store)
(treemacs-import-functions-from "treemacs-rendering"
treemacs-do-delete-single-node
treemacs-do-update-node
treemacs-do-delete-single-node
treemacs--current-screen-line
treemacs--add-root-element
treemacs--expand-root-node
treemacs--collapse-root-node
treemacs--expand-dir-node
treemacs--collapse-dir-node
treemacs--render-projects)
(treemacs-import-functions-from "treemacs-filewatch-mode"
treemacs--stop-filewatch-for-current-buffer
treemacs--stop-watching
treemacs--cancel-refresh-timer)
(treemacs-import-functions-from "treemacs-follow-mode"
treemacs--follow)
(treemacs-import-functions-from "treemacs-visuals"
treemacs-pulse-on-success
treemacs--forget-previously-follow-tag-btn)
(treemacs-import-functions-from "treemacs-async"
treemacs--git-status-process
treemacs--non-simple-git-mode-enabled
treemacs-update-single-file-git-state
treemacs--flattened-dirs-process)
(treemacs-import-functions-from "treemacs-dom"
treemacs-on-collapse
treemacs-dom-node->set-position!
treemacs-find-in-dom
treemacs-dom-node->key
treemacs-dom-node->position)
(treemacs-import-functions-from "treemacs-workspaces"
treemacs--find-workspace
treemacs-current-workspace
treemacs-workspace->projects
treemacs-workspace->is-empty?
treemacs-do-add-project-to-workspace
treemacs-project->path
treemacs-project->name
treemacs-project->refresh!
treemacs-project->position
treemacs-project-p
treemacs--find-project-for-path)
(treemacs-import-functions-from "treemacs-visuals"
treemacs-pulse-on-failure)
(treemacs-import-functions-from "treemacs-persistence"
treemacs--maybe-load-workspaces)
(treemacs-import-functions-from "treemacs-annotations"
treemacs--delete-annotation)
(declare-function treemacs-mode "treemacs-mode")
(defconst treemacs--empty-table (ht)
"Constant value of an empty hash table.
Used to avoid creating unnecessary garbage.")
(defvar treemacs--closed-node-states
'(root-node-closed
dir-node-closed
file-node-closed
tag-node-closed)
"States marking a node as closed.
Used in `treemacs-is-node-collapsed?'")
(defvar treemacs--open-node-states
'(project-node-open
root-node-open
dir-node-open
file-node-open
tag-node-open)
"States marking a node as open.
Used in `treemacs-is-node-expanded?'")
(define-inline treemacs--unslash (path)
"Remove the final slash in PATH."
(declare (pure t) (side-effect-free t))
(inline-letevals (path)
(inline-quote
(if (and (> (length ,path) 1)
(eq ?/ (aref ,path (1- (length ,path)))))
(substring ,path 0 -1)
,path))))
(define-inline treemacs-string-trim-right (string)
"Trim STRING of trailing string matching REGEXP.
Same as the builtin `string-trim-right', but re-implemented here for Emacs 27."
(declare (side-effect-free t))
(inline-letevals (string)
(inline-quote
(let ((i (string-match-p "\\(?:[ \t\n\r]+\\)\\'" ,string)))
(if i (substring ,string 0 i) ,string)))))
(define-inline treemacs--prefix-arg-to-recurse-depth (arg)
"Translates prefix ARG into a number.
Used for depth-based expansion of nodes - a numeric prefix will translate to
itself, the default representation translates to 9999."
(declare (pure t) (side-effect-free t))
(inline-letevals (arg)
(inline-quote
(cond
((null ,arg) 0)
((integerp ,arg) ,arg)
(t 999)))))
(defun treemacs--all-buttons-with-depth (depth)
"Get all buttons with the given DEPTH."
(declare (side-effect-free t))
(save-excursion
(goto-char (point-min))
(let ((current-btn (treemacs-current-button))
(result))
(when (and current-btn
(= depth (treemacs-button-get current-btn :depth)))
(push current-btn result))
(while (= 0 (forward-line 1))
(setf current-btn (treemacs-current-button))
(when (and current-btn
(= depth (treemacs-button-get current-btn :depth)))
(push current-btn result)))
result)))
(define-inline treemacs--parent-dir (path)
"Return the parent of PATH is it's a file, or PATH if it is a directory.
PATH: File Path"
(declare (side-effect-free t) (pure t))
(inline-letevals (path)
(inline-quote
(-> ,path
(file-name-directory)
(treemacs--unslash)))))
(defconst treemacs--buffer-name-prefix " *Treemacs-")
(defconst treemacs-dir
;; locally we're in src/elisp, installed from melpa we're at the package root
(-let [dir (-> (if load-file-name
(file-name-directory load-file-name)
default-directory)
(expand-file-name))]
(if (s-ends-with? "src/elisp/" dir)
(-> dir (treemacs--unslash) (treemacs--parent-dir) (treemacs--parent-dir))
dir))
"The directory treemacs.el is stored in.")
(defvar-local treemacs--width-is-locked t
"Keeps track of whether the width of the treemacs window is locked.")
(defvar-local treemacs--in-this-buffer nil
"Non-nil only in buffers meant to show treemacs.
Used to show an error message if someone mistakenly activates `treemacs-mode'.")
(define-inline treemacs--remove-trailing-newline (str)
"Remove final newline in STR."
(declare (pure t) (side-effect-free t))
(inline-letevals (str)
(inline-quote
(let ((len (1- (length ,str))))
(if (= 10 (aref ,str len))
(substring ,str 0 len)
,str)))))
(define-inline treemacs--add-trailing-slash (str)
"Add final slash to STR.
If STR already has a slash return it unchanged."
(declare (pure t) (side-effect-free t))
(inline-letevals (str)
(inline-quote
(if (eq ?/ (aref ,str (1- (length ,str))))
,str
(concat ,str "/")))))
(define-inline treemacs--delete-line ()
"Delete the current line.
Unlike the function `kill-whole-line' this won't pollute the kill ring."
(inline-quote
(delete-region (line-beginning-position) (min (point-max) (1+ (line-end-position))))))
(define-inline treemacs-current-button ()
"Get the button in the current line.
Returns nil when point is between projects."
(declare (side-effect-free error-free))
(inline-quote
(-some->
(text-property-not-all (line-beginning-position) (line-end-position) 'button nil)
(copy-marker t))))
(defalias 'treemacs-node-at-point #'treemacs-current-button)
(define-inline treemacs-button-put (button prop val)
"Set BUTTON's PROP property to VAL.
Same as `button-put', but faster since it's inlined and does not query the
button type on every call."
(inline-letevals (button prop val)
(inline-quote
(put-text-property
(or (previous-single-property-change (1+ ,button) 'button)
(point-min))
(or (next-single-property-change ,button 'button)
(point-max))
,prop ,val))))
(define-inline treemacs-button-get (button prop)
"Get the property of button BUTTON named PROP.
Same as `button-get', but faster since it's inlined and does not query the
button type on every call."
(declare (side-effect-free t))
(inline-letevals (button prop)
(inline-quote
(get-text-property ,button ,prop))))
(define-inline treemacs-button-start (button)
"Return the start position of BUTTON.
Same as `button-start', but faster since it's inlined and does not query the
button type on every call."
(declare (side-effect-free t))
(inline-letevals (button)
(inline-quote
(or (previous-single-property-change (1+ ,button) 'button)
(point-min)))))
(define-inline treemacs-button-end (button)
"Return the end position of BUTTON.
Same as `button-end', but faster since it's inlined and does not query the
button type on every call."
(declare (side-effect-free t))
(inline-letevals (button)
(inline-quote
(or (next-single-property-change ,button 'button)
(point-max)))))
(define-inline treemacs-is-node-expanded? (btn)
"Return whether BTN is in an open state."
(declare (side-effect-free t))
(inline-quote
(memq (treemacs-button-get ,btn :state) treemacs--open-node-states)))
(define-inline treemacs-is-node-collapsed? (btn)
"Return whether BTN is in a closed state."
(declare (side-effect-free t))
(inline-quote
(memq (treemacs-button-get ,btn :state) treemacs--closed-node-states)))
(define-inline treemacs--get-label-of (btn)
"Return the text label of BTN."
(declare (side-effect-free t))
(inline-quote
(buffer-substring-no-properties (treemacs-button-start ,btn) (treemacs-button-end ,btn))))
(define-inline treemacs--tokenize-path (path exclude-prefix)
"Get the PATH's single elements, excluding EXCLUDE-PREFIX.
For example the input /A/B/C/D/E + /A/B will return [C D E].
PATH: File Path
EXCLUDE-PREFIX: File Path"
(declare (pure t) (side-effect-free t))
(inline-letevals (path exclude-prefix)
(inline-quote
(treemacs-split-path (substring ,path (length ,exclude-prefix))))))
(defun treemacs--replace-recentf-entry (old-file new-file)
"Replace OLD-FILE with NEW-FILE in the recent file list."
;; code taken from spacemacs - is-bound check due to being introduced after emacs24?
;; better safe than sorry so let's keep it
(with-no-warnings
(when (fboundp 'recentf-add-file)
(recentf-add-file new-file)
(recentf-remove-if-non-kept old-file))))
(defun treemacs--select-project-by-name ()
"Interactively choose a project from the current workspace."
(let* ((projects (--map (cons (treemacs-project->name it) it)
(-> (treemacs-current-workspace) (treemacs-workspace->projects))))
(selection (completing-read "Project: " projects)))
(cdr (assoc selection projects))))
(define-inline treemacs--select-not-visible-window ()
"Switch to treemacs buffer, given that it not visible."
(inline-quote
(let ((buffer (current-buffer)))
(treemacs--setup-buffer)
(when (or treemacs-follow-after-init
(with-no-warnings treemacs-follow-mode))
(with-current-buffer buffer (treemacs--follow)))
(run-hook-with-args 'treemacs-select-functions 'exists))))
(define-inline treemacs--button-symbol-switch (new-symbol)
"Replace icon in current line with NEW-SYMBOL."
(inline-letevals (new-symbol)
(inline-quote
(save-excursion
(let ((len (length ,new-symbol)))
(goto-char (- (treemacs-button-start (next-button (line-beginning-position) t)) len))
(insert ,new-symbol)
(delete-char len))))))
(defun treemacs-project-of-node (node)
"Find the project the given NODE belongs to."
(declare (side-effect-free t))
(-let [project (treemacs-button-get node :project)]
(while (not project)
(setq node (treemacs-button-get node :parent)
project (treemacs-button-get node :project)))
project))
(define-inline treemacs--prop-at-point (prop)
"Grab property PROP of the button at point.
Returns nil when there is no button at point."
(declare (side-effect-free t))
(inline-quote
(-when-let (b (treemacs-current-button))
(treemacs-button-get b ,prop))))
(define-inline treemacs--filename (file)
"Return the name of FILE, same as `f-filename', but inlined."
(declare (pure t) (side-effect-free t))
(inline-quote (file-name-nondirectory (directory-file-name ,file))))
(define-inline treemacs--reject-ignored-files (file)
"Return t if FILE is *not* an ignored file.
FILE here is a list consisting of an absolute path and file attributes."
(declare (side-effect-free t))
(inline-letevals (file)
(inline-quote
(let ((filename (treemacs--filename ,file)))
(--none? (funcall it filename ,file) treemacs-ignored-file-predicates)))))
(define-inline treemacs--reject-ignored-and-dotfiles (file)
"Return t when FILE is neither ignored, nor a dotfile.
FILE here is a list consisting of an absolute path and file attributes."
(declare (side-effect-free t))
(inline-letevals (file)
(inline-quote
(let ((filename (treemacs--filename ,file)))
(and (not (s-matches? treemacs-dotfiles-regex filename))
(--none? (funcall it filename ,file) treemacs-ignored-file-predicates))))))
(defun treemacs--file-extension (filename)
"Same as `file-name-extension', but also works with leading periods.
This is something a of workaround to easily allow assigning icons to a FILENAME
with a name like '.gitignore' without always having to check for both filename
extensions and special names like this."
(declare (side-effect-free t))
(if (string-match treemacs-file-extension-regex filename)
(substring filename (1+ (match-beginning 0)))
filename))
(define-inline treemacs-is-treemacs-window? (window)
"Return t when WINDOW is showing a treemacs buffer."
(declare (side-effect-free t))
(inline-quote
(->> ,window (window-buffer) (buffer-name) (s-starts-with? treemacs--buffer-name-prefix))))
(define-inline treemacs--next-neighbour-of (btn)
"Get the next same-level neighbour of BTN, if any."
(declare (side-effect-free t))
(inline-letevals (btn)
(inline-quote
(-let ((depth (treemacs-button-get ,btn :depth))
(next (next-button (treemacs-button-end ,btn))))
(while (and next (< depth (treemacs-button-get next :depth)))
(setq next (next-button (treemacs-button-end next))))
(when (and next (= depth (treemacs-button-get next :depth))) next)))))
(define-inline treemacs--prev-non-child-button (btn)
"Get the previous same-level neighbour of BTN, if any."
(declare (side-effect-free t))
(inline-letevals (btn)
(inline-quote
(let ((depth (treemacs-button-get ,btn :depth))
(prev (previous-button (treemacs-button-start ,btn))))
(while (and prev (< depth (treemacs-button-get prev :depth)))
(setq prev (previous-button (treemacs-button-start prev))))
(when (and prev (= depth (treemacs-button-get prev :depth))) prev)))))
(define-inline treemacs--next-non-child-button (btn)
"Return the next button after BTN that is not a child of BTN."
(declare (side-effect-free t))
(inline-letevals (btn)
(inline-quote
(when ,btn
(let ((depth (treemacs-button-get ,btn :depth))
(next (next-button (treemacs-button-end ,btn) t)))
(while (and next (< depth (treemacs-button-get next :depth)))
(setq next (next-button (treemacs-button-end next) t)))
next)))))
(define-inline treemacs--on-file-deletion (path &optional no-buffer-delete)
"Cleanup to run when treemacs file at PATH was deleted.
Do not try to delete buffers for PATH when NO-BUFFER-DELETE is non-nil. This is
necessary since interacting with magit can cause file delete events for files
being edited to trigger."
(inline-letevals (path no-buffer-delete)
(inline-quote
(progn
(treemacs--delete-annotation ,path)
(unless ,no-buffer-delete (treemacs--kill-buffers-after-deletion ,path t))
(treemacs--stop-watching ,path t)
;; filewatch mode needs the node's information to be in the dom
(unless (with-no-warnings treemacs-filewatch-mode)
(treemacs-run-in-every-buffer
(treemacs-on-collapse ,path t)))
(when (treemacs--non-simple-git-mode-enabled)
(treemacs-run-in-every-buffer
(treemacs-update-single-file-git-state (treemacs--parent-dir ,path))))))))
(define-inline treemacs--refresh-dir (path &optional project)
"Local refresh for button at PATH and PROJECT.
Simply collapses and re-expands the button (if it has not been closed)."
(inline-letevals (path project)
(inline-quote
(let ((btn (treemacs-goto-file-node ,path ,project)))
(when (memq (treemacs-button-get btn :state) '(dir-node-open file-node-open root-node-open))
(goto-char (treemacs-button-start btn))
(treemacs--push-button btn)
(goto-char (treemacs-button-start btn))
(treemacs--push-button btn))))))
(define-inline treemacs-canonical-path (path)
"The canonical version of PATH for being handled by treemacs.
In practice this means expand PATH and remove its final slash."
(declare (pure t) (side-effect-free t))
(inline-letevals (path)
(inline-quote
(if (file-remote-p ,path)
(treemacs--unslash ,path)
(let (file-name-handler-alist)
(-> ,path (expand-file-name) (treemacs--unslash)))))))
;; TODO(2020/12/28): alias is for backwards compatibility, remove it eventually
(defalias 'treemacs--canonical-path #'treemacs-canonical-path)
(define-inline treemacs-is-file-git-ignored? (file git-info)
"Determined if FILE is ignored by git by means of GIT-INFO."
(declare (side-effect-free t))
(inline-letevals (file git-info)
(inline-quote (eq 'treemacs-git-ignored-face (ht-get ,git-info ,file)))))
(define-inline treemacs-is-treemacs-window-selected? ()
"Return t when the treemacs window is selected."
(declare (side-effect-free t))
(inline-quote (s-starts-with? treemacs--buffer-name-prefix (buffer-name))))
(defun treemacs--reload-buffers-after-rename (old-path new-path)
"Reload buffers and windows after OLD-PATH was renamed to NEW-PATH."
;; first buffers shown in windows
(dolist (frame (frame-list))
(dolist (window (window-list frame))
(let* ((win-buff (window-buffer window))
(buff-file (buffer-file-name win-buff)))
(when buff-file
(setq buff-file (expand-file-name buff-file))
(when (treemacs-is-path buff-file :in old-path)
(treemacs-without-following
(with-selected-window window
(kill-buffer win-buff)
(let ((new-file (s-replace old-path new-path buff-file)))
(find-file-existing new-file)
(treemacs--replace-recentf-entry buff-file new-file)))))))))
;; then the rest
(--each (buffer-list)
(-when-let (buff-file (buffer-file-name it))
(setq buff-file (expand-file-name buff-file))
(when (treemacs-is-path buff-file :in old-path)
(let ((new-file (s-replace old-path new-path buff-file)))
(kill-buffer it)
(find-file-noselect new-file)
(treemacs--replace-recentf-entry buff-file new-file))))))
(defun treemacs-collect-child-nodes (parent-btn)
"Get all buttons exactly one level deeper than PARENT-BTN.
The child buttons are returned in the same order as they appear in the treemacs
buffer."
(let (ret)
(treemacs-first-child-node-where parent-btn
(push child-btn ret)
nil)
(nreverse ret)))
(defalias 'treemacs--get-children-of #'treemacs-collect-child-nodes)
(with-no-warnings
(make-obsolete #'treemacs--get-children-of #'treemacs-collect-child-nodes "v2.7"))
(defun treemacs--init (&optional root name)
"Initialise a treemacs buffer from the current workspace.
Add a project for ROOT and NAME if they are non-nil."
(treemacs--maybe-load-workspaces)
(let ((origin-buffer (current-buffer))
(current-workspace (treemacs-current-workspace))
(run-hook? nil)
(visibility (treemacs-current-visibility)))
(pcase visibility
('visible (treemacs--select-visible-window))
('exists (treemacs--select-not-visible-window))
('none
(treemacs--setup-buffer)
(treemacs-mode)
;; Render the projects even if there are none. This ensures that top-level
;; extensions are always rendered, and the project markers are initialized.
(treemacs--render-projects (treemacs-workspace->projects current-workspace))
(when (treemacs-workspace->is-empty?)
(let* ((path (-> (treemacs--read-first-project-path)
(treemacs-canonical-path)))
(name (treemacs--filename path)))
(treemacs-do-add-project-to-workspace path name)
(treemacs-log "Created first project.")))
(goto-char 2)
(run-hooks 'treemacs-post-buffer-init-hook)
(setf run-hook? t)))
(when root (treemacs-do-add-project-to-workspace (treemacs-canonical-path root) name))
(with-no-warnings (setq treemacs--ready-to-follow t))
(let* ((origin-file (buffer-file-name origin-buffer))
(file-project (treemacs-is-path origin-file :in-workspace)))
(cond
((and (or treemacs-follow-after-init (with-no-warnings treemacs-follow-mode))
file-project)
(treemacs-goto-file-node origin-file file-project))
(treemacs-expand-after-init
(treemacs-toggle-node))))
;; The hook should run at the end of the setup, but also only
;; if a new buffer was created, as the other cases are already covered
;; in their respective setup functions.
(when run-hook? (run-hook-with-args 'treemacs-select-functions visibility))))
(defun treemacs--push-button (btn &optional recursive)
"Execute the appropriate action given the state of the pushed BTN.
Optionally do so in a RECURSIVE fashion."
(pcase (treemacs-button-get btn :state)
('root-node-closed (treemacs--expand-root-node btn))
('dir-node-open (treemacs--collapse-dir-node btn recursive))
('dir-node-closed (treemacs--expand-dir-node btn :recursive recursive))
('file-node-open (treemacs--collapse-file-node btn recursive))
('file-node-closed (treemacs--expand-file-node btn recursive))
('tag-node-open (treemacs--collapse-tag-node btn recursive))
('tag-node-closed (treemacs--expand-tag-node btn recursive))
('tag-node (progn (other-window 1) (treemacs--goto-tag btn)))
(_ (error "[Treemacs] Cannot push button with unknown state '%s'" (treemacs-button-get btn :state)))))
(defun treemacs--nearest-path (btn)
"Return the file path of the BTN.
If the `:path' property is not set or not a file, keep looking upward, via the
`:parent' property. Useful to e.g. find the path of the file of the currently
selected tags or extension entry. Must be called from treemacs buffer."
(let ((path (treemacs-button-get btn :path)))
(if (stringp path)
path
(-some-> (treemacs-button-get btn :parent)
(treemacs--nearest-path)))))
(define-inline treemacs--follow-path-elements (btn items)
"Starting at BTN follow (goto and open) every single element in ITEMS.
Return the button that is found or the symbol `follow-failed' if the search
failed."
(inline-letevals (btn items)
(inline-quote
(cl-block search
(when (treemacs-is-node-collapsed? ,btn)
(goto-char ,btn)
(funcall (cdr (assq (treemacs-button-get ,btn :state) treemacs-TAB-actions-config))))
(while ,items
(let ((item (pop ,items)))
(setq ,btn (treemacs-first-child-node-where ,btn
(equal (treemacs-button-get child-btn :key) item)))
(unless ,btn
(cl-return-from search
'follow-failed))
(goto-char ,btn)
(when (and ,items (treemacs-is-node-collapsed? ,btn))
(funcall (cdr (assq (treemacs-button-get ,btn :state) treemacs-TAB-actions-config))))))
,btn))))
(define-inline treemacs--follow-each-dir (btn dir-parts project)
"Starting at BTN follow (goto and open) every single dir in DIR-PARTS.
Return the button that is found or the symbol `follow-failed' if the search
failed. PROJECT is used for determining whether Git actions are appropriate."
(inline-letevals (btn dir-parts project)
(inline-quote
(let* ((root (treemacs-button-get ,btn :path))
(git-future (treemacs--git-status-process root ,project))
(last-index (- (length ,dir-parts) 1))
(depth (treemacs-button-get ,btn :depth)))
(goto-char ,btn)
;; point is currently on the next closest dir to the followed file we could get
;; from the dom, so we expand it to keep going
(pcase (treemacs-button-get ,btn :state)
('dir-node-closed (treemacs--expand-dir-node ,btn :git-future git-future))
('root-node-closed (treemacs--expand-root-node ,btn)))
(catch 'follow-failed
(let ((index 0)
(dir-part nil))
;; for every item in dir-parts append it to the already found path for a new
;; 'root' to follow, so for root = /x/ and dir-parts = [src, config, foo.el]
;; consecutively try to move to /x/src, /x/src/confg and finally /x/src/config/foo.el
(while ,dir-parts
(setq dir-part (pop ,dir-parts)
root (treemacs-join-path root dir-part)
,btn
(let (current-btn)
(cl-block search
;; first a plain text-based search for the current dir-part string
;; then we grab the node we landed at and see what's going on
;; there's a couple ways this can go
(while (progn (goto-char (line-end-position)) (search-forward dir-part nil :no-error))
(setq current-btn (treemacs-current-button))
(cond
;; somehow we landed on a line where there isn't even anything to look at
;; technically this should never happen, but better safe than sorry
((null current-btn)
(cl-return-from search))
;; the search matched a custom button - skip those, as they cannot match
;; and their :paths are not strings, which would cause the following checks
;; to crash
((treemacs-button-get current-btn :custom))
;; perfect match - return the node we're at
((treemacs-is-path root :same-as (treemacs-button-get current-btn :path))
(cl-return-from search current-btn))
;; perfect match - taking collapsed dirs into account
;; return the node, but make sure to advance the loop variables an
;; appropriate nuber of times, since a collapsed directory is basically
;; multiple search iterations bundled as one
((and (treemacs-button-get current-btn :collapsed)
(treemacs-is-path (treemacs-button-get current-btn :path) :parent-of root))
(dotimes (_ (car (treemacs-button-get current-btn :collapsed)))
(setq root (concat root "/" (pop ,dir-parts)))
(cl-incf index))
(cl-return-from search current-btn))
;; node we're at has a smaller depth than the one we started from
;; that means we overshot our target and there's nothing to be found here
((>= depth (treemacs-button-get current-btn :depth))
(cl-return-from search)))))))
(unless ,btn (throw 'follow-failed 'follow-failed))
(goto-char ,btn)
;; don't open dir at the very end of the list since we only want to put
;; point in its line
(when (and (eq 'dir-node-closed (treemacs-button-get ,btn :state))
(< index last-index))
(treemacs--expand-dir-node ,btn :git-future git-future))
(setq index (1+ index))))
,btn)))))
(defun treemacs--find-custom-top-level-node (path)
"Find the position of the top level extension node at PATH."
(let* ((root-key (cadr path))
;; go back here if the search fails
;; the root key isn't really a project, it's just the :root-key-form
(start (prog1 (point) (goto-char (treemacs-project->position root-key))))
;; making a copy since the variable is a reference to a node actual path
;; and will be changed in-place here
(goto-path (copy-sequence path))
(counter (1- (length goto-path)))
;; manual as in to be expanded manually after we moved to the next closest node we can find
;; in the dom
(manual-parts nil)
(dom-node nil))
;; Try to move as close as possible to the followed node, starting with its immediate parent
;; keep moving upwards in the path we move to until reaching the root of the project. Root of
;; project is met when counter is one, (not zero like with other nodes), since the root path of
;; top-level extensions is of form (:CUSTOM Root-Key), already containing two elements.
(while (and (> counter 1)
(null dom-node))
(setq dom-node (treemacs-find-in-dom goto-path)
counter (1- counter))
(cond
((null dom-node)
(push (nth (1+ counter) goto-path) manual-parts)
(setcdr (nthcdr counter goto-path) nil))
((and dom-node (null (treemacs-dom-node->position dom-node)))
(setq dom-node nil)
(push (nth (1+ counter) goto-path) manual-parts)
(setcdr (nthcdr counter goto-path) nil))))
(let* ((btn (if dom-node
(treemacs-dom-node->position dom-node)
(treemacs-project->position root-key)))
;; do the rest manually
(search-result (if manual-parts
(treemacs--follow-path-elements btn manual-parts)
(goto-char btn))))
(if (eq 'follow-failed search-result)
(prog1 nil
(goto-char start))
search-result))))
(cl-macrolet
((define-find-custom-node (name project-form doc)
`(defun ,name (path)
,doc
(let* (;; go back here if the search fails
(project ,project-form)
(start (prog1 (point) (goto-char (treemacs-project->position project))))
;; making a copy since the variable is a reference to a node actual path
;; and will be changed in-place here
(goto-path (copy-sequence path))
;; manual as in to be expanded manually after we moved to the next closest node we can find
;; in the dom
(manual-parts nil)
(dom-node nil))
;; try to move as close as possible to the followed node, starting with its immediate parent
;; keep moving upwards in the path we move to until reaching the root of the project (counter = 0)
;; all the while collecting the parts of the path that beed manual expanding
(-let [continue t]
(while continue
(setf dom-node (treemacs-find-in-dom goto-path))
(if (or (null dom-node)
;; dom node might exist, but a leaf's position is not always known
(null (treemacs-dom-node->position dom-node)))
(progn
(push (-last-item goto-path) manual-parts)
(setf goto-path (-butlast goto-path))
(unless (cdr goto-path) (setf goto-path (car goto-path))))
(setf continue nil))))
(let* ((btn (--if-let (treemacs-dom-node->position dom-node)
it
(treemacs-project->position project)))
;; do the rest manually
(search-result (if manual-parts (treemacs--follow-path-elements btn manual-parts)
(goto-char btn))))
(if (eq 'follow-failed search-result)
(prog1 nil
(goto-char start))
(treemacs-dom-node->set-position! (treemacs-find-in-dom path) search-result)
search-result))))))
(define-find-custom-node treemacs--find-custom-project-node (pop path)
"Move to the project extension node at PATH.")
(define-find-custom-node treemacs--find-custom-dir-node (treemacs--find-project-for-path (car path))
"Move to the directory extension node at PATH."))
(defun treemacs-find-visible-node (path)
"Find position of node at PATH.
Unlike `treemacs-find-node' this will not expand other nodes in the view, but
only look among those currently visible. The result however is the same: either
a marker pointing to the found node or nil.
Unlike `treemacs-find-node', this function does not go to the node.
PATH: Node Path"
(-when-let (dom-node (treemacs-is-path-visible? path))
(or (treemacs-dom-node->position dom-node)
(save-excursion
(treemacs-find-node path)))))
(defun treemacs-find-node (path &optional project)
"Find position of node identified by PATH under PROJECT in the current buffer.
In spite of the signature this function effectively supports two different
calling conventions.
The first one is for movement towards a node that identifies a normal file. In
this case the signature is applied as is, and this function diverges simply into
`treemacs-goto-file-node'. PATH is a file path string while PROJECT is a
`treemacs-project' struct instance and fully optional, as treemacs is able to
determine which project, if any, a given file belongs to. Providing the project
when it happens to be available is therefore only a small optimisation. If
PROJECT is not given it will be found with `treemacs--find-project-for-path'.
No attempt is made to verify that PATH actually falls under a project in the
workspace. It is assumed that this check has already been made.
The second calling convention deals with custom nodes defined by an extension
for treemacs. In this case the PATH is made up of all the node keys that lead
to the node to be moved to and PROJECT is not used.
Either way this function will return a marker to the moved-to position if it was
successful.
PATH: Filepath | Node Path
PROJECT Project Struct"
(save-excursion
(treemacs-with-path path
:file-action (when (and (eq t treemacs--in-this-buffer)
(file-exists-p path))
(treemacs-find-file-node path project))
:extension-action (treemacs--find-custom-node path))))
(defun treemacs--find-custom-node (path)
"Specialisation to find a custom node at the given PATH."
(let* (;; go back here if the search fails
(start (point))
;; (top-pos (treemacs-dom-node->position (treemacs-find-in-dom (car path))))
;; making a copy since the variable is a reference to a node actual path
;; and will be changed in-place here
(goto-path (if (listp path) (copy-sequence path) (list path)))
;; manual as in to be expanded manually after we moved to the next closest node we can find
;; in the dom
(manual-parts nil)
(dom-node nil))
(-let [continue t]
(while continue
(setf dom-node (treemacs-find-in-dom goto-path))
(if (or (null dom-node)
;; dom node might exist, but a leaf's position is not always known
(null (treemacs-dom-node->position dom-node)))
(if (cdr goto-path)
(progn
(push (-last-item goto-path) manual-parts)
(setf goto-path (-butlast goto-path)))
(setf goto-path (car goto-path)))
(setf continue nil))))
(let* ((btn (treemacs-dom-node->position dom-node))
;; do the rest manually
(search-result (if manual-parts (treemacs--follow-path-elements btn manual-parts)
(goto-char btn))))
(if (eq 'follow-failed search-result)
(prog1 nil
(goto-char start))
(treemacs-dom-node->set-position! (treemacs-find-in-dom path) search-result)
search-result))))
(defun treemacs-goto-node (path &optional project ignore-file-exists)
"Move point to button identified by PATH under PROJECT in the current buffer.
Falls under the same constraints as `treemacs-find-node', but will actually move
point. Will do nothing if file at PATH does not exist, unless
IGNORE-FILE-EXISTS is non-nil.
PATH: Filepath | Node Path
PROJECT Project Struct
IGNORE-FILE-EXISTS Boolean"
(treemacs-with-path path
:file-action (when (or ignore-file-exists (file-exists-p path))
(treemacs-goto-file-node path project))
:extension-action (treemacs-goto-extension-node path)))
(define-inline treemacs-goto-extension-node (path)
"Move to an extension node at the given PATH.
Small short-cut over `treemacs-goto-node' if you know for certain that PATH
leads to an extension node."
(inline-letevals (path)
(inline-quote
(-when-let (result (treemacs--find-custom-node ,path))
(treemacs--evade-image)
(hl-line-highlight)
;; Only change window point if the current buffer is actually visible
(-when-let (window (get-buffer-window))
(set-window-point window (point)))
result))))
(defun treemacs-find-file-node (path &optional project)
"Find position of node identified by PATH under PROJECT in the current buffer.
If PROJECT is not given it will be found with `treemacs--find-project-for-path'.
No attempt is made to verify that PATH falls under a project in the workspace.
It is assumed that this check has already been made.
PATH: File Path
PROJECT: Project Struct"
(unless project (setq project (treemacs--find-project-for-path path)))
(let* (;; go back here if the search fails
(start (prog1 (point) (goto-char (treemacs-project->position project))))
;; the path we're moving to minus the project root
(path-minus-root (->> project (treemacs-project->path) (length) (substring path)))
;; the parts of the path that we can try to go to until we arrive at the project root
(dir-parts (nreverse (s-split "/" path-minus-root :omit-nulls)))
;; the path we try to quickly move to because it's already open and thus in the dom
(goto-path path)
;; manual as in to be expanded manually after we moved to the next closest node we can find
;; in the dom
(manual-parts nil)
(dom-node nil))
;; try to move as close as possible to the followed file, starting with its immediate parent
;; keep moving upwards in the path we move to until reaching the root of the project (counter = 0)
;; all the while collecting the parts of the path that beed manual expanding
(-let [continue t]
(while continue
(setf dom-node (treemacs-find-in-dom goto-path)
goto-path (treemacs--parent goto-path))
(if (or (null dom-node)
;; dom node might exist, but a leaf's position is not always known
(null (treemacs-dom-node->position dom-node)))
(progn
(push (pop dir-parts) manual-parts))
(setf continue nil))))
(let* ((btn (--if-let (treemacs-dom-node->position dom-node)
it
(treemacs-project->position project)))
;; do the rest manually - at least the actual file to move to is still left in manual-parts
(search-result (if manual-parts (save-match-data
(treemacs--follow-each-dir btn manual-parts project))
(goto-char btn))))
(if (eq 'follow-failed search-result)
(prog1 nil
(goto-char start))
(treemacs-dom-node->set-position! (treemacs-find-in-dom path) search-result)
search-result))))
(cl-macrolet
((define-goto (name find-function has-project doc)
`(define-inline ,name (path ,@(when has-project '(&optional project)))
,doc
(inline-letevals (path ,@(when has-project '(project)))
(inline-quote
(-when-let (result (,find-function ,(quote ,path) ,@(when has-project '(,project))))
(treemacs--evade-image)
(hl-line-highlight)
;; Only change window point if the current buffer is actually visible
(-when-let (window (get-buffer-window))
(set-window-point window (point)))
result))))))
(define-goto treemacs-goto-file-node treemacs-find-file-node t
"Move point to button identified by PATH under PROJECT in the current buffer.
Relies on `treemacs-find-file-node', and will also set window-point and ensure
hl-line highlighting.
Called by `treemacs-goto-node' when PATH identifies a file name.
PATH: Filepath
PROJECT: Project Struct")
(define-goto treemacs--goto-custom-top-level-node treemacs--find-custom-top-level-node nil
"Move to the top-level extension node at PATH, returning the button's position.")
(define-goto treemacs--goto-custom-dir-node treemacs--find-custom-dir-node nil
"Move to the directory extension node at PATH, returning the button's position.")
(define-goto treemacs--goto-custom-project-node treemacs--find-custom-project-node nil
"Move to the project extension node at PATH, returning the button's position."))
(defun treemacs--on-window-config-change ()
"Collects all tasks that need to run on a window config change."
(-when-let (w (treemacs-get-local-window))
(treemacs-without-following
(with-selected-window w
;; apparently keeping the hook around can lead to a feeback loop together with helms
;; auto-resize mode as seen in path_to_url
(let (window-configuration-change-hook)
(set-window-parameter w 'no-delete-other-windows treemacs-no-delete-other-windows)
(when treemacs-display-in-side-window
(set-window-parameter w 'window-side treemacs-position)
(set-window-parameter w 'window-slot 0))
(when treemacs-is-never-other-window
(set-window-parameter w 'no-other-window t)))))))
(defun treemacs--set-width (width)
"Set the width of the treemacs buffer to WIDTH."
(unless (one-window-p)
(let ((window-size-fixed)
(w (max width window-safe-min-width)))
(cond
((> (window-width) w)
(shrink-window-horizontally (- (window-width) w)))
((< (window-width) w)
(enlarge-window-horizontally (- w (window-width))))))))
(defun treemacs--filter-files-to-be-shown (files)
"Filter FILES for those files which treemacs should show.
These are the files which return nil for every function in
`treemacs-ignored-file-predicates' and do not match `treemacs-dotfiles-regex'.
The second test not apply if `treemacs-show-hidden-files' is t."
(if treemacs-show-hidden-files
(-filter #'treemacs--reject-ignored-files files)
(-filter #'treemacs--reject-ignored-and-dotfiles files)))
(define-inline treemacs--std-ignore-file-predicate (file _)
"The default predicate to detect ignored files.
Will return t when FILE
1) starts with \".#\" (lockfiles)
2) starts with \"flycheck_\" (flycheck temp files)
3) ends with \"~\" (backup files)
4) is surrounded with \"#\" (auto save files)
5) is \".git\" (see also `treemacs-hide-dot-git-directory')
6) is \".\" or \"..\" (default dirs)"
(declare (side-effect-free t) (pure t))
(inline-letevals (file)
(inline-quote
(let ((last (aref ,file (1- (length ,file)))))
(or (string-prefix-p ".#" ,file)
(and (eq ?# last) (eq ?# (aref ,file 0)))
(eq ?~ last)
(string-equal ,file ".")
(string-equal ,file "..")
(and treemacs-hide-dot-git-directory
(string-equal ,file ".git"))
(string-prefix-p "flycheck_" ,file))))))
(define-inline treemacs--mac-ignore-file-predicate (file _)
"Ignore FILE if it is .DS_Store and .localized.
Will be added to `treemacs-ignored-file-predicates' on Macs."
(declare (side-effect-free t) (pure t))
(inline-letevals (file)
(inline-quote
(or (string-equal ,file ".DS_Store")
(string-equal ,file ".localized")))))
(defun treemacs--popup-window ()
"Pop up a side window and buffer for treemacs."
(let ((buf (treemacs-get-local-buffer-create)))
(display-buffer buf
`(,(if treemacs-display-in-side-window
'display-buffer-in-side-window
'display-buffer-in-direction)
. (;; for buffer in direction
(direction . ,treemacs-position)
(window . root)
;; for side windows
(slot . -1)
(side . ,treemacs-position)
;; general-purpose settings
(window-width . ,treemacs-width)
(dedicated . t))))
(select-window (get-buffer-window buf))))
(defun treemacs--setup-buffer ()
"Create and setup a buffer for treemacs in the right position and size."
(-if-let (lv-buffer (-some->
(--find (string= " *LV*" (buffer-name (window-buffer it)))
(window-list (selected-frame)))
(window-buffer)))
(progn
;; workaround for LV windows like spacemacs' transient states preventing
;; side windows from popping up right
;; see path_to_url
(with-current-buffer lv-buffer (setf window-size-fixed nil))
(treemacs--popup-window)
(with-current-buffer lv-buffer (setf window-size-fixed t)))
(treemacs--popup-window))
(setq-local treemacs--in-this-buffer t))
(define-inline treemacs--parent (path)
"Parent of PATH, or PATH itself if PATH is the root directory.
PATH: Node Path"
(declare (pure t) (side-effect-free t))
(inline-letevals (path)
(inline-quote
(treemacs-with-path ,path
:file-action (treemacs--parent-dir ,path)
:extension-action (-butlast ,path)
:no-match-action (user-error "Path %s appears to be neither a file nor an extension" ,path)))))
(define-inline treemacs--evade-image ()
"The cursor visibly blinks when on top of an icon.
It needs to be moved aside in a way that works for all indent depths and
`treemacs-indentation' settings."
(inline-quote
(when (eq major-mode 'treemacs-mode)
(beginning-of-line)
(when (eq 'image (car-safe (get-text-property (point) 'display)))
(forward-char 1)))))
(defun treemacs--read-first-project-path ()
"Read the first project on start with an empty workspace.
This function is extracted here specifically so that treemacs-projectile can
overwrite it so as to present the project root instead of the current dir as the
first choice."
(when (treemacs-workspace->is-empty?)
(file-truename (read-directory-name "Project root: "))))
(defun treemacs--sort-value-selection ()
"Interactive selection for a new `treemacs-sorting' value.
Returns a cons cell of a descriptive string name and the sorting symbol."
(declare (side-effect-free t))
(let* ((sort-names '(("Sort Alphabetically Ascending" . alphabetic-asc)
("Sort Alphabetically Descending" . alphabetic-desc)
("Sort Alphabetically and Numerically Ascending" . alphabetic-numeric-asc)
("Sort Alphabetically and Numerically Descending" . alphabetic-numeric-desc)
("Sort Case Insensitive Alphabetically Ascending" . alphabetic-case-insensitive-asc)
("Sort Case Insensitive Alphabetically Descending" . alphabetic-case-insensitive-desc)
("Sort Case Insensitive Alphabetically and Numerically Ascending" . alphabetic-numeric-case-insensitive-asc)
("Sort Case Insensitive Alphabetically and Numerically Descending" . alphabetic-numeric-case-insensitive-desc)
("Sort by Size Ascending" . size-asc)
("Sort by Size Descending" . size-desc)
("Sort by Modification Date Ascending" . mod-time-asc)
("Sort by Modification Date Descending" . mod-time-desc)))
(selected-value (completing-read (format "Sort Method (current is %s)" treemacs-sorting)
(-map #'car sort-names))))
(--first (s-equals? (car it) selected-value) sort-names)))
(defun treemacs--kill-buffers-after-deletion (path is-file)
"Clean up after a deleted file or directory.
Just kill the buffer visiting PATH if IS-FILE. Otherwise, go
through the buffer list and kill buffer if PATH is a prefix."
(if is-file
(let ((buf (get-file-buffer path)))
(and buf
(y-or-n-p (format "Kill buffer of %s, too? "
(treemacs--filename path)))
(kill-buffer buf)))
;; Prompt for each buffer visiting a file in directory
(--each (buffer-list)
(and
(treemacs-is-path (buffer-file-name it) :in path)
(y-or-n-p (format "Kill buffer %s in %s, too? "
(buffer-name it)
(treemacs--filename path)))
(kill-buffer it)))
;; Kill all dired buffers in one step
(when (bound-and-true-p dired-buffers)
(-when-let (dired-buffers-for-path
(->> dired-buffers
(--filter (treemacs-is-path (car it) :in path))
(-map #'cdr)))
(and (y-or-n-p (format "Kill Dired buffers of %s, too? "
(treemacs--filename path)))
(-each dired-buffers-for-path #'kill-buffer))))))
(defun treemacs--do-refresh (buffer project)
"Execute the refresh process for BUFFER and PROJECT in that buffer.
Specifically extracted with the buffer to refresh being supplied so that
filewatch mode can refresh multiple buffers at once.
Will refresh every project when PROJECT is \\='all."
(with-current-buffer buffer
(treemacs-save-position
(progn
(treemacs--cancel-refresh-timer)
(run-hook-with-args
'treemacs-pre-refresh-hook
project curr-win-line curr-btn curr-state curr-file curr-node-path)
(if (eq 'all project)
(-each (treemacs-workspace->projects (treemacs-current-workspace)) #'treemacs-project->refresh!)
(treemacs-project->refresh! project)))
(run-hook-with-args
'treemacs-post-refresh-hook
project curr-win-line curr-btn curr-state curr-file curr-node-path)
(unless treemacs-silent-refresh
(treemacs-log "Refresh complete.")))))
(define-inline treemacs-is-node-file-or-dir? (node)
"Return t when NODE is a file or directory."
(inline-letevals (node)
(inline-quote
(memq (treemacs-button-get node :state)
'(file-node-open file-node-closed dir-node-open dir-node-closed)))))
(define-inline treemacs-is-path-visible? (path)
"Return whether a node for PATH is displayed in the current buffer.
Returns the backing dom node is the PATH is visible, nil otherwise.
Morally equivalent to `treemacs-find-in-dom'.
PATH: Node Path"
(declare (side-effect-free t))
(inline-letevals (path)
(inline-quote
(treemacs-find-in-dom ,path))))
(defun treemacs--find-repeated-file-name (path)
"Find a fitting copy name for given file PATH.
Returns a name in the /file/name (Copy 1).ext. If that also already
exists it returns /file/name (Copy 2).ext etc."
(let* ((n 0)
(dir (treemacs--parent-dir path))
(filename (treemacs--filename path))
(filename-no-ext (file-name-sans-extension path))
(ext (--when-let (file-name-extension filename) (concat "." it)))
(template " (Copy %d)")
(new-path path))
(while (file-exists-p new-path)
(cl-incf n)
(setf new-path (treemacs-join-path dir (concat filename-no-ext (format template n) ext))))
new-path))
(defun treemacs--read-string (prompt &optional initial-input)
"Read a string with an interface based on `treemacs-read-string-input'.
PROMPT and INITIAL-INPUT will be passed on to the read function.
PROMPT: String
INITIAL-INPUT: String"
(declare (side-effect-free t))
(pcase treemacs-read-string-input
('from-child-frame (cfrs-read prompt initial-input))
('from-minibuffer (read-string prompt initial-input))
(other (user-error "Unknown read-string-input value: `%s'" other))))
(defun treemacs-join-path (&rest items)
"Join the given ITEMS to a single file PATH."
(declare (side-effect-free t))
(--reduce-from (expand-file-name it acc) "/" items))
(define-inline treemacs-split-path (path)
"Split the given PATH into single items."
(declare (pure t) (side-effect-free t))
(inline-letevals (path)
(inline-quote (split-string ,path "/" :omit-nulls))))
(defun treemacs--jump-to-next-treemacs-window ()
"Jump from the current to the next treemacs-based window.
Will do nothing and return nil if no such window exists, or if there is only one
treemacs window."
(let* ((current-window (selected-window))
(treemacs-windows
(--filter
(buffer-local-value 'treemacs--in-this-buffer (window-buffer it))
(window-list))))
(-when-let (idx (--find-index (equal it current-window) treemacs-windows))
(-let [next-window (nth (% (1+ idx) (length treemacs-windows)) treemacs-windows)]
(unless (eq next-window current-window)
(select-window next-window))))))
(defun treemacs--pre-sorted-list (items)
"Return a lambda that includes sorting metadata for `completing-read'.
Ensures that the order of ITEMS is not changed during completion."
(lambda (string pred action)
(pcase action
('metadata `(metadata (display-sort-function . ,#'identity)))
(_ (complete-with-action action items string pred)))))
(provide 'treemacs-core-utils)
;;; treemacs-core-utils.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-core-utils.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 13,019 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Variations of header-line-format treemacs can use.
;;; Code:
(require 'dash)
(require 'treemacs-faces)
(require 'treemacs-interface)
(eval-when-compile
(require 'treemacs-macros)
(require 'cl-lib))
(cl-macrolet
((make-local-map
(&rest body)
`(-doto (make-sparse-keymap)
(define-key [header-line mouse-1]
(lambda (event)
(interactive "e")
,@body)))))
(defconst treemacs-header-close-button
(propertize
"()"
'local-map (make-local-map (delete-window (posn-window (event-start event))))
'face 'treemacs-header-button-face)
"Header button to close the treemacs window.")
(defconst treemacs-header-projects-button
(propertize
"(P)"
'local-map
(make-local-map
(let* ((menu
(easy-menu-create-menu
nil
`(["Add Project" treemacs-add-project]
["Add Projectile Project" treemacs-projectile :visible (featurep 'treemacs-projectile)]
["Remove Project" treemacs-remove-project-from-workspace])))
(choice (x-popup-menu event menu)))
(when choice (call-interactively (lookup-key menu (apply 'vector choice))))))
'face 'treemacs-header-button-face)
"Header button to open a project administration menu.")
(defconst treemacs-header-workspace-button
(propertize
"(W)"
'local-map
(make-local-map
(let* ((menu
(easy-menu-create-menu
nil
`(["Edit Workspaces" treemacs-edit-workspaces]
["Create Workspace" treemacs-create-workspace]
["Remove Workspace" treemacs-remove-workspace]
["Rename Workspace" treemacs-rename-workspace]
["Switch Workspace" treemacs-switch-workspace]
["Set Fallback Workspace" treemacs-set-fallback-workspace])))
(choice (x-popup-menu event menu)))
(when choice (call-interactively (lookup-key menu (apply 'vector choice))))) )
'face 'treemacs-header-button-face)
"Header button to open a workspace administration menu.")
(defconst treemacs-header-toggles-button
(propertize
"(T)"
'local-map
(make-local-map
(let* ((menu
(easy-menu-create-menu
nil
`([,(format "Dotfile Visibility (Currently %s)"
(if treemacs-show-hidden-files "Enabled" "Disabled"))
treemacs-toggle-show-dotfiles]
[,(format "Follow-Mode (Currently %s)"
(if treemacs-follow-mode "Enabled" "Disabled"))
treemacs-follow-mode]
[,(format "Filewatch-Mode (Currently %s)"
(if treemacs-filewatch-mode "Enabled" "Disabled"))
treemacs-filewatch-mode]
[,(format "Fringe-Indicator-Mode (Currently %s)"
(if treemacs-fringe-indicator-mode "Enabled" "Disabled"))
treemacs-fringe-indicator-mode])))
(choice (x-popup-menu event menu)))
(when choice (call-interactively (lookup-key menu (apply 'vector choice))))) )
'face 'treemacs-header-button-face)
"Header button to open a minor-modes/toggles administration menu."))
(defconst treemacs-header-buttons-format
(concat " " treemacs-header-close-button
" " treemacs-header-projects-button
" " treemacs-header-workspace-button
" " treemacs-header-toggles-button)
"Possible value setting for `treemacs-header-line-format'.
Consists for 4 different buttons:
- `treemacs-header-close-button'
- `treemacs-header-projects-button'
- `treemacs-header-workspace-button'
- `treemacs-header-toggles-button'")
(defun treemacs--header-top-scroll-indicator ()
"Determine header line for `treemacs-indicate-top-scroll-mode'."
(if (= (window-start) (point-min))
(car treemacs-header-scroll-indicators)
(cdr treemacs-header-scroll-indicators)))
;;;###autoload
(define-minor-mode treemacs-indicate-top-scroll-mode
"Minor mode which shows whether treemacs is scrolled all the way to the top.
When this mode is enabled the header line of the treemacs window will display
whether the window's first line is visible or not.
The strings used for the display are determined by
`treemacs-header-scroll-indicators'.
This mode makes use of `treemacs-user-header-line-format' - and thus
`header-line-format' - and is therefore incompatible with other modifications to
these options."
:init-value nil
:global t
:group 'treemacs
(setf treemacs-user-header-line-format
(when treemacs-indicate-top-scroll-mode
'("%e" (:eval (treemacs--header-top-scroll-indicator)))))
(treemacs-run-in-every-buffer
(setf header-line-format treemacs-user-header-line-format)))
(provide 'treemacs-header-line)
;;; treemacs-header-line.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-header-line.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,225 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Handling of visuals in general and icons in particular.
;;; Code:
(require 'image)
(require 'pulse)
(require 'hl-line)
(require 'treemacs-core-utils)
(require 'treemacs-scope)
(require 'treemacs-themes)
(require 'treemacs-icons)
(require 'treemacs-customization)
(require 'treemacs-fringe-indicator)
(require 'treemacs-logging)
(eval-when-compile
(require 'inline)
(require 'treemacs-macros))
(treemacs-import-functions-from "treemacs-icons"
treemacs-get-icon-value)
(defvar-local treemacs--indentation-string-cache-key nil
"Cache key for `treemacs--indentation-string-cache.")
(defvar-local treemacs--indentation-string-cache (vector)
"Cached propertized indentation.")
(defvar treemacs--indent-guide-mode nil)
(defvar treemacs--saved-indent-settings nil
"Saved settings overridden by `treemacs-indent-guide-mode'.
Used to save the values of `treemacs-indentation' and
`treemacs-indentation-string'.")
(defun treemacs--do-pulse (face)
"Visually pulse current line using FACE."
(pulse-momentary-highlight-one-line (point) face)
(advice-add 'pulse-momentary-unhighlight :after #'hl-line-highlight))
(defsubst treemacs-pulse-on-success (&rest log-args)
"Pulse current line with `treemacs-on-success-pulse-face'.
Optionally issue a log statement with LOG-ARGS."
(declare (indent 1))
(when log-args
(treemacs-log (apply #'format log-args)))
(when treemacs-pulse-on-success
(treemacs--do-pulse 'treemacs-on-success-pulse-face)))
(defsubst treemacs-pulse-on-failure (&rest log-args)
"Pulse current line with `treemacs-on-failure-pulse-face'.
Optionally issue a log statement with LOG-ARGS."
(declare (indent 1))
(when log-args
(treemacs-log-failure (apply #'format log-args)))
(when treemacs-pulse-on-failure
(treemacs--do-pulse 'treemacs-on-failure-pulse-face)))
(defun treemacs--build-indentation-cache (depth)
"Rebuild indentation string cache up to DEPTH levels deep."
(setq treemacs--indentation-string-cache
(make-vector (1+ depth) nil)
treemacs--indentation-string-cache-key
(cons treemacs-indentation treemacs-indentation-string))
(dotimes (i (1+ depth))
(aset treemacs--indentation-string-cache i
(cond
((listp treemacs-indentation-string)
(let ((str nil)
(len (length treemacs-indentation-string)))
(dotimes (n i)
(setf str (concat str
(nth (% n len) treemacs-indentation-string))))
str))
((integerp treemacs-indentation)
(s-repeat (* i treemacs-indentation) treemacs-indentation-string))
((not window-system)
(s-repeat (* i 2) treemacs-indentation-string))
(t (propertize " "
'display
`(space . (:width (,(* (car treemacs-indentation)
i))))))))))
(define-inline treemacs--get-indentation (depth)
"Gets an indentation string DEPTH levels deep."
(inline-letevals (depth)
(inline-quote
(progn
(when (or (>= ,depth (length treemacs--indentation-string-cache))
(not (eq (car treemacs--indentation-string-cache-key) treemacs-indentation))
;; Eq is faster than string comparison, and accidentally
;; rebuilding the cache in some corner case is not disastrous.
(not (eq (cdr treemacs--indentation-string-cache-key) treemacs-indentation-string)))
(treemacs--build-indentation-cache ,depth))
(aref treemacs--indentation-string-cache ,depth)))))
(define-minor-mode treemacs-indent-guide-mode
"Toggle `treemacs-indent-guide-mode'.
When enabled treemacs will show simple indent guides for its folder structure.
The effect is achieved by overriding the values of `treemacs-indentation' and
`treemacs-indentation-string'. Disabling the mode will restore the previously
used settings."
:init-value nil
:global t
:lighter nil
:group 'treemacs
(if treemacs-indent-guide-mode
(progn
(setf
treemacs--saved-indent-settings
(cons treemacs-indentation treemacs-indentation-string)
treemacs-indentation 1
treemacs-indentation-string
(pcase-exhaustive treemacs-indent-guide-style
('line (propertize " " 'face 'font-lock-comment-face))
('block (list
" "
(propertize "" 'face 'font-lock-comment-face))))))
(setf treemacs-indentation (car treemacs--saved-indent-settings)
treemacs-indentation-string (cdr treemacs--saved-indent-settings)))
(treemacs-without-messages
(treemacs-run-in-every-buffer
(treemacs--do-refresh (current-buffer) 'all))))
(provide 'treemacs-visuals)
;;; treemacs-visuals.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-visuals.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,257 |
```emacs lisp
;;; treemacs-bookmarks.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Integrates treemacs with bookmark.el.
;; NOTE: This module is lazy-loaded.
;;; Code:
(require 'bookmark)
(require 'dash)
(require 'treemacs-follow-mode)
(require 'treemacs-interface)
(require 'treemacs-scope)
(require 'treemacs-logging)
(require 'treemacs-tags)
(require 'treemacs-workspaces)
(eval-when-compile
(require 'cl-lib)
(require 'treemacs-macros))
(treemacs-import-functions-from "treemacs"
treemacs-select-window)
;;;###autoload
(defun treemacs-bookmark (&optional arg)
"Find a bookmark in treemacs.
Only bookmarks marking either a file or a directory are offered for selection.
Treemacs will try to find and focus the given bookmark's location, in a similar
fashion to `treemacs-find-file'.
With a prefix argument ARG treemacs will also open the bookmarked location."
(interactive "P")
(treemacs-block
(bookmark-maybe-load-default-file)
(-let [bookmarks
(cl-loop
for b in bookmark-alist
for name = (car b)
for location = (treemacs-canonical-path (bookmark-location b))
when (or (file-regular-p location) (file-directory-p location))
collect (propertize name 'location location))]
(treemacs-error-return-if (null bookmarks)
"Didn't find any bookmarks pointing to files.")
(let* ((bookmark (completing-read "Bookmark: " bookmarks))
(location (treemacs-canonical-path (get-text-property 0 'location (--first (string= it bookmark) bookmarks))))
(dir (if (file-directory-p location) location (treemacs--parent-dir location)))
(project (treemacs--find-project-for-path dir)))
(treemacs-error-return-if (null project)
"Bookmark at %s does not fall under any project in the workspace."
(propertize location 'face 'font-lock-string-face))
(pcase (treemacs-current-visibility)
('visible (treemacs--select-visible-window))
('exists (treemacs--select-not-visible-window))
('none (treemacs--init)))
(treemacs-goto-file-node location project)
(treemacs-pulse-on-success)
(when arg (treemacs-visit-node-no-split))))))
;;;###autoload
(defun treemacs--bookmark-handler (record)
"Open Treemacs into a bookmark RECORD."
(let ((path (bookmark-prop-get record 'treemacs-bookmark-path)))
(unless path
;; Don't rely on treemacs-pulse-on-failure to display the error, since the
;; error must be handled in bookmark.el.
(user-error "Treemacs--bookmark-handler invoked for a non-Treemacs bookmark"))
(treemacs-select-window)
;; XXX temporary workaround for incorrect move to a saved tag node
;; must be fixed after tags were rewritten in new extension api
(if (and (listp path)
(stringp (car path))
(file-regular-p (car path)))
(treemacs-goto-node (car path))
(treemacs-goto-node path))
;; If the user has bookmarked a directory, they probably want to operate on
;; its contents. Expand it, and select the first child.
(treemacs-with-current-button
"Could not select the current bookmark"
(when (eq (treemacs-button-get current-btn :state) 'dir-node-closed)
(treemacs-TAB-action))
(when (eq (treemacs-button-get current-btn :state) 'dir-node-open)
(let ((depth (treemacs-button-get current-btn :depth))
(next-button (next-button current-btn)))
(when (and next-button (> (treemacs-button-get next-button :depth) depth))
(treemacs-next-line 1)))))))
(defun treemacs--format-bookmark-title (btn)
"Format the bookmark title for BTN with `treemacs-bookmark-title-template'."
(s-format
treemacs-bookmark-title-template
(lambda (pattern)
(or
(cond
;; ${label} - Label of the current button
((string= pattern "label")
(treemacs--get-label-of btn))
;; ${label:1} - Label of Nth parent
((s-starts-with? "label:" pattern)
(let ((depth (string-to-number (s-chop-prefix "label:" pattern)))
(current-button btn))
(dotimes (_ depth)
(setq current-button (when current-button (treemacs-button-get current-button :parent))))
(when current-button
(treemacs--get-label-of current-button))))
;; ${label-path} and ${label-path:4} - Path of labels, optionally limited by a number.
((or (string= pattern "label-path") (s-starts-with? "label-path:" pattern))
(let ((depth (when (s-starts-with? "label-path:" pattern)
(string-to-number (s-chop-prefix "label-path:" pattern))))
(current-button btn)
(path))
(while (and current-button (not (eq 0 depth)))
(push (treemacs--get-label-of current-button) path)
(when depth (cl-decf depth))
(setq current-button (treemacs-button-get current-button :parent)))
(s-join "/" path)))
;; ${project} - Label of the project or top-level extension node.
((string= pattern "project")
;; Find the root button by iterating - don't use `treemacs-project-of-node`
;; to make this work for variadic top-level extensions.
(let ((current-button btn))
(while (> (treemacs-button-get current-button :depth) 0)
(setq current-button (treemacs-button-get current-button :parent)))
(treemacs--get-label-of current-button)))
;; ${file-path} - Filesystem path.
((string= pattern "file-path")
(treemacs--nearest-path btn))
;; ${file-path:3} - N components of the file path
((s-starts-with? "file-path:" pattern)
(let ((n (string-to-number (s-chop-prefix "file-path:" pattern))))
(-when-let (path (treemacs--nearest-path btn))
(let ((components (last (s-split "/" path) (1+ n))))
;; Add the leading slash for absolute paths
(when (and (> (length components) n) (not (string= "" (car components))))
(pop components))
(s-join "/" components)))))
(t
;; Don't rely on treemacs-pulse-on-failure to display the error, since the
;; error must be handled in bookmark.el.
(treemacs-pulse-on-failure)
(user-error "Bookmark template pattern %s was not recognized" pattern)))
""))))
(defun treemacs--make-bookmark-record ()
"Make a bookmark record for the current Treemacs button.
This function is installed as the `bookmark-make-record-function'."
(treemacs-unless-let (current-btn (treemacs-current-button))
(progn
;; Don't rely on treemacs-pulse-on-failure to display the error, since the
;; error must be handled in bookmark.el.
(treemacs-pulse-on-failure)
(user-error "Nothing to bookmark here"))
(let* ((path (treemacs-button-get current-btn :path)))
(unless path
(treemacs-pulse-on-failure)
(user-error "Could not find the path of the current button"))
`((defaults . (,(treemacs--format-bookmark-title current-btn)))
(treemacs-bookmark-path . ,path)
(handler . treemacs--bookmark-handler)
,@(when (stringp path) `((filename . ,path)))))))
;;;###autoload
(defun treemacs-add-bookmark ()
"Add the current node to Emacs' list of bookmarks.
For file and directory nodes their absolute path is saved. Tag nodes
additionally also save the tag's position. A tag can only be bookmarked if the
treemacs node is pointing to a valid buffer position."
(interactive)
(treemacs-with-current-button
"There is nothing to bookmark here."
(pcase (treemacs-button-get current-btn :state)
((or 'file-node-open 'file-node-closed 'dir-node-open 'dir-node-closed)
(-let [name (treemacs--read-string "Bookmark name: ")]
(bookmark-store name `((filename . ,(treemacs-button-get current-btn :path))) nil)))
('tag-node
(-let [(tag-buffer . tag-pos)
(treemacs--extract-position (treemacs-button-get current-btn :marker) nil)]
(if (buffer-live-p tag-buffer)
(bookmark-store
(treemacs--read-string "Bookmark name: ")
`((filename . ,(buffer-file-name tag-buffer))
(position . ,tag-pos))
nil)
(treemacs-log-failure "Tag info can not be saved because it is not pointing to a live buffer."))))
((or 'tag-node-open 'tag-node-closed)
(treemacs-pulse-on-failure "There is nothing to bookmark here.")))))
(provide 'treemacs-bookmarks)
;;; treemacs-bookmarks.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-bookmarks.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 2,127 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Code for adding, removing, and displaying "annotations" for treemacs'
;; nodes. As of now only suffix annotations in extensions are implemented.
;;; Code:
(require 'ht)
(require 'dash)
(require 'treemacs-async)
(require 'treemacs-core-utils)
(require 'treemacs-workspaces)
(require 'treemacs-async)
(eval-when-compile
(require 'treemacs-macros)
(require 'inline)
(require 'cl-lib))
(eval-when-compile
(cl-declaim (optimize (speed 3) (safety 0))))
(defconst treemacs--annotation-store (make-hash-table :size 200 :test 'equal))
;; TODO(2022/02/23): clear on file delete
(cl-defstruct (treemacs-annotation
(:conc-name treemacs-annotation->)
(:constructor treemacs-annotation->create!)
(:copier nil))
suffix
suffix-value
git-face
face
face-value)
(define-inline treemacs-get-annotation (path)
"Get annotation data for the given PATH.
Will return nil if no annotations exists.
PATH: Node Path"
(declare (side-effect-free t))
(inline-letevals (path)
(inline-quote
(ht-get treemacs--annotation-store ,path))))
(define-inline treemacs--remove-annotation-if-empty (ann path)
"Remove annotation ANN for PATH from the store if it is empty."
(inline-letevals (ann path)
(inline-quote
(when (and (null (treemacs-annotation->face ,ann))
(null (treemacs-annotation->git-face ,ann))
(null (treemacs-annotation->suffix ,ann)))
(ht-remove! treemacs--annotation-store ,path)))))
(define-inline treemacs--delete-annotation (path)
"Complete delete annotation information for PATH."
(inline-letevals (path)
(inline-quote
(ht-remove! treemacs--annotation-store ,path))))
;;; Faces
(define-inline treemacs-set-annotation-face (path face source)
"Annotate PATH with the given FACE.
Will save the FACE as coming from SOURCE so it can be combined with faces coming
from other sources.
Source must be a *string* so that multiple face annotations on the same node can
be sorted to always be applied in the same order, regardless of when they were
added.
PATH: Node Path
FACE: Face
SOURCE: String"
(inline-letevals (source path face)
(inline-quote
(-if-let* ((ann (treemacs-get-annotation ,path)))
(let* ((face-list (treemacs-annotation->face ann))
(old-face (--first (string= ,source (car it)) face-list)))
(if old-face
(setcdr old-face ,face)
(setf (treemacs-annotation->face ann)
(--sort (string< (car it) (car other))
(cons (cons ,source ,face) face-list))))
(setf (treemacs-annotation->face-value ann)
(append (mapcar #'cdr (treemacs-annotation->face ann))
(treemacs-annotation->git-face ann))))
(ht-set! treemacs--annotation-store ,path
(treemacs-annotation->create!
:face (list (cons ,source ,face))
:face-value (list ,face)))))))
(define-inline treemacs-remove-annotation-face (path source)
"Remove PATH's face annotation for the given SOURCE.
PATH: Node Path
SOURCE: String"
(inline-letevals (path source)
(inline-quote
(-when-let (ann (treemacs-get-annotation ,path))
(let* ((git-face (treemacs-annotation->git-face ann))
(old-faces (treemacs-annotation->face ann))
(new-faces (--reject-first
(string= ,source (car it))
old-faces)))
(if new-faces
(setf
(treemacs-annotation->face ann)
new-faces
(treemacs-annotation->face-value ann)
(append (mapcar #'cdr new-faces) git-face))
(setf
(treemacs-annotation->face ann) nil
(treemacs-annotation->face-value ann) git-face)))))))
(defun treemacs-clear-annotation-faces (source)
"Remove all face annotations of the given SOURCE."
(treemacs--maphash treemacs--annotation-store (path ann)
(-when-let (face-list (treemacs-annotation->face ann))
(setf
(treemacs-annotation->face ann)
(--reject-first (string= source (car it)) face-list)
(treemacs-annotation->face-value ann)
(append
(mapcar #'cdr (treemacs-annotation->face ann))
(treemacs-annotation->git-face ann)))
(treemacs--remove-annotation-if-empty ann path))))
;; Suffixes
(define-inline treemacs-set-annotation-suffix (path suffix source)
"Annotate PATH with the given SUFFIX.
Will save the SUFFIX as coming from SOURCE so it can be combined with suffixes
coming from other sources.
Source must be a *string* so that multiple suffix annotations on the same node
can be sorted to always appear in the same order, regardless of when they were
added.
Treemacs does not prescribe using a specific face for suffix annotations, users
of this api can propertize suffixes as they see fit.
PATH: Node Path
SUFFIX: String
SOURCE: String"
(inline-letevals (source path suffix)
(inline-quote
(progn
(put-text-property 0 (length ,suffix) 'treemacs-suffix-annotation t ,suffix)
(-if-let (ann (treemacs-get-annotation ,path))
(let* ((suffix-list (treemacs-annotation->suffix ann))
(old-suffix (--first (string= ,source (car it)) suffix-list)))
(if old-suffix
(setcdr old-suffix ,suffix)
(setf (treemacs-annotation->suffix ann)
(--sort (string< (car it) (car other))
(cons (cons ,source ,suffix) suffix-list))))
(setf (treemacs-annotation->suffix-value ann)
(mapconcat #'identity (mapcar #'cdr (treemacs-annotation->suffix ann)) " ")))
(ht-set! treemacs--annotation-store ,path
(treemacs-annotation->create!
:suffix (list (cons ,source ,suffix))
:suffix-value ,suffix)))))))
(define-inline treemacs-remove-annotation-suffix (path source)
"Remove PATH's suffix annotation for the given SOURCE.
PATH: Node Path
SOURCE: String"
(inline-letevals (path source)
(inline-quote
(-when-let (ann (treemacs-get-annotation ,path))
(let* ((old-suffixes (treemacs-annotation->suffix ann))
(new-suffixes (--reject-first
(string= ,source (car it))
old-suffixes)))
(if new-suffixes
(setf
(treemacs-annotation->suffix ann)
new-suffixes
(treemacs-annotation->suffix-value ann)
(mapconcat #'identity (mapcar #'cdr (treemacs-annotation->suffix ann)) " "))
(setf
(treemacs-annotation->suffix ann) nil
(treemacs-annotation->suffix-value ann) nil)))))))
(defun treemacs-clear-annotation-suffixes (source)
"Remove all suffix annotations of the given SOURCE."
(treemacs--maphash treemacs--annotation-store (path ann)
(-when-let (suffix-list (treemacs-annotation->suffix ann))
(setf
(treemacs-annotation->suffix ann)
(--reject-first (string= source (car it)) suffix-list)
(treemacs-annotation->suffix-value ann)
(mapconcat #'identity (mapcar #'cdr (treemacs-annotation->suffix ann)) " "))
(treemacs--remove-annotation-if-empty ann path))))
(defun treemacs--apply-annotations-deferred (btn path buffer git-future)
"Deferred application for annotations for BTN and PATH.
Runs on a timer after BTN was expanded and will apply annotations for all of
BTN's *immediate* children.
Change will happen in BUFFER, given that it is alive.
GIT-FUTURE is only awaited when `deferred' git-mode is used.
BTN: Button
PATH: Node Path
BUFFER: Buffer
GIT-FUTURE: Pfuture"
(when (eq 'deferred treemacs--git-mode)
(ht-set! treemacs--git-cache path
(treemacs--get-or-parse-git-result git-future)))
(when (buffer-live-p buffer)
(with-current-buffer buffer
(save-excursion
(treemacs-with-writable-buffer
(let* ((depth (1+ (treemacs-button-get btn :depth)))
(git-info (or (ht-get treemacs--git-cache (treemacs-button-get btn :key))
treemacs--empty-table)))
;; the depth check ensures that we only iterate over the nodes that
;; are below parent-btn and stop when we've moved on to nodes that
;; are above or belong to the next project
(while (and (setq btn (next-button btn))
(>= (treemacs-button-get btn :depth) depth))
(when (= depth (treemacs-button-get btn :depth))
(treemacs--do-apply-annotation
btn
(ht-get git-info (treemacs-button-get btn :key)))))))))))
(define-inline treemacs--do-apply-annotation (btn git-face)
"Apply a single BTN's annotations.
GIT-FACE is taken from the latest git cache, or nil if it's not known."
(inline-letevals (btn git-face)
(inline-quote
(let* ((path (treemacs-button-get ,btn :path))
(ann (treemacs-get-annotation path))
(btn-start (treemacs-button-start ,btn))
(btn-end (treemacs-button-end ,btn)))
(if (null ann)
;; No annotation - just put git face
(when ,git-face
(put-text-property btn-start btn-end 'face ,git-face)
;; git face must be known for initial render
(ht-set!
treemacs--annotation-store
path
(treemacs-annotation->create!
:git-face ,git-face
:face-value ,git-face)))
(let ((face-value (treemacs-annotation->face-value ann))
(suffix-value (treemacs-annotation->suffix-value ann))
(faces (treemacs-annotation->face ann))
(old-git-face (treemacs-annotation->git-face ann)))
;; Faces
;; annotations are present, value needs updating if the git face
;; has changed
(let ((new-face-value
(or
(cond
((and ,git-face (not (equal ,git-face old-git-face)))
(append (mapcar #'cdr faces)
(list ,git-face)))
((and old-git-face (null ,git-face))
(mapcar #'cdr faces))
(t face-value))
(treemacs-button-get ,btn :default-face))))
(setf (treemacs-annotation->face-value ann)
new-face-value
(treemacs-annotation->git-face ann)
,git-face)
(put-text-property
btn-start btn-end 'face
new-face-value))
;; Suffix
(goto-char ,btn)
(goto-char (or (next-single-property-change
,btn
'treemacs-suffix-annotation
(current-buffer)
(line-end-position))
btn-end))
(delete-region (point) (line-end-position))
(when suffix-value (insert suffix-value))))))))
(defun treemacs-apply-single-annotation (path)
"Apply annotations for a single node at given PATH in all treemacs buffers."
(treemacs-run-in-all-derived-buffers
(-when-let (btn (treemacs-find-node path))
(treemacs-with-writable-buffer
(save-excursion
(treemacs--do-apply-annotation
btn
(-when-let (git-cache
(->> path
(treemacs--parent-dir)
(ht-get treemacs--git-cache)))
(ht-get git-cache path))))))))
(defun treemacs-apply-annotations-in-buffer (buffer)
"Apply annotations for all nodes in the given BUFFER."
(when (buffer-live-p buffer)
(with-current-buffer buffer
(treemacs-with-writable-buffer
(save-excursion
(goto-char (point-min))
(let* ((btn (point)))
(while (setf btn (next-button btn))
(let ((path (treemacs-button-get btn :path))
(use-git (not (treemacs-button-get btn :no-git))))
(treemacs--do-apply-annotation
btn
(-when-let (git-cache
(and use-git
(->> path
(treemacs--parent-dir)
(ht-get treemacs--git-cache))))
(ht-get git-cache path)))))))))))
(defun treemacs-apply-annotations (path)
"Apply annotations for all nodes under the given PATH.
PATH: Node Path"
(treemacs-run-in-all-derived-buffers
(treemacs-with-writable-buffer
(save-excursion
(goto-char (treemacs-find-node path))
(let ((git-info (ht-get treemacs--git-cache path treemacs--empty-table))
(btn (point)))
(treemacs--do-apply-annotation
btn
(ht-get git-info (treemacs-button-get btn :key)))
(while (and (setf btn (next-button btn))
(/= 0 (treemacs-button-get btn :depth)))
(-let [parent-path (treemacs-button-get
(treemacs-button-get btn :parent)
:key)]
(treemacs--do-apply-annotation
btn
(ht-get
(ht-get treemacs--git-cache parent-path git-info)
(treemacs-button-get btn :key))))))))))
(provide 'treemacs-annotations)
;;; treemacs-annotations.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-annotations.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 3,249 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Most of everything related to icons is handled here. Specifically
;; the definition, instantiation, customization, resizing and
;; resetting of icons.
;;; Code:
(require 'image)
(require 'dash)
(require 's)
(require 'ht)
(require 'treemacs-themes)
(require 'treemacs-logging)
(require 'treemacs-scope)
(eval-when-compile
(require 'cl-lib)
(require 'inline)
(require 'treemacs-macros))
(define-inline treemacs--set-img-property (image property value)
"Set IMAGE's PROPERTY to VALUE."
;; the emacs26 code where this is copied from says it's for internal
;; use only - let's se how that goes
(inline-letevals (image property value)
(inline-quote
(progn
(plist-put (cdr ,image) ,property ,value)
,value))))
(define-inline treemacs--get-img-property (image property)
"Return the value of PROPERTY in IMAGE."
;; code aken from emacs 26
(declare (side-effect-free t))
(inline-letevals (image property)
(inline-quote
(plist-get (cdr ,image) ,property))))
(gv-define-setter treemacs--get-img-property (val img prop)
`(plist-put (cdr ,img) ,prop ,val))
(defmacro treemacs-get-icon-value (ext &optional tui theme)
"Get the value of an icon for extension EXT.
If TUI is non-nil the terminal fallback value is returned.
THEME is the name of the theme to look in. Will cause an error if the theme
does not exist."
`(let* ((theme ,(if theme
`(treemacs--find-theme ,theme)
`(treemacs-current-theme)))
(icons ,(if tui
`(treemacs-theme->tui-icons theme)
`(treemacs-theme->gui-icons theme))))
(ht-get icons ,ext)))
(define-inline treemacs--get-local-face-background (face)
"Get the `:background' of the given face.
Unlike `face-attribute' this will take the `faces-remapping-alist' into
account."
(declare (side-effect-free t))
(inline-letevals (face)
(inline-quote
(--if-let (car (alist-get ,face face-remapping-alist))
(plist-get it :background)
(face-attribute ,face :background nil t)))))
(define-inline treemacs--is-image-creation-impossible? ()
"Will return non-nil when Emacs is unable to create images.
In this scenario (usually caused by running Emacs without a graphical
environment) treemacs will not create any of its icons and will be forced to
permanently use its simple string icon fallback."
(declare (pure t) (side-effect-free t))
(inline-quote (not (image-type-available-p 'png))))
(define-inline treemacs--should-use-tui-icons? ()
"Determines whether the current buffer must use TUI instead of GUI icons."
(declare (side-effect-free t))
(inline-quote
(or (treemacs--is-image-creation-impossible?)
treemacs-no-png-images
(not (window-system)))))
(defvar treemacs-icons nil
"Currently used icons.
Aliased to the current theme's gui or tui icons.")
(defvar treemacs--icon-symbols nil
"List of icons with variables.
Every symbol S maps to a variable named \"treemacs-icons-S\". In addition S is
also the key for the icon in both `treemacs-gui-icons' and `treemacs-tui-icons'.
This combination allows these icons-with-variables to be correctly changed in
`treemacs--select-icon-set'.")
(defvar treemacs--icon-size 22
"Size in pixels icons will be resized to.
See also `treemacs-resize-icons'.")
(defvar treemacs--icon-vars nil
"List of all icons assigned to variables.")
(defmacro treemacs--root-icon-size-adjust (width height)
"Special adjust for the WIDTH and HEIGHT of an icon.
Necessary since root icons are not rectangular."
`(let ((w (round (* ,width 0.9090)))
(h (round (* ,height 1.1818))))
(setq ,width w ,height h)))
(defun treemacs--create-image (file-path)
"Load image from FILE-PATH and size it based on `treemacs--icon-size'."
(let ((height treemacs--icon-size)
(width treemacs--icon-size))
(when (and (integerp treemacs--icon-size)
(s-starts-with? "root-" file-path))
(treemacs--root-icon-size-adjust width height))
(if (and (integerp treemacs--icon-size) (image-type-available-p 'imagemagick))
(create-image
file-path 'imagemagick nil
:ascent 'center
:width width
:height height
:mask 'heuristic)
(create-image
file-path
(intern (treemacs--file-extension (treemacs--filename file-path)))
nil
:ascent 'center
:width width
:height height
:mask 'heuristic))))
(defun treemacs--create-icon-strings (file fallback)
"Create propertized icon strings for a given FILE image and TUI FALLBACK."
(let ((tui-icon fallback)
(gui-icon
(if (treemacs--is-image-creation-impossible?)
fallback
(concat (propertize
" "
'display (treemacs--create-image file))
" "))))
(cons gui-icon tui-icon)))
(defmacro treemacs--splice-icon (icon)
"Splice the given ICON data depending on whether it is a value or an sexp."
(if (listp icon)
`(progn ,@icon)
`(progn ,icon)))
(cl-defmacro treemacs-create-icon (&key file icon (fallback " ") icons-dir extensions)
"Create an icon for the current theme.
- FILE is a file path relative to the icon directory of the current theme.
- ICON is a string of an already created icon. Mutually exclusive with FILE.
- FALLBACK is the fallback string for situations where png images are
unavailable. Can be set to `same-as-icon' to use the same value as ICON.
- ICONS-DIR can optionally be used to overwrite the path used to find icons.
Normally the current theme's icon-path is used, but it may be convenient to
use another when calling `treemacs-modify-theme'.
- EXTENSIONS is a list of file extensions the icon should be used for.
Note that treemacs has a loose understanding of what constitutes an extension:
it's either the text past the last period or the entire filename, so names
like \".gitignore\" and \"Makefile\" can be matched as well.
An extension may also be a symbol instead of a string. In this case treemacs
will also create a variable named \"treemacs-icon-%s\" making it universally
accessible."
(treemacs-static-assert (or (null icon) (null file))
"FILE and ICON arguments are mutually exclusive")
(when (and (consp extensions) (or (symbolp (car extensions))
(stringp (car extensions))))
(setf extensions `(quote (,@extensions))))
`(let* ((xs (--map (if (stringp it) (downcase it) it) ,extensions))
(fallback ,(if (equal fallback (quote 'same-as-icon))
icon
fallback))
(icons-dir ,(if icons-dir icons-dir `(treemacs-theme->path treemacs--current-theme)))
(icon-path ,(if file `(treemacs-join-path icons-dir ,file) nil))
(icon-pair ,(if file `(treemacs--create-icon-strings icon-path fallback)
`(cons ,(treemacs--splice-icon icon) fallback)))
(gui-icons (treemacs-theme->gui-icons treemacs--current-theme))
(tui-icons (treemacs-theme->tui-icons treemacs--current-theme))
(gui-icon (car icon-pair))
(tui-icon (cdr icon-pair)))
,(unless file
`(progn
(ignore icon-path)
(ignore icons-dir)))
;; prefer to have icons as empty strings with a display property for compatibility
;; in e.g. dired, where an actual text icon would break `dired-goto-file-1'
(unless (get-text-property 0 'display gui-icon)
(setf gui-icon (propertize " " 'display gui-icon)))
(dolist (ext xs)
(when (symbolp ext)
(-let [symbol (intern (format "treemacs-icon-%s" ext))]
(add-to-list 'treemacs--icon-symbols ext)
(set symbol nil))))
(--each xs
;; NOTE: Disable creation of GUI svg icons without getting in the way of the rest
;; of the icon creation process. This is good enough a workaround for Emacs versions
;; that don't support svg images for as long as svg icons are a minority.
(unless (and ,file
(not (image-type-available-p 'svg))
(string= (treemacs--file-extension ,file) "svg"))
(ht-set! gui-icons it gui-icon))
(ht-set! tui-icons it tui-icon))))
(treemacs-create-theme "Default"
:icon-directory (treemacs-join-path treemacs-dir "icons/default")
:config
(progn
;; directory and other icons
(treemacs-create-icon :file "vsc/root-closed.png" :extensions (root-closed) :fallback "")
(treemacs-create-icon :file "vsc/root-open.png" :extensions (root-open) :fallback "")
(treemacs-create-icon :file "vsc/dir-closed.png" :extensions (dir-closed) :fallback (propertize "+ " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "vsc/dir-open.png" :extensions (dir-open) :fallback (propertize "- " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "tags-leaf.png" :extensions (tag-leaf) :fallback (propertize " " 'face 'font-lock-constant-face))
(treemacs-create-icon :file "tags-open.png" :extensions (tag-open) :fallback (propertize " " 'face 'font-lock-string-face))
(treemacs-create-icon :file "tags-closed.png" :extensions (tag-closed) :fallback (propertize " " 'face 'font-lock-string-face))
(treemacs-create-icon :file "error.png" :extensions (error) :fallback (propertize " " 'face 'font-lock-string-face))
(treemacs-create-icon :file "warning.png" :extensions (warning) :fallback (propertize " " 'face 'font-lock-string-face))
(treemacs-create-icon :file "info.png" :extensions (info) :fallback (propertize " " 'face 'font-lock-string-face))
(treemacs-create-icon :file "bookmark.png" :extensions (bookmark) :fallback " ")
(treemacs-create-icon :file "svgrepo/screen.png" :extensions (screen) :fallback " ")
(treemacs-create-icon :file "svgrepo/house.png" :extensions (house) :fallback " ")
(treemacs-create-icon :file "svgrepo/list.png" :extensions (list) :fallback " ")
(treemacs-create-icon :file "svgrepo/repeat.png" :extensions (repeat) :fallback " ")
(treemacs-create-icon :file "svgrepo/suitcase.png" :extensions (suitcase) :fallback " ")
(treemacs-create-icon :file "svgrepo/close.png" :extensions (close) :fallback " ")
(treemacs-create-icon :file "svgrepo/cal.png" :extensions (calendar) :fallback " ")
(treemacs-create-icon :file "svgrepo/briefcase.png" :extensions (briefcase) :fallback " ")
(treemacs-create-icon :file "svgrepo/mail.png" :extensions (mail) :fallback " ")
(treemacs-create-icon :file "svgrepo/mail-plus.png" :extensions (mail-plus) :fallback " ")
(treemacs-create-icon :file "svgrepo/inbox.png" :extensions (inbox) :fallback " ")
;; custom dir icons
(treemacs-create-icon :file "svgrepo/dir-src-closed.png" :extensions ("src-closed") :fallback (propertize "+ " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "svgrepo/dir-src-open.png" :extensions ("src-open") :fallback (propertize "- " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "svgrepo/dir-test-closed.png" :extensions ("test-closed") :fallback (propertize "+ " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "svgrepo/dir-test-open.png" :extensions ("test-open") :fallback (propertize "- " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "vsc/dir-binary-closed.png" :extensions ("bin-closed") :fallback (propertize "+ " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "vsc/dir-binary-open.png" :extensions ("bin-open") :fallback (propertize "- " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "vsc/dir-services-closed.png" :extensions ("build-closed") :fallback (propertize "+ " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "vsc/dir-services-open.png" :extensions ("build-open") :fallback (propertize "- " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "svgrepo/dir-git-closed.png" :extensions ("git-closed") :fallback (propertize "+ " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "svgrepo/dir-git-open.png" :extensions ("git-open") :fallback (propertize "- " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "vsc/dir-github-closed.png" :extensions ("github-closed") :fallback (propertize "+ " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "vsc/dir-github-open.png" :extensions ("github-open") :fallback (propertize "- " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "vsc/dir-public-closed.png" :extensions ("public-closed") :fallback (propertize "+ " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "vsc/dir-public-open.png" :extensions ("public-open") :fallback (propertize "- " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "vsc/dir-private-closed.png" :extensions ("private-closed") :fallback (propertize "+ " 'face 'treemacs-term-node-face))
(treemacs-create-icon :file "vsc/dir-private-open.png" :extensions ("private-open") :fallback (propertize "- " 'face 'treemacs-term-node-face))
(treemacs-create-icon
:file "vsc/dir-temp-closed.png" :extensions ("temp-closed" "tmp-closed")
:fallback (propertize "+ " 'face 'treemacs-term-node-face))
(treemacs-create-icon
:file "vsc/dir-temp-open.png" :extensions ("temp-open" "tmp-open")
:fallback (propertize "- " 'face 'treemacs-term-node-face))
(treemacs-create-icon
:file "vsc/dir-docs-closed.png" :extensions ("readme-closed" "docs-closed")
:fallback (propertize "+ " 'face 'treemacs-term-node-face))
(treemacs-create-icon
:file "vsc/dir-docs-open.png" :extensions ("readme-open" "docs-open")
:fallback (propertize "- " 'face 'treemacs-term-node-face))
(treemacs-create-icon
:file "vsc/dir-images-closed.png" :extensions ("screenshots-closed" "icons-closed")
:fallback (propertize "+ " 'face 'treemacs-term-node-face))
(treemacs-create-icon
:file "vsc/dir-images-open.png" :extensions ("screenshots-open" "icons-open")
:fallback (propertize "- " 'face 'treemacs-term-node-face))
;; file icons
(treemacs-create-icon :file "txt.png" :extensions (fallback))
(treemacs-create-icon :file "emacs.png" :extensions ("el" "elc" "eln"))
(treemacs-create-icon :file "ledger.png" :extensions ("ledger" "beancount"))
(treemacs-create-icon :file "yaml.png" :extensions ("yml" "yaml" "travis.yml"))
(treemacs-create-icon
:file "shell.png"
:extensions ("sh" "zsh" "zshrc" "zshenv" "fish" "zprofile" "zlogin" "zlogout" "bash"
"bash_profile" "bashrc" "bash_login" "profile" "bash_aliases"))
(treemacs-create-icon :file "pdf.png" :extensions ("pdf"))
(treemacs-create-icon :file "c.png" :extensions ("c" "h"))
(treemacs-create-icon :file "haskell.png" :extensions ("hs" "lhs"))
(treemacs-create-icon :file "cabal.png" :extensions ("cabal"))
(treemacs-create-icon :file "lock.png" :extensions ("lock"))
(treemacs-create-icon :file "python.png" :extensions ("py" "pyc"))
(treemacs-create-icon :file "markdown.png" :extensions ("md"))
(treemacs-create-icon :file "asciidoc.png" :extensions ("adoc" "asciidoc"))
(treemacs-create-icon :file "rust.png" :extensions ("rs"))
(treemacs-create-icon :file "image.png" :extensions ("jpg" "jpeg" "bmp" "svg" "png" "xpm" "gif"))
(treemacs-create-icon :file "clojure.png" :extensions ("clj" "cljs" "cljc" "edn"))
(treemacs-create-icon :file "ts.png" :extensions ("ts" "tsx"))
(treemacs-create-icon :file "vue.png" :extensions ("vue"))
(treemacs-create-icon :file "css.png" :extensions ("css"))
(treemacs-create-icon :file "conf.png" :extensions ("properties" "conf" "config" "cfg" "ini" "xdefaults" "xresources" "terminalrc" "ledgerrc"))
(treemacs-create-icon :file "html.png" :extensions ("html" "htm"))
(treemacs-create-icon :file "git.png" :extensions ("git" "gitignore" "gitconfig" "gitmodules" "gitattributes"))
(treemacs-create-icon :file "dart.png" :extensions ("dart"))
(treemacs-create-icon :file "jar.png" :extensions ("jar"))
(treemacs-create-icon :file "kotlin.png" :extensions ("kt"))
(treemacs-create-icon :file "scala.png" :extensions ("scala"))
(treemacs-create-icon :file "gradle.png" :extensions ("gradle"))
(treemacs-create-icon :file "sbt.png" :extensions ("sbt"))
(treemacs-create-icon :file "go.png" :extensions ("go"))
(treemacs-create-icon :file "systemd.png" :extensions ("service" "timer"))
(treemacs-create-icon :file "php.png" :extensions ("php"))
(treemacs-create-icon :file "js.png" :extensions ("js" "jsx"))
(treemacs-create-icon :file "babel.png" :extensions ("babel"))
(treemacs-create-icon :file "hy.png" :extensions ("hy"))
(treemacs-create-icon :file "json.png" :extensions ("json"))
(treemacs-create-icon :file "julia.png" :extensions ("jl"))
(treemacs-create-icon :file "elx.png" :extensions ("ex"))
(treemacs-create-icon :file "elx-light.png" :extensions ("exs" "eex" "leex" "heex"))
(treemacs-create-icon :file "ocaml.png" :extensions ("ml" "mli" "merlin" "ocaml"))
(treemacs-create-icon :file "direnv.png" :extensions ("envrc"))
(treemacs-create-icon :file "puppet.png" :extensions ("pp"))
(treemacs-create-icon :file "docker.png" :extensions ("dockerfile" "docker-compose.yml"))
(treemacs-create-icon :file "vagrant.png" :extensions ("vagrantfile"))
(treemacs-create-icon :file "jinja2.png" :extensions ("j2" "jinja2"))
(treemacs-create-icon :file "video.png" :extensions ("webm" "mp4" "avi" "mkv" "flv" "mov" "wmv" "mpg" "mpeg" "mpv"))
(treemacs-create-icon :file "audio.png" :extensions ("mp3" "ogg" "oga" "wav" "flac"))
(treemacs-create-icon :file "tex.png" :extensions ("tex"))
(treemacs-create-icon :file "racket.png" :extensions ("racket" "rkt" "rktl" "rktd" "scrbl" "scribble" "plt"))
(treemacs-create-icon :file "erlang.png" :extensions ("erl" "hrl"))
(treemacs-create-icon :file "purescript.png" :extensions ("purs"))
(treemacs-create-icon :file "nix.png" :extensions ("nix"))
(treemacs-create-icon :file "project.png" :extensions ("project"))
(treemacs-create-icon :file "scons.png" :extensions ("sconstruct" "sconstript"))
(treemacs-create-icon :file "vsc/make.png" :extensions ("makefile"))
(treemacs-create-icon :file "vsc/license.png" :extensions ("license"))
(treemacs-create-icon :file "vsc/zip.png" :extensions ("zip" "7z" "tar" "gz" "rar" "tar.gz"))
(treemacs-create-icon :file "vsc/elm.png" :extensions ("elm"))
(treemacs-create-icon :file "vsc/xml.png" :extensions ("xml" "xsl"))
(treemacs-create-icon :file "vsc/access.png" :extensions ("accdb" "accdt" "accdt"))
(treemacs-create-icon :file "vsc/ascript.png" :extensions ("actionscript"))
(treemacs-create-icon :file "vsc/ai.png" :extensions ("ai"))
(treemacs-create-icon :file "vsc/alaw.png" :extensions ("al"))
(treemacs-create-icon :file "vsc/angular.png" :extensions ("angular-cli.json" "angular.json"))
(treemacs-create-icon :file "vsc/ansible.png" :extensions ("ansible"))
(treemacs-create-icon :file "vsc/antlr.png" :extensions ("antlr"))
(treemacs-create-icon :file "vsc/any.png" :extensions ("anyscript"))
(treemacs-create-icon :file "vsc/apache.png" :extensions ("apacheconf"))
(treemacs-create-icon :file "vsc/apple.png" :extensions ("applescript"))
(treemacs-create-icon :file "vsc/appveyor.png" :extensions ("appveyor.yml"))
(treemacs-create-icon :file "vsc/arduino.png" :extensions ("ino" "pde"))
(treemacs-create-icon :file "vsc/asp.png" :extensions ("asp"))
(treemacs-create-icon :file "vsc/asm.png" :extensions ("asm" "arm"))
(treemacs-create-icon :file "vsc/autohk.png" :extensions ("ahk"))
(treemacs-create-icon :file "vsc/babel.png" :extensions ("babelrc" "babelignore" "babelrc.js" "babelrc.json" "babel.config.js"))
(treemacs-create-icon :file "vsc/bat.png" :extensions ("bat"))
(treemacs-create-icon :file "vsc/binary.png" :extensions ("exe" "dll" "obj" "so" "o"))
(treemacs-create-icon :file "vsc/bazel.png" :extensions ("bazelrc" "bazel"))
(treemacs-create-icon :file "vsc/bower.png" :extensions ("bowerrc" "bower.json"))
(treemacs-create-icon :file "vsc/bundler.png" :extensions ("gemfile" "gemfile.lock"))
(treemacs-create-icon :file "vsc/cargo.png" :extensions ("cargo.toml" "cargo.lock"))
(treemacs-create-icon :file "vsc/cert.png" :extensions ("csr" "crt" "cer" "der" "pfx" "p12" "p7b" "p7r" "src" "crl" "sst" "stl"))
(treemacs-create-icon :file "vsc/class.png" :extensions ("class"))
(treemacs-create-icon :file "vsc/cmake.png" :extensions ("cmake" "cmake-cache"))
(treemacs-create-icon :file "vsc/cobol.png" :extensions ("cobol"))
(treemacs-create-icon :file "vsc/cfscript.png" :extensions ("coffeescript"))
(treemacs-create-icon :file "vsc/cpp.png" :extensions ("cpp" "cxx" "tpp" "cc"))
(treemacs-create-icon :file "vsc/cpph.png" :extensions ("hpp" "hxx" "hh"))
(treemacs-create-icon :file "vsc/cucumber.png" :extensions ("feature"))
(treemacs-create-icon :file "vsc/cython.png" :extensions ("cython"))
(treemacs-create-icon :file "vsc/delphi.png" :extensions ("pascal" "objectpascal"))
(treemacs-create-icon :file "vsc/django.png" :extensions ("djt" "django-html" "django-txt"))
(treemacs-create-icon :file "vsc/dlang.png" :extensions ("d" "dscript" "dml" "diet"))
(treemacs-create-icon :file "vsc/diff.png" :extensions ("diff"))
(treemacs-create-icon :file "vsc/editorcfg.png" :extensions ("editorconfig"))
(treemacs-create-icon :file "vsc/erb.png" :extensions ("erb"))
(treemacs-create-icon :file "vsc/eslint.png" :extensions ("eslintrc" "eslintignore" "eslintcache"))
(treemacs-create-icon :file "vsc/excel.png" :extensions ("xls" "xlsx" "xlsm" "ods" "fods"))
(treemacs-create-icon :file "vsc/font.png" :extensions ("woff" "woff2" "ttf" "otf" "eot" "pfa" "pfb" "sfd"))
(treemacs-create-icon :file "vsc/fortran.png" :extensions ("fortran" "fortran-modern" "fortranfreeform"))
(treemacs-create-icon :file "vsc/fsharp.png" :extensions ("fsharp"))
(treemacs-create-icon :file "vsc/fsproj.png" :extensions ("fsproj"))
(treemacs-create-icon :file "vsc/godot.png" :extensions ("gdscript"))
(treemacs-create-icon :file "vsc/graphql.png" :extensions ("graphql"))
(treemacs-create-icon :file "vsc/helm.png" :extensions ("helm"))
(treemacs-create-icon :file "vsc/java.png" :extensions ("java"))
(treemacs-create-icon :file "vsc/jenkins.png" :extensions ("jenkins"))
(treemacs-create-icon :file "vsc/jupyter.png" :extensions ("ipynb"))
(treemacs-create-icon :file "vsc/key.png" :extensions ("key" "pem"))
(treemacs-create-icon :file "vsc/less.png" :extensions ("less"))
(treemacs-create-icon :file "vsc/locale.png" :extensions ("locale"))
(treemacs-create-icon :file "vsc/manifest.png" :extensions ("manifest"))
(treemacs-create-icon :file "vsc/maven.png" :extensions ("pom.xml" "maven.config" "extensions.xml" "settings.xml"))
(treemacs-create-icon :file "vsc/meson.png" :extensions ("meson" "meson.build"))
(treemacs-create-icon :file "vsc/nginx.png" :extensions ("nginx.conf" "nginx"))
(treemacs-create-icon :file "vsc/npm.png" :extensions ("npmignore" "npmrc" "package.json" "package-lock.json" "npm-shrinwrap.json"))
(treemacs-create-icon :file "vsc/wasm.png" :extensions ("wasm" "wat"))
(treemacs-create-icon :file "vsc/yarn.png" :extensions ("yarn.lock" "yarnrc" "yarnclean" "yarn-integrity" "yarn-metadata.json" "yarnignore"))
(treemacs-create-icon :file "vsc/pkg.png" :extensions ("pkg"))
(treemacs-create-icon :file "vsc/patch.png" :extensions ("patch"))
(treemacs-create-icon :file "vsc/perl6.png" :extensions ("perl6"))
(treemacs-create-icon :file "vsc/pgsql.png" :extensions ("pgsql"))
(treemacs-create-icon :file "vsc/phpunit.png" :extensions ("phpunit" "phpunit.xml"))
(treemacs-create-icon :file "vsc/pip.png" :extensions ("pipfile" "pipfile.lock" "pip-requirements"))
(treemacs-create-icon :file "vsc/plsql.png" :extensions ("plsql" "orcale"))
(treemacs-create-icon :file "vsc/pp.png" :extensions ("pot" "potx" "potm" "pps" "ppsx" "ppsm" "ppt" "pptx" "pptm" "pa" "ppa" "ppam" "sldm" "sldx"))
(treemacs-create-icon :file "vsc/prettier.png" :extensions ("prettier.config.js" "prettierrc.js" "prettierrc.json" "prettierrc.yml" "prettierrc.yaml"))
(treemacs-create-icon :file "vsc/prolog.png" :extensions ("pro" "prolog"))
(treemacs-create-icon :file "vsc/protobuf.png" :extensions ("proto" "proto3"))
(treemacs-create-icon :file "vsc/rake.png" :extensions ("rake" "rakefile"))
(treemacs-create-icon :file "vsc/sqlite.png" :extensions ("sqlite" "db3" "sqlite3"))
(treemacs-create-icon :file "vsc/swagger.png" :extensions ("swagger"))
(treemacs-create-icon :file "vsc/swift.png" :extensions ("swift"))
(treemacs-create-icon :file "vsc/ruby.png" :extensions ("rb"))
(treemacs-create-icon :file "vsc/scss.png" :extensions ("scss"))
(treemacs-create-icon :file "vsc/lua.png" :extensions ("lua"))
(treemacs-create-icon :file "vsc/log.png" :extensions ("log"))
(treemacs-create-icon :file "vsc/lisp.png" :extensions ("lisp"))
(treemacs-create-icon :file "vsc/sql.png" :extensions ("sql"))
(treemacs-create-icon :file "vsc/toml.png" :extensions ("toml"))
(treemacs-create-icon :file "vsc/nim.png" :extensions ("nim"))
(treemacs-create-icon :file "vsc/org.png" :extensions ("org" "org_archive"))
(treemacs-create-icon :file "vsc/perl.png" :extensions ("pl" "pm" "perl"))
(treemacs-create-icon :file "vsc/vim.png" :extensions ("vimrc" "tridactylrc" "vimperatorrc" "ideavimrc" "vrapperrc"))
(treemacs-create-icon :file "vsc/deps.png" :extensions ("cask"))
(treemacs-create-icon :file "vsc/r.png" :extensions ("r"))
(treemacs-create-icon :file "vsc/terraform.png" :extensions ("tf" "terraform"))
(treemacs-create-icon :file "vsc/reason.png" :extensions ("re" "rei"))))
(define-inline treemacs-icon-for-file (file)
"Retrieve an icon for FILE from `treemacs-icons' based on its extension.
Works only with files, not directories.
Uses `treemacs-icon-fallback' as fallback."
(declare (side-effect-free t))
(inline-letevals (file)
(inline-quote
(let ((file-downcased (-> ,file (treemacs--filename) (downcase))))
(or (ht-get treemacs-icons file-downcased)
(ht-get treemacs-icons
(treemacs--file-extension file-downcased)
(with-no-warnings treemacs-icon-fallback)))))))
(define-inline treemacs-icon-for-dir (dir state)
"Retrieve an icon for DIR from `treemacs-icons' in given STATE.
STATE must be either `open' or `closed'.
Works only with directories, not files.
Uses the `dir-open' and `dir-closed' icons as fallback."
(declare (side-effect-free t))
(inline-letevals (dir state)
(inline-quote
(let ((name-downcased (-> ,dir (treemacs--filename) (downcase))))
(when (eq ?. (aref name-downcased 0))
(setf name-downcased (substring name-downcased 1)))
(pcase-exhaustive ,state
(`open
(let ((name (format "%s-%s" name-downcased "open")))
(or (ht-get treemacs-icons name)
(ht-get treemacs-icons 'dir-open))))
(`closed
(let ((name (format "%s-%s" name-downcased "closed")))
(or (ht-get treemacs-icons name)
(ht-get treemacs-icons 'dir-closed)))))))))
;;;###autoload
(defun treemacs-resize-icons (size)
"Resize the current theme's icons to the given SIZE.
If SIZE is \\='nil' the icons are not resized and will retain their default size
of 22 pixels.
There is only one size, the icons are square and the aspect ratio will be
preserved when resizing them therefore width and height are the same.
Resizing the icons only works if Emacs was built with ImageMagick support, or if
using Emacs >= 27.1,which has native image resizing support. If this is not the
case this function will not have any effect.
Custom icons are not taken into account, only the size of treemacs' own icons
png are changed."
(interactive "nIcon size in pixels: ")
(if (not (or (and (functionp 'image-transforms-p) (member 'scale (image-transforms-p)))
(image-type-available-p 'imagemagick)))
(treemacs-log-failure "Icons cannot be resized without image transforms or imagemagick support.")
(setq treemacs--icon-size size)
(treemacs--maphash (treemacs-theme->gui-icons treemacs--current-theme) (_ icon)
(let ((display (get-text-property 0 'display icon))
(width treemacs--icon-size)
(height treemacs--icon-size))
(when (eq 'image (car-safe display))
(when (s-ends-with? "root.png" (plist-get (cdr display) :file))
(treemacs--root-icon-size-adjust width height))
(plist-put (cdr display) :height height)
(plist-put (cdr display) :width width))))))
(defun treemacs--select-icon-set ()
"Select the right set of icons for the current buffer.
Will select either the GUI or the TUI icons of the current theme.
TUI icons will be used if
* `treemacs--is-image-creation-impossible?' returns t,
* `treemacs-no-png-images' is it
* or if the current frame is a TUI frame"
(-let [icons (if (treemacs--should-use-tui-icons?)
(treemacs-theme->tui-icons treemacs--current-theme)
(treemacs-theme->gui-icons treemacs--current-theme))]
(setq-local treemacs-icons icons)
(dolist (icon-symbol treemacs--icon-symbols)
(let ((variable (intern (format "treemacs-icon-%s" icon-symbol)))
(value (ht-get icons icon-symbol)))
(set (make-local-variable variable) value)))))
(define-inline treemacs-current-icons (&optional tui)
"Return the current theme's icons.
Return the fallback icons if TUI is non-nil."
(inline-letevals (tui)
(inline-quote
(if ,tui
(treemacs-theme->tui-icons treemacs--current-theme)
(treemacs-theme->gui-icons treemacs--current-theme)))))
;;;###autoload
(defun treemacs-define-custom-icon (icon &rest file-extensions)
"Define a custom ICON for the current theme to use for FILE-EXTENSIONS.
Note that treemacs has a very loose definition of what constitutes a file
extension - it's either everything past the last period, or just the file's full
name if there is no period. This makes it possible to match file names like
\\='.gitignore' and \\='Makefile'.
Additionally FILE-EXTENSIONS are also not case sensitive and will be stored in a
down-cased state."
(unless icon
(user-error "Custom icon cannot be nil"))
(dolist (ext file-extensions)
(ht-set! (treemacs-theme->gui-icons treemacs--current-theme)
(downcase ext)
(concat icon " "))))
;;;###autoload
(defun treemacs-define-custom-image-icon (file &rest file-extensions)
"Same as `treemacs-define-custom-icon' but for image icons instead of strings.
FILE is the path to an icon image (and not the actual icon string).
FILE-EXTENSIONS are all the (not case-sensitive) file extensions the icon
should be used for."
(unless file
(user-error "Custom icon cannot be nil"))
(-let [icon (car (treemacs--create-icon-strings file " "))]
(dolist (ext file-extensions)
(ht-set! (treemacs-theme->gui-icons treemacs--current-theme)
(downcase ext)
icon))))
;;;###autoload
(defun treemacs-map-icons-with-auto-mode-alist (extensions mode-icon-alist)
"Remaps icons for EXTENSIONS according to `auto-mode-alist'.
EXTENSIONS should be a list of file extensions such that they match the regex
stored in `auto-mode-alist', for example \\='(\".cc\").
MODE-ICON-ALIST is an alist that maps which mode from `auto-mode-alist' should
be assigned which treemacs icon, for example
`((c-mode . ,(treemacs-get-icon-value \"c\"))
(c++-mode . ,(treemacs-get-icon-value \"cpp\")))"
(dolist (extension extensions)
(-when-let* ((mode (cdr (--first (s-matches? (car it) extension) auto-mode-alist)))
(icon (cdr (assq mode mode-icon-alist))))
(ht-set! (treemacs-theme->gui-icons treemacs--current-theme)
(substring extension 1)
icon))))
(treemacs-only-during-init
(treemacs-load-theme "Default"))
(provide 'treemacs-icons)
;;; treemacs-icons.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-icons.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 9,196 |
```emacs lisp
;;; treemacs-diagnostics.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; WIP implementation of diagnostics display.
;;; Code:
(require 'ht)
(require 'thunk)
(require 'dash)
(require 'overlay)
(require 'treemacs-dom)
(require 'treemacs-scope)
(require 'treemacs-workspaces)
(require 'treemacs-core-utils)
(eval-when-compile
(require 'treemacs-macros))
(defconst treemacs--diag-store (make-hash-table :size 50 :test 'equal))
(defvar treemacs--diagnostic-timer nil
"Debounce guard for the application of diagnostics.")
(defconst treemacs--apply-diagnostics-delay 3
"Debounce delay for the application of diagnostics.")
(defface treemacs-diagnostic-error-face
'((t :underline "red"))
"TODO."
:group 'treemacs-faces)
(defface treemacs-diagnostic-warning-face
'((t :underline "yellow"))
"TODO."
:group 'treemacs-faces)
(defun treemacs--reset-and-save-diagnosics (path diagnostics)
"TODO PATH DIAGNOSTICS."
(-let [ht (ht-get treemacs--diag-store path)]
(if ht
(ht-clear! ht)
(setf ht (make-hash-table :size 100 :test 'equal))
(ht-set! treemacs--diag-store path ht))
(while diagnostics
(ht-set! ht (pop diagnostics) (pop diagnostics)))))
(defun treemacs-apply-diagnostics (provider)
"Display diagnostics based on the given arguments PROVIDER.
PROVIDER should be a `thunk' (see thunk.el) that, when evaluated, returns a flat
list of consecutive path and face items.
File paths should use treemacs' canonical format - they should be absolute,
expanded and *not* have a trailing slash.
The diagnostic faces could be any face symbols or raw face literals. Treemacs
features several pre-made faces named `treemacs-diagnostic-*-face'.
This method is debounced, it will never run more often than once every 3
seconds. In addition the use of a lazy thunk ensures that potentially expensive
transformations happen only once and only when required. Performance is thus
not expected to be a major issue.
A basic example use would look like this:
\(treemacs-apply-diagnostics
(thunk-delay \\='(\"/path/to/file/x\" \\='treemacs-diagnostic-warning-face
\"/path/to/file/y\" \\='treemacs-diagnostic-error-face
\"/path/to/file/z\" \\='((:underline \"green\")))))"
(treemacs-debounce treemacs--diagnostic-timer treemacs--apply-diagnostics-delay
(treemacs-run-in-every-buffer
(save-excursion
(-each (overlays-in (point-min) (point-max)) #'delete-overlay)
(-let [diagnostics (thunk-force provider)]
(while diagnostics
(let ((path (pop diagnostics))
(state (pop diagnostics)))
(when (treemacs-is-path-visible? path)
(-let [btn (treemacs-find-file-node path)]
(-doto (make-overlay (treemacs-button-start btn) (treemacs-button-end btn))
(overlay-put 'face state))))))))
(hl-line-highlight))))
(provide 'treemacs-diagnostics)
;;; treemacs-diagnostics.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-diagnostics.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 817 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Treemacs faces.
;;; Code:
(defface treemacs-directory-face
'((t :inherit font-lock-function-name-face))
"Face used by treemacs for directories."
:group 'treemacs-faces)
(defface treemacs-directory-collapsed-face
'((t :inherit treemacs-directory-face))
"Face used by treemacs for collapsed directories.
This is the face used for the collapsed part of nodes, so if the node is
\"foo/bar/baz\", the face is used for \"foo/bar/\".
Using this face is incompatible with `treemacs-git-mode' (exept for the simple
variant), so it will only be used if git-mode is disabled or set to simple."
:group 'treemacs-faces)
(defface treemacs-window-background-face
'((t :inherit default))
"Face used for the background of the treemacs window."
:group 'treemacs-faces)
(defface treemacs-hl-line-face
'((t :inherit hl-line))
"Face used for the hl-line selection in the treemacs window."
:group 'treemacs-faces)
(defface treemacs-file-face
'((t :inherit default))
"Face used by treemacs for files."
:group 'treemacs-faces)
(defface treemacs-root-face
'((t :inherit font-lock-constant-face :underline t :bold t :height 1.2))
"Face used by treemacs for its root nodes."
:group 'treemacs-faces)
(defface treemacs-root-unreadable-face
'((t :inherit treemacs-root-face :strike-through t))
"Face used by treemacs for unreadable root nodes."
:group 'treemacs-faces)
(defface treemacs-root-remote-face
'((t :inherit (font-lock-function-name-face treemacs-root-face)))
"Face used by treemacs for remote (Tramp) root nodes."
:group 'treemacs-faces)
(defface treemacs-root-remote-unreadable-face
'((t :inherit treemacs-root-unreadable-face))
"Face used by treemacs for unreadable remote (Tramp) root nodes."
:group 'treemacs-faces)
(defface treemacs-root-remote-disconnected-face
'((t :inherit (warning treemacs-root-remote-face)))
"Face used by treemacs for disconnected remote (Tramp) root nodes."
:group 'treemacs-faces)
(defface treemacs-term-node-face
'((t :inherit font-lock-string-face))
"Face used by treemacs in the terminal for directory node symbols."
:group 'treemacs-faces)
(defface treemacs-git-unmodified-face
'((t :inherit treemacs-file-face))
"Face used for unmodified files."
:group 'treemacs-faces)
(defface treemacs-git-modified-face
'((t :inherit font-lock-variable-name-face))
"Face used for modified files."
:group 'treemacs-faces)
(defface treemacs-git-renamed-face
'((t :inherit font-lock-doc-face))
"Face used for renamed files."
:group 'treemacs-faces)
(defface treemacs-git-ignored-face
'((t :inherit font-lock-comment-face))
"Face for ignored files."
:group 'treemacs-faces)
(defface treemacs-git-untracked-face
'((t :inherit font-lock-string-face))
"Face for untracked files."
:group 'treemacs-faces)
(defface treemacs-git-added-face
'((t :inherit font-lock-type-face))
"Face for newly added files."
:group 'treemacs-faces)
(defface treemacs-git-conflict-face
'((t :inherit error))
"Face for conflicting files."
:group 'treemacs-faces)
(defface treemacs-tags-face
'((t :inherit font-lock-builtin-face))
"Face for tags."
:group 'treemacs-faces)
(defface treemacs-help-title-face
`((t :inherit ,(if (facep 'spacemacs-transient-state-title-face)
'spacemacs-transient-state-title-face
'font-lock-constant-face)))
"Face for the title of the helpful hydra."
:group 'treemacs-faces)
(defface treemacs-help-column-face
'((t :inherit font-lock-keyword-face :underline t))
"Face for column headers of the helpful hydra."
:group 'treemacs-faces)
(defface treemacs-on-failure-pulse-face
'((t :foreground "#111111" :background "#ab3737" :extend t))
"Pulse face used when an error occurs or an action fails."
:group 'treemacs-faces)
(defface treemacs-on-success-pulse-face
'((t :foreground "#111111" :background "#669966" :extend t))
"Pulse face used to signal a successful action."
:group 'treemacs-faces)
(defface treemacs-fringe-indicator-face
`((t :foreground ,(face-background 'cursor nil t)))
"Face for the fringe indicator."
:group 'treemacs-faces)
(defface treemacs-header-button-face
'((t :inherit 'font-lock-keyword-face))
"Face used for header buttons.
Applies to buttons like
- `treemacs-header-close-button'
- `treemacs-header-projects-button'
- `treemacs-header-workspace-button'"
:group 'treemacs-faces)
(defface treemacs-peek-mode-indicator-face
'((t :background "#669966"))
"Face used to indicate that `treemacs-peek-mode' is enabled."
:group 'treemacs-faces)
(defface treemacs-marked-file-face
'((t :foreground "#F0C674" :background "#AB3737" :bold t))
"Face for files marked by treemacs."
:group 'treemacs-faces)
(defface treemacs-git-commit-diff-face
'((t :inherit 'font-lock-comment-face))
"Face for `treemacs-git-commit-diff-mode' annotations."
:group 'treemacs-faces)
(defface treemacs-async-loading-face
'((t :inherit 'font-lock-comment-face :height 0.8))
"Face used for the \"Loading\" string used by asynchronous extensions."
:group 'treemacs-faces)
(provide 'treemacs-faces)
;;; treemacs-faces.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-faces.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,507 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Persistence of treemacs' workspaces into an org-mode compatible file.
;;; Code:
(require 's)
(require 'dash)
(require 'treemacs-workspaces)
(require 'treemacs-customization)
(require 'treemacs-logging)
(eval-when-compile
(require 'rx)
(require 'cl-lib)
(require 'inline)
(require 'treemacs-macros))
(eval-when-compile
(cl-declaim (optimize (speed 3) (safety 0))))
(defconst treemacs--org-edit-buffer-name "*Edit Treemacs Workspaces*"
"The name of the buffer used to edit treemacs' workspace.")
(defconst treemacs--last-error-persist-file
(treemacs-join-path user-emacs-directory ".cache" "treemacs-persist-at-last-error")
"File that stores the treemacs state as it was during the last load error.")
(make-obsolete-variable 'treemacs--last-error-persist-file 'treemacs-last-error-persist-file "v2.7")
(defconst treemacs--persist-kv-regex
(rx bol (? " ") "- path :: " (1+ any) eol)
"The regular expression to match org's \"key :: value\" lines.")
(defconst treemacs--persist-workspace-name-regex
(rx bol "* " (1+ any) eol)
"The regular expression to match lines with workspace names.")
(defconst treemacs--persist-project-name-regex
(rx bol "** " (1+ any) eol)
"The regular expression to match lines with projects names.")
(cl-defstruct (treemacs-iter
(:conc-name treemacs-iter->)
(:constructor treemacs-iter->create!))
list)
(defvar treemacs--no-abbr-on-persist-prefixes nil
"Prefixes for paths to be saved as is, without using `abbreviate-file-name'.
Will be set to all the `tramp-methods', after tramp has been loaded.")
(define-inline treemacs-iter->next! (self)
"Get the next element of iterator SELF.
SELF: Treemacs-Iter struct."
(inline-letevals (self)
(inline-quote
(let ((head (car (treemacs-iter->list ,self)))
(tail (cdr (treemacs-iter->list ,self))))
(setf (treemacs-iter->list ,self) tail)
head))))
(define-inline treemacs-iter->peek (self)
"Peek at the first element of SELF.
SELF: Treemacs-Iter struct."
(declare (side-effect-free t))
(inline-letevals (self)
(inline-quote
(or (car (treemacs-iter->list ,self))
;; we still need something to make the `s-matches?' calls work
"__EMPTY__"))))
(define-inline treemacs--should-not-run-persistence? ()
"No saving and loading in noninteractive and CI environments."
(inline-quote (or noninteractive (getenv "CI") (null treemacs-persist-file))))
(defun treemacs--read-workspaces (iter)
"Read a list of workspaces from the lines in ITER.
Returns a list with 2 elements: the first one is a list of all enabled
workspaces, the second is a list of all non-disabled workspaces.
ITER: Treemacs-Iter Struct."
(let ((workspaces)
(comment-prefix "COMMENT "))
(while (s-matches? treemacs--persist-workspace-name-regex (treemacs-iter->peek iter))
(let ((workspace (treemacs-workspace->create!))
(workspace-name (substring (treemacs-iter->next! iter) 2))
(workspace-projects (treemacs--read-projects iter)))
(when (s-starts-with? comment-prefix workspace-name)
(setf workspace-name (substring workspace-name (length comment-prefix))
(treemacs-workspace->is-disabled? workspace) t))
(setf (treemacs-workspace->name workspace) workspace-name
(treemacs-workspace->projects workspace) workspace-projects)
(push workspace workspaces)))
(--separate (treemacs-workspace->is-disabled? it)
(nreverse workspaces))))
(defun treemacs--read-projects (iter)
"Read a list of projects from ITER until another section is found.
ITER: Treemacs-Iter Struct"
(let (projects)
(while (s-matches? treemacs--persist-project-name-regex (treemacs-iter->peek iter))
(let ((kv-lines nil)
(project (treemacs-project->create!))
(project-name (substring (treemacs-iter->next! iter) 3))
(comment-prefix "COMMENT "))
(when (s-starts-with? comment-prefix project-name)
(setf project-name (substring project-name (length comment-prefix))
(treemacs-project->is-disabled? project) t))
(setf (treemacs-project->name project) project-name)
(while (s-matches? treemacs--persist-kv-regex (treemacs-iter->peek iter))
(push (treemacs-iter->next! iter) kv-lines))
(if (null kv-lines)
(treemacs-log-failure "Project %s has no path and will be ignored."
(propertize (treemacs-project->name project)
'face 'font-lock-type-face))
(dolist (kv-line kv-lines)
(-let [(key val) (s-split " :: " kv-line)]
(pcase (s-trim key)
("- path"
(setf (treemacs-project->path project) (treemacs-canonical-path val)))
(_
(treemacs-log-failure "Encountered unknown project key-value in line [%s]" kv-line)))))
(let ((action 'retry))
(while (eq action 'retry)
(setf (treemacs-project->path-status project)
(-> (treemacs-project->path project)
(treemacs--get-path-status)))
(setq action
(cond
((or (treemacs-project->is-disabled? project)
(not (treemacs-project->is-unreadable? project)))
'keep)
((eq treemacs-missing-project-action 'ask)
(let ((completions
'(("Keep the project in the project list" . keep)
("Retry" . retry)
("Remove the project from the project list" . remove))))
(cdr (assoc (completing-read
(format "Project %s at %s cannot be read."
(treemacs-project->name project)
(treemacs-project->path project))
completions nil t)
completions))))
(treemacs-missing-project-action))))
(if (eq action 'remove)
(treemacs-log-failure "The location of project %s at %s cannot be read. Project was removed from the project list."
(propertize (treemacs-project->name project) 'face 'font-lock-type-face)
(propertize (treemacs-project->path project) 'face 'font-lock-string-face))
(push project projects))))))
(nreverse projects)))
(defun treemacs--persist ()
"Persist treemacs' state in `treemacs-persist-file'."
(unless (or (treemacs--should-not-run-persistence?)
(null (get 'treemacs :state-is-restored)))
(unless (file-exists-p treemacs-persist-file)
(make-directory (file-name-directory treemacs-persist-file) :with-parents))
(condition-case e
(let ((txt nil)
(buffer nil)
(no-kill nil)
;; no surprisese when using `abbreviate-file-name'
(directory-abbrev-alist nil)
(abbreviated-home-dir nil)
(file-precious-flag t))
(--if-let (get-file-buffer treemacs-persist-file)
(setq buffer it
no-kill t)
(setq buffer (find-file-noselect treemacs-persist-file :no-warn)
desktop-save-buffer nil))
(with-current-buffer buffer
(dolist (ws (--reject (null (treemacs-workspace->projects it))
(append (treemacs-workspaces)
(treemacs-disabled-workspaces))))
(push (format "* %s%s\n"
(if (treemacs-workspace->is-disabled? ws) "COMMENT " "")
(treemacs-workspace->name ws))
txt)
(dolist (pr (treemacs-workspace->projects ws))
(push (format "** %s%s\n"
(if (treemacs-project->is-disabled? pr) "COMMENT " "")
(treemacs-project->name pr))
txt)
(push (format
" - path :: %s\n"
(-let [path (treemacs-project->path pr)]
(if (--any? (string-prefix-p it path) treemacs--no-abbr-on-persist-prefixes)
path
(abbreviate-file-name path))))
txt)))
(delete-region (point-min) (point-max))
(insert (apply #'concat (nreverse txt)))
(-let [inhibit-message t] (save-buffer))
(unless no-kill (kill-buffer))))
(error (treemacs-log-err "Error '%s' when persisting workspace." e)))))
(defun treemacs--read-persist-lines (&optional txt)
"Read the relevant lines from given TXT or `treemacs-persist-file'.
Will read all lines, except those that start with # or contain only whitespace."
(-some->> (or txt (when (file-exists-p treemacs-persist-file)
(with-temp-buffer
(insert-file-contents treemacs-persist-file)
(buffer-string))))
(s-trim)
(s-lines)
(--reject (or (s-blank-str? it)
(s-starts-with? "#" it)))))
(cl-defun treemacs--validate-persist-lines
(lines
&optional
(context :start)
(prev nil)
(paths nil)
(proj-count 0)
(ws-count 0))
"Recursively verify the make-up of the given LINES, based on their CONTEXT.
Lines must start with a workspace name, followed by a project name, followed by
the project's path property, followed by either the next project or the next
workspace.
The previously looked at line type is given by CONTEXT.
The previously looked at line is given by PREV.
PATHS contains all the project paths previously seen in the current workspace.
These are used to make sure that no file path appears in the workspaces more
than once.
PROJ-COUNT counts the number of non-disabled projects in a workspace to make
sure that there is at least one project that will be displayed.
WS-COUNT counts the number of non-disabled workspaces to make sure that there is
at least one workspace that will be used.
A successful validation returns just the symbol \\='success, in case of an error
a list of 3 items is returned: the symbol \\='error, the exact line where the
error happened, and the error message. In some circumstances (for example when
a project is missing a path property) it makes sense to display the error not in
the currently looked at line, but the one above, which is why the previously
looked at line PREV is given as well.
LINES: List of Strings
CONTEXT: Keyword
PREV: String
PATHS: List<String>
PROJ-COUNT: Int"
(treemacs-block
(cl-labels ((as-warning (txt) (propertize txt 'face 'warning)))
(treemacs-unless-let (line (car lines))
(pcase context
(:property
(treemacs-return-if (= 0 proj-count)
`(error ,prev ,(as-warning "Workspace must contain at least 1 project that is not disabled.")))
(treemacs-return-if (= 0 ws-count)
`(error ,prev ,(as-warning "There must be at least 1 worspace that is not disabled.")))
(treemacs-return
'success))
(:start
(treemacs-return
(list 'error :start (as-warning "Input is empty"))))
(_
(treemacs-return
(list 'error prev (as-warning "Cannot end with a project or workspace name")))))
(pcase context
(:start
(treemacs-return-if (not (s-matches? treemacs--persist-workspace-name-regex line))
`(error ,line ,(as-warning "First item must be a workspace name")))
(-let [ws-is-disabled? (s-starts-with? "* COMMENT" line)]
(unless ws-is-disabled? (cl-incf ws-count)))
(treemacs--validate-persist-lines (cdr lines) :workspace line nil 0 ws-count))
(:workspace
(treemacs-return-if (not (s-matches? treemacs--persist-project-name-regex line))
`(error ,line ,(as-warning "Workspace name must be followed by project name")))
(-let [proj-is-disabled? (s-starts-with? "** COMMENT" line)]
(unless proj-is-disabled? (cl-incf proj-count))
(treemacs--validate-persist-lines (cdr lines) :project line nil proj-count ws-count)))
(:project
(treemacs-return-if (not (s-matches? treemacs--persist-kv-regex line))
`(error ,prev ,(as-warning "Project name must be followed by path declaration")))
(-let [path (cadr (s-split " :: " line))]
;; Path not existing is only a hard error when org-editing, when loading on boot
;; its significance is determined by the customization setting
;; `treemacs-missing-project-action'. Remote files are skipped to avoid opening
;; Tramp connections.
(treemacs-return-if (and (string= treemacs--org-edit-buffer-name (buffer-name))
(not (s-starts-with? "** COMMENT" prev))
(not (file-remote-p path))
(not (file-exists-p path)))
`(error ,line ,(format (as-warning "File '%s' does not exist") (propertize path 'face 'font-lock-string-face))))
(treemacs-return-if (or (--any (treemacs-is-path path :in it) paths)
(--any (treemacs-is-path it :in path) paths))
`(error ,line ,(format (as-warning "Path '%s' appears in the workspace more than once.")
(propertize path 'face 'font-lock-string-face))))
(treemacs--validate-persist-lines (cdr lines) :property line (cons path paths) proj-count ws-count)))
(:property
(let ((line-is-workspace-name (s-matches? treemacs--persist-workspace-name-regex line))
(line-is-project-name (s-matches? treemacs--persist-project-name-regex line)))
(cond
(line-is-workspace-name
(treemacs-return-if (= 0 proj-count)
`(error ,prev ,(as-warning "Workspace must contain at least 1 project that is not disabled.")))
(-let [ws-is-disabled? (s-starts-with? "* COMMENT" line)]
(unless ws-is-disabled? (cl-incf ws-count)))
(treemacs--validate-persist-lines (cdr lines) :workspace line nil 0 ws-count))
(line-is-project-name
(-let [proj-is-disabled? (s-starts-with? "** COMMENT" line)]
(unless proj-is-disabled? (cl-incf proj-count)))
(treemacs--validate-persist-lines (cdr lines) :project line paths proj-count ws-count))
(t
(treemacs-return-if (-none? #'identity (list line-is-workspace-name line-is-project-name))
`(error ,prev ,(as-warning "Path property must be followed by the next workspace or project"))))))))))))
(defun treemacs--restore ()
"Restore treemacs' state from `treemacs-persist-file'."
(unless (treemacs--should-not-run-persistence?)
(treemacs-unless-let (lines (treemacs--read-persist-lines))
(setf treemacs--workspaces (list (treemacs-workspace->create! :name "Default"))
(treemacs-current-workspace) (car treemacs--workspaces))
;; Don't persist during restore. Otherwise, if the user would quit
;; Emacs during restore, for example during the completing read for
;; missing project action, the whole persist file would be emptied.
(let ((kill-emacs-hook (remq #'treemacs--persist kill-emacs-hook)))
;; run in a temp buffer since validation and read functions rely on elisp-based syntax tables
;; for their regexes
(with-temp-buffer
(condition-case e
(pcase (treemacs--validate-persist-lines lines)
('success
(let* ((ws-lists (treemacs--read-workspaces (treemacs-iter->create! :list lines))))
(setf treemacs--disabled-workspaces (car ws-lists))
(setf treemacs--workspaces (cadr ws-lists))))
(`(error ,line ,error-msg)
(treemacs--write-error-persist-state lines (format "'%s' in line '%s'" error-msg line))
(treemacs-log-err "Could not restore saved state, %s:\n%s\n%s"
(pcase line
(:start "found error in the first line")
(:end "found error in the last line")
(other (format "found error in line '%s'" other)))
error-msg
(format "Broken state was saved to %s"
(propertize treemacs-last-error-persist-file 'face 'font-lock-string-face)))))
(error
(progn
(treemacs--write-error-persist-state lines e)
(treemacs-log-err "Error '%s' when loading the persisted workspace.\n%s"
e
(format "Broken state was saved to %s"
(propertize treemacs-last-error-persist-file 'face 'font-lock-string-face)))))))))))
(define-inline treemacs--maybe-load-workspaces ()
"First load of the workspaces, if it hasn't happened already."
(inline-quote
(unless (get 'treemacs :state-is-restored)
(treemacs--restore)
(put 'treemacs :state-is-restored t))))
(defun treemacs--write-error-persist-state (lines error)
"Write broken state LINES and ERROR to `treemacs-last-error-persist-file'."
(-let [txt (concat (format "# State when last error occurred on %s\n" (format-time-string "%F %T"))
(format "# Error was %s\n\n" error)
(apply #'concat (--map (concat it "\n") lines)))]
(unless (file-exists-p treemacs-last-error-persist-file)
(make-directory (file-name-directory treemacs-last-error-persist-file) :with-parents))
(write-region txt nil treemacs-last-error-persist-file nil :silent)))
(add-hook 'kill-emacs-hook #'treemacs--persist)
(provide 'treemacs-persistence)
;;; treemacs-persistence.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-persistence.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 4,297 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Follow mode definition.
;;; Code:
(require 'hl-line)
(require 'dash)
(require 's)
(require 'treemacs-customization)
(require 'treemacs-rendering)
(require 'treemacs-dom)
(require 'treemacs-async)
(require 'treemacs-core-utils)
(eval-when-compile
(require 'treemacs-macros))
(treemacs-import-functions-from "dired"
dired-current-directory)
(defvar treemacs--ready-to-follow nil
"Signals to `treemacs-follow-mode' if a follow action may be run.
Must be set to nil when no following should be triggered, e.g. when the
treemacs buffer is being rebuilt or during treemacs' own window selection
functions.")
(defvar treemacs--follow-timer nil
"Idle timer for `treemacs--follow' to run.")
(defun treemacs--follow ()
"Move point to the current file in the treemacs buffer.
Expand directories if needed. Do nothing if current file does not exist in the
file system or is not below current treemacs root or if the treemacs buffer is
not visible."
;; Treemacs selecting files with `ace-window' results in a large amount of
;; window selections, so we should be breaking out as soon as possbile
(setq treemacs--follow-timer nil)
(when treemacs--ready-to-follow
(treemacs-without-following
(let* ((treemacs-window (treemacs-get-local-window))
(current-buffer (current-buffer))
(buffer-name (buffer-name current-buffer))
(current-file (or (buffer-file-name current-buffer)
(when (eq major-mode 'dired-mode)
(treemacs-canonical-path (dired-current-directory))))))
(when (and treemacs-window
current-file
(not (s-starts-with? treemacs--buffer-name-prefix buffer-name))
(file-exists-p current-file)
(not (string= buffer-name "COMMIT_EDITMSG")))
(-when-let (project-for-file (treemacs--find-project-for-buffer current-file))
(with-selected-window treemacs-window
(-let [selected-file (--if-let (treemacs-current-button)
(treemacs--nearest-path it)
(treemacs-project->path project-for-file))]
(unless (treemacs-is-path selected-file :same-as current-file)
(when (treemacs-goto-file-node current-file project-for-file)
(when treemacs-project-follow-cleanup
(dolist (project (treemacs-workspace->projects (treemacs-current-workspace)))
(unless (or (not (treemacs-project->is-expanded? project))
(eq project project-for-file))
(-when-let (project-pos (treemacs-project->position project))
(goto-char project-pos)
(treemacs--collapse-root-node project-pos)))))
(when treemacs-recenter-after-file-follow
(treemacs--maybe-recenter treemacs-recenter-after-file-follow))))))))))))
(defun treemacs--follow-after-buffer-list-update ()
"Debounced call to `treemacs--follow'."
(when treemacs--ready-to-follow
(unless treemacs--follow-timer
(setq treemacs--follow-timer
(run-with-idle-timer treemacs-file-follow-delay nil #'treemacs--follow)))))
(defun treemacs--setup-follow-mode ()
"Setup all the hooks needed for `treemacs-follow-mode'."
(add-hook 'buffer-list-update-hook #'treemacs--follow-after-buffer-list-update)
(treemacs--follow))
(defun treemacs--tear-down-follow-mode ()
"Remove the hooks added by `treemacs--setup-follow-mode'."
(remove-hook 'buffer-list-update-hook #'treemacs--follow-after-buffer-list-update))
(define-minor-mode treemacs-follow-mode
"Toggle `treemacs-follow-mode'.
When enabled treemacs will keep track of and focus the currently selected
buffer's file. This only applies if the file is within the treemacs root
directory.
This functionality can also be manually invoked with `treemacs-find-file'."
:init-value nil
:global t
:lighter nil
:group 'treemacs
(if treemacs-follow-mode
(treemacs--setup-follow-mode)
(treemacs--tear-down-follow-mode)))
(treemacs-only-during-init (treemacs-follow-mode))
(provide 'treemacs-follow-mode)
;;; treemacs-follow-mode.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-follow-mode.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,064 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Customize interface definitions.
;;; Code:
(require 's)
(require 'widget)
(require 'dash)
(eval-when-compile
(require 'cl-lib))
(defun treemacs--find-python3 ()
"Determine the location of python 3."
(--if-let (executable-find "python3") it
(when (eq system-type 'windows-nt)
(condition-case _
(->> "where python"
(shell-command-to-string)
(s-trim)
(s-lines)
(--first
(when (file-exists-p it)
(condition-case _
(->> (concat (shell-quote-argument it) " --version")
(shell-command-to-string)
(s-trim)
(s-replace "Python " "")
(s-left 1)
(version<= "3"))
(error nil)))))
(error nil)))))
(cl-macrolet
((define-action-widget (name include-default include-tab include-ret)
`(define-widget ',name 'lazy
"Treemacs button action"
:format "%v"
:type '(choice
:tag "Action"
,@(when include-default `((const :tag "Default visit action" treemacs-visit-node-default)))
,@(when include-tab `((const :tag "Same as TAB" treemacs-TAB-action)))
,@(when include-ret `((const :tag "Same as RET" treemacs-RET-action)))
(const :tag "Visit node without splitting" treemacs-visit-node-no-split)
(const :tag "Visit node in a vertical split" treemacs-visit-node-vertical-split)
(const :tag "Visit node in a horizontal split" treemacs-visit-node-horizontal-split)
(const :tag "Visit node with Ace" treemacs-visit-node-ace)
(const :tag "Visit node with Ace in a horizontal split" treemacs-visit-node-ace-horizontal-split)
(const :tag "Visit node with Ace in a vertical split" treemacs-visit-node-ace-vertical-split)
(const :tag "Visit node in the most recently used window" treemacs-visit-node-in-most-recently-used-window)
(const :tag "Toggle node" treemacs-toggle-node)
(const :tag "Toggle node (prefer tag visit)" treemacs-toggle-node-prefer-tag-visit)
(function :tag "Custom function")))))
(define-action-widget treemacs-default-action nil nil nil)
(define-action-widget treemacs-ret-action t t nil)
(define-action-widget treemacs-tab-action t nil t)
(define-action-widget treemacs-mouse-action t t t))
(defgroup treemacs nil
"Treemacs configuration options."
:group 'treemacs
:prefix "treemacs-")
(defgroup treemacs-faces nil
"Faces for treemacs' syntax highlighting."
:group 'treemacs
:group 'faces
:prefix "treemacs-"
:link '(url-link :tag "Repository" "path_to_url"))
(defgroup treemacs-git nil
"Customisations for treemacs' git integration."
:group 'treemacs
:prefix "treemacs-"
:link '(url-link :tag "Repository" "path_to_url"))
(defgroup treemacs-hooks nil
"Hooks provided by treemacs."
:group 'treemacs
:prefix "treemacs-"
:link '(url-link :tag "Repository" "path_to_url"))
(defgroup treemacs-follow nil
"Customisations for the behaviour of the treemacs' file and tag following."
:group 'treemacs
:prefix "treemacs-"
:link '(url-link :tag "Repository" "path_to_url"))
(defgroup treemacs-mouse nil
"Customisations for treemacs' mouse integration."
:group 'treemacs
:prefix "treemacs-"
:link '(url-link :tag "Repository" "path_to_url"))
(defgroup treemacs-window nil
"Customisations for the behaviour of the treemacs window."
:group 'treemacs
:prefix "treemacs-"
:link '(url-link :tag "Repository" "path_to_url"))
(defcustom treemacs-indentation 2
"The number of spaces or pixels each level is indented in the file tree.
If the value is integer, indentation is created by repeating
`treemacs-indentation-string'. If the value is a list of form \\='(INTEGER px),
indentation will be a space INTEGER pixels wide."
:type '(choice (integer :tag "Spaces" :value 2)
(list :tag "Pixels"
(integer :tag "Pixels" :value 16)
(const :tag "" px)))
:group 'treemacs)
(defcustom treemacs-litter-directories '("/node_modules" "/.venv" "/.cask")
"List of directories affected by `treemacs-cleanup-litter'.
Every item in the list is a regular expression, to be recognised a directory
must be matched with `string-match-p'.
Regexp-quoting the items in this list is *not* necessary, the quoting will
happen automatically when needed."
:type 'list
:group 'treemacs)
(defcustom treemacs-read-string-input
(if (getenv "WAYLAND_DISPLAY") 'from-minibuffer 'from-child-frame)
"The function treemacs uses to read user input.
Only applies to plaintext input, like when renaming a project, file or
workspace.
There are 2 options:
- `from-child-frame': will use the `cfrs' package to read input from a small
child frame pop-up. Only available in GUI frames, otherwise the default
minibuffer input is used.
- `from-minibuffer': will read input from the minibuffer, same as baseline
Emacs.
Note: there seem to be issues with focusing child frames on wayland, therefore
treemacs will use the minibuffer if it thinks you are running wayland."
:type '(choice (const :tag "With Child Frame Popup" from-child-frame)
(const :tag "From the Minibuffer (Emacs Default)" from-minibuffer))
:group 'treemacs)
(defcustom treemacs-move-forward-on-expand nil
"When non-nil treemacs will move to the first child of an expanded node."
:type 'boolean
:group 'treemacs)
(defcustom treemacs-eldoc-display 'simple
"Enables eldoc display of the file path at point.
There are 2 options:
- `simple': shows the absolute path of the file at point
- `detailed': shows the absolute path, size, last modification time and
permissions of the file at point
Requires eldoc mode to be enabled."
:type '(choice (const :tag "Simple" simple)
(const :tag "Detailed" detailed))
:group 'treemacs)
(defcustom treemacs-indent-guide-style 'line
"Determines the appearance of `treemacs-indent-guide-mode'.
The choices are
- `line' for indent guides to use the ' ' character for every indentation
level
- `block' to use a thick '' block interspersed at every second indentation
level"
:type '(choice (const :tag "Line" line)
(const :tag "Block" block))
:group 'treemacs)
(defcustom treemacs-indentation-string " "
"The string that is for indentation in the file tree.
Indentation is created by repeating this string `treemacs-indentation' many
times. If `treemacs-indentation' is specified in pixels, this value is only
used when there is no windowing system available."
:type 'string
:group 'treemacs)
(defcustom treemacs-show-hidden-files t
"Dotfiles will be shown if this is set to t and be hidden otherwise.
Can be toggled by `treemacs-toggle-show-dotfiles'."
:type 'boolean
:group 'treemacs)
(defcustom treemacs-show-edit-workspace-help t
"When non-nil the workspace-edit buffer will display a short help greeting.
See also `treemacs-edit-workspaces'."
:type 'boolean
:group 'treemacs)
(defcustom treemacs-TAB-actions-config
'((root-node-open . treemacs-toggle-node)
(root-node-closed . treemacs-toggle-node)
(dir-node-open . treemacs-toggle-node)
(dir-node-closed . treemacs-toggle-node)
(file-node-open . treemacs-toggle-node)
(file-node-closed . treemacs-toggle-node)
(tag-node-open . treemacs-toggle-node)
(tag-node-closed . treemacs-toggle-node)
(tag-node . treemacs-visit-node-default))
"Defines the behaviour of `treemacs-TAB-action'.
See the doc string of `treemacs-RET-actions-config' for a detailed description
of how this config works and how to modify it."
:type '(alist :key-type symbol :value-type treemacs-tab-action)
:group 'treemacs)
(defcustom treemacs-doubleclick-actions-config
'((root-node-open . treemacs-toggle-node)
(root-node-closed . treemacs-toggle-node)
(dir-node-open . treemacs-toggle-node)
(dir-node-closed . treemacs-toggle-node)
(file-node-open . treemacs-visit-node-in-most-recently-used-window)
(file-node-closed . treemacs-visit-node-in-most-recently-used-window)
(tag-node-open . treemacs-toggle-node)
(tag-node-closed . treemacs-toggle-node)
(tag-node . treemacs-visit-node-in-most-recently-used-window))
"Defines the behaviour of `treemacs-doubleclick-action'.
See the doc string of `treemacs-RET-actions-config' for a detailed description
of how this config works and how to modify it."
:type '(alist :key-type symbol :value-type treemacs-mouse-action)
:group 'treemacs)
(defcustom treemacs-default-visit-action 'treemacs-visit-node-no-split
"Defines the behaviour of `treemacs-visit-node-default'."
:type 'treemacs-default-action
:group 'treemacs)
(defcustom treemacs-RET-actions-config
'((root-node-open . treemacs-toggle-node)
(root-node-closed . treemacs-toggle-node)
(dir-node-open . treemacs-toggle-node)
(dir-node-closed . treemacs-toggle-node)
(file-node-open . treemacs-visit-node-default)
(file-node-closed . treemacs-visit-node-default)
(tag-node-open . treemacs-toggle-node-prefer-tag-visit)
(tag-node-closed . treemacs-toggle-node-prefer-tag-visit)
(tag-node . treemacs-visit-node-default))
"Defines the behaviour of `treemacs-RET-action'.
Each alist element maps from a button state to the function that should be used
for that state. The list of all possible button states is defined in
`treemacs-valid-button-states'. Possible values are all treemacs-visit-node-*
functions as well as `treemacs-toggle-node' for simple open/close actions,
though in general you can use any function that accepts the prefix arg as its
single argument.
To keep the alist clean changes should not be made directly, but with
`treemacs-define-RET-action', for example like this:
\(treemacs-define-RET-action \\='file-node-closed #\\='treemacs-visit-node-ace)"
:type '(alist :key-type symbol :value-type treemacs-ret-action)
:group 'treemacs)
(defcustom treemacs-COLLAPSE-actions-config
'((root-node-open . treemacs-toggle-node)
(root-node-closed . treemacs-goto-parent-node)
(dir-node-open . treemacs-toggle-node)
(dir-node-closed . treemacs-goto-parent-node)
(file-node-open . treemacs-toggle-node)
(file-node-closed . treemacs-goto-parent-node)
(tag-node-open . treemacs-toggle-node)
(tag-node-closed . treemacs-goto-parent-node)
(tag-node . treemacs-goto-parent-node))
"Defines the behaviour of `treemacs-COLLAPSE-action'.
See the doc string of `treemacs-RET-actions-config' for a detailed description
of how this config works and how to modify it."
:type '(alist :key-type symbol :value-type treemacs-collapse-action)
:group 'treemacs)
(defcustom treemacs-dotfiles-regex (rx bol "." (1+ any))
"Files matching this regular expression count as dotfiles.
This controls the matching behaviour of `treemacs-toggle-show-dotfiles'."
:type 'regexp
:group 'treemacs)
(defcustom treemacs-hide-dot-git-directory t
"Indicates whether the .git directory should be hidden.
When this is non-nil the .git dir will be hidden regardless of current setting
of `treemacs-toggle-show-dotfiles'."
:type 'list
:group 'treemacs)
(defcustom treemacs-sorting 'alphabetic-asc
"Indicates how treemacs will sort its files and directories.
Files will still always be shown after directories.
Valid values are:
* `alphabetic-asc',
* `alphabetic-desc',
* `alphabetic-numeric-asc',
* `alphabetic-numeric-desc',
* `alphabetic-case-insensitive-asc',
* `alphabetic-case-insensitive-desc',
* `alphabetic-numeric-case-insensitive-asc',
* `alphabetic-numeric-case-insensitive-desc',
* `size-asc',
* `size-desc',
* `mod-time-asc',
* `mod-time-desc'
* a custom function
In the latter case it must be a function that can be passed to `sort' to sort
absolute filepaths. For an example see `treemacs--sort-alphabetic-asc'
Note about performance:
Treemacs does its best to optimise its performance critical path, it does so
by doing as little work as possible and producing as little garbage as possible.
Deciding on the order in which its nodes are inserted is a part of this path.
As such certain trade-offs need to be accounted far.
In plaintext: some sort settings are much slower than others. Alphabetic
sorting (the default) is fastest and causes no additional overhead (even when
compared against foregoing sorting altogether).
Modification time sorting takes the middle, being ca. 4x slower than
alphabetic. Sorting by size is slowest, being ca. 5-6x slower than alphabetic.
It also produces the most garbage, making it more like for you to run into a
garbage collection pause.
Lest these numbers scare you off keep in mind that they will likely have little
to no effect on your usage of treemacs until you begin frequently refreshing
treemacs views containing hundreds or even thousands of nodes."
:type '(choice (const alphabetic-asc)
(const alphabetic-desc)
(const alphabetic-numeric-asc)
(const alphabetic-numeric-desc)
(const alphabetic-case-insensitive-asc)
(const alphabetic-case-insensitive-desc)
(const alphabetic-numeric-case-insensitive-asc)
(const alphabetic-numeric-case-insensitive-desc)
(const size-asc)
(const size-desc)
(const mod-time-asc)
(const mod-time-desc))
:group 'treemacs)
(defcustom treemacs-ignored-file-predicates
(pcase system-type
('darwin '(treemacs--std-ignore-file-predicate treemacs--mac-ignore-file-predicate))
(_ '(treemacs--std-ignore-file-predicate)))
"List of predicates to test for files and directories ignored by treemacs.
Ignored files will *never* be shown in the treemacs buffer (unlike dotfiles
whose presence is controlled by `treemacs-show-hidden-files').
Each predicate is a function that takes 2 arguments: a file's name and its
absolute path and returns t if the file should be ignored and nil otherwise. A
file which returns t for *any* function in this list counts as ignored.
By default this list contains `treemacs--std-ignore-file-predicate' which
filters out \".\", \"..\", Emacs' lock files as well temp files created by
flycheck. This means that this variable should *not* be set directly, but
instead modified with functions like `add-to-list'.
Additionally `treemacs--mac-ignore-file-predicate' is also included on
Mac-derived operating systems (when `system-type' is `darwin')."
:type 'list
:group 'treemacs)
(defcustom treemacs-pre-file-insert-predicates nil
"List of predicates to test for files and directories that shouldn't be shown.
The difference between this and `treemacs-ignored-file-predicates' is that the
functions in this list will be called on files just before they would be
rendered, when the files' git status information is now available. This for
example allows to make files ignored by git invisible (however this particular
use-case is already covered by `treemacs-hide-gitignored-files-mode').
The functions in this list are therefore expected to have a different signature:
They must take two arguments - a file's absolute path and a hash table that maps
files to their git status. The files' paths are the table's keys, its values
are characters (and not strings) indicating the file's git condition. The chars
map map as follows: (the pattern is derived from \\='git status --porcelain\\=')
* M - file is modified
* U - file is in conflict
* ? - file is untracked
* ! - file is ignored
* A - file is added to index
* other - file is unchanged
Otherwise the behaviour is the same as `treemacs-ignored-file-predicates', in
that any one function returning t for a file means that this file will not
be rendered."
:type 'list
:group 'treemacs)
(defcustom treemacs-file-event-delay 2000
"How long (in milliseconds) to collect file events before refreshing.
When treemacs receives a file change notification it doesn't immediately refresh
and instead waits `treemacs-file-event-delay' milliseconds to collect further
file change events. This is done so as to avoid refreshing multiple times in a
short time.
See also `treemacs-filewatch-mode'."
:type 'integer
:group 'treemacs)
(defcustom treemacs-goto-tag-strategy 'refetch-index
"Indicates how to move to a tag when its buffer is dead.
The tags in the treemacs view store their position as markers (or overlays if
semantic mode is on) pointing to a buffer. If that buffer is killed, or has
never really been open, as treemacs kills buffer after fetching their tags if
they did no exist before, the stored positions become stale, and treemacs needs
to use a different method to move to that tag. This variable sets that method.
Its possible values are:
* refetch-index
Call up the file's imenu index again and use its information to jump.
* call-xref
Call `xref-find-definitions' to find the tag.
* issue-warning
Just issue a warning that the tag's position pointer is invalid."
:type 'integer
:group 'treemacs)
(defcustom treemacs-collapse-dirs 0
"When > 0 treemacs will collapse directories into one when possible.
A directory is collapsible when its content consists of nothing but another
directory.
The value determines how many directories can be collapsed at once, both as a
performance cap and to prevent too long directory names in the treemacs view.
To minimise this option's impact on display performance the search for
directories to collapse is done asynchronously in a python script and will thus
only work when python installed. The script should work both on python 2 and 3.
If you experience incorrect display of CJK characters while using this feature
you have to inform Emacs about your language environment using
`set-language-environment'."
:type 'integer
:group 'treemacs)
(defcustom treemacs-silent-refresh nil
"When non-nil a completed refresh will not be announced with a message.
This applies to refreshing both manual as well as automatic (due to e.g.
`treemacs-filewatch-mode').
To only disable messages from refreshes induced by filewatch mode use
`treemacs-silent-filewatch'."
:type 'boolean
:group 'treemacs)
(defcustom treemacs-silent-filewatch nil
"When non-nil a refresh due to filewatch mode will cause no log message.
To disable all refresh messages use `treemacs-silent-refresh'."
:type 'boolean
:group 'treemacs)
(defcustom treemacs-no-png-images nil
"When non-nil treemacs will use TUI string icons even when running in a GUI.
The change will apply the next time a treemacs buffer is created."
:type 'boolean
:group 'treemacs)
(defcustom treemacs-expand-after-init t
"When non-nil expand the first project after treemacs is first initialised.
Might be superseded by `treemacs-follow-after-init'."
:type 'boolean
:group 'treemacs)
(defcustom treemacs-expand-added-projects t
"When non-nil newly added projects will be expanded."
:type 'boolean
:group 'treemacs)
(defcustom treemacs-recenter-after-project-jump 'always
"Decides when to recenter view after moving between projects.
Specifically applies to calling `treemacs-next-project' and
`treemacs-previous-project'.
Possible values are:
* nil: never recenter
* \\='always: always recenter
* \\='on-distance: recenter based on `treemacs-recenter-distance'"
:type '(choice (const :tag "Always" always)
(const :tag "Based on Distance" on-distance)
(const :tag "Never" nil))
:group 'treemacs)
(defcustom treemacs-recenter-after-project-expand 'on-visibility
"Decides when to recenter view after expanding a project root node.
Possible values are:
* nil: never recenter
* \\='always: always recenter
* \\='on-distance: recenter based on `treemacs-recenter-distance'
* \\='on-visibility: recenter only when the newly rendered lines don't fit the
current screen"
:type '(choice (const :tag "Always" always)
(const :tag "Based on Distance" on-distance)
(const :tag "Based on Visibility" on-visibility)
(const :tag "Never" nil))
:group 'treemacs)
(defcustom treemacs-pulse-on-success t
"When non-nil treemacs will pulse the current line as a success indicator.
This applies to actions like `treemacs-copy-relative-path-at-point'."
:type 'boolean
:group 'treemacs)
(defcustom treemacs-pulse-on-failure t
"When non-nil treemacs will pulse the current line as a failure indicator.
This applies to actions like treemacs not finding any tags it can show when
`treemacs-toggle-node' is called on a file node."
:type 'boolean
:group 'treemacs)
(defcustom treemacs-recenter-distance 0.1
"Minimum distance from a window's top/bottom for treemacs to call `recenter'.
This value will apply when any one of the following options is set to
`on-distance':
* treemacs-recenter-after-tag-follow
* treemacs-recenter-after-file-follow
* treemacs-recenter-after-project-jump
* treemacs-recenter-after-project-expand
In that case a call to `recenter' will be made when the distance between point
and the top/bottom of the treemacs window is less then this many lines. The
value is not an absolute line count, but a relative floating-point percentage,
with 0.0 being 0% and 1.0 being 100%.
This means that, for example, when this variable is set to 0.1 `recenter' will
be called within a 10% distance of the treemacs window's top/bottom. For a
window height of 40 lines that means point being within the first or last 4
lines of the treemacs window.
Note that this does *not* take `scroll-margin' into account."
:type 'float
:group 'treemacs)
(defcustom treemacs-elisp-imenu-expression
(let ((name (rx (1+ whitespace) (? "'") (group-n 2 symbol-start (1+ (or (syntax word) (syntax symbol))) symbol-end)))
(prefix (rx bol (0+ (syntax whitespace)) "(")))
`(("Functions"
,(concat prefix (rx (? "cl-") (or "defgeneric" "defmethod" "defun" "defadvice")) name)
2)
("Dependencies"
,(concat prefix "require" name)
2)
("Inline Functions"
,(concat prefix (rx (? "cl-") (or "defsubst" "define-inline")) name)
2)
("Customizations"
,(concat prefix "defcustom" name)
2)
;; struct whose name maybe be wrapped in parens
("Types" ,(rx (group-n 1 (? "cl-") "defstruct" (1+ whitespace) (? "(" (0+ whitespace)))
(group-n 2 symbol-start (1+ (or (syntax word) (syntax symbol))) symbol-end))
2)
("Types"
,(concat
prefix
(rx (group-n
1 (or (seq (? "cl-") "defstruct" (? " ("))
"defclass"
"deftype"
"defgroup"
"define-widget"
"deferror")))
name)
2)
("Variables"
,(concat prefix (rx (or "defvar" "defvar-local" "defconst" "defconst-mode-local")) name)
2)
("Macros"
,(concat prefix (rx (? "cl-") (or "define-compiler-macro" "defmacro")) name)
2)
("Faces"
,(concat prefix (rx "defface") name)
2)))
"The value for `imenu-generic-expression' treemacs uses in elisp buffers.
More discriminating than the default as it distinguishes between functions,
inline functions, macros, faces, variables, customisations and types.
Can be set to nil to use the default value."
:type 'alist
:group 'treemacs)
(defcustom treemacs-persist-file
(expand-file-name ".cache/treemacs-persist" user-emacs-directory)
"Path to the file treemacs uses to persist its state.
Can be set to nil to disable workspace persistence."
:group 'treemacs
:type 'string)
(defcustom treemacs-last-error-persist-file
(expand-file-name ".cache/treemacs-persist-at-last-error" user-emacs-directory)
"File that stores the treemacs state as it was during the last load error."
:group 'treemacs
:type 'string)
(defcustom treemacs-missing-project-action 'ask
"Action to perform when a persisted project is not found on the disk.
If the project is not found, the project can either be kept in the project list,
or removed from it. If the project is removed, when projects are persisted, the
missing project will not appear in the project list next time Emacs is started.
Possible values are:
- `ask'
- `remove'
- `keep'"
:type '(choice (const :tag "Ask whether to remove" ask)
(const :tag "Remove without asking" remove)
(const :tag "Keep without asking" keep))
:group 'treemacs)
(defcustom treemacs-space-between-root-nodes t
"When non-nil treemacs will separate root nodes with an empty line."
:type 'boolean
:group 'treemacs)
(defcustom treemacs-wrap-around t
"When non-nil treemacs will wrap around buffer edges when moving between lines."
:type 'boolean
:group 'treemacs)
(defcustom treemacs--fringe-indicator-bitmap
(if (fboundp 'define-fringe-bitmap)
(define-fringe-bitmap 'treemacs--fringe-indicator-bitmap-default (make-vector 200 #b00000111))
'vertical-bar)
"The fringe bitmap used by the fringe-indicator minor mode."
:type (append '(choice)
;; :type is evaluated before the call to define-fringe-bitmap
;; so 'treemacs--fringe-indicator-bitmap-default is not yet in
;; fringe-bitmaps
'((const treemacs--fringe-indicator-bitmap-default))
;; `fringe-bitmpas' is void in the CI build Emacs
(when (bound-and-true-p fringe-bitmaps)
(mapcar (lambda (sym) `(const ,sym)) fringe-bitmaps)))
:group 'treemacs)
(defcustom treemacs-show-cursor nil
"When non-nil treemacs the cursor will remain visible in the treemacs buffer."
:type 'boolean
:group 'treemacs)
(defcustom treemacs-directory-name-transformer #'identity
"Transformer to apply to directory names before rendering for cosmetic effect."
:type 'function
:group 'treemacs)
(defcustom treemacs-file-name-transformer #'identity
"Transformer to apply to file names before rendering for cosmetic effect."
:type 'function
:group 'treemacs)
(make-obsolete-variable 'treemacs-follow-recenter-distance 'treemacs-recenter-distance "v2.5")
(defcustom treemacs-follow-recenter-distance 0.1
"Minimum distance from the top/bottom for (tag-)follow mode to recenter.
Treemacs will be calling `recenter' after following a file/tag if the distance
between point and the top/bottom of the treemacs window is less then this many
lines. The value is not an absolute line count, but a percentage, with 0.0
being 0% and 1.0 being 100%. This means that when this variable is set to 0.1
`recenter' will be called within a 10% distance of the window top/bottom. For a
window height of 40 lines that means point being within the first or last 4
lines of the treemacs window.
Will only take effect if `treemacs-recenter-after-tag-follow' and/or
`treemacs-recenter-after-file-follow' is non-nil.
Note that this does *not* take `scroll-margin' into account."
:type 'float
:group 'treemacs-follow)
(defcustom treemacs-follow-after-init nil
"When non-nil find the current file in treemacs after it is first initialised.
Might supersede `treemacs-expand-after-init'."
:type 'boolean
:group 'treemacs-follow)
(defcustom treemacs-file-follow-delay 0.2
"Delay in seconds of idle time for treemacs to follow the selected window."
:type 'number
:group 'treemacs-follow)
(defcustom treemacs-tag-follow-delay 1.5
"Delay in seconds of inactivity for `treemacs-tag-follow-mode' to trigger."
:type 'number
:group 'treemacs-follow)
(defcustom treemacs-tag-follow-cleanup t
"When non-nil `treemacs-tag-follow-mode' will close file nodes it is leaving.
When jumping between different files this can prevent the view from being
flooded with their tags."
:type 'boolean
:group 'treemacs-follow)
(defcustom treemacs-recenter-after-file-follow nil
"Decides when to recenter view after following a file.
Possible values are:
* nil: never recenter
* \\='always: always recenter
* \\='on-distance: recenter based on `treemacs-recenter-distance'"
:type '(choice (const :tag "Always" always)
(const :tag "Based on Distance" on-distance)
(const :tag "Never" nil))
:group 'treemacs-follow)
(defcustom treemacs-recenter-after-tag-follow nil
"Decides when to recenter view after following a tag.
Possible values are:
* nil: never recenter
* \\='always: always recenter
* \\='on-distance: recenter based on `treemacs-recenter-distance'"
:type '(choice (const :tag "Always" always)
(const :tag "Based on Distance" on-distance)
(const :tag "Never" nil))
:group 'treemacs-follow)
(defcustom treemacs-project-follow-cleanup nil
"When non-nil `treemacs-follow-mode' will close projects it is leaving.
This means that treemacs will make sure that only the currently followed project
is expanded while all others will remain collapsed.
Setting this to t might lead to noticeable slowdowns, at least when
`treemacs-git-mode' is enabled, since constantly expanding an entire project is
fairly expensive."
:type 'boolean
:group 'treemacs-follow)
(defcustom treemacs-project-follow-into-home nil
"When non-nil `treemacs-project-follow-mode' will also follow into $HOME.
By default project-following excludes the home directory as an option for the
current project. Setting this to non-nil will open up $HOME to being the final
fallback."
:type 'boolean
:group 'treemacs-follow)
(defcustom treemacs-move-files-by-mouse-dragging t
"When non-nil treemacs will move files by dragging with the mouse."
:group 'treemacs-mouse
:type 'boolean)
(defcustom treemacs-deferred-git-apply-delay 0.5
"Delay in seconds of idle time before git fontification is applied.
This is only relevant when using the deferred variant of git-mode."
:type 'number
:group 'treemacs-git)
(defcustom treemacs-max-git-entries 5000
"Maximum number of git status entries treemacs will process.
Information for entries that number will be silently ignored. The \"entries\"
refer to the lines output by `git status --porcelain --ignored=matching'. The
limit does not apply to the simple `treemacs-git-mode.'"
:type 'number
:group 'treemacs-git)
(defcustom treemacs-python-executable (treemacs--find-python3)
"The python executable used by treemacs.
An asynchronous python process is used in two optional features:
`treemacs-collapse-dirs' and the extended variant of `treemacs-git-mode'.
There is generally only one reason to change this value: an extended
`treemacs-git-mode' requires python3 to work. If the default python executable
is pointing to python2 this config variable can be used to direct treemacs to
the python3 binary."
:type 'string
:group 'treemacs-git)
(defcustom treemacs-git-command-pipe ""
"Text to be appended to treemacs' git command.
With `treemacs-git-mode' the command
`git status --porcelain --ignored=matching .' is run to fetch a directory's git
information. The content of this variable will be appended to this git command.
This might be useful in cases when the output produced by git is so large that
it leads to palpable delays, while setting `treemacs-max-git-entries' leads to
loss of information. In such a scenario an additional filter statement (for
example `| grep -v \"/vendor_dir/\"') can be used to reduce the size of the
output to a manageable volume for treemacs."
:type 'string
:group 'treemacs-git)
(defcustom treemacs-is-never-other-window nil
"When non-nil treemacs will use the `no-other-window' parameter.
In practice it means that treemacs will become invisible to commands like
`other-window' or `evil-window-left'."
:type 'boolean
:group 'treemacs-window)
(defcustom treemacs-width-is-initially-locked t
"Indicates whether the width of the treemacs window is initially locked.
A locked width means that changes it is only possible with the commands
`treemacs-set-width' or `treemacs-toggle-fixed-width'."
:type 'boolean
:group 'treemacs-window)
(defcustom treemacs-window-background-color nil
"This variable is obsolete and no longer in use.
Instead you can modify `treemacs-window-background-face' and
`treemacs-hl-line-face'."
:type '(cons color color)
:group 'treemacs-window)
(make-obsolete-variable
'treemacs-window-background-color
"`treemacs-window-background-face' & `treemacs-hl-line-face'"
"v3.2" 'set)
(defcustom treemacs-width 35
"Width of the treemacs window."
:type 'integer
:group 'treemacs-window)
(defcustom treemacs-wide-toggle-width 70
"When resizing, this value is added or subtracted from the window width."
:type 'integer
:group 'treemacs-window)
(defcustom treemacs-width-increment 1
"When resizing, this value is added or subtracted from the window width."
:type 'integer
:group 'treemacs-window)
(defcustom treemacs-display-in-side-window t
"When non-nil treemacs will use a dedicated side-window.
On the one hand this will alleviate issues of unequally sized window splits when
treemacs is visible (since Emacs does not quite understand that treemacs has
fixed window size). On the other hand it may lead to issues with other packages
like shell-pop, as making treemacs a side-window renders it un-splittable."
:type 'boolean
:group 'treemacs-window)
(defcustom treemacs-no-delete-other-windows t
"When non-nil treemacs will have the `no-delete-other-windows' parameter.
This parameter prevents the treemacs window from closing when calling
`delete-other-windows' or when a command like `magit-status' would launch a new
full-screen buffer.
Note that treemacs has its own delete-windows command with
`treemacs-delete-other-windows' that behaves the same as `delete-other-windows',
but won't close treemacs itself.
This parameter was only introduced in Emacs 26. On Emacs 25 its effect is
included in `treemacs-display-in-side-window'."
:type 'boolean
:group 'treemacs-window)
(defcustom treemacs-user-header-line-format nil
"The header line used in the treemacs window.
Can be set either to `treemacs-header-buttons-format' or any one of its
constituent parts, or any other value acceptable for `header-line-format'."
:type 'string
:group 'treemacs-window)
(defcustom treemacs-text-scale nil
"Optional scale for the text (not the icons) in the treemacs window.
If set the value will be passed to `text-scale-increase'. Both positive and
negative values are possible."
:type 'integer
:group 'treemacs-window)
(defcustom treemacs-header-scroll-indicators '(nil . "^^^^^^")
"The strings used for `treemacs-indicate-top-scroll-mode'.
The value must be a cons, where the car is the string used when treemacs is
scrolled all the way to the top, and the cdr is used when it isn't."
:type '(cons string string)
:group 'treemacs-window)
(defcustom treemacs-select-when-already-in-treemacs 'move-back
"How `treemacs-select-window' behaves when treemacs is already selected.
Possible values are:
- `stay' - remain in the treemacs windows, effectively doing nothing
- `close' - close the treemacs window
- `goto-next' - jump to the next treemacs-based window (e.g. treemacs-mu4e)
- `move-back' - move point back to the most recently used window (as selected
by `get-mru-window')
- `next-or-back' - a combination of the two previous options. First try to
move to the next treemacs-based window, if none exists move back to the most
recently used window"
:type '(choice (const stay)
(const close)
(const move-back))
:group 'treemacs)
(defcustom treemacs-position 'left
"Position of treemacs buffer.
Valid values are
* `left',
* `right'"
:type '(choice (const left)
(const right))
:group 'treemacs)
(defcustom treemacs-post-buffer-init-hook nil
"Hook run after a treemacs buffer is first initialised.
Only applies to treemacs filetree buffers, not extensions."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-post-project-refresh-functions nil
"Hook that runs after a project was updated with `treemacs-refresh'.
Will be called with the new project as the sole argument."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-create-project-functions nil
"Hooks to run whenever a project is created.
Will be called with the new project as the sole argument."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-create-file-functions nil
"Hooks to run whenever a file or directory is created.
Applies only when using `treemacs-create-file' or `treemacs-create-dir'.
Will be called with the created file's or dir's path as the sole argument."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-delete-file-functions nil
"Hooks to run whenever a file or directory is deleted.
Applies only when using `treemacs-delete'. Will be called with the created
file's or dir's path as the sole argument."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-rename-file-functions nil
"Hooks to run whenever a file or directory is renamed.
Applies only when using `treemacs-rename'. Will be called with 2 arguments: the
file's old name, and the file's new name, both as absolute paths."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-move-file-functions nil
"Hooks to run whenever a file or directory is moved.
Applies only when using `treemacs-move-file'. Will be called with 2 arguments:
the file's old location, and the file's new location, both as absolute paths."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-copy-file-functions nil
"Hooks to run whenever a file or directory is copied.
Applies only when using `treemacs-copy-file'. Will be called with 2 arguments:
the original file's location, and the copy's location, both as absolute paths."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-delete-project-functions nil
"Hooks to run whenever a project is deleted.
Will be called with the deleted project as the sole argument *after* it has been
deleted."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-find-workspace-method 'find-for-file-or-pick-first
"The method by which treemacs selects a workspace when first starting.
There are 3 options:
- `find-for-file-or-pick-first' means treemacs will select the first workspace
with a project that contains the current buffer's file. If no such workspace
exists, or if the current buffer is not visiting a file, the first workspace
in the list (as seen in `treemacs-edit-workspaces' or picked with
`treemacs-set-fallback-workspace') is selected
- `find-for-file-or-manually-select' works the same, but an interactive
selection is used as fallback instead
- `always-ask' means the workspace *always* has to be manually selected
Note that the selection process will be skipped if there is only one workspace."
:type '(choice (const
:tag "Find workspace for current file, pick the first workspace as falback"
find-for-file-or-pick-first)
(const
:tag "Find workspace for current file, interactively select workspace as falback"
find-for-file-or-manually-select)
(const :tag "Always ask" always-ask))
:group 'treemacs-hooks)
(defcustom treemacs-rename-project-functions nil
"Hooks to run whenever a project is renamed.
Will be called with the renamed project and the old name as its arguments."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-create-workspace-functions nil
"Hooks to run whenever a workspace is created.
Will be called with the new workspace as the sole argument."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-delete-workspace-functions nil
"Hooks to run whenever a workspace is deleted.
Will be called with the deleted workspace as the sole argument *after* it has
been deleted."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-rename-workspace-functions nil
"Hooks to run whenever a workspace is renamed.
Will be called with the renamed workspace and the old name as its arguments."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-switch-workspace-hook nil
"Hooks to run whenever the workspace is changed.
The current workspace will be available as `treemacs-current-workspace'."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-workspace-edit-hook nil
"Hooks to run whenever the entire workspace layout has been rebuilt.
This hook runs after `treemacs-finish-edit' has been called. After such an edit
any number (including zero) of workspaces and projects may have been changed or
created or deleted."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-bookmark-title-template "Treemacs - ${project}: ${label}"
"Template for default bookmark titles.
The following replacements are available:
* ${project}: The label of the project.
* ${label}: Label of the current button.
* ${label:N} Label of the Nth parent.
If the parent does not exist, an empty string.
* ${label-path}: Label path of the button.
For example, \"Project/directory/file.txt\"
* ${label-path:N}: Last N components of the label path.
* ${file-path}: Absolute file-system path of the node.
If the node is a top-level extension node, this expands to an empty string.
If the node is a directory or or project extension, the path of its parent.
* ${file-path:N}: Last N components of the filesystem path."
:type 'string
:group 'treemacs)
(defcustom treemacs-pre-refresh-hook nil
"Hooks to run right before the refresh process for a project kicks off.
During the refresh the project is effectively collapsed and then expanded again.
This hook runs *before* that happens. It runs with treemacs as the
`current-buffer' and receives as its arguments all the information that treemacs
collects for its refresh process:
* The project being refreshed (might be \\='all)
* The current screen-line number (can be nil).
* The current button. Might be nil if point is on the header line.
* The current button's state. See also `treemacs-valid-button-states'. Is nil
if the current button is nil.
* The nearest file path, as collected with `treemacs--nearest-path'. Is nil if
point is on the header.
* The current button's tag path. Is nil if the current button is nil."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-post-refresh-hook nil
"Hooks to run right before the refresh process is finished off.
During the refresh the project is effectively collapsed and then expanded again.
This hook runs *after* that has happened. It runs with treemacs as the
`current-buffer' and receives as its arguments all the information that treemacs
collects for its refresh process. Note that these values were collected at the
start of the refresh, and may now be longer valid (for example the current
button's position will be wrong, even if it wasn't deleted outright):
* The project being refreshed (might be \\='all)
* The current screen-line number (can be nil).
* The current button. Might be nil if point was on the header line.
* The current button's state. See also `treemacs-valid-button-states'. Is nil
if the current button is nil.
* The nearest file path, as collected with `treemacs--nearest-path'. Is nil if
point was on the header.
* The current button's tag path. Is nil if the current button is nil."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-quit-hook nil
"Hooks to run when `treemacs-quit' is called.
The hooks will be run *after* the treemacs buffer was buried."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-kill-hook nil
"Hooks to run when `treemacs-kill-buffer' is called.
The hooks will be run *after* the treemacs buffer was destroyed."
:type 'hook
:group 'treemacs-hooks)
(define-obsolete-variable-alias 'treemacs-select-hook 'treemacs-select-functions "2.9")
(defcustom treemacs-select-functions nil
"Hooks to run when the treemacs window is selected.
The hook should accept one argument which is a symbol describing treemacs'
visibility before the select was invoked, as it would have been returned by
`treemacs-current-visibility'.
This hook only applies to commands like `treemacs' or `treemacs-select-window',
not general window selection commands like `other-window'."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-workspace-first-found-functions nil
"Hooks that run when treemacs finds a workspace for the first time.
Hooks are expected to take 2 arguments: the workspace that was found and the
current scope (frame or perspective) it was found for."
:type 'hook
:group 'treemacs-hooks)
(defcustom treemacs-after-visit-functions nil
"Hooks that run after treemacs executes a `treemacs-visit-node-***' command.
Does not apply to `treemacs-visit-node-in-external-application'. Hooks are
expected to take 1 argument, which is the buffer where the node is visited in."
:type 'hook
:group 'treemacs-hooks)
(defconst treemacs-last-period-regex-value "\\.[^.]*\\'")
(defconst treemacs-first-period-regex-value "\\.")
(defcustom treemacs-file-extension-regex treemacs-last-period-regex-value
"Decides how treemacs determines a file's extension.
There are 2 options:
- An extension should be everything past the *last* period of the file name.
In this case this should be set to `treemacs-last-period-regex-value'
- An extension should be everything past the *first* period of the file name.
In this case this should be set to `treemacs-first-period-regex-value'"
:group 'treemacs
:type `(choice (const :tag "Text after first period" ,treemacs-first-period-regex-value)
(const :tag "Text after last period" ,treemacs-last-period-regex-value)))
(defcustom treemacs-user-mode-line-format nil
"Custom mode line format to be used in `treemacs-mode'.
If nil treemacs will look for default value provided by `spaceline', `moody'
or `doom-modeline' in that order. Finally, if none of these packages is
available \"Treemacs\" text will be displayed.
Setting this to `none' will disable the modeline.
For more specific information about formatting mode line check
`mode-line-format'."
:type 'sexp
:group 'treemacs)
(defcustom treemacs-workspace-switch-cleanup nil
"Indicates which, if any, buffers should be deleted on a workspace switch.
Only applies when interactively calling `treemacs-switch-workspace'.
Valid values are
- nil to do nothing
- `files' to delete buffers visiting files
- `all' to delete all buffers other than treemacs and the scratch buffer
In any case treemacs itself and the scratch and messages buffer will be
unaffected."
:type '(choice (const :tag "All Buffers" all)
(const :tag "Only File Buffers" files)
(const :tag "None" nil))
:group 'treemacs)
(defcustom treemacs-imenu-scope 'everything
"Determines which items treemacs' imenu function will collect.
There are 2 options:
- `everything' will collect entries from every project in the workspace.
- `current-project' will only gather the index for the project at point."
:type '(choice (const :tag "Everything" everything)
(const :tag "Current Project Only" current-project))
:group 'treemacs)
(provide 'treemacs-customization)
;;; treemacs-customization.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-customization.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 11,690 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; File event watch and reaction implementation.
;; Open directories are put under watch and file changes event
;; collected even if filewatch-mode is disabled. This allows to
;; remove deleted files from all the caches they are in. Activating
;; filewatch-mode will therefore only enable automatic refresh of
;; treemacs buffers.
;;; Code:
(require 'dash)
(require 's)
(require 'ht)
(require 'filenotify)
(require 'treemacs-core-utils)
(require 'treemacs-async)
(require 'treemacs-dom)
(require 'treemacs-rendering)
(eval-when-compile
(require 'treemacs-macros)
(require 'inline))
(defvar treemacs--collapsed-filewatch-index (make-hash-table :size 100 :test #'equal)
"Keeps track of dirs under filewatch due to being collapsed into one.
Collapsed directories require special handling since all directories of a series
need to be put under watch so as to be notified when the collapsed structure
needs to change, but removing the file watch is not straightforward:
Assume a series of directories are collapsed into one as \"/c1/c2/c3/c4\" and a
new file is created in \"/c1/c2\". A refresh is started and only \"/c1/c2\" is
collapsed now, c3 and c4 are no longer part of the treemacs view and must be
removed from the filewatch list. However the event that triggered the refresh
was one of a file being created, so it is not possible to know that c3 and c4
need to stop being watched unless one also knows that they and c2 are under file
watch because they have been collapsed.
This is why this hash is used to keep track of collapsed directories under file
watch.")
(defvar treemacs--filewatch-index (make-hash-table :size 100 :test 'equal)
"Hash of all directories being watched for changes.
A file path is the key, the value is a cons, its car is a list of the treemacs
buffers watching that path, its cdr is the watch descriptor.")
(defvar treemacs--refresh-timer nil
"Timer that will run a refresh after `treemacs-file-event-delay' ms.
Stored here to allow it to be cancelled by a manual refresh.")
(define-inline treemacs--start-filewatch-timer ()
"Start the filewatch timer if it is not already running."
(inline-quote
(unless treemacs--refresh-timer
(setf treemacs--refresh-timer
(run-with-timer (/ treemacs-file-event-delay 1000) nil
#'treemacs--process-file-events)))))
(define-inline treemacs--cancel-refresh-timer ()
"Cancel a the running refresh timer if it is active."
(inline-quote
(when treemacs--refresh-timer
(cancel-timer treemacs--refresh-timer)
(setq treemacs--refresh-timer nil))))
(define-inline treemacs--start-watching (path &optional collapse)
"Watch PATH for file system events.
Assumes to be run in the treemacs buffer as it will set PATH to be watched by
`current-buffer'.
Also add PATH to `treemacs--collapsed-filewatch-index' when COLLAPSE is non-nil.
PATH: Filepath
COLLAPSE: Bool"
(inline-letevals (path collapse)
(inline-quote
(progn
(when ,collapse
(ht-set! treemacs--collapsed-filewatch-index ,path t))
(-if-let (watch-info (ht-get treemacs--filewatch-index ,path))
;; just add current buffer to watch list if path is watched already
(unless (memq (current-buffer) (car watch-info))
(setcar watch-info (cons (current-buffer) (car watch-info))))
;; if the Tramp connection does not support watches, don't show an error
;; every time a watch is started.
(treemacs-with-ignored-errors
((file-notify-error "No file notification program found"))
;; make new entry otherwise and set a new watcher
(ht-set! treemacs--filewatch-index
,path
(cons (list (current-buffer))
(file-notify-add-watch ,path '(change) #'treemacs--filewatch-callback)))))))))
(define-inline treemacs--stop-watching (path &optional all)
"Stop watching PATH for file events.
This also means stopping the watch over all dirs below path.
Must be called inside the treemacs buffer since it will remove `current-buffer'
from PATH's watch list. Does not apply if this is called in reaction to a file
being deleted. In this case ALL is t and all buffers watching PATH will be
removed from the filewatch hashes.
PATH: Filepath
ALL: Bool"
(inline-letevals (path all)
(inline-quote
(let (to-remove)
(treemacs--maphash treemacs--filewatch-index (watched-path watch-info)
(when (treemacs-is-path watched-path :in ,path)
(let ((watching-buffers (car watch-info))
(watch-descr (cdr watch-info)))
(if ,all
(progn
(file-notify-rm-watch watch-descr)
(ht-remove! treemacs--collapsed-filewatch-index watched-path)
(push watched-path to-remove))
(when (memq (current-buffer) watching-buffers)
(if (cdr watching-buffers)
(setcar watch-info (delq (current-buffer) watching-buffers))
(file-notify-rm-watch watch-descr)
(ht-remove! treemacs--collapsed-filewatch-index watched-path)
(push watched-path to-remove)))))))
(dolist (it to-remove)
(ht-remove! treemacs--filewatch-index it))))))
(define-inline treemacs--is-event-relevant? (event)
"Decide if EVENT is relevant to treemacs or should be ignored.
An event counts as relevant when
1) The event's action is not \"stopped\".
2) The event's action is not \"changed\" while `treemacs-git-mode' is disabled
3) The event's file will not return t when given to any of the functions which
are part of `treemacs-ignored-file-predicates'."
(declare (side-effect-free t))
(inline-letevals (event)
(inline-quote
(when (with-no-warnings treemacs-filewatch-mode)
(let ((action (cadr ,event)))
(not (or (eq action 'stopped)
(and (eq action 'changed)
(not treemacs-git-mode))
(and treemacs-hide-gitignored-files-mode
(let* ((file (caddr ,event))
(parent (treemacs--parent-dir file))
(cache (ht-get treemacs--git-cache parent)))
(and cache (eq 'treemacs-git-ignored-face (ht-get cache file)))))
(let* ((dir (caddr ,event))
(filename (treemacs--filename dir)))
(--any? (funcall it filename dir) treemacs-ignored-file-predicates)))))))))
(define-inline treemacs--set-refresh-flags (location type path)
"Set refresh flags at LOCATION for TYPE and PATH in the dom of every buffer.
Also start the refresh timer if it's not started already."
(inline-letevals (location type path)
(inline-quote
(progn
(when (ht-get treemacs--collapsed-filewatch-index ,path)
(ht-remove! treemacs--collapsed-filewatch-index ,path)
(treemacs--stop-watching ,path))
(treemacs-run-in-every-buffer
(--when-let (treemacs-find-in-dom ,location)
(let ((current-flag (assoc ,path (treemacs-dom-node->refresh-flag it))))
(pcase (cdr current-flag)
(`nil
(push (cons ,path ,type) (treemacs-dom-node->refresh-flag it)))
('created
(when (eq ,type 'deleted)
(setf (cdr current-flag) 'deleted)))
('deleted
(when (eq ,type 'created)
(setf (cdr current-flag) 'created)))
('changed
(when (eq ,type 'deleted)
(setf (cdr current-flag) 'deleted))))))
(treemacs--start-filewatch-timer))))))
(defun treemacs--filewatch-callback (event)
"Add EVENT to the list of file change events.
Do nothing if this event's file is irrelevant as per
`treemacs--is-event-relevant?'. Otherwise start a timer to process the
collected events if it has not been started already. Also immediately remove
the changed file from caches if it has been deleted instead of waiting for file
processing."
(when (treemacs--is-event-relevant? event)
(-let [(_ event-type path) event]
(when (eq 'deleted event-type)
(treemacs--on-file-deletion path :no-buffer-delete))
(if (eq 'renamed event-type)
(let ((old-name path)
(new-name (cadddr event)))
(treemacs-run-in-every-buffer
(treemacs--on-rename old-name new-name (with-no-warnings treemacs-filewatch-mode)))
(treemacs--set-refresh-flags (treemacs--parent old-name) 'deleted old-name)
(when (--none? (funcall it (treemacs--filename new-name) new-name) treemacs-ignored-file-predicates)
(treemacs--set-refresh-flags (treemacs--parent new-name) 'created new-name)))
(treemacs--set-refresh-flags (treemacs--parent path) event-type path)))))
(define-inline treemacs--do-process-file-events ()
"Dumb helper function.
Extracted only so `treemacs--process-file-events' can decide when to call
`save-excursion' without code duplication."
(inline-quote
(treemacs-run-in-every-buffer
(treemacs-save-position
(-let [treemacs--no-messages (or treemacs-silent-refresh treemacs-silent-filewatch)]
(dolist (project (treemacs-workspace->projects workspace))
(-when-let (root-node (-> project (treemacs-project->path) (treemacs-find-in-dom)))
(treemacs--recursive-refresh-descent root-node project)))))
(hl-line-highlight))))
(defun treemacs--process-file-events ()
"Process the file events that have been collected.
Stop watching deleted dirs and refresh all the buffers that need updating."
(setf treemacs--refresh-timer nil)
(treemacs-without-following
(if (eq treemacs--in-this-buffer t)
(treemacs--do-process-file-events)
;; need to save excursion here because an update when the treemacs window is not visible
;; will actually move point in the current buffer
;; TODO(2019/07/18): check if this is still necessary after granular filewatch is done
(save-excursion
(treemacs--do-process-file-events)))))
(defun treemacs--stop-filewatch-for-current-buffer ()
"Called when a treemacs buffer is torn down/killed.
Will stop file watch on every path watched by this buffer."
(let ((buffer (treemacs-get-local-buffer))
(to-remove))
(treemacs--maphash treemacs--filewatch-index (watched-path watch-info)
(-let [(watching-buffers . watch-descr) watch-info]
(when (memq buffer watching-buffers)
(if (= 1 (length watching-buffers))
(progn
(file-notify-rm-watch watch-descr)
(ht-remove! treemacs--collapsed-filewatch-index watched-path)
(push watched-path to-remove))
(setcar watch-info (delq buffer watching-buffers))))))
(dolist (it to-remove)
(ht-remove! treemacs--filewatch-index it))))
(defun treemacs--stop-watching-all ()
"Cancel any and all running file watch processes.
Clear the filewatch and collapsed filewatch indices.
Reset the refresh flags of every buffer.
Called when filewatch mode is disabled."
(treemacs-run-in-every-buffer
(treemacs--maphash treemacs-dom (_ node)
(setf (treemacs-dom-node->refresh-flag node) nil)))
(treemacs--maphash treemacs--filewatch-index (_ watch-info)
(file-notify-rm-watch (cdr watch-info)))
(ht-clear! treemacs--filewatch-index)
(ht-clear! treemacs--collapsed-filewatch-index))
(define-inline treemacs--tear-down-filewatch-mode ()
"Stop watch processes, throw away file events, stop the timer."
(inline-quote
(progn
(treemacs--stop-watching-all)
(treemacs--cancel-refresh-timer))))
(define-minor-mode treemacs-filewatch-mode
"Minor mode to let treemacs auto-refresh itself on file system changes.
Activating this mode enables treemacs to watch the files it is displaying (and
only those) for changes and automatically refresh its view when it detects a
change that it decides is relevant.
A file change event is relevant for treemacs if a new file has been created or
deleted or a file has been changed and `treemacs-git-mode' is enabled. Events
caused by files that are ignored as per `treemacs-ignored-file-predicates' are
counted as not relevant.
The refresh is not called immediately after an event was received, treemacs
instead waits `treemacs-file-event-delay' ms to see if any more files have
changed to avoid having to refresh multiple times over a short period of time.
Due to limitations in the underlying kqueue library this mode may not be able to
track file modifications on MacOS, making it miss potentially useful updates
when used in combination with `treemacs-git-mode.'
The watch mechanism only applies to directories opened *after* this mode has
been activated. This means that to enable file watching in an already existing
treemacs buffer it needs to be torn down and rebuilt by calling `treemacs' or
`treemacs-projectile'.
Turning off this mode is, on the other hand, instantaneous - it will immediately
turn off all existing file watch processes and outstanding refresh actions."
:init-value nil
:global t
:lighter nil
:group 'treemacs
(unless treemacs-filewatch-mode
(treemacs--tear-down-filewatch-mode)))
;; in case we don't have a file notification library (like on travis CI)
(unless file-notify--library
(fset 'treemacs--start-watching (lambda (_x &optional _y) (ignore)))
(fset 'treemacs--stop-watching (lambda (_x &optional _y) (ignore))))
(treemacs-only-during-init (treemacs-filewatch-mode))
(provide 'treemacs-filewatch-mode)
;;; treemacs-filewatch-mode.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-filewatch-mode.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 3,353 |
```emacs lisp
;;; treemacs-mode.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Major mode definition.
;;; Code:
(require 'eldoc)
(require 's)
(require 'treemacs-interface)
(require 'treemacs-customization)
(require 'treemacs-faces)
(require 'treemacs-core-utils)
(require 'treemacs-icons)
(require 'treemacs-scope)
(require 'treemacs-persistence)
(require 'treemacs-dom)
(require 'treemacs-workspaces)
(require 'treemacs-visuals)
(eval-when-compile
(require 'treemacs-macros)
(require 'cl-lib))
(with-eval-after-load 'bookmark
(require 'treemacs-bookmarks))
(treemacs-import-functions-from "treemacs"
treemacs-refresh
treemacs-version
treemacs-edit-workspaces)
(treemacs-import-functions-from "treemacs-bookmarks"
treemacs-add-bookmark
treemacs--make-bookmark-record)
(treemacs-import-functions-from "treemacs-hydras"
treemacs-helpful-hydra
treemacs-common-helpful-hydra
treemacs-advanced-helpful-hydra)
(treemacs-import-functions-from "treemacs-tags"
treemacs--create-imenu-index-function)
(defvar bookmark-make-record-function)
(defvar-local treemacs--eldoc-msg nil
"Message to be output by `treemacs--eldoc-function'.
Will be set by `treemacs--post-command'.")
(defconst treemacs--eldoc-obarray
(-let [ob (make-vector 59 0)]
(mapatoms
(lambda (cmd) (set (intern (symbol-name cmd) ob) t))
eldoc-message-commands)
(dolist (cmd '(treemacs-next-line
treemacs-previous-line
treemacs-next-neighbour
treemacs-previous-neighbour
treemacs-next-project
treemacs-previous-project
treemacs-goto-parent-node
treemacs-TAB-action
treemacs-select-window
treemacs-leftclick-action))
(set (intern (symbol-name cmd) ob) t))
ob)
"Treemacs' own eldoc obarray.")
(defvar treemacs-project-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "r") 'treemacs-rename-project)
(define-key map (kbd "a") 'treemacs-add-project-to-workspace)
(define-key map (kbd "d") 'treemacs-remove-project-from-workspace)
(define-key map (kbd "c c") 'treemacs-collapse-project)
(define-key map (kbd "c o") 'treemacs-collapse-other-projects)
(define-key map (kbd "c a") 'treemacs-collapse-all-projects)
map)
"Keymap for project-related commands in `treemacs-mode'.")
(defvar treemacs-workspace-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "r") 'treemacs-rename-workspace)
(define-key map (kbd "a") 'treemacs-create-workspace)
(define-key map (kbd "d") 'treemacs-remove-workspace)
(define-key map (kbd "s") 'treemacs-switch-workspace)
(define-key map (kbd "e") 'treemacs-edit-workspaces)
(define-key map (kbd "f") 'treemacs-set-fallback-workspace)
(define-key map (kbd "n") 'treemacs-next-workspace)
map)
"Keymap for workspace-related commands in `treemacs-mode'.")
(defvar treemacs-node-visit-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "v") 'treemacs-visit-node-vertical-split)
(define-key map (kbd "c") 'treemacs-visit-node-close-treemacs)
(define-key map (kbd "h") 'treemacs-visit-node-horizontal-split)
(define-key map (kbd "o") 'treemacs-visit-node-no-split)
(define-key map (kbd "aa") 'treemacs-visit-node-ace)
(define-key map (kbd "ah") 'treemacs-visit-node-ace-horizontal-split)
(define-key map (kbd "av") 'treemacs-visit-node-ace-vertical-split)
(define-key map (kbd "r") 'treemacs-visit-node-in-most-recently-used-window)
(define-key map (kbd "x") 'treemacs-visit-node-in-external-application)
map)
"Keymap for node-visiting commands in `treemacs-mode'.")
(defvar treemacs-toggle-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "h") 'treemacs-toggle-show-dotfiles)
(define-key map (kbd "i") 'treemacs-hide-gitignored-files-mode)
(define-key map (kbd "w") 'treemacs-toggle-fixed-width)
(define-key map (kbd "v") 'treemacs-fringe-indicator-mode)
(define-key map (kbd "g") 'treemacs-git-mode)
(define-key map (kbd "f") 'treemacs-follow-mode)
(define-key map (kbd "a") 'treemacs-filewatch-mode)
(define-key map (kbd "n") 'treemacs-indent-guide-mode)
(define-key map (kbd "c") 'treemacs-indicate-top-scroll-mode)
(define-key map (kbd "d") 'treemacs-git-commit-diff-mode)
map)
"Keymap for commands that toggle state in `treemacs-mode'.")
(defvar treemacs-copy-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "a") 'treemacs-copy-absolute-path-at-point)
(define-key map (kbd "r") 'treemacs-copy-relative-path-at-point)
(define-key map (kbd "p") 'treemacs-copy-project-path-at-point)
(define-key map (kbd "f") 'treemacs-copy-file)
(define-key map (kbd "v") 'treemacs-paste-dir-at-point-to-minibuffer)
map)
"Keymap for copy commands in `treemacs-mode'.")
(defvar treemacs-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "?") 'treemacs-common-helpful-hydra)
(define-key map (kbd "C-?") 'treemacs-advanced-helpful-hydra)
(define-key map [down-mouse-1] 'treemacs-leftclick-action)
(define-key map [drag-mouse-1] 'treemacs-dragleftclick-action)
(define-key map [double-mouse-1] 'treemacs-doubleclick-action)
(define-key map [mouse-3] 'treemacs-rightclick-menu)
(define-key map [tab] 'treemacs-TAB-action)
(define-key map [?\t] 'treemacs-TAB-action)
(define-key map [return] 'treemacs-RET-action)
(define-key map (kbd "RET") 'treemacs-RET-action)
(define-key map (kbd "r") 'treemacs-refresh)
(define-key map (kbd "d") 'treemacs-delete-file)
(define-key map (kbd "cf") 'treemacs-create-file)
(define-key map (kbd "cd") 'treemacs-create-dir)
(define-key map (kbd "R") 'treemacs-rename-file)
(define-key map (kbd "u") 'treemacs-goto-parent-node)
(define-key map (kbd "q") 'treemacs-quit)
(define-key map (kbd "Q") 'treemacs-kill-buffer)
(define-key map (kbd "o") treemacs-node-visit-map)
(define-key map (kbd "P") 'treemacs-peek-mode)
(define-key map (kbd "n") 'treemacs-next-line)
(define-key map (kbd "p") 'treemacs-previous-line)
(define-key map (kbd "M-N") 'treemacs-next-line-other-window)
(define-key map (kbd "M-P") 'treemacs-previous-line-other-window)
(define-key map (kbd "<prior>") 'treemacs-previous-page-other-window)
(define-key map (kbd "<next>") 'treemacs-next-page-other-window)
(define-key map (kbd "M-n") 'treemacs-next-neighbour)
(define-key map (kbd "M-p") 'treemacs-previous-neighbour)
(define-key map (kbd "t") treemacs-toggle-map)
(define-key map (kbd "w") 'treemacs-set-width)
(define-key map (kbd "<") 'treemacs-decrease-width)
(define-key map (kbd ">") 'treemacs-increase-width)
(define-key map (kbd "y") treemacs-copy-map)
(define-key map (kbd "m") 'treemacs-move-file)
(define-key map (kbd "g") 'treemacs-refresh)
(define-key map (kbd "s") 'treemacs-resort)
(define-key map (kbd "b") 'treemacs-add-bookmark)
(define-key map (kbd "C-c C-p") treemacs-project-map)
(define-key map (kbd "C-c C-w") treemacs-workspace-map)
(define-key map (kbd "<M-up>") 'treemacs-move-project-up)
(define-key map (kbd "<M-down>") 'treemacs-move-project-down)
(define-key map (kbd "<backtab>") 'treemacs-collapse-all-projects)
(define-key map (kbd "C-j") 'treemacs-next-project)
(define-key map (kbd "C-k") 'treemacs-previous-project)
(define-key map (kbd "h") 'treemacs-COLLAPSE-action)
(define-key map (kbd "l") 'treemacs-RET-action)
(define-key map (kbd "M-h") 'treemacs-COLLAPSE-action)
(define-key map (kbd "M-l") 'treemacs-RET-action)
(define-key map (kbd "M-H") 'treemacs-root-up)
(define-key map (kbd "M-L") 'treemacs-root-down)
(define-key map (kbd "H") 'treemacs-collapse-parent-node)
(define-key map (kbd "!") 'treemacs-run-shell-command-for-current-node)
(define-key map (kbd "M-!") 'treemacs-run-shell-command-in-project-root)
(define-key map (kbd "C") 'treemacs-cleanup-litter)
(define-key map (kbd "=") 'treemacs-fit-window-width)
(define-key map (kbd "W") 'treemacs-extra-wide-toggle)
(define-key map (kbd "M-m") 'treemacs-bulk-file-actions)
(unless (window-system)
(define-key map [C-i] 'treemacs-TAB-action))
map)
"Keymap for `treemacs-mode'.")
(defun treemacs--setup-mode-line ()
"Create either a simple modeline, or integrate into spaceline."
(setq mode-line-format
(cond (treemacs-user-mode-line-format
(if (eq 'none treemacs-user-mode-line-format)
nil
treemacs-user-mode-line-format))
((fboundp 'spaceline-install)
(spaceline-install
"treemacs" '((workspace-number
:face highlight-face)
major-mode)
nil)
'("%e" (:eval (spaceline-ml-treemacs))))
((and (listp (default-value 'mode-line-format))
(member 'moody-mode-line-buffer-identification
(default-value 'mode-line-format)))
'(:eval (moody-tab " Treemacs " 10 'down)))
((featurep 'doom-modeline)
(with-no-warnings
(eval
'(progn
(require 'doom-modeline)
(doom-modeline-def-segment treemacs-workspace-name
"Display treemacs."
(propertize (format " %s " (treemacs-workspace->name (treemacs-current-workspace)))
'face (doom-modeline-face 'doom-modeline-buffer-minor-mode)))
(doom-modeline-def-modeline 'treemacs '(bar " " major-mode) '(treemacs-workspace-name))
(doom-modeline 'treemacs)))))
(t
'(:eval (format " Treemacs: %s"
(treemacs-workspace->name (treemacs-current-workspace))))))))
(defun treemacs--post-command ()
"Set the default directory to the nearest directory of the current node.
If there is no node at point use \"~/\" instead.
Also skip hidden buttons (as employed by variadic extensions).
Used as a post command hook."
(let ((newline-char 10)
(point-max (point-max)))
(unless (equal newline-char (char-before point-max))
(treemacs-with-writable-buffer
(save-excursion
(goto-char point-max)
(insert newline-char)
;; make sure that the projects-end marker keeps pointing at
;; the end of the last project button
(when (and (eq t treemacs--in-this-buffer)
(equal (point) (marker-position (treemacs--projects-end))))
(move-marker (treemacs--projects-end) (1- (point))))))))
(-when-let (btn (treemacs-current-button))
(when (treemacs-button-get btn 'invisible)
(treemacs-next-line 1))
(-if-let* ((project (treemacs-project-of-node btn))
(path (or (treemacs-button-get btn :default-directory)
(treemacs--nearest-path btn))))
(when (and (treemacs-project->is-readable? project)
(file-readable-p path))
(setf treemacs--eldoc-msg (treemacs--get-eldoc-message path)
default-directory (treemacs--add-trailing-slash
(if (file-directory-p path) path (file-name-directory path)))))
(setf treemacs--eldoc-msg nil)
(when (eq t treemacs--in-this-buffer)
(setf default-directory "~/")))))
(defun treemacs--get-eldoc-message (path)
"Set the eldoc message for given PATH.
Message will be either just the path, or the path plus meta info like file size,
depending on the value of `treemacs-eldoc-display'."
(pcase treemacs-eldoc-display
('detailed
(-let [attr (file-attributes path)]
(format "%s -- %s: %s %s: %s %s: %s"
(propertize path 'face 'font-lock-string-face)
(propertize "Size" 'face 'font-lock-keyword-face)
(propertize
(treemacs--human-readable-bytes (file-attribute-size attr))
'face 'font-lock-type-face)
(propertize "Last Modified" 'face 'font-lock-keyword-face)
(propertize
(format-time-string "%F %T" (file-attribute-modification-time attr))
'face 'font-lock-type-face)
(propertize "Permissions" 'face 'font-lock-keyword-face)
(propertize
(file-attribute-modes attr)
'face 'font-lock-type-face))))
('simple (propertize path 'face 'font-lock-string-face))
(_ (propertize path 'face 'font-lock-string-face))))
(define-inline treemacs--human-readable-bytes (bytes)
"Return a human-readable string version of BYTES."
(declare (pure t) (side-effect-free t))
(inline-letevals (bytes)
(inline-quote
(cl-loop with result = (cons "B" ,bytes)
for i in '("k" "M" "G" "T" "P" "E" "Z" "Y")
while (>= (cdr result) 1024.0)
do (setf result (cons i (/ (cdr result) 1024.0)))
finally return
(pcase (car result)
("B" (format "%sb" ,bytes))
(_ (format "%.1f%s" (cdr result) (car result))))))))
(defun treemacs--eldoc-function ()
"Treemacs' implementation of `eldoc-documentation-function'.
Will simply return `treemacs--eldoc-msg'."
(when (and treemacs-eldoc-display treemacs--eldoc-msg)
treemacs--eldoc-msg))
;;;###autoload
(define-derived-mode treemacs-mode special-mode "Treemacs"
"A major mode for displaying the file system in a tree layout."
(setq buffer-read-only t
truncate-lines t
indent-tabs-mode nil
desktop-save-buffer nil
window-size-fixed (when treemacs-width-is-initially-locked 'width)
treemacs--in-this-buffer t)
(unless treemacs-show-cursor
(setq cursor-type nil))
(when (boundp 'evil-treemacs-state-cursor)
(with-no-warnings
(setq evil-treemacs-state-cursor
(if treemacs-show-cursor
evil-motion-state-cursor
(lambda () (setq cursor-type nil))))))
;; higher fuzz value makes it less likely to start a mouse drag
;; and make a switch to visual state
(setq-local double-click-fuzz 15)
(setq-local show-paren-mode nil)
(setq-local tab-width 1)
(setq-local eldoc-documentation-function #'treemacs--eldoc-function)
(setq-local eldoc-message-commands treemacs--eldoc-obarray)
(setq-local imenu-create-index-function #'treemacs--create-imenu-index-function)
(when (boundp 'context-menu-functions)
(setq-local context-menu-functions nil))
;; integrate with bookmark.el
(setq-local bookmark-make-record-function #'treemacs--make-bookmark-record)
(electric-indent-local-mode -1)
(visual-line-mode -1)
(font-lock-mode -1)
(jit-lock-mode nil)
(buffer-disable-undo)
;; fringe indicator must be set up right here, before hl-line-mode, since activating hl-line-mode will
;; invoke the movement of the fringe overlay that would otherwise be nil
(when treemacs-fringe-indicator-mode
(treemacs--enable-fringe-indicator))
(if treemacs-user-header-line-format
(setf header-line-format treemacs-user-header-line-format)
(when header-line-format
(setf header-line-format nil)))
(hl-line-mode t)
;; needs to run manually the first time treemacs is loaded, since the hook is only added *after*
;; the window config was changed to show treemacs
(unless (member #'treemacs--on-window-config-change (default-value 'window-configuration-change-hook))
(treemacs--on-window-config-change))
;; set the parameter immediately so it can take effect when `treemacs' is called programatically
;; alongside other window layout chaning commands that might delete it again
(set-window-parameter (selected-window) 'no-delete-other-windows treemacs-no-delete-other-windows)
(face-remap-add-relative 'default 'treemacs-window-background-face)
(face-remap-add-relative 'fringe 'treemacs-window-background-face)
(face-remap-add-relative 'hl-line 'treemacs-hl-line-face)
(when treemacs-text-scale
(text-scale-increase treemacs-text-scale))
(add-hook 'window-configuration-change-hook #'treemacs--on-window-config-change)
(add-hook 'kill-buffer-hook #'treemacs--on-buffer-kill nil t)
(add-hook 'post-command-hook #'treemacs--post-command nil t)
(treemacs--build-indentation-cache 6)
(treemacs--select-icon-set)
(treemacs--setup-mode-line)
(treemacs--reset-dom))
(defun treemacs--mode-check-advice (mode-activation &rest args)
"Verify that `treemacs-mode' is called in the right place.
Must be run as advice to prevent changing of the major mode.
Will run original MODE-ACTIVATION and its ARGS only when
`treemacs--in-this-buffer' is non-nil."
(cond
(treemacs--in-this-buffer
(apply mode-activation args))
((eq major-mode 'treemacs-mode)
(ignore "Reactivating the major-mode resets buffer-local variables."))
(t
(switch-to-buffer (get-buffer-create "*Clippy*"))
(erase-buffer)
(insert
(format
"
your_sha256_hash----------------------
| It looks like you are trying to run treemacs. Would you like some help with that? |
| You have called %s, but that is just the major mode for treemacs' |
| buffers, it is not meant to be used manually. |
| |
| Instead you should call a function like |
| * %s, |
| * %s, or |
| * %s |
| |
| You can safely delete this buffer. |
your_sha256_hash----------------------
%s
"
(propertize "treemacs-mode" 'face 'font-lock-function-name-face)
(propertize "treemacs" 'face 'font-lock-function-name-face)
(propertize "treemacs-select-window" 'face 'font-lock-function-name-face)
(propertize "treemacs-add-and-display-current-project" 'face 'font-lock-function-name-face)
(propertize
"\
\\
\\
____
/ \\
| |
@ @
| |
|| |/
|| ||
|\\_/|
\\___/" 'face 'font-lock-keyword-face))))))
(advice-add #'treemacs-mode :around #'treemacs--mode-check-advice)
(provide 'treemacs-mode)
;;; treemacs-mode.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-mode.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 4,994 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Definitions for the theme type, their creation, and, the means to
;; change themes.
;;; Code:
(require 'dash)
(require 'ht)
(require 'treemacs-core-utils)
(require 'treemacs-logging)
(eval-when-compile
(require 'inline)
(require 'treemacs-macros)
(require 'cl-lib))
(eval-when-compile
(cl-declaim (optimize (speed 3) (safety 0))))
(treemacs-import-functions-from "treemacs-icons"
treemacs--select-icon-set)
(cl-defstruct (treemacs-theme
(:conc-name treemacs-theme->)
(:constructor treemacs-theme->create!)
(:named t))
name path gui-icons tui-icons)
(defvar treemacs--current-theme nil "The currently used theme.")
(defvar treemacs--themes nil "List of all known themes.")
(define-inline treemacs-current-theme ()
"Get the current theme."
(declare (side-effect-free t))
(inline-quote treemacs--current-theme))
(define-inline treemacs--find-theme (name)
"Find theme with the given NAME."
(declare (side-effect-free t))
(inline-letevals (name)
(inline-quote
(--first (string= (treemacs-theme->name it) ,name) treemacs--themes))))
(cl-defmacro treemacs-create-theme (name &key icon-directory extends config)
"Create a new (bare) theme with the given NAME.
- ICON-DIRECTORY is the (mandatory) theme's location.
- EXTENDS is the theme to be extended.
- CONFIG is a code block to fill the created theme with icons via
`treemacs-create-icon'."
(declare (indent 1))
`(let* ((gui-icons (make-hash-table :size 300 :test 'equal))
(tui-icons (make-hash-table :size 300 :test 'equal))
(theme (treemacs-theme->create!
:name ,name
:path ,icon-directory
:gui-icons gui-icons
:tui-icons tui-icons)))
(add-to-list 'treemacs--themes theme)
,(when extends
`(treemacs-unless-let (base-theme (treemacs--find-theme ,extends))
(treemacs-log-failure "Could not find base theme %s when creating theme %s." ,extends ,name)
(treemacs--maphash (treemacs-theme->gui-icons base-theme) (ext icon)
(ht-set! gui-icons ext icon))
(treemacs--maphash (treemacs-theme->tui-icons base-theme) (ext icon)
(ht-set! tui-icons ext icon))))
(-let [treemacs--current-theme theme]
,config
(treemacs--propagate-new-icons theme))
,name))
(cl-defmacro treemacs-modify-theme (theme &key icon-directory config)
"Modify an existing THEME.
- THEME can either be a treemacs-theme object or the name of a theme.
- For the scope of the modification an alternative ICON-DIRECTORY can also be
used.
- CONFIG will be applied to the THEME in the same manner as in
`treemacs-create-theme'."
(declare (indent 1))
(treemacs-static-assert (not (null theme))
"Theme may not be null.")
`(treemacs-unless-let (theme (if (stringp ,theme) (treemacs--find-theme ,theme) ,theme))
(user-error "Theme '%s' does not exist" ,theme)
(let* ((treemacs--current-theme theme)
(original-icon-dir (treemacs-theme->path theme))
(new-icon-dir (if ,icon-directory ,icon-directory original-icon-dir)))
(unwind-protect
(progn
(setf (treemacs-theme->path theme) new-icon-dir)
,config
(treemacs--propagate-new-icons theme))
(setf (treemacs-theme->path theme) original-icon-dir))
nil)))
(defun treemacs--propagate-new-icons (theme)
"Add THEME's new icons to the other themes."
(unless (string= (treemacs-theme->name theme) "Default")
(dolist (other-theme (delete theme treemacs--themes))
(pcase-dolist (`(,current-icons . ,other-icons)
`(,(cons (treemacs-theme->gui-icons theme)
(treemacs-theme->gui-icons other-theme))
,(cons (treemacs-theme->tui-icons theme)
(treemacs-theme->tui-icons other-theme))))
(treemacs--maphash current-icons (ext icon)
(unless (ht-get other-icons ext)
(ht-set! other-icons ext icon)))))))
(defun treemacs-load-theme (name)
"Load the theme with the given NAME.
Note that some changes will only take effect after a treemacs buffer was killed
and restored."
(interactive
(list (completing-read "Theme: " (-map #'treemacs-theme->name treemacs--themes))))
(treemacs-unless-let (theme (treemacs--find-theme name))
(treemacs-log-failure "Cannot find theme '%s'." name)
(setq treemacs--current-theme theme)
(dolist (buffer (buffer-list))
(when (memq (buffer-local-value 'major-mode buffer) '(treemacs-mode dired-mode))
(with-current-buffer buffer
(treemacs--select-icon-set))))))
(provide 'treemacs-themes)
;;; treemacs-themes.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-themes.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,300 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Handling of visuals in general and icons in particular.
;;; Code:
(require 'dash)
(require 'treemacs-core-utils)
(require 'treemacs-scope)
(require 'treemacs-customization)
(eval-when-compile
(require 'inline)
(require 'treemacs-macros))
(defvar-local treemacs--fringe-indicator-overlay nil)
(defconst treemacs--fringe-overlay-before-string
(propertize
" " 'display
`(left-fringe ,treemacs--fringe-indicator-bitmap treemacs-fringe-indicator-face))
"The `before-string' property value used by the fringe indicator overlay.")
(defun treemacs--move-fringe-indicator-to-point ()
"Move the fringe indicator to the position of point."
(when treemacs--fringe-indicator-overlay
(-let [pabol (line-beginning-position)]
(move-overlay treemacs--fringe-indicator-overlay pabol (1+ pabol)))))
(defun treemacs--enable-fringe-indicator ()
"Enabled the fringe indicator in the current buffer."
(unless treemacs--fringe-indicator-overlay
(setq-local
treemacs--fringe-indicator-overlay
(-doto (make-overlay 1 1 (current-buffer))
(overlay-put 'before-string treemacs--fringe-overlay-before-string)))
(treemacs--move-fringe-indicator-to-point)))
(defun treemacs--disable-fringe-indicator ()
"Enabled the fringe indicator in the current buffer."
(when treemacs--fringe-indicator-overlay
(delete-overlay treemacs--fringe-indicator-overlay)
(setf treemacs--fringe-indicator-overlay nil)))
(defun treemacs--show-fringe-indicator-only-when-focused (window)
"Hook to ensure the fringe indicator not shown when treemacs is not selected.
WINDOW is the treemacs window that has just been focused or unfocused."
(if (eq treemacs--in-this-buffer t)
(when treemacs--fringe-indicator-overlay
(overlay-put
treemacs--fringe-indicator-overlay 'before-string
treemacs--fringe-overlay-before-string))
(with-selected-window window
(when treemacs--fringe-indicator-overlay
(overlay-put
treemacs--fringe-indicator-overlay
'before-string nil)))))
(defun treemacs--tear-down-fringe-indicator-mode ()
"Tear down `treemacs-fringe-indicator-mode'."
(remove-hook 'treemacs-mode-hook
#'treemacs--enable-fringe-indicator-in-current-buffer)
(treemacs-run-in-all-derived-buffers
(treemacs--disable-fringe-indicator)
(advice-remove #'hl-line-highlight #'treemacs--move-fringe-indicator-to-point)
(remove-hook 'window-selection-change-functions
#'treemacs--show-fringe-indicator-only-when-focused
:local)))
(define-minor-mode treemacs-fringe-indicator-mode
"Toggle `treemacs-fringe-indicator-mode'.
When enabled, a visual indicator in the fringe will be displayed to highlight
the selected line in addition to `hl-line-mode'. Useful if `hl-line-mode'
doesn't stand out enough with your colour theme.
Can be called with one of two arguments:
- `always' will always show the fringe indicator.
- `only-when-focused' will only show the fringe indicator when the treemacs
window is focused (only possible with Emacs 27+).
For backward compatibility just enabling this mode without an explicit argument
has the same effect as using `always'."
:init-value nil
:global t
:lighter nil
:group 'treemacs
(if treemacs-fringe-indicator-mode
(progn
(setf arg (or arg t))
(if (memq arg '(always only-when-focused t))
(treemacs--setup-fringe-indicator-mode arg)
(call-interactively #'treemacs--setup-fringe-indicator-mode)))
(treemacs--tear-down-fringe-indicator-mode)))
(defun treemacs--setup-fringe-indicator-mode (arg)
"Setup `treemacs-fringe-indicator-mode'.
When ARG is `only-when-focused' a hook will be set up to only display the
fringe indicator when the treemacs window is selected."
(interactive (list (->> (completing-read "Fringe Indicator" '("Always" "Only When Focused"))
(downcase)
(s-split " ")
(s-join "-")
(intern))))
(setf treemacs-fringe-indicator-mode arg)
(add-hook 'treemacs-mode-hook
#'treemacs--enable-fringe-indicator-in-current-buffer)
(treemacs-run-in-all-derived-buffers
(treemacs--enable-fringe-indicator-in-current-buffer)))
(defun treemacs--enable-fringe-indicator-in-current-buffer ()
"Set up fringe-indicator-mode for the current buffer."
(treemacs--enable-fringe-indicator)
(advice-add #'hl-line-highlight
:after #'treemacs--move-fringe-indicator-to-point)
(when (memq treemacs-fringe-indicator-mode '(t only-when-focused))
(add-hook 'window-selection-change-functions
#'treemacs--show-fringe-indicator-only-when-focused
nil :local)))
(treemacs-only-during-init (treemacs-fringe-indicator-mode))
(provide 'treemacs-fringe-indicator)
;;; treemacs-fringe-indicator.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-fringe-indicator.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,294 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Everything about creating, (re)moving, (re)naming and otherwise
;; editing projects and workspaces.
;;; Code:
(require 'dash)
(require 'ht)
(require 'treemacs-core-utils)
(require 'treemacs-dom)
(require 'treemacs-scope)
(require 'treemacs-customization)
(eval-when-compile
(require 'cl-lib)
(require 'inline)
(require 'treemacs-macros))
(eval-when-compile
(cl-declaim (optimize (speed 3) (safety 0))))
(treemacs-import-functions-from "treemacs"
treemacs-select-window)
(treemacs-import-functions-from "treemacs-rendering"
treemacs--projects-end
treemacs--collapse-root-node
treemacs--expand-root-node
treemacs--add-root-element
treemacs--render-projects
treemacs--insert-root-separator
treemacs--root-face)
(treemacs-import-functions-from "treemacs-interface"
treemacs-previous-project
treemacs-next-project)
(treemacs-import-functions-from "treemacs-persistence"
treemacs--persist
treemacs--maybe-load-workspaces)
(treemacs-import-functions-from "treemacs-visuals"
treemacs-pulse-on-failure)
(treemacs-import-functions-from "treemacs-async"
treemacs--prefetch-gitignore-cache)
(cl-defstruct (treemacs-project
(:conc-name treemacs-project->)
(:constructor treemacs-project->create!))
name
path
path-status
is-disabled?)
(cl-defstruct (treemacs-workspace
(:conc-name treemacs-workspace->)
(:constructor treemacs-workspace->create!))
name
projects
is-disabled?)
(defvar treemacs--workspaces (list (treemacs-workspace->create! :name "Default")))
(defvar treemacs--disabled-workspaces (list))
(defvar treemacs--find-user-project-functions
(list #'treemacs--current-builtin-project-function
#'treemacs--current-directory-project-function)
"List of functions to find the user project for the current buffer.")
(defvar-local treemacs--org-err-ov nil
"The overlay that will display validations when org-editing.")
(defvar-local treemacs--project-of-buffer nil
"The project that the current buffer falls under, if any.")
(defvar treemacs-override-workspace nil
"Used to override the return value of `treemacs-current-workspace'.
Used by `treemacs-run-in-every-buffer' to make sure all workspace-related
functions can be used since make functions (like `treemacs-find-file-node')
rely on the current buffer and workspace being aligned.")
(define-inline treemacs--invalidate-buffer-project-cache ()
"Set all buffers' `treemacs--project-of-buffer' to nil.
To be called whenever a project or workspace changes."
(inline-quote
(dolist (buf (buffer-list))
(with-current-buffer buf
(setf treemacs--project-of-buffer nil)))))
(defun treemacs--current-builtin-project-function ()
"Find the current project.el project."
(declare (side-effect-free t))
(-when-let (project (project-current))
(if (fboundp 'project-root)
(-> project (project-root) (file-truename) (treemacs-canonical-path))
(-> project (cdr) (file-truename) (treemacs-canonical-path)))))
(defun treemacs--current-directory-project-function ()
"Find the current working directory."
(declare (side-effect-free t))
(-some-> default-directory (treemacs--canonical-path)))
(define-inline treemacs-workspaces ()
"Return the list of all workspaces in treemacs."
(declare (side-effect-free t))
(inline-quote treemacs--workspaces))
(define-inline treemacs-disabled-workspaces ()
"Return the list of all workspaces in treemacs that are disabled."
(declare (side-effect-free t))
(inline-quote treemacs--disabled-workspaces))
(defun treemacs-current-workspace ()
"Get the current workspace.
The return value can be overridden by let-binding `treemacs-override-workspace'.
This will happen when using `treemacs-run-in-every-buffer' to make sure that
this function returns the right workspace for the iterated-over buffers.
If no workspace is assigned to the current scope the persisted workspaces will
be loaded and a workspace will be found based on the `current-buffer'.
This function can be used with `setf'."
(or treemacs-override-workspace
(-if-let (shelf (treemacs-current-scope-shelf))
(treemacs-scope-shelf->workspace shelf)
(treemacs--maybe-load-workspaces)
(let* ((workspace (treemacs--find-workspace (buffer-file-name (current-buffer))))
(new-shelf (treemacs-scope-shelf->create! :workspace workspace)))
(setf (treemacs-current-scope-shelf) new-shelf)
(run-hook-with-args treemacs-workspace-first-found-functions
workspace (treemacs-current-scope))
workspace))))
(gv-define-setter treemacs-current-workspace (val)
`(let ((shelf (treemacs-current-scope-shelf)))
(unless shelf
(setf shelf (treemacs-scope-shelf->create!))
(push (cons (treemacs-current-scope) shelf) treemacs--scope-storage))
(setf (treemacs-scope-shelf->workspace shelf) ,val)))
(define-inline treemacs--find-workspace (&optional path)
"Find the right workspace the given PATH.
PATH: String"
(declare (side-effect-free t))
(inline-letevals (path)
(inline-quote
(let ((ws-for-path (--first (treemacs-is-path ,path :in-workspace it)
treemacs--workspaces)))
(setf (treemacs-current-workspace)
(pcase-exhaustive treemacs-find-workspace-method
('find-for-file-or-pick-first
(or ws-for-path (car treemacs--workspaces)))
('find-for-file-or-manually-select
(or ws-for-path (treemacs--select-workspace-by-name)))
('always-ask
(treemacs--select-workspace-by-name))))))))
;; TODO(2020/11/25): NAME
(define-inline treemacs--find-project-for-buffer (&optional buffer-file)
"In the current workspace find the project current buffer's file falls under.
Optionally supply the BUFFER-FILE in case it is not available by calling the
function `buffer-file-name' (like in Dired).
FILE: Filepath"
(inline-letevals (buffer-file)
(inline-quote
(progn
(unless treemacs--project-of-buffer
(let ((path (or ,buffer-file (buffer-file-name))))
(when path (setf treemacs--project-of-buffer (treemacs-is-path path :in-workspace)))))
treemacs--project-of-buffer))))
(define-inline treemacs--find-project-for-path (path)
"Return the project for PATH in the current workspace."
(declare (side-effect-free t))
(inline-letevals (path)
(inline-quote (treemacs-is-path ,path :in-workspace))))
(define-inline treemacs-workspace->is-empty? ()
"Return t when there are no projects in the current workspace."
(declare (side-effect-free t))
(inline-quote
(null (treemacs-workspace->projects (treemacs-current-workspace)))))
(define-inline treemacs--add-project-to-current-workspace (project)
"Add PROJECT to the current workspace."
(inline-letevals (project)
(inline-quote
(setf (treemacs-workspace->projects (treemacs-current-workspace))
;; reversing around to get the order right - new project goes to the *bottom* of the list
(-let [reversed (nreverse (treemacs-workspace->projects (treemacs-current-workspace)))]
(nreverse (push ,project reversed)))))))
(define-inline treemacs--remove-project-from-current-workspace (project)
"Remove PROJECT from the current workspace."
(inline-letevals (project)
(inline-quote
(progn
(setf (treemacs-workspace->projects (treemacs-current-workspace))
(delete ,project (treemacs-workspace->projects (treemacs-current-workspace))))
;; also reset the cached buffers' projects
(dolist (buffer (buffer-list))
(with-current-buffer buffer
(when (equal treemacs--project-of-buffer ,project)
(setq treemacs--project-of-buffer nil))))))))
(define-inline treemacs--next-project-pos ()
"Get the position of the next project.
Will return `point-max' if there is no next project."
(declare (side-effect-free t))
(inline-quote (next-single-char-property-change (line-end-position) :project)))
(define-inline treemacs--prev-project-pos ()
"Get the position of the next project.
Will return `point-min' if there is no next project."
(declare (side-effect-free t))
(inline-quote (previous-single-char-property-change (line-beginning-position) :project)))
(define-inline treemacs-project->key (self)
"Get the hash table key of SELF.
SELF may be a project struct or a root key of a top level extension."
(declare (side-effect-free t))
(inline-letevals (self)
(inline-quote
;; Top-level extensions are added to the project positions their root-key,
;; not a real project.
(if (treemacs-project-p ,self)
(treemacs-project->path ,self)
,self))))
(define-inline treemacs-project->position (self)
"Return the position of project SELF in the current buffer."
(declare (side-effect-free t))
(inline-letevals (self)
(inline-quote
(treemacs-dom-node->position
(treemacs-find-in-dom (treemacs-project->path ,self))))))
(define-inline treemacs-project->is-expanded? (self)
"Return non-nil if project SELF is expanded in the current buffer."
(declare (side-effect-free t))
(inline-letevals (self)
(inline-quote
(memq (-> ,self (treemacs-project->position) (treemacs-button-get :state))
treemacs--open-node-states))))
(defun treemacs-project->refresh-path-status! (self)
"Refresh the path status of project SELF in the current buffer.
Does not preserve the current position in the buffer."
(let ((old-path-status (treemacs-project->path-status self))
(new-path-status (treemacs--get-path-status (treemacs-project->path self))))
(unless (eq old-path-status new-path-status)
(setf (treemacs-project->path-status self) new-path-status)
;; When the path transforms from unreadable or disconnected to readable,
;; update the :symlink status on its button.
(let ((pos (treemacs-project->position self))
(path (treemacs-project->path self)))
(when (treemacs-project->is-readable? self)
(treemacs-button-put pos :symlink (file-symlink-p path)))
(treemacs-button-put pos 'face (treemacs--root-face self))))))
;; TODO(2021/08/17): -> rendering
(defun treemacs-project->refresh! (self)
"Refresh project SELF in the current buffer.
Does not preserve the current position in the buffer."
(treemacs-project->refresh-path-status! self)
(when (treemacs-project->is-expanded? self)
(let ((root-btn (treemacs-project->position self)))
(goto-char root-btn)
(funcall (alist-get (treemacs-button-get root-btn :state)
treemacs-TAB-actions-config))
(unless (treemacs-project->is-unreadable? self)
(funcall (alist-get (treemacs-button-get root-btn :state)
treemacs-TAB-actions-config))))))
(define-inline treemacs-project->is-last? (self)
"Return t when root node of project SELF is the last in the view."
(declare (side-effect-free t))
(inline-letevals (self)
(inline-quote
(-> ,self
(treemacs-project->position)
(treemacs-button-end)
(next-single-property-change :project)
(null)))))
(defun treemacs-do-create-workspace (&optional name)
"Create a new workspace with optional NAME.
Return values may be as follows:
* If a workspace for the given name already exists:
- the symbol `duplicate-name'
- the workspace with the duplicate name
* If the given name is invalid:
- the symbol `invalid-name'
- the name
* If everything went well:
- the symbol `success'
- the created workspace"
(treemacs-block
(-let [name (or name (treemacs--read-string "Workspace name: "))]
(treemacs-return-if (treemacs--is-name-invalid? name)
`(invalid-name ,name))
(-when-let (ws (--first (string= name (treemacs-workspace->name it))
treemacs--workspaces))
(treemacs-return `(duplicate-name ,ws)))
(-let [workspace (treemacs-workspace->create! :name name)]
(add-to-list 'treemacs--workspaces workspace :append)
(treemacs--persist)
(run-hook-with-args 'treemacs-create-workspace-functions workspace)
`(success ,workspace)))))
(defun treemacs-do-remove-workspace (&optional workspace ask-to-confirm)
"Delete a WORKSPACE.
Ask the user to confirm the deletion when ASK-TO-CONFIRM is t (it will be when
this is called from `treemacs-remove-workspace').
If no WORKSPACE name is given it will be selected interactively.
Return values may be as follows:
* If only a single workspace remains:
- the symbol `only-one-workspace'
* If the user cancels the deletion:
- the symbol `user-cancel'
* If the workspace cannot be found:
- the symbol `workspace-not-found'
* If everything went well:
- the symbol `success'
- the deleted workspace
- the list of the remaining workspaces"
(treemacs-block
(treemacs-return-if (= 1 (length treemacs--workspaces))
'only-one-workspace)
(let* ((name (or workspace
(completing-read "Delete: " (-map #'treemacs-workspace->name treemacs--workspaces) nil t)))
(to-delete (treemacs-find-workspace-by-name name)))
(treemacs-return-if
(and ask-to-confirm
(not (yes-or-no-p (format "Delete workspace %s and all its projects?"
(propertize (treemacs-workspace->name to-delete)
'face 'font-lock-type-face)))))
'user-cancel)
(treemacs-return-if (null to-delete)
`(workspace-not-found ,name))
(setq treemacs--workspaces (delete to-delete treemacs--workspaces))
(treemacs--persist)
(treemacs--invalidate-buffer-project-cache)
(treemacs-run-in-every-buffer
(let ((current-ws (treemacs-current-workspace)))
(when (eq current-ws to-delete)
(treemacs--rerender-after-workspace-change))))
(run-hook-with-args 'treemacs-delete-workspace-functions to-delete)
`(success ,to-delete ,treemacs--workspaces))))
(defun treemacs--rerender-after-workspace-change ()
"Redraw treemacs after the current workspace was changed or deleted."
(let* ((treemacs-buffer (treemacs-get-local-buffer))
(in-treemacs? (eq (current-buffer) treemacs-buffer)))
(pcase (treemacs-current-visibility)
('none
(ignore))
('exists
(kill-buffer treemacs-buffer)
(save-selected-window (treemacs-select-window))
(delete-window (treemacs-get-local-window)))
('visible
(kill-buffer treemacs-buffer)
(if in-treemacs?
(treemacs-select-window)
(save-selected-window (treemacs-select-window)))))))
(defun treemacs--get-path-status (path)
"Get the status of PATH.
Returns either
* `local-readable' when PATH is a local readable file or directory,
* `local-unreadable' when PATH is a local unreadable file or directory,
* `remote-readable' when PATH is a remote readable file or directory,
* `remote-unreadable' when PATH is a remote unreadable file or directory,
* `remote-disconnected' when PATH is remote, but the connection is down, or
* `extension' when PATH is not a string."
(declare (side-effect-free t))
(cond
((not (stringp path)) 'extension)
((not (file-remote-p path))
(if (file-readable-p path) 'local-readable 'local-unreadable))
((not (file-remote-p path nil t)) 'remote-disconnected)
((file-readable-p path) 'remote-readable)
(t 'remote-unreadable)))
(define-inline treemacs-project->is-unreadable? (self)
"Return non-nil if the project SELF is definitely unreadable.
If `path-status' of the project is `remote-disconnected', the return value will
be nil even though the path might still be unreadable. Does not verify the
readability, the cached path-state is used. Extension projects will count as
readable."
(declare (side-effect-free t))
(inline-quote (memq (treemacs-project->path-status ,self)
'(local-unreadable remote-unreadable))))
(define-inline treemacs-project->is-readable? (self)
"Return t if the project SELF is definitely readable for file operations.
Does not verify the readability - the cached state is used."
(declare (side-effect-free t))
(inline-quote (memq (treemacs-project->path-status ,self)
'(local-readable remote-readable))))
(define-inline treemacs-project->is-remote? (self)
"Return t if the project SELF is remote."
(declare (side-effect-free t))
(inline-letevals (self)
(inline-quote (memq (treemacs-project->path-status ,self)
'(remote-disconnected remote-readable remote-unreadable)))))
(define-inline treemacs-project->is-local? (self)
"Return t if the project SELF is local. Returns nil for extensions."
(declare (side-effect-free t))
(inline-letevals (self)
(inline-quote (memq (treemacs-project->path-status ,self)
'(local-readable local-unreadable)))))
(define-inline treemacs-project->is-local-and-readable? (self)
"Return t if the project SELF is local and readable."
(declare (side-effect-free t))
(inline-quote (eq (treemacs-project->path-status ,self) 'local-readable)))
(defun treemacs-do-add-project-to-workspace (path name)
"Add project at PATH to the current workspace.
NAME is provided during ad-hoc navigation only.
Return values may be as follows:
* If the given path is invalid (is nil or does not exist)
- the symbol `invalid-path'
- a string describing the problem
* If the project for the given path already exists:
- the symbol `duplicate-project'
- the project the PATH falls into
* If a project under given path already exists:
- the symbol `includes-project'
- the project the PATH contains
* If a project for the given name already exists:
- the symbol `duplicate-name'
- the project with the duplicate name
* If the given name is invalid:
- the symbol `invalid-name'
- the name
* If everything went well:
- the symbol `success'
- the created project
PATH: Filepath
NAME: String"
(treemacs-block
(treemacs-return-if (null path)
`(invalid-path "Path is nil."))
(let ((path-status (treemacs--get-path-status path))
(added-in-workspace (treemacs-current-workspace)))
(treemacs-return-if (not (file-readable-p path))
`(invalid-path "Path is not readable does not exist."))
(setq path (-> path (file-truename) (treemacs-canonical-path)))
(-when-let (project (treemacs--find-project-for-path path))
(treemacs-return `(duplicate-project ,project)))
(treemacs-return-if (treemacs--is-name-invalid? name)
`(invalid-name ,name))
(-when-let (project (--first (treemacs-is-path (treemacs-project->path it) :in path)
(treemacs-workspace->projects (treemacs-current-workspace))))
(treemacs-return `(includes-project ,project)))
(let ((project (treemacs-project->create! :name name :path path :path-status path-status)))
(-when-let (double (--first (string= name (treemacs-project->name it))
(treemacs-workspace->projects (treemacs-current-workspace))))
(treemacs-return `(duplicate-name ,double)))
(treemacs--add-project-to-current-workspace project)
(treemacs--invalidate-buffer-project-cache)
(treemacs-run-in-every-buffer
(when (eq added-in-workspace workspace)
(treemacs-with-writable-buffer
(goto-char (treemacs--projects-end))
(cond
;; Inserting the first and only button - no need to add spacing
((not (treemacs-current-button)))
;; Inserting before a button. This happens when only bottom extensions exist.
((bolp)
(save-excursion (treemacs--insert-root-separator))
;; Unlock the marker - when the marker is at the beginning of the buffer,
;; expanding/collapsing extension nodes would move the marker and it was thus locked.
(set-marker-insertion-type (treemacs--projects-end) t))
;; Inserting after a button (the standard case)
;; We should already be at EOL, but play it safe.
(t
(end-of-line)
(treemacs--insert-root-separator)))
(treemacs--add-root-element project)
(treemacs-dom-node->insert-into-dom!
(treemacs-dom-node->create! :key path :position (treemacs-project->position project)))
(when treemacs-expand-added-projects
(treemacs--expand-root-node (treemacs-project->position project))))))
(treemacs--persist)
(treemacs--invalidate-buffer-project-cache)
(when (with-no-warnings treemacs-hide-gitignored-files-mode)
(treemacs--prefetch-gitignore-cache path))
(run-hook-with-args 'treemacs-create-project-functions project)
`(success ,project)))))
(defalias 'treemacs-add-project-at #'treemacs-do-add-project-to-workspace)
(with-no-warnings
(make-obsolete #'treemacs-add-project-at #'treemacs-do-add-project-to-workspace "v.2.2.1"))
(defun treemacs-do-remove-project-from-workspace
(project &optional ignore-last-project-restriction ask-to-confirm)
"Remove the given PROJECT from the current workspace.
PROJECT may either be a `treemacs-project' instance or a string path. In the
latter case the project containing the path will be selected.
When IGNORE-LAST-PROJECT-RESTRICTION is non-nil removing the last project will
not count as an error. This is meant to be used in non-interactive code, where
another project is immediately added afterwards, as leaving the project list
empty is generally a bad idea.
Ask the user to confirm the deletion when ASK-TO-CONFIRM is t (it will be when
this is called from `treemacs-remove-project-from-workspace').
Return values may be as follows:
* If the given path is invalid (is nil or does not exist):
- the symbol `invalid-project'
- a string describing the problem
* If the user cancels the deletion:
- the symbol `user-cancel'
* If there is only one project:
- the symbol `cannot-delete-last-project'
* If everything went well:
- the symbol `success'"
(treemacs-block
(unless ignore-last-project-restriction
(treemacs-return-if (>= 1 (length (treemacs-workspace->projects (treemacs-current-workspace))))
'cannot-delete-last-project))
(treemacs-return-if (null project)
`(invalid-project "Project is nil"))
;; when used from outside treemacs it is much easier to supply a path string than to
;; look up the project instance
(when (stringp project)
(-let [found-project (treemacs-is-path (treemacs-canonical-path project) :in-workspace)]
(treemacs-return-if (null found-project)
`(invalid-project ,(format "Given path '%s' is not in the workspace" project)))
(setf project found-project)))
(treemacs-return-if
(and ask-to-confirm
(not (yes-or-no-p (format "Remove project %s from the current workspace?"
(propertize (treemacs-project->name project)
'face 'font-lock-type-face)))))
'user-cancel)
(treemacs-run-in-every-buffer
(treemacs-with-writable-buffer
(let* ((project-pos (goto-char (treemacs-project->position project)))
(prev-project-pos (move-marker (make-marker) (treemacs--prev-project-pos)))
(next-project-pos (move-marker (make-marker) (treemacs--next-project-pos))))
(when (treemacs-project->is-expanded? project)
(treemacs--collapse-root-node project-pos t))
(treemacs--remove-project-from-current-workspace project)
(treemacs--invalidate-buffer-project-cache)
(let ((previous-button (previous-button project-pos))
(next-button (next-button project-pos)))
(cond
;; Previous button exists. Delete from the end of the current line to
;; the end of the previous button's line. If the `treemacs--projects-end'
;; is at the EOL of the it will move to EOL of the previous button.
(previous-button
(delete-region (treemacs-button-end previous-button) (line-end-position))
(when next-button (forward-button 1)))
;; Previous project does not exist, but a next button exists. Delete from
;; BOL to the start of the next buttons line.
(next-button
(when (> next-button (treemacs--projects-end))
;; The first item after the deletion will be bottom extensions. Project
;; end will be at its BOL, making it move upon expand/collapse. Lock the marker.
(set-marker-insertion-type (treemacs--projects-end) nil))
(delete-region (line-beginning-position) (progn (goto-char next-button) (forward-line 0) (point))))
;; Neither the previous nor the next button exists. Simply delete the
;; current line.
(t
(delete-region (line-beginning-position) (line-end-position)))))
(if (equal (point-min) prev-project-pos)
(goto-char next-project-pos)
(goto-char prev-project-pos)))
(treemacs--invalidate-buffer-project-cache)
(--when-let (treemacs-get-local-window)
(with-selected-window it
(recenter)))
(treemacs--evade-image)
(hl-line-highlight)))
(run-hook-with-args 'treemacs-delete-project-functions project)
(treemacs--persist)
'success))
(defun treemacs-do-switch-workspace (&optional workspace)
"Switch to a new WORKSPACE.
Workspace may either be a workspace name, a workspace object, or be left out.
In the latter case the workspace to switch to will be selected interactively.
Return values may be as follows:
* If there are no workspaces to switch to:
- the symbol `only-one-workspace'
* If the given workspace could not be found (if WORKSPACE was a name string)
- the symbol `workspace-not-found'
- the given workspace name
* If everything went well:
- the symbol `success'
- the selected workspace"
(treemacs--maybe-load-workspaces)
(treemacs-block
(treemacs-return-if (= 1 (length treemacs--workspaces))
'only-one-workspace)
(let (new-workspace)
(cond
((treemacs-workspace-p workspace)
(setf new-workspace workspace))
((stringp workspace)
(setf new-workspace (treemacs-find-workspace-by-name workspace))
(treemacs-return-if (null new-workspace)
`(workspace-not-found ,workspace)))
((null workspace)
(let* ((workspaces (->> treemacs--workspaces
(--reject (eq it (treemacs-current-workspace)))
(--map (cons (treemacs-workspace->name it) it))))
(name (completing-read
"Switch to: "
(treemacs--pre-sorted-list workspaces)
nil :require-match)))
(setf new-workspace (cdr (--first (string= (car it) name) workspaces))))))
(setf (treemacs-current-workspace) new-workspace)
(treemacs--invalidate-buffer-project-cache)
(treemacs--rerender-after-workspace-change)
(when (with-no-warnings treemacs-hide-gitignored-files-mode)
(treemacs--prefetch-gitignore-cache 'all))
(run-hooks 'treemacs-switch-workspace-hook)
(treemacs-return
`(success ,new-workspace)))))
(defun treemacs-do-rename-workspace (&optional workspace new-name)
"Rename a workspace.
Takes either a WORKSPACE and a NEW-NAME as arguments or reads them
interactively.
Return values may be as follows:
* If the given name is invalid:
- the symbol `invalid-name'
- the name
* If everything went well:
- the symbol `success'
- the old-name
- the renamed workspace"
(treemacs-block
(let ((old-name))
(unless workspace
(let* ((current-ws (treemacs-current-workspace))
(old-name (treemacs-workspace->name current-ws))
(name-map (-> (--map (cons (treemacs-workspace->name it) it) treemacs--workspaces)
(sort (lambda (n _) (string= (car n) old-name)))))
(str-to-rename (completing-read "Rename: " name-map)))
(setf workspace (cdr (assoc str-to-rename name-map)))))
(setf old-name (treemacs-workspace->name workspace))
(unless new-name
(setf new-name (treemacs--read-string "New name: ")))
(treemacs-return-if (treemacs--is-name-invalid? new-name)
`(invalid-name ,new-name))
(setf (treemacs-workspace->name workspace) new-name)
(treemacs--persist)
(run-hook-with-args 'treemacs-rename-workspace-functions workspace old-name)
`(success ,old-name ,workspace))))
(defun treemacs--is-name-invalid? (name)
"Validate the NAME of a project or workspace.
Returns t when the name is invalid.
NAME: String"
(declare (pure t) (side-effect-free t))
(or (s-blank-str? name)
(s-contains? "\n" name)
(not (s-matches? (rx (1+ (or space (syntax word) (syntax symbol) (syntax punctuation)))) name))))
(define-inline treemacs-project-at-point ()
"Get the project for the (nearest) project at point.
Return nil when `treemacs-current-button' is nil."
(declare (side-effect-free t))
(inline-quote
(-when-let (btn (treemacs-current-button))
(treemacs-project-of-node btn))))
(defun treemacs--get-bounds-of-project (project)
"Get the bounds a PROJECT in the current buffer.
Returns a cons cell of buffer positions at the very start and end of the
PROJECT, excluding newlines.
PROJECT: Project Struct"
(interactive)
(save-excursion
(goto-char (treemacs-project->position project))
(let* ((start (line-beginning-position))
(next (treemacs--next-non-child-button (treemacs-project->position project)))
(end (if next
(-> next (treemacs-button-start) (previous-button) (treemacs-button-end))
;; final position minus the final newline
(1- (point-max)))))
(cons start end))))
(defun treemacs--consolidate-projects ()
"Correct treemacs buffers' content after the workspace was edited."
(treemacs--invalidate-buffer-project-cache)
(treemacs-run-in-every-buffer
(let* ((current-file (--when-let (treemacs-current-button) (treemacs--nearest-path it)))
(current-workspace (treemacs-current-workspace))
;; gather both the projects actually in the workspace ...
(projects-in-workspace (treemacs-workspace->projects current-workspace))
(projects-in-buffer)
(expanded-projects-in-buffer))
(goto-char 0)
;; ... as well as the projects currently shown in the buffer
(unless (s-blank? (buffer-string))
(push (treemacs-project-at-point) projects-in-buffer)
(let (next-pos)
(while (/= (point-max)
(setq next-pos (treemacs--next-project-pos)))
(goto-char next-pos)
(unless (treemacs-button-get (treemacs-current-button) :custom)
(push (treemacs-project-at-point) projects-in-buffer)))))
;; remember which ones are expanded, close them so the dom position can be rebuilt
(dolist (project-in-buffer projects-in-buffer)
(-let [project-btn (treemacs-project->position project-in-buffer)]
(when (eq 'root-node-open (treemacs-button-get project-btn :state))
(push project-in-buffer expanded-projects-in-buffer)
(goto-char project-btn)
(treemacs--collapse-root-node project-btn))))
;; figure out which ones have been deleted and and remove them from the dom
(dolist (project-in-buffer projects-in-buffer)
(unless (member project-in-buffer projects-in-workspace)
(treemacs-on-collapse (treemacs-project->path project-in-buffer) :purge)
(ht-remove! treemacs-dom (treemacs-project->path project-in-buffer))
(setf projects-in-buffer (delete project-in-buffer projects-in-buffer))))
(treemacs-with-writable-buffer
(treemacs--reset-dom)
;; delete everything's that's visible and render it again - the order of projects could
;; have been changed
(erase-buffer)
(treemacs--render-projects projects-in-workspace)
(goto-char 0)
;; re-expand the projects that were expanded before the consolidation
(let (next-pos)
(-let [btn (treemacs-current-button)]
(when (member (treemacs-button-get btn :project) expanded-projects-in-buffer)
(treemacs--expand-root-node btn)))
(while (/= (point-max)
(setq next-pos (treemacs--next-project-pos)))
(goto-char next-pos)
(-let [btn (treemacs-current-button)]
(when (member (treemacs-button-get btn :project) expanded-projects-in-buffer)
(treemacs--expand-root-node btn))))))
;; go back to the previous position
(if (and current-file
(treemacs-is-path current-file :in-workspace))
(treemacs-goto-file-node current-file)
(goto-char 0)
(treemacs--evade-image))
(hl-line-highlight))))
(defun treemacs--org-edit-display-validation-msg (message line)
"Display an inline validation MESSAGE in LINE when org-editing."
(save-excursion
(pcase line
(:start
(goto-char 0)
(forward-line (if treemacs-show-edit-workspace-help 4 2)))
(_
(goto-char 0)
(search-forward-regexp (rx-to-string `(seq bol ,line eol)))))
(setf treemacs--org-err-ov (make-overlay (line-end-position) (line-end-position)))
(overlay-put treemacs--org-err-ov 'after-string
(concat (propertize " " 'face 'error) message))
(add-hook 'after-change-functions #'treemacs--org-edit-remove-validation-msg nil :local)))
(defun treemacs--org-edit-remove-validation-msg (&rest _)
"Remove the validation message overlay."
(when (and treemacs--org-err-ov
(overlayp treemacs--org-err-ov))
(delete-overlay treemacs--org-err-ov))
(remove-hook 'after-change-functions #'treemacs--org-edit-remove-validation-msg :local))
(defun treemacs--find-current-user-project ()
"Find current project by calling `treemacs--find-user-project-functions'."
(declare (side-effect-free t))
(treemacs-block
(dolist (fun treemacs--find-user-project-functions)
(--when-let (funcall fun)
(treemacs-return it)))))
(defun treemacs--find-workspace-by-name (name)
"Find a workspace with the given NAME.
Returns nil when there is no match."
(treemacs--maybe-load-workspaces)
(--first (string= name (treemacs-workspace->name it))
treemacs--workspaces))
(defun treemacs--select-workspace-by-name ()
"Interactively select the workspace.
Selection is based on the list of names of all workspaces and still happens
when there is only one workspace."
(treemacs--maybe-load-workspaces)
(let (name)
(while (or (null name) (string= "" name))
(setf name (completing-read
"Workspace: "
(->> treemacs--workspaces
(--map (cons (treemacs-workspace->name it) it)))
nil :require-match)))
(--first (string= name (treemacs-workspace->name it))
treemacs--workspaces)))
(defun treemacs--maybe-clean-buffers-on-workspace-switch (which)
"Delete buffers depending on the value of WHICH.
- When it is nil do nothing.
- When it is `files' delete all buffers visiting files.
- When it is `all' delete all buffers
In any case treemacs itself, and the scratch and messages buffers will be left
alive."
(when which
(let* ((scratch (get-buffer-create "*scratch*"))
(messages (get-buffer "*Messages*"))
(no-delete-test
(pcase which
('files (lambda (b) (null (buffer-file-name b))))
('all (lambda (_) nil)))))
(dolist (buffer (buffer-list))
(unless (or (eq t (buffer-local-value 'treemacs--in-this-buffer buffer))
(eq buffer scratch)
(eq buffer messages)
(funcall no-delete-test buffer))
(kill-buffer buffer))))))
(defun treemacs-find-workspace-by-name (name)
"Find a workspace with the given NAME.
The check is case-sensitive. nil is returned when no workspace is found."
(declare (side-effect-free t))
(--first (string= name (treemacs-workspace->name it))
treemacs--workspaces))
(defun treemacs-find-workspace-by-path (path)
"Find a workspace with a project containing the given PATH.
nil is returned when no workspace is found."
(declare (side-effect-free t))
(--first (treemacs-is-path path :in-workspace it)
treemacs--workspaces))
(defun treemacs-find-workspace-where (predicate)
"Find a workspace matching the given PREDICATE.
Predicate should be a function that takes a `treemacs-workspace' as its single
argument. nil is returned when no workspace is found."
(--first (funcall predicate it) treemacs--workspaces))
(provide 'treemacs-workspaces)
;;; treemacs-workspaces.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-workspaces.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 8,858 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Minor mode to automatically display just the current project.
;; NOTE: This module is lazy-loaded.
;;; Code:
(require 'treemacs-scope)
(require 'treemacs-follow-mode)
(require 'treemacs-core-utils)
(eval-when-compile
(require 'treemacs-macros))
(defvar treemacs--project-follow-timer nil
"Idle timer for `treemacs-project-follow-mode'.")
(defconst treemacs--project-follow-delay 1.5
"Delay in seconds for `treemacs-project-follow-mode'.")
(defun treemacs--follow-project (_)
"Debounced display of the current project for `treemacs-project-follow-mode'.
Used as a hook for `window-buffer-change-functions', thus the ignored parameter."
(treemacs-debounce treemacs--project-follow-timer treemacs--project-follow-delay
(treemacs--do-follow-project)))
(defun treemacs--do-follow-project()
"Actual, un-debounced, implementation of project following."
(-when-let (window (treemacs-get-local-window))
(treemacs-block
(let* ((ws (treemacs-current-workspace))
(new-project-path (treemacs--find-current-user-project))
(old-project-path (-some-> ws
(treemacs-workspace->projects)
(car)
(treemacs-project->path))))
(treemacs-return-if
(or treemacs--in-this-buffer
(null new-project-path)
(and
(null treemacs-project-follow-into-home)
(string=
(expand-file-name "~")
new-project-path))
(bound-and-true-p edebug-mode)
(frame-parent)
(and (= 1 (length (treemacs-workspace->projects ws)))
(string= new-project-path old-project-path))))
(save-selected-window
(treemacs--show-single-project
new-project-path (treemacs--filename new-project-path))
(treemacs--follow)
(hl-line-highlight))))))
(defun treemacs--follow-project-after-buffer-init ()
"Hook to follow the current project when a treemacs buffer is created.
Used for `treemacs-post-buffer-init-hook', so it will run inside the treemacs
window."
(with-selected-window (next-window (selected-window))
(treemacs--do-follow-project)))
(defun treemacs--setup-project-follow-mode ()
"Setup all the hooks needed for `treemacs-project-follow-mode'."
(when treemacs--project-follow-timer (cancel-timer treemacs--project-follow-timer))
(setf treemacs--project-follow-timer nil)
(add-hook 'window-buffer-change-functions #'treemacs--follow-project)
(add-hook 'window-selection-change-functions #'treemacs--follow-project)
(add-hook 'treemacs-post-buffer-init-hook #'treemacs--follow-project-after-buffer-init))
(defun treemacs--tear-down-project-follow-mode ()
"Remove the hooks added by `treemacs--setup-project-follow-mode'."
(cancel-timer treemacs--project-follow-timer)
(remove-hook 'window-buffer-change-functions #'treemacs--follow-project)
(remove-hook 'window-selection-change-functions #'treemacs--follow-project)
(remove-hook 'treemacs-post-buffer-init-hook #'treemacs--follow-project-after-buffer-init))
;;;###autoload
(define-minor-mode treemacs-project-follow-mode
"Toggle `treemacs-only-current-project-mode'.
This is a minor mode meant for those who do not care about treemacs' workspace
features, or its preference to work with multiple projects simultaneously. When
enabled it will function as an automated version of
`treemacs-display-current-project-exclusively', making sure that, after a small
idle delay, the current project, and *only* the current project, is displayed in
treemacs.
The project detection is based on the current buffer, and will try to determine
the project using the following methods, in the order they are listed:
- the current projectile.el project, if `treemacs-projectile' is installed
- the current project.el project
- the current `default-directory'
The update will only happen when treemacs is in the foreground, meaning a
treemacs window must exist in the current scope.
This mode requires at least Emacs version 27 since it relies on
`window-buffer-change-functions' and `window-selection-change-functions'."
:init-value nil
:global t
:lighter nil
:group 'treemacs
(if treemacs-project-follow-mode
(progn
(unless (and (boundp 'window-buffer-change-functions)
(boundp 'window-selection-change-functions))
(user-error "%s %s"
"Project-Follow-Mode is only available in Emacs"
"versions that support `window-buffer-change-functions'"))
(treemacs--setup-project-follow-mode))
(treemacs--tear-down-project-follow-mode)))
(provide 'treemacs-project-follow-mode)
;;; treemacs-project-follow-mode.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-project-follow-mode.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,164 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Simple bits of code to make treemacs compatible with other packages
;; that aren't worth the effort of being turned into their own package.
;;; Code:
(require 'dash)
(require 'treemacs-customization)
(require 'treemacs-logging)
(require 'treemacs-scope)
(require 'treemacs-core-utils)
(require 'treemacs-interface)
(require 'treemacs-persistence)
(eval-when-compile
(require 'treemacs-macros))
(treemacs-only-during-init
;; make sure frame params are not persisted by desktop-save-mode
(push '(treemacs-id . :never) frameset-filter-alist)
(push '(treemacs-workspace . :never) frameset-filter-alist))
(with-eval-after-load 'tramp
(setf
treemacs--no-abbr-on-persist-prefixes
(--map (format "/%s:" (car it)) (with-no-warnings tramp-methods))
treemacs--file-name-handler-alist
(with-no-warnings
(list
(cons tramp-file-name-regexp #'tramp-file-name-handler)))))
(with-eval-after-load 'recentf
(with-no-warnings
(add-to-list 'recentf-exclude treemacs-persist-file)
(add-to-list 'recentf-exclude treemacs-last-error-persist-file)))
(with-eval-after-load 'eyebrowse
(defun treemacs--follow-after-eyebrowse-switch ()
(when treemacs-follow-mode
(--when-let (treemacs-get-local-window)
(with-selected-window it
(treemacs--follow-after-buffer-list-update)
(hl-line-highlight)))))
(declare-function treemacs--follow-after-eyebrowse-switch "treemacs-compatibility")
(add-hook 'eyebrowse-post-window-switch-hook #'treemacs--follow-after-eyebrowse-switch))
(with-eval-after-load 'winum
(when (boundp 'winum-ignored-buffers-regexp)
(add-to-list 'winum-ignored-buffers-regexp (regexp-quote (format "%sScoped-Buffer-" treemacs--buffer-name-prefix)))))
(with-eval-after-load 'ace-window
(when (boundp 'aw-ignored-buffers)
(push 'treemacs-mode aw-ignored-buffers)))
(with-eval-after-load 'golden-ratio
(when (boundp 'golden-ratio-exclude-modes)
(add-to-list 'golden-ratio-exclude-modes 'treemacs-mode)))
(with-eval-after-load 'indent-guide
(when (boundp 'indent-guide-inhibit-modes)
(push 'treemacs-mode indent-guide-inhibit-modes)))
(with-eval-after-load 'ediff
(add-hook
'ediff-before-setup-hook
(defun treemacs--dont-diff-in-treemacs-window ()
"Select `next-window' before ediff's window setup.
Treemacs is by default a side-window, meaning it'll throw an error if ediff trys
to split it."
(when treemacs--in-this-buffer
(select-window (next-window))))))
(with-eval-after-load 'persp-mode
(defun treemacs--remove-treemacs-window-in-new-frames (persp-activated-for)
(when (eq persp-activated-for 'frame)
(-when-let (w (--first (treemacs-is-treemacs-window? it)
(window-list)))
(unless (assoc (treemacs-scope->current-scope treemacs--current-scope-type) treemacs--scope-storage)
(delete-window w)))))
(declare-function treemacs--remove-treemacs-window-in-new-frames "treemacs-compatibility")
(if (boundp 'persp-activated-functions)
(add-to-list 'persp-activated-functions #'treemacs--remove-treemacs-window-in-new-frames)
(treemacs-log-failure "`persp-activated-functions' not defined - couldn't add compatibility.")))
(with-eval-after-load 'perspective
(defun treemacs--remove-treemacs-window-in-new-frames (&rest _)
(-when-let (w (--first (treemacs-is-treemacs-window? it)
(window-list)))
(unless (assoc (treemacs-scope->current-scope treemacs--current-scope-type) treemacs--scope-storage)
(delete-window w))))
(declare-function treemacs--remove-treemacs-window-in-new-frames "treemacs-compatibility")
(if (boundp 'persp-activated-hook)
(add-to-list 'persp-activated-hook #'treemacs--remove-treemacs-window-in-new-frames)
(treemacs-log-failure "`persp-activated-hook' not defined - couldn't add compatibility.")))
(defun treemacs--split-window-advice (original-split-function &rest args)
"Advice to make sure window splits are sized correctly with treemacs.
This will treat the treemacs window as a side-window for the duration of the
split, calling the ORIGINAL-SPLIT-FUNCTION with its ARGS. This prevents the
calculations in `split-window-right' from outputting the wrong result for the
width of the new window when the treemacs window is visible."
(-let [w (treemacs-get-local-window)]
(unwind-protect
(progn
(when w (set-window-parameter w 'window-side treemacs-position))
(apply original-split-function args))
(when (and w (null treemacs-display-in-side-window))
(set-window-parameter w 'window-side nil)))))
(advice-add 'split-window-right :around #'treemacs--split-window-advice)
(with-eval-after-load 'org
(defun treemacs-store-org-link ()
"Store an `org-mode' link for the node at point."
(when (eq major-mode 'treemacs-mode)
(-when-let* ((btn (treemacs-current-button))
(file (treemacs--nearest-path btn)))
(-let [link (format "file:%s" (abbreviate-file-name file))]
(with-no-warnings
(org-add-link-props
:link link
:description (treemacs--filename file)))
link))))
(with-no-warnings
(if (fboundp 'org-link-set-parameters)
(org-link-set-parameters "treemacs" :store #'treemacs-store-org-link)
(add-hook 'org-store-link-functions #'treemacs-store-org-link))))
(when (fboundp 'context-menu-mode)
(defun treemacs--disable-context-menu-mode ()
(treemacs-run-in-all-derived-buffers
(with-no-warnings
(setq-local context-menu-functions nil))))
(add-hook 'context-menu-mode-hook 'treemacs--disable-context-menu-mode))
(defun treemacs-load-all-the-icons-with-workaround-font (font)
"Load the `treemacs-all-the-icons' package using a workaround FONT for tabs.
Use this if you experience the issue of icons jumping around when they are
closed or opened which can appear when using specific fonts.
FONT should be a simple string name, for example \"Hermit\".
Finding the right FONT is a matter of trial and error, you can quickly try
different fonts using `set-frame-font'.
The workaround will overwrite the values for `treemacs-indentation' and
`treemacs-indentation-string', using your own values for them is no longer
possible.
Can only work if the `treemacs-all-the-icons' module has not been loaded yet."
(defvar treemacs-all-the-icons-tab-font font)
(setf treemacs-indentation 1
treemacs-indentation-string (propertize "\t" 'face `((:family ,treemacs-all-the-icons-tab-font))))
(require 'treemacs-all-the-icons)
(treemacs-load-theme "all-the-icons"))
(provide 'treemacs-compatibility)
;;; treemacs-compatibility.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-compatibility.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,801 |
```emacs lisp
;;; treemacs-git-commit-diff-mode.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Minor mode to annotate project with the number of commits a repo is ahead
;; and/or behind its remote.
;; NOTE: This module is lazy-loaded.
;;; Code:
(require 'vc-git)
(require 'dash)
(require 'pfuture)
(require 'treemacs-customization)
(require 'treemacs-workspaces)
(require 'treemacs-annotations)
(eval-when-compile
(require 'treemacs-macros))
(defconst treemacs--git-commit-diff.py
(if (member "treemacs-git-commit-diff.py" (directory-files treemacs-dir))
(treemacs-join-path treemacs-dir "treemacs-git-commit-diff.py")
(treemacs-join-path treemacs-dir "src/scripts/treemacs-git-commit-diff.py")))
(defconst treemacs--commit-diff-ann-source "treemacs-commit-diff"
"Annotation source name for commit diffs.")
(defun treemacs--update-git-commit-diff (project &optional buffer)
"Update the commit diff for a single PROJECT.
Look for the PROJECT either in BUFFER or the local treemacs buffer."
(let ((path (treemacs-project->path project))
(buffer (or buffer (treemacs-get-local-buffer))))
(treemacs-with-path path
:no-match-action
(ignore)
:file-action
(pfuture-callback `(,treemacs-python-executable "-O" ,treemacs--git-commit-diff.py ,path)
:directory path
:on-success
(when (buffer-live-p buffer)
(-let [out (-> (pfuture-callback-output)
(treemacs-string-trim-right)
(read))]
(with-current-buffer buffer
(if out
(treemacs-set-annotation-suffix path out treemacs--commit-diff-ann-source)
(treemacs-remove-annotation-suffix path treemacs--commit-diff-ann-source))
(treemacs-apply-single-annotation path))))))))
(defun treemacs--update-commit-diff-in-every-project ()
"Update diffs for every project in the current scope.
To be run when commt-diff-mode is activated or a treemacs buffer is created."
(dolist (project (treemacs-workspace->projects (treemacs-current-workspace)))
(when (vc-git-responsible-p (treemacs-project->path project))
(treemacs--update-git-commit-diff project))))
(defun treemacs--enable-git-commit-diff-mode ()
"Setup for `treemacs-comit-diff-mode'."
(add-hook 'treemacs-post-project-refresh-functions #'treemacs--update-git-commit-diff)
(add-hook 'treemacs-post-buffer-init-hook #'treemacs--update-commit-diff-in-every-project)
(treemacs-run-in-every-buffer
(treemacs--update-commit-diff-in-every-project)))
(defun treemacs--disable-git-commit-diff-mode ()
"Tear-down for `treemacs-comit-diff-mode'."
(remove-hook 'treemacs-post-project-refresh-functions #'treemacs--update-git-commit-diff)
(remove-hook 'treemacs-post-buffer-init-hook #'treemacs--update-commit-diff-in-every-project)
(treemacs-run-in-every-buffer
(dolist (project (treemacs-workspace->projects (treemacs-current-workspace)))
(-let [path (treemacs-project->path project)]
(treemacs-remove-annotation-suffix path treemacs--commit-diff-ann-source)
(treemacs-apply-single-annotation path)))))
;;;###autoload
(define-minor-mode treemacs-git-commit-diff-mode
"Minor mode to display commit differences for your git-tracked projects.
When enabled treemacs will add an annotation next to every git project showing
how many commits ahead or behind your current branch is compared to its remote
counterpart.
The difference will be shown using the format `x y', where `x' and `y' are the
numbers of commits a project is ahead or behind. The numbers are determined
based on the output of `git status -sb'.
By default the annotation is only updated when manually updating a project with
`treemacs-refresh'. You can install `treemacs-magit' to enable automatic
updates whenever you commit/fetch/rebase etc. in magit.
Does not require `treemacs-git-mode' to be active."
:init-value nil
:global t
:lighter nil
:group 'treemacs
(if treemacs-git-commit-diff-mode
(treemacs--enable-git-commit-diff-mode)
(treemacs--disable-git-commit-diff-mode)))
(provide 'treemacs-git-commit-diff-mode)
;;; treemacs-git-commit-diff-mode.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-git-commit-diff-mode.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,116 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; TODO
;; NOTE: This module is lazy-loaded.
;;; Code:
(require 'treemacs-tags)
(require 'treemacs-core-utils)
(eval-when-compile
(require 'treemacs-macros))
(defvar treemacs--peek-timer nil)
(defvar treemacs--peeked-buffers nil)
(defvar treemacs--pre-peek-state nil
"List of window, buffer to restore and buffer to kill treemacs used for peeking.")
(defun treemacs--kill-peek-buffers ()
"Kill buffers opened during peeking that are no longer needed."
(-each treemacs--peeked-buffers #'kill-buffer)
(setf treemacs--peeked-buffers nil))
(defun treemacs--setup-peek-buffer (path)
"Setup the peek buffer and window for PATH."
(let* ((inhibit-message t)
(file-buffer (get-file-buffer path))
(next-window (next-window (selected-window)))
(window (if file-buffer
(or (get-buffer-window file-buffer)
next-window)
next-window)))
(save-selected-window
(select-window window)
(unless treemacs--pre-peek-state
(setf treemacs--pre-peek-state (list window (window-buffer window))))
(if file-buffer
(switch-to-buffer file-buffer :norecord)
(find-file-existing path)
(add-to-list 'treemacs--peeked-buffers (current-buffer))))))
(defun treemacs--do-peek ()
"Timer callback to set up the peeked buffer.
Check if the node at point is a file, and if yes take a peek."
(when (eq t treemacs--in-this-buffer)
(let* ((btn (treemacs-current-button))
(path (and btn (treemacs-button-get btn :path))))
(when (and path
(stringp path)
(file-exists-p path))
(treemacs--setup-peek-buffer path)))))
(defun treemacs--finish-peek-on-window-leave (&optional _)
"Finish peeking when the treemacs window is no longer selected.
Shut down peek-mode while making sure that the current buffer will not be
purged."
(let ((treemacs-buffer (treemacs-get-local-buffer))
(current-buffer (current-buffer)))
(unless (equal treemacs-buffer current-buffer)
(setf treemacs--peeked-buffers
(delete current-buffer treemacs--peeked-buffers))
(treemacs-peek-mode -1))))
(defun treemacs--disable-peek-mode ()
"Hook function for `treemacs-quit-hook'."
(treemacs-peek-mode -1))
(defun treemacs--setup-peek-mode ()
"Set up faces, timers, and hooks etc."
(when treemacs--fringe-indicator-overlay
(overlay-put treemacs--fringe-indicator-overlay
'face 'treemacs-peek-mode-indicator-face))
(when treemacs--peek-timer (cancel-timer treemacs--peek-timer))
(setf treemacs--peek-timer
(run-with-idle-timer 0.5 :repeat #'treemacs--do-peek))
(add-hook
'window-selection-change-functions #'treemacs--finish-peek-on-window-leave
nil :local)
(add-hook 'treemacs-quit-hook #'treemacs--disable-peek-mode))
(defun treemacs--tear-down-peek-mode (&optional restore-window)
"Tear down faces, timers.
Restore the initial window buffer when RESTORE-WINDOW is non-nil. Will only
happen when `treemacs-peek-mode' has been called interactively, when the
tear-down happens on account of the window-leave hook the current buffer is
kept."
(with-current-buffer (treemacs-get-local-buffer)
(when treemacs--fringe-indicator-overlay
(overlay-put treemacs--fringe-indicator-overlay
'face 'treemacs-fringe-indicator-face))
(when treemacs--peek-timer (cancel-timer treemacs--peek-timer))
(treemacs--kill-peek-buffers)
(remove-hook
'window-selection-change-functions
#'treemacs--finish-peek-on-window-leave
:local)
(when (and restore-window treemacs--pre-peek-state)
(-let [(window buffer) treemacs--pre-peek-state]
(with-selected-window window
(switch-to-buffer buffer))))
(setf treemacs--pre-peek-state nil))
(remove-hook 'treemacs-quit-hook #'treemacs--disable-peek-mode))
;;;###autoload
(define-minor-mode treemacs-peek-mode
"Minor mode that allows you to peek at buffers before deciding to open them.
While the mode is active treemacs will automatically display the file at point,
without leaving the treemacs window.
Peeking will stop when you leave the treemacs window, be it through a command
like `treemacs-RET-action' or some other window selection change.
Files' buffers that have been opened for peeking will be cleaned up if they did
not exist before peeking started.
The peeked window can be scrolled using
`treemacs-next/previous-line-other-window' and
`treemacs-next/previous-page-other-window'"
:init-value nil
:global t
:lighter nil
:group 'treemacs
(if treemacs-peek-mode
(progn
(unless (boundp 'window-selection-change-functions)
(user-error "%s %s"
"Peek-mode is only available in Emacs"
"versions that support `window-selection-change-functions'"))
(treemacs--setup-peek-mode))
(treemacs--tear-down-peek-mode (called-interactively-p 'interactive))))
(provide 'treemacs-peek-mode)
;;; treemacs-peek-mode.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-peek-mode.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,370 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Code for dealing with treemacs' asynchronous features.
;;; Code:
(require 'dash)
(require 'ht)
(require 's)
(require 'vc-hooks)
(require 'pfuture)
(require 'treemacs-core-utils)
(require 'treemacs-customization)
(require 'treemacs-workspaces)
(require 'treemacs-dom)
(require 'treemacs-logging)
(require 'treemacs-visuals)
(eval-when-compile
(require 'inline)
(require 'treemacs-macros))
(treemacs-import-functions-from treemacs-rendering
treemacs-do-delete-single-node)
(treemacs-import-functions-from treemacs-annotations
treemacs--do-apply-annotation)
(defconst treemacs--dirs-to-collapse.py
(if (member "treemacs-dirs-to-collapse.py" (directory-files treemacs-dir))
(treemacs-join-path treemacs-dir "treemacs-dirs-to-collapse.py")
(treemacs-join-path treemacs-dir "src/scripts/treemacs-dirs-to-collapse.py")))
(defconst treemacs--git-status.py
(if (member "treemacs-git-status.py" (directory-files treemacs-dir))
(treemacs-join-path treemacs-dir "treemacs-git-status.py")
(treemacs-join-path treemacs-dir "src/scripts/treemacs-git-status.py")))
(defconst treemacs--single-file-git-status.py
(if (member "treemacs-single-file-git-status.py" (directory-files treemacs-dir))
(treemacs-join-path treemacs-dir "treemacs-single-file-git-status.py")
(treemacs-join-path treemacs-dir "src/scripts/treemacs-single-file-git-status.py")))
(defconst treemacs--find-ignored-files.py
(if (member "treemacs-find-ignored-files.py" (directory-files treemacs-dir))
(treemacs-join-path treemacs-dir "treemacs-find-ignored-files.py")
(treemacs-join-path treemacs-dir "src/scripts/treemacs-find-ignored-files.py")))
(defconst treemacs--single-git-update-debouce-store (make-hash-table :size 10)
"Table to keep track of files that will already be updated.")
(defvar treemacs--git-cache-max-size 60
"Maximum size for `treemacs--git-cache'.
If it does reach that size it will be cut back to 30 entries.")
(defvar treemacs--git-cache (make-hash-table :size treemacs--git-cache-max-size :test #'equal)
"Stores the results of previous git status calls for directories.
Its effective type is HashMap<FilePath, HashMap<FilePath, Char>>.
These cached results are used as a stand-in during immediate rendering when
`treemacs-git-mode' is set to be deferred, so as to minimise the effect of large
face changes, especially when a full project is refreshed.
Since this table is a global value that can effectively grow indefinitely its
value is limited by `treemacs--git-cache-max-size'.")
(defvar treemacs-git-mode)
(define-inline treemacs--git-status-face (status default)
"Get the git face for the given STATUS.
Use DEFAULT as default match.
STATUS: String
DEFAULT: Face"
(declare (pure t) (side-effect-free t))
(inline-letevals (status default)
(inline-quote
(pcase ,status
("M" 'treemacs-git-modified-face)
("U" 'treemacs-git-conflict-face)
("?" 'treemacs-git-untracked-face)
("!" 'treemacs-git-ignored-face)
("A" 'treemacs-git-added-face)
("R" 'treemacs-git-renamed-face)
(_ ,default)))))
(defvar treemacs--git-mode nil
"Saves the specific version of git-mode that is active.
Values are either `simple', `extended', `deferred' or nil.")
(defun treemacs--non-simple-git-mode-enabled ()
"Indicate whether a version of git-mode is enabled that affects directories."
(declare (side-effect-free t))
(memq treemacs--git-mode '(deferred extended)))
(defun treemacs--resize-git-cache ()
"Cuts `treemacs--git-cache' back down to size.
Specifically its size will be reduced to half of `treemacs--git-cache-max-size'."
(treemacs-block
(let* ((size (ht-size treemacs--git-cache))
(count (- size (/ treemacs--git-cache-max-size 2))))
(treemacs--maphash treemacs--git-cache (key _)
(ht-remove! treemacs--git-cache key)
(when (>= 0 (cl-decf count))
(treemacs-return :done))))))
(defun treemacs--git-status-process-function (path)
"Dummy with PATH.
Real implementation will be `fset' based on `treemacs-git-mode' value."
(ignore path))
(defun treemacs--git-status-process (path project)
"Run `treemacs--git-status-process-function' on PATH, if allowed for PROJECT.
Remote projects are ignored."
(when (treemacs-project->is-local-and-readable? project)
(treemacs--git-status-process-function path)))
(defun treemacs--git-status-parse-function (_future)
"Dummy with FUTURE.
Real implementation will be `fset' based on `treemacs-git-mode' value."
treemacs--empty-table)
(defun treemacs--git-status-process-extended (path)
"Start an extended python-parsed git status process for files under PATH."
(-when-let (git-root (vc-call-backend 'Git 'root path))
(let* ((file-name-handler-alist nil)
(git-root (expand-file-name git-root))
(default-directory path)
(open-dirs (cons
path
(-some->>
path
(treemacs-find-in-dom)
(treemacs-dom-node->reentry-nodes)
(-map #'treemacs-dom-node->key)
;; Remove extension nodes
(-filter #'stringp))))
(command `(,treemacs-python-executable
"-O"
,treemacs--git-status.py
,git-root
,(number-to-string treemacs-max-git-entries)
,treemacs-git-command-pipe
,@open-dirs))
(future (apply #'pfuture-new command)))
future)))
(defun treemacs--parse-git-status-extended (git-future)
"Parse the git status derived from the output of GIT-FUTURE.
The real parsing and formatting is done by the python process. All that's
really left to do is pick up the cons list and put it in a hash table.
GIT-FUTURE: Pfuture"
(or (when git-future
(let* ((git-output (pfuture-await-to-finish git-future))
(git-stderr (pfuture-stderr git-future)))
;; Check stderr separately from parsing, often git status displays
;; warnings which do not affect the final result.
(unless (s-blank? git-stderr)
(let ((visible-error (--> (s-trim git-stderr)
(s-replace "\n" ", " it)
(s-truncate 80 it)
(propertize it 'face 'error))))
(if (< (length git-stderr) 80)
(treemacs-log-err "treemacs-git-status.py wrote to stderr: %s" visible-error)
(treemacs-log-err "treemacs-git-status.py wrote to stderr (see full output in *Messages*): %s" visible-error)
(let ((inhibit-message t))
(treemacs-log "treemacs-git-status.py wrote to stderr: %s" git-stderr)))))
(when (= 0 (process-exit-status git-future))
(-let [parsed-output (read git-output)]
(if (hash-table-p parsed-output)
parsed-output
(let ((inhibit-message t))
(treemacs-log-err "treemacs-git-status.py output: %s" git-output))
(treemacs-log-err "treemacs-git-status.py did not output a valid hash table. See full output in *Messages*.")
nil)))))
treemacs--empty-table))
(defun treemacs--git-status-process-simple (path)
"Start a simple git status process for files under PATH."
(let* ((default-directory (file-truename path))
(process-environment (cons "GIT_OPTIONAL_LOCKS=0" process-environment))
(future (pfuture-new "git" "status" "--porcelain" "--ignored=matching" "-z" ".")))
(process-put future 'default-directory default-directory)
future))
(defun treemacs--parse-git-status-simple (git-future)
"Parse the output of GIT-FUTURE into a hash table."
(-let [git-info-hash (make-hash-table :test #'equal :size 300)]
(when git-future
(pfuture-await-to-finish git-future)
(when (= 0 (process-exit-status git-future))
(-let [git-output (pfuture-result git-future)]
(unless (s-blank? git-output)
;; need the actual git root since git status outputs paths relative to it
;; and the output must be valid also for files in dirs being reopened
(let* ((git-root (vc-call-backend 'Git 'root (process-get git-future 'default-directory)))
(status-list (->> (substring git-output 0 -1)
(s-split "\0")
(--map (s-split-up-to " " (s-trim it) 1)))))
(let ((len (length status-list))
(i 0))
(while (< i len)
(let* ((status-cons (nth i status-list))
(status (car status-cons))
(path (cadr status-cons)))
;; don't include directories since only a part of the untracked dirs
;; would be shown anway
(unless (eq ?/ (aref path (1- (length path))))
;; there's a NUL after every filename, so a rename looks like
;; 'R oldnameNULnewnameNUL' which would break parsing that expects that a NUL separates
;; status entries and not just filenames
(if (eq ?R (aref status 0))
(setq i (1+ i))
(ht-set! git-info-hash
(treemacs-join-path git-root (s-trim-left path))
(treemacs--git-status-face
(substring (s-trim-left status) 0 1)
'treemacs-git-unmodified-face)))))
(setq i (1+ i)))))))))
git-info-hash))
(defun treemacs-update-single-file-git-state (file)
"Update the FILE node's git state, wrapped in `treemacs-save-position'.
Internally calls `treemacs-do-update-single-file-git-state'.
FILE: FilePath"
(treemacs-save-position
(treemacs-do-update-single-file-git-state file)))
(defun treemacs-do-update-single-file-git-state (file &optional exclude-parents override-status)
"Asynchronously update the given FILE node's git fontification.
Since an update to a single node can potentially also mean a change to the
states of all its parents they will likewise be updated by this function. If
the file's current and new git status are the same this function will do
nothing.
When EXCLUDE-PARENTS is non-nil only the given FILE only the file node is
updated. This is only used in case a file-watch update requires the insertion
of a new file that, due to being recently created, does not have a git status
cache entry.
When OVERRIDE-STATUS is non-nil the FILE's cached git status will not be used.
FILE: FilePath
EXCLUDE-PARENTS: Boolean
OVERRIDE-STATUS: Boolean"
(let* ((local-buffer (current-buffer))
(parent (treemacs--parent file))
(parent-node (treemacs-find-in-dom parent)))
(when (and
treemacs-git-mode
parent-node
(null (ht-get treemacs--single-git-update-debouce-store file)))
(ht-set! treemacs--single-git-update-debouce-store file t)
(let* ((parents (unless (or exclude-parents
(eq 'simple treemacs--git-mode)
(null (treemacs-dom-node->parent parent-node)))
;; include the first parent...
(cons (treemacs-dom-node->key parent-node)
;; ...but exclude the project root
(cdr (-map #'treemacs-dom-node->key
(treemacs-dom-node->all-parents parent-node))))))
(git-cache (ht-get treemacs--git-cache parent))
(current-face (if override-status
"OVERRIDE"
(or (-some-> git-cache (ht-get file) (symbol-name))
"NONE")))
(cmd `(,treemacs-python-executable
"-O"
,treemacs--single-file-git-status.py ,file ,current-face ,@parents)))
(pfuture-callback cmd
:directory parent
:name "Treemacs Update Single File Process"
:on-success
(progn
(ht-remove! treemacs--single-git-update-debouce-store file)
(when (buffer-live-p local-buffer)
(with-current-buffer local-buffer
(treemacs-with-writable-buffer
(save-excursion
;; first the file node with its own default face
(-let [output (read (pfuture-callback-output))]
(-let [(path . face) (pop output)]
(treemacs--git-face-quick-change path face git-cache))
;; then the directories
(pcase-dolist (`(,path . ,face) output)
(treemacs--git-face-quick-change path face))))))))
:on-error
(progn
(ht-remove! treemacs--single-git-update-debouce-store file)
(pcase (process-exit-status process)
(2 (ignore "No Change, Do Nothing"))
(_
(-let [err-str (treemacs--remove-trailing-newline (pfuture-output-from-buffer pfuture-buffer))]
(treemacs-log-err "Update of node \"%s\" failed with status \"%s\" and result"
file (treemacs--remove-trailing-newline status))
(treemacs-log-err "\"%s\"" (treemacs--remove-trailing-newline err-str)))))))))))
(define-inline treemacs--git-face-quick-change (path git-face &optional git-cache)
"Quick-change of PATH's GIT-FACE.
Updates the visible face and git-cache + annotation store entries. GIT-CACHE
might be already known or not. If not it will be pulled from BTN's parent.
Used when asynchronous processes report back git changes."
(inline-letevals (path git-face git-cache)
(inline-quote
(let ((git-cache (or ,git-cache
(ht-get treemacs--git-cache
(treemacs--parent-dir ,path))))
(btn (treemacs-find-visible-node ,path)))
(when git-cache
(ht-set! git-cache ,path ,git-face))
(when btn
(treemacs--do-apply-annotation btn ,git-face))))))
(defun treemacs--flattened-dirs-process (path project)
"Start a new process to determine directories to collapse under PATH.
Only starts the process if PROJECT is locally accessible (i.e. exists, and
is not remote.)
Output format is an elisp list of string lists that's read directly.
Every string list consists of the following elements:
1) the extra text that must be appended in the view
2) The original full and non-collapsed path
3) a series of intermediate steps which are the result of appending the
collapsed path elements onto the original, ending in
4) the full path to the
directory that the collapsing leads to. For Example:
(\"/26.0/elpa\"
\"/home/a/Documents/git/treemacs/.cask\"
\"/home/a/Documents/git/treemacs/.cask/26.0\"
\"/home/a/Documents/git/treemacs/.cask/26.0/elpa\")"
(when (and (> treemacs-collapse-dirs 0)
treemacs-python-executable
(treemacs-project->is-local-and-readable? project))
(let (;; needs to be set or we'll run into trouble when deleting
;; haven't taken the time to figure out why, so let's just leave it at that
(default-directory path)
(search-paths nil))
(treemacs-walk-reentry-dom (treemacs-find-in-dom path)
(lambda (node)
(-let [key (treemacs-dom-node->key node)]
(when (stringp key) (push key search-paths)))))
(-let [command
`(,treemacs-python-executable
"-O"
,treemacs--dirs-to-collapse.py
,(number-to-string treemacs-collapse-dirs)
,(if treemacs-show-hidden-files "t" "x")
,@search-paths)]
(apply #'pfuture-new command)))))
(defun treemacs--parse-flattened-dirs (path future)
"Parse the output of flattened dirs in PATH with FUTURE."
(when future
(-if-let (output (process-get future 'output))
(ht-get output path)
(let* ((stdout (pfuture-await-to-finish future))
(output (if (= 0 (process-exit-status future))
(read stdout)
(ht))))
(process-put future 'output output)
(ht-get output path)))))
(defun treemacs--prefetch-gitignore-cache (path)
"Pre-load all the git-ignored files in the given PATH.
PATH is either the symbol `all', in which case the state of all projects in the
current workspace is gathered instead, or a single project's path, when that
project has just been added to the workspace.
Required for `treemacs-hide-gitignored-files-mode' to properly work with
deferred git-mode, as otherwise ignored files will not be hidden on the first
run because the git cache has yet to be filled."
(if (eq path 'all)
(setf path (-map #'treemacs-project->path
(treemacs-workspace->projects (treemacs-current-workspace))))
(setf path (list path)))
(pfuture-callback `(,treemacs-python-executable
"-O"
,treemacs--find-ignored-files.py
,@path)
:on-error (ignore)
:on-success
(let ((ignore-pairs (read (pfuture-callback-output)))
(ignored-files nil))
(while ignore-pairs
(let* ((root (pop ignore-pairs))
(file (pop ignore-pairs))
(cache (ht-get treemacs--git-cache root)))
(unless cache
(setf cache (make-hash-table :size 20 :test 'equal))
(ht-set! treemacs--git-cache root cache))
(ht-set! cache file 'treemacs-git-ignored-face)
(push file ignored-files)))
(treemacs-run-in-every-buffer
(treemacs-save-position
(dolist (file ignored-files)
(-when-let (treemacs-is-path-visible? file)
(treemacs-do-delete-single-node file))))))))
(define-minor-mode treemacs-git-mode
"Toggle `treemacs-git-mode'.
When enabled treemacs will check files' git status and highlight them
accordingly. This git integration is available in 3 variants: simple, extended
and deferred.
The simple variant will start a git status process whose output is parsed in
elisp. This version is simpler and slightly faster, but incomplete - it will
highlight only files, not directories.
The extended variant requires a non-trivial amount of parsing to be done, which
is achieved with python (specifically python3). It is slightly slower, but
complete - both files and directories will be highlighted according to their git
status.
The deferred variant is the same is extended, except the tasks of rendering
nodes and highlighting them are separated. The former happens immediately, the
latter after `treemacs-deferred-git-apply-delay' seconds of idle time. This may
be faster (if not in truth then at least in appearance) as the git process is
given a much greater amount of time to finish. The downside is that the effect
of nodes changing their colours may be somewhat jarring, though this issue is
largely mitigated due to the use of a caching layer.
All versions run asynchronously and are optimised for not doing more work than
is necessary, so their performance cost should, for the most part, be the
constant time needed to fork a subprocess."
:init-value nil
:global t
:lighter nil
:group 'treemacs-git
;; case when the mode is re-activated by `custom-set-minor-mode'
(when (and (equal arg 1) treemacs--git-mode)
(setf arg treemacs--git-mode))
(if treemacs-git-mode
(if (memq arg '(simple extended deferred))
(treemacs--setup-git-mode arg)
(call-interactively 'treemacs--setup-git-mode))
(treemacs--tear-down-git-mode)))
(defun treemacs--setup-git-mode (&optional arg)
"Set up `treemacs-git-mode'.
Use either ARG as git integration value of read it interactively."
(interactive (list (-> (completing-read "Git Integration: " '("Simple" "Extended" "Deferred"))
(downcase)
(intern))))
(setf treemacs--git-mode arg)
(pcase treemacs--git-mode
((or 'extended 'deferred)
(fset 'treemacs--git-status-process-function #'treemacs--git-status-process-extended)
(fset 'treemacs--git-status-parse-function #'treemacs--parse-git-status-extended))
('simple
(fset 'treemacs--git-status-process-function #'treemacs--git-status-process-simple)
(fset 'treemacs--git-status-parse-function #'treemacs--parse-git-status-simple))
(_
(fset 'treemacs--git-status-process-function #'ignore)
(fset 'treemacs--git-status-parse-function (lambda (_) treemacs--empty-table)))))
(defun treemacs--tear-down-git-mode ()
"Tear down `treemacs-git-mode'."
(setf treemacs--git-mode nil)
(fset 'treemacs--git-status-process-function #'ignore)
(fset 'treemacs--git-status-parse-function (lambda (_) treemacs--empty-table)))
(define-inline treemacs--get-or-parse-git-result (future)
"Get the parsed git result of FUTURE.
Parse and set it if it hasn't been done yet. If FUTURE is nil an empty hash
table is returned.
FUTURE: Pfuture process"
(inline-letevals (future)
(inline-quote
(if ,future
(--if-let (process-get ,future 'git-table)
it
(let ((result (treemacs--git-status-parse-function ,future)))
(process-put ,future 'git-table result)
result))
treemacs--empty-table))))
(define-minor-mode treemacs-hide-gitignored-files-mode
"Toggle `treemacs-hide-gitignored-files-mode'.
When enabled treemacs will hide files that are ignored by git.
Some form of `treemacs-git-mode' *must* be enabled, otherwise this feature will
have no effect.
Both `extended' and `deferred' git-mode settings will work in full (in case of
`deferred' git-mode treemacs will pre-load the list of ignored files so they
will be hidden even on the first run). The limitations of `simple' git-mode
apply here as well: since it only knows about files and not directories only
files will be hidden."
:init-value nil
:global t
:lighter nil
:group 'treemacs-git
(if treemacs-hide-gitignored-files-mode
(progn
(add-to-list 'treemacs-pre-file-insert-predicates
#'treemacs-is-file-git-ignored?)
(when (and (eq 'deferred treemacs--git-mode)
(not (get 'treemacs-hide-gitignored-files-mode
:prefetch-done)))
(treemacs--prefetch-gitignore-cache 'all)
(put 'treemacs-hide-gitignored-files-mode :prefetch-done t)))
(setf treemacs-pre-file-insert-predicates
(delete #'treemacs-is-file-git-ignored?
treemacs-pre-file-insert-predicates)))
(treemacs-run-in-every-buffer
(treemacs--do-refresh (current-buffer) 'all))
(when (called-interactively-p 'interactive)
(treemacs-pulse-on-success "Git-ignored files will now be %s"
(propertize
(if treemacs-hide-gitignored-files-mode "hidden." "displayed.")
'face 'font-lock-constant-face))) )
(treemacs-only-during-init
(let ((has-git (not (null (executable-find "git"))))
(has-python (not (null treemacs-python-executable))))
(pcase (cons has-git has-python)
(`(t . t)
(treemacs-git-mode 'deferred))
(`(t . _)
(treemacs-git-mode 'simple)))
(when has-python
(setf treemacs-collapse-dirs 3))
(unless (or has-python (boundp 'treemacs-no-load-time-warnings))
(treemacs-log-failure "Python3 not found, advanced git-mode and directory flattening features will be disabled."))))
(provide 'treemacs-async)
;;; treemacs-async.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-async.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 5,744 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; Definition for the Helpful Hydras.
;; NOTE: This module is lazy-loaded.
;;; Code:
(require 'cl-lib)
(require 'dash)
(require 'treemacs-logging)
(require 'treemacs-scope)
(require 'treemacs-interface)
(require 'treemacs-bookmarks)
(eval-when-compile
(require 'treemacs-macros))
(treemacs-import-functions-from "treemacs"
treemacs-edit-workspaces
treemacs-version)
(treemacs-import-functions-from "treemacs-file-management"
treemacs-rename-file
treemacs-create-file
treemacs-create-dir
treemacs-copy-file
treemacs-move-file
treemacs-delete-file
treemacs-bulk-file-actions)
(treemacs-import-functions-from "treemacs-hydras"
treemacs--common-helpful-hydra/body
treemacs--advanced-helpful-hydra/body)
(treemacs-import-functions-from "treemacs-peek-mode"
treemacs-peek-mode)
(treemacs-import-functions-from "treemacs-header-line"
treemacs-indicate-top-scroll-mode)
(treemacs-import-functions-from "treemacs-git-commit-diff-mode"
treemacs-git-commit-diff-mode)
(cl-defun treemacs--find-keybind (func &optional (pad 8))
"Find the keybind for FUNC in treemacs.
Return of cons of the key formatted for inclusion in the hydra string, including
a minimum PAD width for alignment, and the key itself for the hydra heads.
Prefer evil keybinds, otherwise pick the first result."
(-if-let (keys (where-is-internal func))
(let ((key
(key-description
(-if-let (evil-keys (--first (eq 'treemacs-state (aref it 0)) keys))
(--map (aref evil-keys it) (number-sequence 1 (- (length evil-keys) 1)))
(--map (aref (car keys) it) (number-sequence 0 (- (length (car keys)) 1)))))))
(setf key
(s-replace-all
'(("<return>" . "RET")
("<left>" . "LEFT")
("<right>" . "RIGHT")
("<up>" . "UP")
("<down>" . "DOWN")
("^" . "C-")
("" . ">O-")
("" . "O-")
("" . ">#-")
("" . "#-")
("" . "S-"))
key))
(cons (s-pad-right pad " " (format "_%s_:" key)) key))
(cons (s-pad-right pad " " (format "_%s_:" " ")) " ")))
;;;###autoload
(defun treemacs-common-helpful-hydra ()
"Summon a helpful hydra to show you the treemacs keymap.
This hydra will show the most commonly used keybinds for treemacs. For the more
advanced (probably rarely used keybinds) see `treemacs-advanced-helpful-hydra'.
The keybinds shown in this hydra are not static, but reflect the actual
keybindings currently in use (including evil mode). If the hydra is unable to
find the key a command is bound to it will show a blank instead."
(interactive)
(-if-let (b (treemacs-get-local-buffer))
(with-current-buffer b
(let*
((title (format (propertize "Treemacs %s Common Helpful Hydra" 'face 'treemacs-help-title-face) (treemacs-version)))
(adv-hint (format "%s %s"
(propertize "For advanced keybinds see" 'face 'treemacs-help-title-face)
(propertize "treemacs-advanced-helpful-hydra" 'face 'font-lock-function-name-face)))
(column-nav (propertize "Navigation" 'face 'treemacs-help-column-face))
(column-nodes (propertize "Opening Nodes" 'face 'treemacs-help-column-face))
(column-toggles (propertize "Toggles " 'face 'treemacs-help-column-face))
(column-projects (propertize "Projects" 'face 'treemacs-help-column-face))
(key-adv-hydra (treemacs--find-keybind #'treemacs-advanced-helpful-hydra))
(key-root-up (treemacs--find-keybind #'treemacs-root-up))
(key-root-down (treemacs--find-keybind #'treemacs-root-down))
(key-next-line (treemacs--find-keybind #'treemacs-next-line))
(key-prev-line (treemacs--find-keybind #'treemacs-previous-line))
(key-next-neighbour (treemacs--find-keybind #'treemacs-next-neighbour))
(key-prev-neighbour (treemacs--find-keybind #'treemacs-previous-neighbour))
(key-goto-parent (treemacs--find-keybind #'treemacs-goto-parent-node))
(key-down-next-w (treemacs--find-keybind #'treemacs-next-line-other-window))
(key-up-next-w (treemacs--find-keybind #'treemacs-previous-line-other-window))
(key-ret (treemacs--find-keybind #'treemacs-RET-action))
(key-tab (treemacs--find-keybind #'treemacs-TAB-action))
(key-open (treemacs--find-keybind #'treemacs-visit-node-no-split))
(key-open-horiz (treemacs--find-keybind #'treemacs-visit-node-horizontal-split))
(key-open-vert (treemacs--find-keybind #'treemacs-visit-node-vertical-split))
(key-open-ace (treemacs--find-keybind #'treemacs-visit-node-ace))
(key-open-ace-h (treemacs--find-keybind #'treemacs-visit-node-ace-horizontal-split))
(key-open-ace-v (treemacs--find-keybind #'treemacs-visit-node-ace-vertical-split))
(key-open-ext (treemacs--find-keybind #'treemacs-visit-node-in-external-application))
(key-open-mru (treemacs--find-keybind #'treemacs-visit-node-in-most-recently-used-window))
(key-open-close (treemacs--find-keybind #'treemacs-visit-node-close-treemacs))
(key-close-above (treemacs--find-keybind #'treemacs-collapse-parent-node))
(key-follow-mode (treemacs--find-keybind #'treemacs-follow-mode))
(key-header-mode (treemacs--find-keybind #'treemacs-indicate-top-scroll-mode))
(key-fringe-mode (treemacs--find-keybind #'treemacs-fringe-indicator-mode))
(key-fwatch-mode (treemacs--find-keybind #'treemacs-filewatch-mode))
(key-commit-diff (treemacs--find-keybind #'treemacs-git-commit-diff-mode))
(key-git-mode (treemacs--find-keybind #'treemacs-git-mode))
(key-show-dotfiles (treemacs--find-keybind #'treemacs-toggle-show-dotfiles))
(key-indent-guide (treemacs--find-keybind #'treemacs-indent-guide-mode))
(key-show-gitignore (treemacs--find-keybind #'treemacs-hide-gitignored-files-mode))
(key-toggle-width (treemacs--find-keybind #'treemacs-toggle-fixed-width))
(key-add-project (treemacs--find-keybind #'treemacs-add-project-to-workspace 12))
(key-remove-project (treemacs--find-keybind #'treemacs-remove-project-from-workspace 12))
(key-rename-project (treemacs--find-keybind #'treemacs-rename-project 12))
(hydra-str
(format
"
%s
%s (%s)
%s ^^^^^^^^ %s ^^^^^^^^^^^ %s ^^^^^^ %s
%s next line ^^^^ %s dwim TAB ^^^^ %s follow mode ^^^^ %s add project
%s prev line ^^^^ %s dwim RET ^^^^ %s filewatch mode ^^^^ %s remove project
%s next neighbour ^^^^ %s open no split ^^^^ %s git mode ^^^^ %s rename project
%s prev neighbour ^^^^ %s open horizontal ^^^^ %s show dotfiles ^^^^
%s goto parent ^^^^ %s open vertical ^^^^ %s show gitignored files ^^^^
%s down next window ^^^^ %s open ace ^^^^ %s resizability ^^^^
%s up next window ^^^^ %s open ace horizontal ^^^^ %s fringe indicator ^^^^
%s root up ^^^^ %s open ace vertical ^^^^ %s indent guide ^^^^
%s root down ^^^^ %s open mru window ^^^^ %s top scroll indicator ^^^^
%s open externally ^^^^ %s git commit difference ^^^^
%s open close treemacs ^^^^
%s close parent ^^^^
"
title
adv-hint (car (s-split":" (car key-adv-hydra)))
column-nav column-nodes column-toggles column-projects
(car key-next-line) (car key-tab) (car key-follow-mode) (car key-add-project)
(car key-prev-line) (car key-ret) (car key-fwatch-mode) (car key-remove-project)
(car key-next-neighbour) (car key-open) (car key-git-mode) (car key-rename-project)
(car key-prev-neighbour) (car key-open-horiz) (car key-show-dotfiles)
(car key-goto-parent) (car key-open-vert) (car key-show-gitignore)
(car key-down-next-w) (car key-open-ace) (car key-toggle-width)
(car key-up-next-w) (car key-open-ace-h) (car key-fringe-mode)
(car key-root-up) (car key-open-ace-v) (car key-indent-guide)
(car key-root-down) (car key-open-mru) (car key-header-mode)
(car key-open-ext) (car key-commit-diff)
(car key-open-close)
(car key-close-above))))
(eval
`(defhydra treemacs--common-helpful-hydra (:exit nil :hint nil :columns 4)
,hydra-str
(,(cdr key-adv-hydra) #'treemacs-advanced-helpful-hydra :exit t)
(,(cdr key-next-line) #'treemacs-next-line)
(,(cdr key-prev-line) #'treemacs-previous-line)
(,(cdr key-root-up) #'treemacs-root-up)
(,(cdr key-root-down) #'treemacs-root-down)
(,(cdr key-down-next-w) #'treemacs-next-line-other-window)
(,(cdr key-up-next-w) #'treemacs-previous-line-other-window)
(,(cdr key-next-neighbour) #'treemacs-next-neighbour)
(,(cdr key-prev-neighbour) #'treemacs-previous-neighbour)
(,(cdr key-goto-parent) #'treemacs-goto-parent-node)
(,(cdr key-ret) #'treemacs-RET-action)
(,(cdr key-tab) #'treemacs-TAB-action)
(,(cdr key-open) #'treemacs-visit-node-no-split)
(,(cdr key-open-horiz) #'treemacs-visit-node-horizontal-split)
(,(cdr key-open-vert) #'treemacs-visit-node-vertical-split)
(,(cdr key-open-ace) #'treemacs-visit-node-ace)
(,(cdr key-open-ace-h) #'treemacs-visit-node-ace-horizontal-split)
(,(cdr key-open-ace-v) #'treemacs-visit-node-ace-vertical-split)
(,(cdr key-open-mru) #'treemacs-visit-node-in-most-recently-used-window)
(,(cdr key-open-ext) #'treemacs-visit-node-in-external-application)
(,(cdr key-open-close) #'treemacs-visit-node-close-treemacs)
(,(cdr key-close-above) #'treemacs-collapse-parent-node)
(,(cdr key-follow-mode) #'treemacs-follow-mode)
(,(cdr key-header-mode) #'treemacs-indicate-top-scroll-mode)
(,(cdr key-show-dotfiles) #'treemacs-toggle-show-dotfiles)
(,(cdr key-show-gitignore) #'treemacs-hide-gitignored-files-mode)
(,(cdr key-toggle-width) #'treemacs-toggle-fixed-width)
(,(cdr key-commit-diff) #'treemacs-git-commit-diff-mode)
(,(cdr key-fringe-mode) #'treemacs-fringe-indicator-mode)
(,(cdr key-indent-guide) #'treemacs-indent-guide-mode)
(,(cdr key-git-mode) #'treemacs-git-mode)
(,(cdr key-fwatch-mode) #'treemacs-filewatch-mode)
(,(cdr key-add-project) #'treemacs-add-project-to-workspace)
(,(cdr key-remove-project) #'treemacs-remove-project-from-workspace)
(,(cdr key-rename-project) #'treemacs-rename-project)
("<escape>" nil "Exit"))))
(treemacs--common-helpful-hydra/body))
(treemacs-log-failure "The helpful hydra cannot be summoned without an existing treemacs buffer.")))
(defalias 'treemacs-helpful-hydra #'treemacs-common-helpful-hydra)
;;;###autoload
(defun treemacs-advanced-helpful-hydra ()
"Summon a helpful hydra to show you the treemacs keymap.
This hydra will show the more advanced (rarely used) keybinds for treemacs. For
the more commonly used keybinds see `treemacs-common-helpful-hydra'.
The keybinds shown in this hydra are not static, but reflect the actual
keybindings currently in use (including evil mode). If the hydra is unable to
find the key a command is bound to it will show a blank instead."
(interactive)
(-if-let (b (treemacs-get-local-buffer))
(with-current-buffer b
(let*
((title (format (propertize "Treemacs %s Advanced Helpful Hydra" 'face 'treemacs-help-title-face) (treemacs-version)))
(column-files (propertize "File Management" 'face 'treemacs-help-column-face))
(column-ws (propertize "Workspaces" 'face 'treemacs-help-column-face))
(column-misc (propertize "Misc." 'face 'treemacs-help-column-face))
(column-window (propertize "Other Window" 'face 'treemacs-help-column-face))
(common-hint (format "%s %s"
(propertize "For common keybinds see" 'face 'treemacs-help-title-face)
(propertize "treemacs-common-helpful-hydra" 'face 'font-lock-function-name-face)))
(key-common-hydra (treemacs--find-keybind #'treemacs-common-helpful-hydra))
(key-create-file (treemacs--find-keybind #'treemacs-create-file))
(key-create-dir (treemacs--find-keybind #'treemacs-create-dir))
(key-rename (treemacs--find-keybind #'treemacs-rename-file))
(key-delete (treemacs--find-keybind #'treemacs-delete-file))
(key-copy-file (treemacs--find-keybind #'treemacs-copy-file))
(key-move-file (treemacs--find-keybind #'treemacs-move-file))
(key-refresh (treemacs--find-keybind #'treemacs-refresh))
(key-set-width (treemacs--find-keybind #'treemacs-set-width))
(key-copy-path-abs (treemacs--find-keybind #'treemacs-copy-absolute-path-at-point))
(key-copy-path-rel (treemacs--find-keybind #'treemacs-copy-relative-path-at-point))
(key-copy-root (treemacs--find-keybind #'treemacs-copy-project-path-at-point))
(key-resort (treemacs--find-keybind #'treemacs-resort))
(key-bookmark (treemacs--find-keybind #'treemacs-add-bookmark))
(key-edit-ws (treemacs--find-keybind #'treemacs-edit-workspaces 12))
(key-create-ws (treemacs--find-keybind #'treemacs-create-workspace 12))
(key-remove-ws (treemacs--find-keybind #'treemacs-remove-workspace 12))
(key-rename-ws (treemacs--find-keybind #'treemacs-rename-workspace 12))
(key-switch-ws (treemacs--find-keybind #'treemacs-switch-workspace 12))
(key-next-ws (treemacs--find-keybind #'treemacs-next-workspace 12))
(key-fallback-ws (treemacs--find-keybind #'treemacs-set-fallback-workspace 12))
(key-peek (treemacs--find-keybind #'treemacs-peek-mode 10))
(key-line-down (treemacs--find-keybind #'treemacs-next-line-other-window 10))
(key-line-up (treemacs--find-keybind #'treemacs-previous-line-other-window 10))
(key-page-down (treemacs--find-keybind #'treemacs-next-page-other-window 10))
(key-page-up (treemacs--find-keybind #'treemacs-previous-page-other-window 10))
(key-bulk-actions (treemacs--find-keybind #'treemacs-bulk-file-actions))
(hydra-str
(format
"
%s
%s (%s)
%s ^^^^^^^^^^^^^ %s ^^^^^^^^ %s ^^^^^^^^^^ %s
%s create file ^^^^ %s Edit Workspaces ^^^^^^^^ %s peek ^^^^^^ %s refresh
%s create dir ^^^^ %s Create Workspace ^^^^^^^^ %s line down ^^^^^^ %s (re)set width
%s rename ^^^^ %s Remove Workspace ^^^^^^^^ %s line up ^^^^^^ %s copy path absolute
%s delete ^^^^ %s Rename Workspace ^^^^^^^^ %s page down ^^^^^^ %s copy path relative
%s copy ^^^^ %s Switch Workspace ^^^^^^^^ %s page up ^^^^^^ %s copy root path
%s move ^^^^ %s Next Workspace ^^^^^^^^ %s re-sort
%s bulk actions ^^^^ %s Set Fallback ^^^^^^^^ %s bookmark
"
title
common-hint (car (s-split":" (car key-common-hydra)))
column-files column-ws column-window column-misc
(car key-create-file) (car key-edit-ws) (car key-peek) (car key-refresh)
(car key-create-dir) (car key-create-ws) (car key-line-down) (car key-set-width)
(car key-rename) (car key-remove-ws) (car key-line-up) (car key-copy-path-abs)
(car key-delete) (car key-rename-ws) (car key-page-down) (car key-copy-path-rel)
(car key-copy-file) (car key-switch-ws) (car key-page-up) (car key-copy-root)
(car key-move-file) (car key-next-ws) (car key-resort)
(car key-bulk-actions) (car key-fallback-ws) (car key-bookmark))))
(eval
`(defhydra treemacs--advanced-helpful-hydra (:exit nil :hint nil :columns 3)
,hydra-str
(,(cdr key-common-hydra) #'treemacs-common-helpful-hydra :exit t)
(,(cdr key-create-file) #'treemacs-create-file)
(,(cdr key-create-dir) #'treemacs-create-dir)
(,(cdr key-rename) #'treemacs-rename-file)
(,(cdr key-delete) #'treemacs-delete-file)
(,(cdr key-copy-file) #'treemacs-copy-file)
(,(cdr key-move-file) #'treemacs-move-file)
(,(cdr key-refresh) #'treemacs-refresh)
(,(cdr key-set-width) #'treemacs-set-width)
(,(cdr key-copy-path-rel) #'treemacs-copy-absolute-path-at-point)
(,(cdr key-copy-path-abs) #'treemacs-copy-relative-path-at-point)
(,(cdr key-copy-root) #'treemacs-copy-project-path-at-point)
(,(cdr key-resort) #'treemacs-resort)
(,(cdr key-bookmark) #'treemacs-add-bookmark)
(,(cdr key-edit-ws) #'treemacs-edit-workspaces)
(,(cdr key-create-ws) #'treemacs-create-workspace)
(,(cdr key-remove-ws) #'treemacs-remove-workspace)
(,(cdr key-rename-ws) #'treemacs-rename-workspace)
(,(cdr key-switch-ws) #'treemacs-switch-workspace)
(,(cdr key-next-ws) #'treemacs-next-workspace)
(,(cdr key-fallback-ws) #'treemacs-set-fallback-workspace)
(,(cdr key-peek) #'treemacs-peek-mode)
(,(cdr key-line-down) #'treemacs-next-line-other-window)
(,(cdr key-line-up) #'treemacs-previous-line-other-window)
(,(cdr key-page-down) #'treemacs-next-page-other-window)
(,(cdr key-page-up) #'treemacs-previous-previous-other-window)
(,(cdr key-bulk-actions) #'treemacs-bulk-file-actions)
("<escape>" nil "Exit"))))
(treemacs--advanced-helpful-hydra/body))
(treemacs-log-failure "The helpful hydra cannot be summoned without an existing treemacs buffer.")))
(provide 'treemacs-hydras)
;;; treemacs-hydras.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-hydras.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 5,078 |
```emacs lisp
;;; treemacs-tab-bar.el --- Tab bar integration for treemacs -*- lexical-binding: t -*-
;; Author: Alexander Miller <alexanderm@web.de>
;; Jason Dufair <jase@dufair.org>
;; Aaron Jensen <aaronjensen@gmail.com>
;; Package-Requires: ((emacs "27.1") (treemacs "0.0") (dash "2.11.0"))
;; Version: 0
;; Homepage: path_to_url
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;;; Integration of tab-bar-mode into treemacs' buffer scoping framework.
;;; Code:
(require 'dash)
(require 'tab-bar)
(require 'treemacs)
(eval-when-compile
(require 'treemacs-macros)
(require 'cl-lib))
(defclass treemacs-tab-bar-scope (treemacs-scope) () :abstract t)
(add-to-list 'treemacs-scope-types (cons 'Tabs 'treemacs-tab-bar-scope))
(cl-defmethod treemacs-scope->current-scope ((_ (subclass treemacs-tab-bar-scope)))
"Get the current tab as scope.
Return symbol `none' unless variable `tab-bar-mode' is non-nil."
(if tab-bar-mode
(cdr (assq 'name (tab-bar-get-buffer-tab nil)))
'none))
(cl-defmethod treemacs-scope->current-scope-name ((_ (subclass treemacs-tab-bar-scope)) tab)
"Return the name of the given TAB.
Will return \"No Tab\" if no tab is active."
(if (eq 'none tab)
"No Tab"
(format "Tab %s" tab)))
(cl-defmethod treemacs-scope->setup ((_ (subclass treemacs-tab-bar-scope)))
"Tabs-scope setup."
(when (fboundp 'tab-bar-tabs-set)
(advice-add #'tab-bar-tabs-set :after #'treemacs-tab-bar--on-tab-switch))
(advice-add #'tab-bar-select-tab :after #'treemacs-tab-bar--on-tab-switch)
(add-to-list 'tab-bar-tab-post-open-functions #'treemacs-tab-bar--on-tab-switch)
(add-to-list 'tab-bar-tab-pre-close-functions #'treemacs-tab-bar--on-tab-close)
(treemacs-tab-bar--ensure-workspace-exists))
(cl-defmethod treemacs-scope->cleanup ((_ (subclass treemacs-tab-bar-scope)))
"Tabs-scope tear-down."
(when (fboundp 'tab-bar-tabs-set)
(advice-remove #'tab-bar-tabs-set #'treemacs-tab-bar--on-tab-switch))
(advice-remove #'tab-bar-select-tab #'treemacs-tab-bar--on-tab-switch)
(setq tab-bar-tab-post-open-functions
(delete #'treemacs-tab-bar--on-tab-switch tab-bar-tab-post-open-functions))
(setq tab-bar-tab-pre-close-functions
(delete #'treemacs-tab-bar--on-tab-close tab-bar-tab-pre-close-functions)))
(defun treemacs-tab-bar--on-tab-close (tab &rest _)
"Cleanup hook to run when a TAB is closed."
(treemacs--on-scope-kill (cdr (assq 'name tab))))
(defun treemacs-tab-bar--on-tab-switch (&rest _)
"Hook running after the tab was switched.
Will select a workspace for the now active tab, creating it if
necessary."
(treemacs-without-following
(treemacs-tab-bar--ensure-workspace-exists)
(treemacs--change-buffer-on-scope-change)))
(defun treemacs-tab-bar--ensure-workspace-exists ()
"Make sure a workspace exists for the given TAB-NAME.
Matching happens by name. If no workspace can be found it will be created."
(let* ((tab-name (treemacs-scope->current-scope-name
(treemacs-current-scope-type) (treemacs-current-scope)))
(workspace (or (treemacs--find-workspace-by-name tab-name)
(treemacs-tab-bar--create-workspace tab-name))))
(setf (treemacs-current-workspace) workspace)
(treemacs--invalidate-buffer-project-cache)
(run-hooks 'treemacs-switch-workspace-hook)
workspace))
(defun treemacs-tab-bar--create-workspace (name)
"Create a new workspace for the given tab NAME.
Projects will be found as per `treemacs--find-user-project-functions'. If that
does not return anything the projects of the fallback workspace will be copied."
(treemacs-block
(let* ((ws-result (treemacs-do-create-workspace name))
(ws-status (car ws-result))
(ws (cadr ws-result))
(root-path (treemacs--find-current-user-project))
(project-list))
(unless (eq ws-status 'success)
(treemacs-log "Failed to create workspace for tab: %s, using fallback instead." ws)
(treemacs-return (car treemacs--workspaces)))
(if root-path
(setf project-list
(list (treemacs-project->create!
:name (treemacs--filename root-path)
:path root-path
:path-status (treemacs--get-path-status root-path))))
(-let [fallback-workspace (car treemacs--workspaces)]
;; copy the projects instead of reusing them so we don't accidentally rename
;; a project in 2 workspaces
(dolist (project (treemacs-workspace->projects fallback-workspace))
(push (treemacs-project->create!
:name (treemacs-project->name project)
:path (treemacs-project->path project)
:path-status (treemacs-project->path-status project))
project-list))))
(setf (treemacs-workspace->projects ws) (nreverse project-list))
(treemacs-return ws))))
(provide 'treemacs-tab-bar)
;;; treemacs-tab-bar.el ends here
``` | /content/code_sandbox/src/extra/treemacs-tab-bar.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,329 |
```emacs lisp
;;; treemacs.el --- A tree style file viewer package -*- lexical-binding: t -*-
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; API required for writing extensions for/with treemacs.
;;; Code:
(require 'dash)
(require 's)
(require 'treemacs-rendering)
(require 'treemacs-core-utils)
(require 'treemacs-fringe-indicator)
(require 'treemacs-mouse-interface)
(eval-when-compile
(require 'treemacs-macros)
(require 'cl-lib))
(treemacs-import-functions-from "treemacs-mode"
treemacs-mode)
(treemacs-import-functions-from "treemacs-rendering"
treemacs--insert-root-separator)
(treemacs-import-functions-from "treemacs-visuals"
treemacs--get-indentation)
(defmacro treemacs--build-extension-addition (name)
"Internal building block.
Creates a `treemacs-define-${NAME}-extension' function and the necessary
helpers."
(let ((define-function-name (intern (s-lex-format "treemacs-define-${name}-extension")))
(top-extension-point (intern (s-lex-format "treemacs--${name}-top-extensions")))
(bottom-extension-point (intern (s-lex-format "treemacs--${name}-bottom-extensions"))))
`(progn
(defvar ,top-extension-point nil)
(defvar ,bottom-extension-point nil)
(cl-defun ,define-function-name (&key extension predicate position)
,(s-lex-format
"Define an extension of type `${name}' for treemacs to use.
EXTENSION is an extension function, as created by
`treemacs-define-expandable-node' when a `:root' argument is given.
PREDICATE is a function that will be called to determine whether the extension
should be displayed. It is invoked with a single argument, which is the treemacs
project struct that is being expanded. All methods that can be invoked on this
type start with the `treemacs-project->' prefix.
POSITION is either `top' or `bottom', indicating whether the extension should be
rendered as the first or last element of a project.
See also `treemacs-remove-${name}-extension'.")
(-let [cell (cons extension predicate)]
(pcase position
('top (add-to-list ',top-extension-point cell))
('bottom (add-to-list ',bottom-extension-point cell))
(other (error "Invalid extension position value `%s'" other)))
t)))))
(defmacro treemacs--build-extension-removal (name)
"Internal building block.
Creates a `treemacs-remove-${NAME}-extension' function and the necessary
helpers."
(let ((remove-function-name (intern (s-lex-format "treemacs-remove-${name}-extension")))
(top-extension-point (intern (s-lex-format "treemacs--${name}-top-extensions")))
(bottom-extension-point (intern (s-lex-format "treemacs--${name}-bottom-extensions"))))
`(progn
(cl-defun ,remove-function-name (extension posistion)
,(s-lex-format
"Remove an EXTENSION of type `${name}' at a given POSITION.
See also `treemacs-define-${name}-extension'.")
(pcase posistion
('top
(setq ,top-extension-point
(--reject (equal extension (car it)) ,top-extension-point)))
('bottom
(setq ,bottom-extension-point
(--reject (equal extension (car it)) ,bottom-extension-point)))
(other
(error "Invalid extension position value `%s'" other)))
t))))
(defmacro treemacs--build-extension-application (name)
"Internal building block.
Creates treemacs--apply-${NAME}-top/bottom-extensions functions."
(let ((apply-top-name (intern (s-lex-format "treemacs--apply-${name}-top-extensions")))
(apply-bottom-name (intern (s-lex-format "treemacs--apply-${name}-bottom-extensions")))
(top-extension-point (intern (s-lex-format "treemacs--${name}-top-extensions")))
(bottom-extension-point (intern (s-lex-format "treemacs--${name}-bottom-extensions"))))
`(progn
(defsubst ,apply-top-name (node data)
,(s-lex-format
"Apply the top extensions for NODE of type `${name}'
Also pass additional DATA to predicate function.")
(dolist (cell ,top-extension-point)
(let ((extension (car cell))
(predicate (cdr cell)))
(when (or (null predicate) (funcall predicate data))
(funcall extension node)))))
(defsubst ,apply-bottom-name (node data)
,(s-lex-format
"Apply the bottom extensions for NODE of type `${name}'
Also pass additional DATA to predicate function.")
(dolist (cell ,bottom-extension-point)
(let ((extension (car cell))
(predicate (cdr cell)))
(when (or (null predicate) (funcall predicate data))
(funcall extension node))))))))
(treemacs--build-extension-addition "project")
(treemacs--build-extension-removal "project")
(treemacs--build-extension-application "project")
(treemacs--build-extension-addition "directory")
(treemacs--build-extension-removal "directory")
(treemacs--build-extension-application "directory")
(treemacs--build-extension-addition "top-level")
(treemacs--build-extension-removal "top-level")
(define-obsolete-function-alias 'treemacs-define-root-extension #'treemacs-define-top-level-extension "v2.4")
(define-obsolete-function-alias 'treemacs-remove-root-extension #'treemacs-remove-top-level-extension "v2.4")
;; slighty non-standard application for root extensions
(cl-macrolet
((define-root-extension-application (name variable doc)
`(defun ,name (workspace &optional has-previous)
,doc
(let ((is-first (not has-previous)))
(--each ,variable
(let ((extension (car it))
(predicate (cdr it)))
(when (or (null predicate) (funcall predicate workspace))
(unless is-first
(treemacs--insert-root-separator))
(setq is-first (funcall extension)))))
(not is-first)))))
(define-root-extension-application
treemacs--apply-root-top-extensions
treemacs--top-level-top-extensions
"Apply the top extensions for NODE of type `root' for the current WORKSPACE.
Returns t if extensions were inserted.")
(define-root-extension-application
treemacs--apply-root-bottom-extensions
treemacs--top-level-bottom-extensions
"Apply the bottom extensions for NODE of type `root' for the current WORKSPACE.
Returns t if extensions were inserted."))
(defsubst treemacs-as-icon (string &rest more-properties)
"Turn STRING into an icon for treemacs.
Optionally include MORE-PROPERTIES (like `face' or `display')."
(declare (indent 1))
(apply #'propertize string 'icon t more-properties))
(cl-defmacro treemacs-render-node
(&key icon
label-form
state
face
key-form
more-properties)
"Macro that produces the strings required to render a single treemacs node.
Meant to be used as a `:render-action' for `treemacs-define-expandable-node'.
ICON is a simple string serving as the node's icon, and must be created with
`treemacs-as-icon'. If the icon is for a file you can also use
`treemacs-icon-for-file'.
LABEL-FORM must return the string that will serve as the node's label text,
based on the element that should be rendered being bound as `item'. So for
example if rendering a list of buffers RENDER-FORM would look like
`(buffer-name item)'.
STATE is the symbol that will identify the type of the node.
FACE is its face.
KEY-FORM is the form that will give the node a unique key, necessary for
the node's (and the full custom tree's) ability to stay expanded and visible
when the project is refreshed, but also for compatibility and integration with
`follow-mode' and `filewatch-mode.'
MORE-PROPERTIES is a plist of text properties that can arbitrarily added to the
node for quick retrieval later."
(treemacs-static-assert (and icon label-form state key-form)
"All values except :more-properties and :face are mandatory")
`(let* ((path (append (treemacs-button-get node :path) (list ,key-form)))
(dom-node (treemacs-dom-node->create! :key path :parent parent-dom-node)))
(treemacs-dom-node->insert-into-dom! dom-node)
(when parent-dom-node
(treemacs-dom-node->add-child! parent-dom-node dom-node))
(list (unless (zerop depth) prefix)
,icon
(propertize ,label-form
'button '(t)
'category 'treemacs-button
,@(when face `((quote face) ,face))
:custom t
:state ,state
:parent node
:depth depth
:path path
:key ,key-form
,@more-properties)
(when (zerop depth) (if treemacs-space-between-root-nodes "\n\n" "\n")))))
(cl-defmacro treemacs-define-leaf-node (name icon &key ret-action tab-action mouse1-action visit-action)
"Define a type of node that is a leaf and cannot be further expanded.
Based on the given NAME this macro will define a `treemacs-${name}-state' state
variable and a `treemacs-${name}-icon' icon variable. If the icon should not be
static, and should be instead computed every time this node is rendered in its
parent's :render-action use \\='dynamic-icon as a value for ICON.
The ICON is a string that should be created with `treemacs-as-icon'. If the
icon is for a file you can also use `treemacs-icon-for-file'.
RET-ACTION, TAB-ACTION and MOUSE1-ACTION are function references that will be
invoked when RET or TAB are pressed or mouse1 is double-clicked a node of this
type. VISIT-ACTION is used in `treemacs-visit-node-no-split' actions."
(declare (indent 1))
(let ((state-name (intern (format "treemacs-%s-state" name)))
(icon-name (intern (format "treemacs-%s-icon" name))))
`(progn
(defvar ,state-name ',state-name)
,(unless (equal icon (quote 'dynamic-icon))
`(defvar ,icon-name ,icon))
,(when (or ret-action visit-action)
`(treemacs-define-RET-action ,state-name ,(or ret-action '(quote treemacs-visit-node-default))))
,(when tab-action
`(treemacs-define-TAB-action ,state-name ,tab-action))
,(when mouse1-action
`(treemacs-define-doubleclick-action ,state-name ,mouse1-action))
,(when visit-action
`(put ',state-name :treemacs-visit-action ,visit-action))
t)))
(cl-defmacro treemacs-define-expandable-node
(name &key
icon-open
icon-closed
icon-open-form
icon-closed-form
render-action
query-function
ret-action
visit-action
after-expand
after-collapse
root-marker
root-label
root-face
root-key-form
top-level-marker)
"Define a type of node with given NAME that can be further expanded.
ICON-OPEN and ICON-CLOSED are strings and must be created by `treemacs-as-icon'.
They will be defvar'd as \\='treemacs-icon-${name}-open/closed'. As an
alternative to static icons you can also supply ICON-OPEN-FORM and
ICON-CLOSED-FORM that will be dynamically executed whenever a new icon is
needed. Keep in mind that, since child nodes are first rendered by their
parents, an ICON-CLOSED-FORM will need to be repeated in the parent's
RENDER-ACTION.
QUERY-FUNCTION is a form and will be invoked when the node is expanded. It must
provide the list of elements that will be rendered with RENDER-ACTION.
RENDER-ACTION is another form that will render the single items provided by
QUERY-FUNCTION. For every RENDER-FORM invocation the element to be rendered is
bound under the name `item'. The form itself should end in a call to
`treemacs-render-node'.
RET-ACTION will define what function is called when RET is pressed on this type
of node. Only RET, without TAB and mouse1 can be defined since for expandable
nodes both TAB and RET should toggle expansion/collapse. VISIT-ACTION is used
in `treemacs-visit-node-no-split' actions.
AFTER-EXPAND and AFTER-COLLAPSE are optional forms that will be called after a
node has been expanded or collapsed. The closed or opened node marker will be
visible under the name `node' in their scope.
ROOT-MARKER is a simple boolean. It indicates the special case that the node
being defined is a top level entry point. When this value is non-nil this macro
will create an additional function in the form `treemacs-${NAME}-extension'
that can be passed to `treemacs-define-project-extension'. It also means that
the following pieces of additional information are required to render this node:
ROOT-LABEL is the displayed label of the root node.
ROOT-FACE is its face.
ROOT-KEY-FORM is the form that will give the root node its unique key, the same
way as the KEY-FORM argument in `treemacs-render-node'.
TOP-LEVEL-MARKER works much the same way as ROOT-MARKER (and is mutually
exclusive with it). The difference is that it declares the node defined here to
a top level element with nothing above it, like a project, instead of a top
level node *inside* a project. Other than that things work the same. Setting
TOP-LEVEL-MARKER will define a function named `treemacs-${NAME}-extension' that
can be passed to `treemacs-define-root-extension', and it requires the same
additional keys."
(declare (indent 1))
;; TODO(2019/01/29): simplify
(treemacs-static-assert
(or (when top-level-marker (not root-marker))
(when root-marker (not top-level-marker))
(and (not root-marker) (not top-level-marker)))
"Root and top-level markers cannot both be set.")
(treemacs-static-assert (and (or icon-open-form icon-open)
(or icon-closed-form icon-closed)
query-function render-action)
"All values (except additional root information) are mandatory")
(treemacs-static-assert (or (null icon-open) (null icon-open-form))
":icon-open and :icon-open-form are mutually exclusive.")
(treemacs-static-assert (or (null icon-closed) (null icon-closed-form))
":icon-closed and :icon-closed-form are mutually exclusive.")
(let ((variadic? (equal top-level-marker (quote 'variadic)))
(open-icon-name (intern (format "treemacs-icon-%s-open" (symbol-name name))))
(closed-icon-name (intern (format "treemacs-icon-%s-closed" (symbol-name name))))
(open-state-name (intern (format "treemacs-%s-open-state" (symbol-name name))))
(closed-state-name (intern (format "treemacs-%s-closed-state" (symbol-name name))))
(expand-name (intern (format "treemacs-expand-%s" (symbol-name name))))
(collapse-name (intern (format "treemacs-collapse-%s" (symbol-name name))))
(do-expand-name (intern (format "treemacs--do-expand-%s" (symbol-name name))))
(do-collapse-name (intern (format "treemacs--do-collapse-%s" (symbol-name name)))))
`(progn
,(when open-icon-name
`(defvar ,open-icon-name ,icon-open))
,(when closed-icon-name
`(defvar ,closed-icon-name ,icon-closed))
(defvar ,open-state-name ',open-state-name)
(defvar ,closed-state-name ',closed-state-name)
(add-to-list 'treemacs--open-node-states ,open-state-name)
(add-to-list 'treemacs--closed-node-states ,closed-state-name)
(add-to-list 'treemacs-valid-button-states ,closed-state-name)
(add-to-list 'treemacs-valid-button-states ,open-state-name)
,(when (or ret-action visit-action)
`(progn
(treemacs-define-RET-action ,open-state-name ,(or ret-action '(quote treemacs-visit-node-default)))
(treemacs-define-RET-action ,closed-state-name ,(or ret-action '(quote treemacs-visit-node-default)))))
,@(when visit-action
`((put ',open-state-name :treemacs-visit-action ,visit-action)
(put ',closed-state-name :treemacs-visit-action ,visit-action)))
(defun ,expand-name (&optional _)
,(format "Expand treemacs nodes of type `%s'." name)
(interactive)
(treemacs-block
(-let [node (treemacs-node-at-point)]
(when (null node)
(treemacs-return
(treemacs-pulse-on-failure "There is nothing to do here.")))
(when (not (eq ',closed-state-name (treemacs-button-get node :state)))
(treemacs-return
(treemacs-pulse-on-failure "This function cannot expand a node of type '%s'."
(propertize (format "%s" (treemacs-button-get node :state)) 'face 'font-lock-type-face))))
(,do-expand-name node))))
(defun ,do-expand-name (node)
,(format "Execute expansion of treemacs nodes of type `%s'." name)
(let ((items ,query-function)
(depth (1+ (treemacs-button-get node :depth)))
;; must be implicitly in scope for calls to `treemacs-render-node'
(parent-dom-node (treemacs-find-in-dom (treemacs-button-get node :path))))
(treemacs--button-open
:button node
:new-state ',open-state-name
:new-icon ,(unless variadic? (if icon-open open-icon-name icon-open-form))
:immediate-insert t
:open-action
(treemacs--create-buttons
:nodes items
:depth depth
:node-name item
:node-action ,render-action)
:post-open-action
(progn
(treemacs-on-expand (treemacs-button-get node :path) node)
(treemacs--reentry (treemacs-button-get node :path))
,after-expand))))
(defun ,collapse-name (&optional _)
,(format "Collapse treemacs nodes of type `%s'." name)
(interactive)
(treemacs-block
(-let [node (treemacs-node-at-point)]
(when (null node)
(treemacs-return
(treemacs-pulse-on-failure "There is nothing to do here.")))
(when (not (eq ',open-state-name (treemacs-button-get node :state)))
(treemacs-return
(treemacs-pulse-on-failure "This function cannot collapse a node of type '%s'."
(propertize (format "%s" (treemacs-button-get node :state)) 'face 'font-lock-type-face))))
(,do-collapse-name node))))
(defun ,do-collapse-name (node)
,(format "Collapse treemacs nodes of type `%s'." name)
(treemacs--button-close
:button node
:new-state ',closed-state-name
:new-icon ,(unless variadic? (if icon-closed closed-icon-name icon-closed-form))
:post-close-action
(progn
(treemacs-on-collapse (treemacs-button-get node :path))
,after-collapse)))
(treemacs-define-TAB-action ',open-state-name #',collapse-name)
(treemacs-define-TAB-action ',closed-state-name #',expand-name)
,(when root-marker
(treemacs-static-assert (and root-label root-face root-key-form)
":root-label, :root-face and :root-key-form must be provided when `:root-marker' is non-nil")
`(cl-defun ,(intern (format "treemacs-%s-extension" (upcase (symbol-name name)))) (parent)
(let* ((depth (1+ (treemacs-button-get parent :depth)))
(path (list (or (treemacs-button-get parent :project)
(treemacs-button-get parent :key))
,root-key-form))
(parent-dom-node (treemacs-find-in-dom (treemacs-button-get parent :path)))
(new-dom-node (treemacs-dom-node->create! :key path :parent parent-dom-node)))
(treemacs-dom-node->insert-into-dom! new-dom-node)
(when parent-dom-node
(treemacs-dom-node->add-child! parent-dom-node new-dom-node))
(insert
"\n"
(treemacs--get-indentation depth)
,(if icon-closed closed-icon-name icon-closed-form)
(propertize ,root-label
'button '(t)
'category 'treemacs-button
'face ,root-face
:custom t
:key ,root-key-form
:path path
:depth depth
:no-git t
:parent parent
:state ,closed-state-name)))
nil))
,(when top-level-marker
(treemacs-static-assert (and root-label root-face root-key-form)
":root-label :root-face :root-key-form must be provided when `:top-level-marker' is non-nil")
(let ((ext-name (intern (format "treemacs-%s-extension" (upcase (symbol-name name))))))
(put ext-name :defined-in (or load-file-name (buffer-name)))
`(progn
,(if variadic?
;; When the extension is variadic it will be managed by a hidden top-level
;; node. Its depth is -1 and it is not visible, but can still be used to update
;; the entire extension without explicitly worrying about complex dom changes.
`(defun ,ext-name ()
(treemacs-with-writable-buffer
(save-excursion
(let* ((pr (treemacs-project->create!
:name ,root-label
:path ,root-key-form
:path-status 'extension))
(button-start (point-marker))
(dom-node (treemacs-dom-node->create!
:key ,root-key-form
:position button-start)))
(treemacs-dom-node->insert-into-dom! dom-node)
(insert (propertize "Hidden Node\n"
'button '(t)
'category 'treemacs-button
'invisible t
'skip t
:custom t
:key ,root-key-form
:path (list :custom ,root-key-form)
:depth -1
:project pr
:state ,closed-state-name))
(let ((marker (copy-marker (point) t)))
(funcall ',do-expand-name button-start)
(goto-char marker)))))
t)
`(progn
(defun ,ext-name (&rest _)
(treemacs-with-writable-buffer
(-let [pr (treemacs-project->create!
:name ,root-label
:path ,root-key-form
:path-status 'extension)]
(insert ,(if icon-closed closed-icon-name icon-closed-form))
(insert (propertize ,root-label
'button '(t)
'category 'treemacs-button
'face ,root-face
:custom t
:key ,root-key-form
:path (list :custom ,root-key-form)
:depth 0
:project pr
:state ,closed-state-name))))
nil)))))))))
(cl-defmacro treemacs-define-variadic-node
(name &key
query-function
render-action
root-key-form)
"Define a variadic top level node with given NAME.
The term \"variadic\" means that the node will produce an unknown amount of
child nodes when expanded. For example think of an extension that groups buffers
based on the major mode, with each major-mode being its own top-level group, so
it is not known which (if any) major-mode groupings exist.
Works the same as `treemacs-define-expandable-node', so the same restrictions
and rules apply for QUERY-FUNCTION, RENDER-ACTION and ROOT-KEY-FORM."
(declare (indent 1))
`(treemacs-define-expandable-node ,name
:icon-closed ""
:icon-open ""
:root-label ""
:root-face ""
:top-level-marker 'variadic
:query-function ,query-function
:render-action ,render-action
:root-key-form ,root-key-form))
(defun treemacs-initialize ()
"Initialise treemacs in an external buffer for extension use."
(treemacs--disable-fringe-indicator)
(treemacs-with-writable-buffer
(erase-buffer))
;; make sure the fringe indicator is enabled later, otherwise treemacs attempts
;; to move it right after the `treemacs-mode' call
;; the indicator cannot be created before either since the major-mode activation
;; wipes out buffer-local variables' values
(let ((treemacs-fringe-indicator-mode nil)
(treemacs--in-this-buffer t))
(treemacs-mode))
(setq-local treemacs--in-this-buffer :extension))
(treemacs-log "The treemacs-extensions module is obsolete, treemacs-treelib should be used instead.")
(provide 'treemacs-extensions)
;;; treemacs-extensions.el ends here
``` | /content/code_sandbox/src/elisp/treemacs-extensions.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 5,782 |
```emacs lisp
;;; treemacs-mu4e.el --- mu4e integration for treemacs -*- lexical-binding: t -*-
;; Author: Alexander Miller <alexanderm@web.de>
;; Package-Requires: ((emacs "26.1") (treemacs "0.0") (pfuture "1.7") (dash "2.11.0") (s "1.10.0") (ht "2.2"))
;; Homepage: path_to_url
;; Version: 0
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;; This package creates a thunderbird-inspired sidebar for mu4e using
;; treemacs' treelib api.
;;
;; Some of mu's directories are not part of a maildir hierarchy, but stand at the
;; top alone. Like in thunderbird, they are grouped in a fake "Local Folders" tree.
;; Since the top of this does not really exist it is sometimes necessary to make
;; the mapping towards the "true" maildir' folder, e.g. when displaying the maildir
;; in mu4e and getting the message counts from python.
;;; Code:
(require 'mu4e)
(require 'pfuture)
(require 'treemacs)
(require 'treemacs-treelib)
(require 's)
(require 'ht)
(require 'dash)
(eval-when-compile
(require 'cl-lib)
(require 'inline))
(eval-when-compile
(cl-declaim (optimize (speed 3) (safety 0))))
;;;;; Customization
(defgroup treemacs-mu4e nil
"Treemacs+mu4e configuration options."
:group 'treemacs-mu4e
:prefix "treemacs-mu4e-")
(defface treemacs-mu4e-mailcount-face
'((t :inherit font-lock-comment-face))
"Face for message count annotations."
:group 'treemacs-mu4e)
(defcustom treemacs-mu4e-local-folders "Local Folders"
"Name for group of local folders."
:group 'treemacs-mu4e
:type 'string)
;;;;; Globals
(defconst treemacs-mu4e--buffer-name " *Treemacs Mu4e*")
(defconst treemacs-mu4e--count-script
(expand-file-name "src/scripts/treemacs-count-mail.py" treemacs-dir))
(defconst treemacs-mu4e--maildir-map
(make-hash-table :size 200 :test 'equal)
"Maps mu's maildir names to maildir objects.")
(defconst treemacs-mu4e--label-map
(make-hash-table :size 200 :test 'equal)
"Maps maildir names to their display labels.")
(defconst treemacs-mu4e--weight-map (make-hash-table :size 200 :test 'equal)
"Maps maildir names to their weights.")
(defvar treemacs-mu4e--mailcount-update-timer nil
"Timer for debounced the maildir updates.")
(cl-defstruct (treemacs-maildir
(:conc-name treemacs-maildir->)
(:constructor treemacs-maildir->create!))
(mu-dir nil :read-only t)
label
weight
children
parent)
;;;;; Maildir collection & setup
(define-inline treemacs-maildir->true-folder (self)
"Get the maildir of SELF, but without the workaround for local folders.
Will replace the folder string's `treemacs-mu4e-local-folders' prefix with just
\"/\" again."
(declare (side-effect-free t))
(inline-letevals (self)
(inline-quote
(s-replace (concat "/" treemacs-mu4e-local-folders)
""
(treemacs-maildir->mu-dir ,self)))))
(define-inline treemacs-mu4e--get-default-label (maildir)
"Use the string after the last slash as MAILDIR's default label."
(declare (pure t) (side-effect-free t))
(inline-letevals (maildir)
(inline-quote
(-last-item (-reject #'s-blank? (s-split "/" ,maildir))))))
(define-inline treemacs-mu4e--maildir-sort-function (m1 m2)
"Sort M1 and M2 based on their weight values."
(declare (side-effect-free t))
(inline-letevals (m1 m2)
(inline-quote
(< (treemacs-maildir->weight ,m1)
(treemacs-maildir->weight ,m2)))))
(defun treemacs-mu4e--collect-maildirs ()
"Collect all maildirs when this module is first loaded.
Maildir strings will be mapped to maildir objects in
`treemacs-mu4e--maildir-map'.
Local folders (without subdirs) will be collected under the
`treemacs-mu4e-local-folders' prefix.
Label and weight metadata will be sourced from possibly pre-filled
`treemacs-mu4e--label-map' and `treemacs-mu4e--weight-map'."
(ht-clear! treemacs-mu4e--maildir-map)
(let ((mu-maildirs (mu4e-get-maildirs)))
(dolist (mu-maildir mu-maildirs)
(let* ((is-leaf? (not (s-ends-with? "/" mu-maildir)))
(strs (cdr (s-split "/" mu-maildir)))
(strs (if (length= strs 1)
(list treemacs-mu4e-local-folders (car strs))
strs))
(max (length strs))
(steps))
(dolist (n (number-sequence 1 max))
(push (format (if (and is-leaf? (= n max))
"/%s"
"/%s/")
(s-join "/" (-take n strs)))
steps))
(let ((previous))
(dolist (step (nreverse steps))
(let* ((default-label (treemacs-mu4e--get-default-label step))
(maildir
(or (ht-get treemacs-mu4e--maildir-map step)
(-let ((new-maildir
(treemacs-maildir->create!
:mu-dir step
:parent previous
:label (ht-get treemacs-mu4e--label-map step default-label)
:weight (ht-get treemacs-mu4e--weight-map step 1000))))
(ht-set! treemacs-mu4e--maildir-map step new-maildir)
new-maildir))))
(when previous
(cl-pushnew maildir (treemacs-maildir->children previous)))
(setf previous maildir))))))))
;;;;; Treelib setup
(defun treemacs-mu4e--top-level-maildirs-datasource ()
"Data source for the very first level of maildirs."
(->> (ht-values treemacs-mu4e--maildir-map)
(--filter (null (treemacs-maildir->parent it)))
(-sort #'treemacs-mu4e--maildir-sort-function)))
(defun treemacs-mu4e--child-maidirs-datasource (btn)
"Data source for maildirs whose direct parent is BTN."
(-let [parent-dir (treemacs-maildir->mu-dir (treemacs-button-get btn :maildir))]
(->> (ht-get treemacs-mu4e--maildir-map parent-dir)
(treemacs-maildir->children)
(-sort #'treemacs-mu4e--maildir-sort-function))))
(defun treemacs-mu4e--visit-maildir (&optional _arg)
"Open the maildir at point in mu4e."
(-> (treemacs-current-button)
(treemacs-button-get :maildir)
(treemacs-maildir->true-folder)
(mu4e~headers-jump-to-maildir))
(select-window
(--first (eq 'mu4e-headers-mode
(buffer-local-value 'major-mode (window-buffer it)))
(window-list))))
(treemacs-define-variadic-entry-node-type mu4e-top-maildirs
:key 'treemacs-mu4e
:children (treemacs-mu4e--top-level-maildirs-datasource)
:child-type 'mu4e-maildir)
(treemacs-define-expandable-node-type mu4e-maildir
:open-icon
(cond
((null (treemacs-maildir->parent item))
(treemacs-get-icon-value 'inbox))
((treemacs-maildir->children item)
(treemacs-get-icon-value 'mail-plus))
(t
(treemacs-get-icon-value 'mail)))
:closed-icon
(cond
((null (treemacs-maildir->parent item))
(treemacs-get-icon-value 'mail-inbox))
((treemacs-maildir->children item)
(treemacs-get-icon-value 'mail-plus))
(t
(treemacs-get-icon-value 'mail)))
:ret-action #'treemacs-mu4e--visit-maildir
:label
(if (treemacs-maildir->parent item)
(propertize (treemacs-maildir->label item)
'face 'treemacs-directory-face)
(propertize (treemacs-maildir->label item)
'face 'treemacs-root-face))
:key (treemacs-maildir->mu-dir item)
:children (treemacs-mu4e--child-maidirs-datasource btn)
:more-properties
`(:maildir ,item
:default-face
,(if (treemacs-maildir->parent item)
'treemacs-directory-face
'treemacs-root-face)
,@(unless (treemacs-maildir->children item)
'(:leaf t)))
:child-type 'mu4e-maildir)
;;;;; Configuration setup
(defun treemacs-mu4e-define-aliases (&rest pairs)
"Define a set of display name PAIRS.
The first item is the actual name of the maildir, the second item is how it
should be displayed.
\(fn [MAILDIR DISPLAY-LABEL]...)"
(treemacs-static-assert (= 0 (% (length pairs) 2))
"Uneven number of name items.")
(while pairs
(let* ((name (pop pairs))
(label (pop pairs)))
(ht-set! treemacs-mu4e--label-map name label)
(--when-let (ht-get treemacs-mu4e--maildir-map name)
(setf (treemacs-maildir->label it) label)))))
(defun treemacs-mu4e-define-weights (&rest pairs)
"Define set of display weight PAIRS.
The first item is the actual name of the maildir, the second item is its sorting
weight in the view. Higher values are sorted later. The default weight is 100.
\(fn [MAILDIR WEIGHT]...)"
(treemacs-static-assert (= 0 (% (length pairs) 2))
"Uneven number of name items.")
(while pairs
(let* ((name (pop pairs))
(weight (pop pairs)))
(ht-set! treemacs-mu4e--weight-map name weight)
(--when-let (ht-get treemacs-mu4e--maildir-map name)
(setf (treemacs-maildir->weight it) weight)))))
;;;;; Interactive commands
(defun treemacs-mu4e-print-all-maildirs ()
"Provides an overview of all maildirs and their configuration.
This might be useful when filling up setting up `treemacs-mu4e-define-aliases'
and `treemacs-mu4e-define-weights'."
(interactive)
(pop-to-buffer (get-buffer-create "Treemacs Mu4e Maildirs"))
(erase-buffer)
(org-mode)
(setq-local org-hide-emphasis-markers nil)
(let ((roots (--filter
(null (treemacs-maildir->parent it))
(ht-values treemacs-mu4e--maildir-map))))
(dolist (root roots)
(treemacs-mu4e--print-maildir root 1)))
(goto-char 0))
(defun treemacs-mu4e--print-maildir (maildir d)
"Print MAILDIR at depth D as an org sub-tree."
(insert (format
"%s %s\n- label :: %s\n- weight :: %s\n"
(make-string d ?*)
(treemacs-maildir->mu-dir maildir)
(treemacs-maildir->label maildir)
(treemacs-maildir->weight maildir) ))
(dolist (child (-sort #'treemacs-mu4e--maildir-sort-function
(treemacs-maildir->children maildir)))
(treemacs-mu4e--print-maildir child (1+ d))))
;;;###autoload
(defun treemacs-mu4e ()
"Select or display the Mu4e side-bar."
(interactive)
(--if-let (get-buffer-window treemacs-mu4e--buffer-name)
(select-window it)
(-let [start-fn
(lambda ()
(when (ht-empty? treemacs-mu4e--maildir-map)
(treemacs-mu4e--collect-maildirs))
(treemacs-mu4e--display))]
(if (ignore-errors (mu4e-root-maildir))
(funcall start-fn)
(mu4e--init-handlers)
(mu4e--start start-fn)))))
(defun treemacs-mu4e--display ()
"Display the mu4e buffer in a side-window."
(--when-let (get-buffer treemacs-mu4e--buffer-name) (kill-buffer it))
(let* ((buf (get-buffer-create treemacs-mu4e--buffer-name))
(window (display-buffer-in-side-window buf `((side . ,treemacs-position) (slot . 1)))))
(select-window window)
(treemacs-initialize mu4e-top-maildirs
:with-expand-depth 1
:and-do (setq-local treemacs-space-between-root-nodes t))
(treemacs-mu4e--update-mailcounts)
(treemacs--evade-image)))
;;;;; Async Mailcount
(defun treemacs-mu4e--update-mailcounts (&rest _)
"Shell out to mu to update the message counts and redraw them."
(treemacs-debounce treemacs-mu4e--mailcount-update-timer 3
(-let [maildirs (-map #'treemacs-maildir->mu-dir
(ht-values treemacs-mu4e--maildir-map))]
(pfuture-callback `("python"
"-O" "-S"
,treemacs-mu4e--count-script
,treemacs-mu4e-local-folders
,@maildirs)
:on-error
(treemacs-log-failure "Mail count update error: %s" (pfuture-callback-output))
:on-success
(-let [source "treemacs-mu4e-mailcount"]
(treemacs-clear-annotation-suffixes source)
(pcase-dolist (`(,path ,suffix) (read (pfuture-callback-output)))
(put-text-property 0 (length suffix) 'face 'treemacs-mu4e-mailcount-face suffix)
(treemacs-set-annotation-suffix
path suffix source)
(-let [buffer (get-buffer treemacs-mu4e--buffer-name)]
(when (buffer-live-p buffer)
(treemacs-apply-annotations-in-buffer buffer)))))))))
(add-hook 'mu4e-index-updated-hook #'treemacs-mu4e--update-mailcounts)
(add-hook 'mu4e-message-changed-hook #'treemacs-mu4e--update-mailcounts)
(with-no-warnings
(with-eval-after-load 'winum
(add-to-list 'winum-ignored-buffers treemacs-mu4e--buffer-name)))
(provide 'treemacs-mu4e)
;;; treemacs-mu4e.el ends here
``` | /content/code_sandbox/src/extra/treemacs-mu4e.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 3,577 |
```emacs lisp
;;; treemacs-persp.el --- Persp-mode integration for treemacs -*- lexical-binding: t -*-
;; Author: Alexander Miller <alexanderm@web.de>
;; Package-Requires: ((emacs "26.1") (treemacs "0.0") (persp-mode "2.9.7") (dash "2.11.0"))
;; Version: 0
;; Homepage: path_to_url
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;;; Integration of persp-mode into treemacs' buffer scoping framework.
;;; Code:
(require 'treemacs)
(require 'persp-mode)
(require 'eieio)
(require 'dash)
(eval-when-compile
(require 'treemacs-macros)
(require 'cl-lib))
;; remove base compatibility hook
(remove-hook 'persp-activated-functions #'treemacs--remove-treemacs-window-in-new-frames)
(defclass treemacs-persp-scope (treemacs-scope) () :abstract t)
(add-to-list 'treemacs-scope-types (cons 'Perspectives 'treemacs-persp-scope))
(cl-defmethod treemacs-scope->current-scope ((_ (subclass treemacs-persp-scope)))
"Get the current perspective as scope.
Returns the symbol `none' if no perspective is active."
(or (get-current-persp) 'none))
(cl-defmethod treemacs-scope->current-scope-name ((_ (subclass treemacs-persp-scope)) persp)
"Return the name of the given perspective PERSP.
Will return \"No Perspective\" if no perspective is active."
(if (eq 'none persp)
"No Perspective"
(format "Perspective %s" (persp-name persp))))
(cl-defmethod treemacs-scope->setup ((_ (subclass treemacs-persp-scope)))
"Persp-scope setup."
(add-hook 'persp-activated-functions #'treemacs-persp--on-perspective-switch)
(add-hook 'persp-renamed-functions #'treemacs-persp--on-perspective-rename)
(add-hook 'persp-before-kill-functions #'treemacs--on-scope-kill)
(treemacs-persp--ensure-workspace-exists))
(cl-defmethod treemacs-scope->cleanup ((_ (subclass treemacs-persp-scope)))
"Persp-scope tear-down."
(remove-hook 'persp-activated-functions #'treemacs-persp--on-perspective-switch)
(remove-hook 'persp-renamed-functions #'treemacs-persp--on-perspective-rename)
(remove-hook 'persp-before-kill-functions #'treemacs--on-scope-kill))
(defun treemacs-persp--on-perspective-rename (_perspective old-name new-name)
"Hook running after perspective was renamed.
Will rename treemacs perspective workspace OLD-NAME to use NEW-NAME."
(treemacs-do-rename-workspace
(treemacs--find-workspace-by-name (treemacs-persp--format-workspace-name old-name))
(treemacs-persp--format-workspace-name new-name)))
(defun treemacs-persp--on-perspective-switch (&rest _)
"Hook running after the perspective was switched.
Will select a workspace for the now active perspective, creating it if
necessary."
;; running with a timer ensures that any other post-processing is finished after a perspective
;; was run since commands like `spacemacs/helm-persp-switch-project' first create a perspective
;; and only afterwards select the file to display
(run-with-timer
0.1 nil
(lambda ()
(treemacs-without-following
(treemacs-persp--ensure-workspace-exists)
(treemacs--change-buffer-on-scope-change)))))
(defun treemacs-persp--ensure-workspace-exists ()
"Make sure a workspace exists for the given PERSP-NAME.
Matching happens by name. If no workspace can be found it will be created."
(let* ((persp-name (treemacs-scope->current-scope-name
(treemacs-current-scope-type) (treemacs-current-scope)))
(workspace (or (treemacs--find-workspace-by-name persp-name)
(treemacs-persp--create-workspace persp-name))))
(setf (treemacs-current-workspace) workspace)
(treemacs--invalidate-buffer-project-cache)
(run-hooks 'treemacs-switch-workspace-hook)
workspace))
(defun treemacs-persp--create-workspace (name)
"Create a new workspace for the given persp NAME.
Projects will be found as per `treemacs--find-user-project-functions'. If that
does not return anything the projects of the fallback workspace will be copied."
(treemacs-block
(let* ((ws-result (treemacs-do-create-workspace name))
(ws-status (car ws-result))
(ws (cadr ws-result))
(root-path (treemacs--find-current-user-project))
(project-list))
(unless (eq ws-status 'success)
(treemacs-log "Failed to create workspace for perspective: %s, using fallback instead." ws)
(treemacs-return (car treemacs--workspaces)))
(if root-path
(setf project-list
(list (treemacs-project->create!
:name (treemacs--filename root-path)
:path root-path
:path-status (treemacs--get-path-status root-path))))
(-let [fallback-workspace (car treemacs--workspaces)]
;; copy the projects instead of reusing them so we don't accidentally rename
;; a project in 2 workspaces
(dolist (project (treemacs-workspace->projects fallback-workspace))
(push (treemacs-project->create!
:name (treemacs-project->name project)
:path (treemacs-project->path project)
:path-status (treemacs-project->path-status project))
project-list))))
(setf (treemacs-workspace->projects ws) (nreverse project-list))
(treemacs-return ws))))
(defun treemacs-persp--format-workspace-name (perspective-name)
"Format of the workspace name used for a perspective named PERSPECTIVE-NAME."
(format "Perspective %s" perspective-name))
(provide 'treemacs-persp)
;;; treemacs-persp.el ends here
``` | /content/code_sandbox/src/extra/treemacs-persp.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,456 |
```emacs lisp
;;; treemacs-evil.el --- Evil mode integration for treemacs -*- lexical-binding: t -*-
;; Author: Alexander Miller <alexanderm@web.de>
;; Package-Requires: ((emacs "26.1") (evil "1.2.12") (treemacs "0.0"))
;; Version: 0
;; Homepage: path_to_url
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;;; Evil mode compatibility.
;;; Code:
(require 'evil)
(require 'treemacs)
(treemacs-import-functions-from "treemacs-hydras"
treemacs-common-helpful-hydra
treemacs-advanced-helpful-hydra)
(treemacs-import-functions-from "treemacs-mouse-interface"
treemacs-dragleftclick-action
treemacs-leftclick-action)
(treemacs-import-functions-from "treemacs-mouse-interface"
treemacs-copy-file)
(declare-function treemacs-add-bookmark "treemacs-bookmarks.el")
(declare-function treemacs-git-commit-diff-mode "treemacs-commit-diff-mode.el")
(evil-define-state treemacs
"Treemacs state"
:cursor '(bar . 0)
:enable (motion))
(evil-set-initial-state 'treemacs-mode 'treemacs)
(defun treemacs-evil---turn-off-visual-state-after-click (&rest _)
"Go back to `evil-treemacs-state' after a mouse click."
;; a double click will likely have opened a file so we need to make
;; sure to go back in the right buffer
(--when-let (treemacs-get-local-buffer)
(with-current-buffer it
(evil-treemacs-state))))
(defun treemacs-evil--window-move-compatibility-advice (orig-fun &rest args)
"Close Treemacs while moving windows around.
Then call ORIG-FUN with its ARGS and reopen treemacs if it was open before."
(let* ((treemacs-window (treemacs-get-local-window))
(is-active (and treemacs-window (window-live-p treemacs-window))))
(when is-active (treemacs))
(apply orig-fun args)
(when is-active
(save-selected-window
(treemacs)))))
(dolist (func '(evil-window-move-far-left
evil-window-move-far-right
evil-window-move-very-top
evil-window-move-very-bottom))
(advice-add func :around #'treemacs-evil--window-move-compatibility-advice))
(advice-add 'treemacs-leftclick-action :after #'treemacs-evil---turn-off-visual-state-after-click)
(advice-add 'treemacs-doubleclick-action :after #'treemacs-evil---turn-off-visual-state-after-click)
(define-key evil-treemacs-state-map (kbd "j") #'treemacs-next-line)
(define-key evil-treemacs-state-map (kbd "k") #'treemacs-previous-line)
(define-key evil-treemacs-state-map (kbd "M-j") #'treemacs-next-neighbour)
(define-key evil-treemacs-state-map (kbd "M-k") #'treemacs-previous-neighbour)
(define-key evil-treemacs-state-map (kbd "M-J") #'treemacs-next-line-other-window)
(define-key evil-treemacs-state-map (kbd "M-K") #'treemacs-previous-line-other-window)
(define-key evil-treemacs-state-map (kbd "th") #'treemacs-toggle-show-dotfiles)
(define-key evil-treemacs-state-map (kbd "ti") #'treemacs-hide-gitignored-files-mode)
(define-key evil-treemacs-state-map (kbd "tw") #'treemacs-toggle-fixed-width)
(define-key evil-treemacs-state-map (kbd "tv") #'treemacs-fringe-indicator-mode)
(define-key evil-treemacs-state-map (kbd "tf") #'treemacs-follow-mode)
(define-key evil-treemacs-state-map (kbd "ta") #'treemacs-filewatch-mode)
(define-key evil-treemacs-state-map (kbd "tg") #'treemacs-git-mode)
(define-key evil-treemacs-state-map (kbd "tc") #'treemacs-indicate-top-scroll-mode)
(define-key evil-treemacs-state-map (kbd "td") #'treemacs-git-commit-diff-mode)
(define-key evil-treemacs-state-map (kbd "tn") #'treemacs-indent-guide-mode)
(define-key evil-treemacs-state-map (kbd "w") #'treemacs-set-width)
(define-key evil-treemacs-state-map (kbd ">") #'treemacs-increase-width)
(define-key evil-treemacs-state-map (kbd "<") #'treemacs-decrease-width)
(define-key evil-treemacs-state-map (kbd "b") #'treemacs-add-bookmark)
(define-key evil-treemacs-state-map (kbd "?") #'treemacs-common-helpful-hydra)
(define-key evil-treemacs-state-map (kbd "C-?") #'treemacs-advanced-helpful-hydra)
(define-key evil-treemacs-state-map (kbd "RET") #'treemacs-RET-action)
(define-key evil-treemacs-state-map (kbd "TAB") #'treemacs-TAB-action)
(define-key evil-treemacs-state-map (kbd "H") #'treemacs-collapse-parent-node)
(define-key evil-treemacs-state-map (kbd "!") #'treemacs-run-shell-command-for-current-node)
(define-key evil-treemacs-state-map (kbd "=") #'treemacs-fit-window-width)
(define-key evil-treemacs-state-map (kbd "W") #'treemacs-extra-wide-toggle)
(evil-define-key 'treemacs treemacs-mode-map (kbd "yp") #'treemacs-copy-project-path-at-point)
(evil-define-key 'treemacs treemacs-mode-map (kbd "ya") #'treemacs-copy-absolute-path-at-point)
(evil-define-key 'treemacs treemacs-mode-map (kbd "yr") #'treemacs-copy-relative-path-at-point)
(evil-define-key 'treemacs treemacs-mode-map (kbd "yf") #'treemacs-copy-file)
(evil-define-key 'treemacs treemacs-mode-map (kbd "yv") #'treemacs-paste-dir-at-point-to-minibuffer)
(evil-define-key 'treemacs treemacs-mode-map (kbd "gr") #'treemacs-refresh)
(evil-define-key 'treemacs treemacs-mode-map [down-mouse-1] #'treemacs-leftclick-action)
(evil-define-key 'treemacs treemacs-mode-map [drag-mouse-1] #'treemacs-dragleftclick-action)
(evil-define-key 'treemacs treemacs-mode-map (kbd "h") #'treemacs-COLLAPSE-action)
(evil-define-key 'treemacs treemacs-mode-map (kbd "RET") #'treemacs-RET-action)
(evil-define-key 'treemacs treemacs-mode-map (kbd "l") #'treemacs-RET-action)
(unless (window-system)
(evil-define-key 'treemacs treemacs-mode-map [C-i] #'treemacs-TAB-action))
(provide 'treemacs-evil)
;;; treemacs-evil.el ends here
``` | /content/code_sandbox/src/extra/treemacs-evil.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,590 |
```emacs lisp
;;; treemacs-projectile.el --- Projectile integration for treemacs -*- lexical-binding: t -*-
;; Author: Alexander Miller <alexanderm@web.de>
;; Package-Requires: ((emacs "26.1") (projectile "0.14.0") (treemacs "0.0"))
;; Version: 0
;; Homepage: path_to_url
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;;; Projectile integration for treemacs
;;; Code:
(require 'treemacs)
(require 'projectile)
(eval-when-compile
(require 'treemacs-macros))
;;;###autoload
(defun treemacs-projectile (&optional arg)
"Add one of `projectile-known-projects' to the treemacs workspace.
With a prefix ARG was for the name of the project instead of using the name of
the project's root directory."
(interactive)
(if (and (bound-and-true-p projectile-known-projects)
(listp projectile-known-projects)
projectile-known-projects)
(let* ((projects (--reject (treemacs-is-path (treemacs-canonical-path it) :in-workspace (treemacs-current-workspace))
(-map #'treemacs--unslash projectile-known-projects)))
(path (completing-read "Project: " projects))
(name (unless arg (treemacs--filename path))))
(if (treemacs-workspace->is-empty?)
(treemacs--init path name)
(save-selected-window
(treemacs-select-window)
;; not casing the full error list since some are excluded
(pcase (treemacs-do-add-project-to-workspace path name)
(`(success ,project)
(treemacs-pulse-on-success "Added project %s to the workspace."
(propertize (treemacs-project->name project) 'face 'font-lock-type-face)))
(`(duplicate-name ,duplicate)
(goto-char (treemacs-project->position duplicate))
(treemacs-pulse-on-failure "A project with the name %s already exists."
(propertize (treemacs-project->name duplicate) 'face 'font-lock-type-face)))))))
(treemacs-pulse-on-failure "It looks like projectile does not know any projects.")))
(define-key treemacs-project-map (kbd "p") #'treemacs-projectile)
(defun treemacs--read-first-project-path ()
"Overwrites the original definition from `treemacs-core-utils'.
This version will read a directory based on the current project root instead of
the current dir."
(when (treemacs-workspace->is-empty?)
(file-truename
(read-directory-name "Project root: "
(condition-case _
(projectile-project-root)
(error nil))))))
(defun treemacs--projectile-current-user-project-function ()
"Get the current projectile project root."
(declare (side-effect-free t))
(-some-> (projectile-project-root) (file-truename) (treemacs-canonical-path)))
(defun treemacs-projectile--add-file-to-projectile-cache (path)
"Add created file PATH to projectile's cache."
(let ((file-buffer (get-file-buffer path))
(kill? nil))
(unless file-buffer
(setf file-buffer (find-file-noselect path)
kill? t))
(with-current-buffer file-buffer
(projectile-find-file-hook-function))
(when kill? (kill-buffer file-buffer))))
(defun treemacs--projectile-project-mouse-selection-menu ()
"Build a mouse selection menu for projectile projects."
(if (null projectile-known-projects)
(list (vector "Projectile list is empty" #'ignore))
(-let [projects
(->> projectile-known-projects
(-map #'treemacs-canonical-path)
(--reject (treemacs-is-path it :in-workspace))
(-sort #'string<))]
(if (null projects)
(list (vector "All Projectile projects are already in the workspace" #'ignore))
(--map (vector it (lambda () (interactive) (treemacs-add-project-to-workspace it))) projects)))))
(add-to-list 'treemacs--find-user-project-functions #'treemacs--projectile-current-user-project-function)
(add-hook 'treemacs-create-file-functions #'treemacs-projectile--add-file-to-projectile-cache)
(with-eval-after-load 'treemacs-mouse-interface
(add-to-list
(with-no-warnings 'treemacs--mouse-project-list-functions)
'("Add Projectile project" . treemacs--projectile-project-mouse-selection-menu)
:append))
(defun treemacs-projectile--remove-from-cache (path)
"Remove PATH from projectile's cache."
(let* ((dir (if (file-directory-p path) path (treemacs--parent-dir path)))
(projectile-root (projectile-project-root dir)))
(when projectile-root
(let ((file-relative (file-relative-name path projectile-root)))
(ignore-errors (projectile-purge-file-from-cache file-relative))))))
(defun treemacs-projectile--add-to-cache (path)
"Add PATH to projectile's cache."
(let* ((projectile-root (projectile-project-root path))
(relative-path (file-relative-name path projectile-root)))
(unless (or (projectile-file-cached-p relative-path projectile-root)
(projectile-ignored-directory-p (file-name-directory path))
(projectile-ignored-file-p path))
(puthash projectile-root
(cons relative-path (gethash projectile-root projectile-projects-cache))
projectile-projects-cache)
(projectile-serialize-cache))))
(defun treemacs-projectile--rename-cache-entry (old-path new-path)
"Exchange OLD-PATH for NEW-PATH in projectile's cache."
(treemacs-projectile--remove-from-cache old-path)
(treemacs-projectile--add-to-cache new-path))
(defun treemacs-projectile--add-copied-file-to-cache (_ path)
"Add PATH to projectile's cache.
First argument is ignored because it is the file's original path, supplied
as part of `treemacs-copy-file-functions'."
(treemacs-projectile--add-file-to-projectile-cache path))
(add-hook 'treemacs-delete-file-functions #'treemacs-projectile--remove-from-cache)
(add-hook 'treemacs-rename-file-functions #'treemacs-projectile--rename-cache-entry)
(add-hook 'treemacs-move-file-functions #'treemacs-projectile--rename-cache-entry)
(add-hook 'treemacs-copy-file-functions #'treemacs-projectile--add-copied-file-to-cache)
(provide 'treemacs-projectile)
;;; treemacs-projectile.el ends here
``` | /content/code_sandbox/src/extra/treemacs-projectile.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,482 |
```emacs lisp
;;; treemacs-perspective.el --- Perspective integration for treemacs -*- lexical-binding: t -*-
;; Author: Alexander Miller <alexanderm@web.de>
;; Jason Dufair <jase@dufair.org>
;; Package-Requires: ((emacs "26.1") (treemacs "0.0") (perspective "2.8") (dash "2.11.0"))
;; Version: 0
;; Homepage: path_to_url
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;;; Integration of perspective.el into treemacs' buffer scoping framework.
;;; Code:
(require 'treemacs)
(require 'perspective)
(require 'eieio)
(require 'dash)
(eval-when-compile
(require 'treemacs-macros)
(require 'cl-lib))
;; remove base compatibility hook
(remove-hook 'perspective-activated-functions #'treemacs--remove-treemacs-window-in-new-frames)
(defclass treemacs-perspective-scope (treemacs-scope) () :abstract t)
(add-to-list 'treemacs-scope-types (cons 'Perspectives 'treemacs-perspective-scope))
(cl-defmethod treemacs-scope->current-scope ((_ (subclass treemacs-perspective-scope)))
"Get the current perspective as scope.
Returns the symbol `none' if no perspective is active."
(or (persp-curr) 'none))
(cl-defmethod treemacs-scope->current-scope-name ((_ (subclass treemacs-perspective-scope)) perspective)
"Return the name of the given PERSPECTIVE.
Will return \"No Perspective\" if no perspective is active."
(if (eq 'none perspective)
"No Perspective"
(treemacs-perspective--format-workspace-name (persp-name perspective))))
(defun treemacs-perspective--on-scope-kill ()
"Cleanup hook to run when a perspective is killed."
(treemacs--on-scope-kill (persp-current-name)))
(cl-defmethod treemacs-scope->setup ((_ (subclass treemacs-perspective-scope)))
"Perspective-scope setup."
(add-hook 'persp-switch-hook #'treemacs-perspective--on-perspective-switch)
(add-hook 'persp-after-rename-hook #'treemacs-perspective--on-perspective-rename)
(add-hook 'persp-killed-hook #'treemacs-perspective--on-scope-kill)
(treemacs-perspective--ensure-workspace-exists))
(cl-defmethod treemacs-scope->cleanup ((_ (subclass treemacs-perspective-scope)))
"Perspective-scope tear-down."
(remove-hook 'persp-switch-hook #'treemacs-perspective--on-perspective-switch)
(remove-hook 'persp-after-rename-hook #'treemacs-perspective--on-perspective-rename)
(remove-hook 'persp-killed-hook #'treemacs-perspective--on-scope-kill))
(defun treemacs-perspective--on-perspective-rename ()
"Hook running after the perspective was renamed.
Will rename the current workspace to the current perspective's name."
(treemacs-do-rename-workspace
;; Current workspace's name
(treemacs-current-workspace)
(treemacs-perspective--format-workspace-name (persp-current-name))))
(defun treemacs-perspective--on-perspective-switch (&rest _)
"Hook running after the perspective was switched.
Will select a workspace for the now active perspective, creating it if
necessary."
;; running with a timer ensures that any other post-processing is finished after a perspective
;; was run since commands like `spacemacs/helm-persp-switch-project' first create a perspective
;; and only afterwards select the file to display
(run-with-timer
0.1 nil
(lambda ()
(treemacs-without-following
(treemacs-perspective--ensure-workspace-exists)
(treemacs--change-buffer-on-scope-change)))))
(defun treemacs-perspective--ensure-workspace-exists ()
"Make sure a workspace exists for the given PERSPECTIVE-NAME.
Matching happens by name. If no workspace can be found it will be created."
(let* ((perspective-name (treemacs-scope->current-scope-name
(treemacs-current-scope-type) (treemacs-current-scope)))
(workspace (or (treemacs--find-workspace-by-name perspective-name)
(treemacs-perspective--create-workspace perspective-name))))
(setf (treemacs-current-workspace) workspace)
(treemacs--invalidate-buffer-project-cache)
(run-hooks 'treemacs-switch-workspace-hook)
workspace))
(defun treemacs-perspective--create-workspace (name)
"Create a new workspace for the given perspective NAME.
Projects will be found as per `treemacs--find-user-project-functions'. If that
does not return anything the projects of the fallback workspace will be copied."
(treemacs-block
(let* ((ws-result (treemacs-do-create-workspace name))
(ws-status (car ws-result))
(ws (cadr ws-result))
(root-path (treemacs--find-current-user-project))
(project-list))
(unless (eq ws-status 'success)
(treemacs-log "Failed to create workspace for perspective: %s, using fallback instead." ws)
(treemacs-return (car treemacs--workspaces)))
(if root-path
(setf project-list
(list (treemacs-project->create!
:name (treemacs--filename root-path)
:path root-path
:path-status (treemacs--get-path-status root-path))))
(-let [fallback-workspace (car treemacs--workspaces)]
;; copy the projects instead of reusing them so we don't accidentally rename
;; a project in 2 workspaces
(dolist (project (treemacs-workspace->projects fallback-workspace))
(push (treemacs-project->create!
:name (treemacs-project->name project)
:path (treemacs-project->path project)
:path-status (treemacs-project->path-status project))
project-list))))
(setf (treemacs-workspace->projects ws) (nreverse project-list))
(treemacs-return ws))))
(defun treemacs-perspective--format-workspace-name (perspective-name)
"Format of the workspace name used for a perspective named PERSPECTIVE-NAME."
(format "Perspective %s" perspective-name))
(provide 'treemacs-perspective)
;;; treemacs-perspective.el ends here
``` | /content/code_sandbox/src/extra/treemacs-perspective.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,464 |
```emacs lisp
;;; treemacs-magit.el --- Magit integration for treemacs -*- lexical-binding: t -*-
;; Author: Alexander Miller <alexanderm@web.de>
;; Package-Requires: ((emacs "26.1") (treemacs "0.0") (pfuture "1.3" ) (magit "2.90.0"))
;; Version: 0
;; Homepage: path_to_url
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;;; Closing the gaps for filewatch- and git-modes in conjunction with magit.
;;; Specifically this package will hook into magit so as to artificially
;;; produce filewatch events for changes that treemacs would otherwise
;;; not catch, namely the committing and (un)staging of files.
;;; Code:
(require 'treemacs)
(require 'magit)
(require 'pfuture)
(require 'seq)
;; no need for dash for a single when-let
(eval-when-compile
(when (version< emacs-version "26")
(defalias 'if-let* #'if-let)
(defalias 'when-let* #'when-let)))
;;;; Filewatch
(defvar treemacs-magit--timers nil
"Cached list of roots an update is scheduled for.")
(defun treemacs-magit--schedule-update ()
"Schedule an update to potentially run after 3 seconds of idle time.
In order for the update to fully run several conditions must be met:
* A timer for an update for the given directory must not already exist
(see `treemacs-magit--timers')
* The directory must be part of a treemacs workspace, and
* The project must not be set for refresh already."
(when treemacs-git-mode
(let ((magit-root (treemacs-canonical-path (magit-toplevel))))
(unless (member magit-root treemacs-magit--timers)
(push magit-root treemacs-magit--timers)
(run-with-idle-timer
3 nil
(lambda ()
(unwind-protect
(pcase treemacs--git-mode
('simple
(treemacs-magit--simple-git-mode-update magit-root))
((or 'extended 'deferred)
(treemacs-magit--extended-git-mode-update magit-root)))
(setf treemacs-magit--timers (delete magit-root treemacs-magit--timers)))))))))
(defun treemacs-magit--simple-git-mode-update (magit-root)
"Update the project at the given MAGIT-ROOT.
Without the parsing ability of extended git-mode this update uses
filewatch-mode's mechanics to update the entire project."
(treemacs-run-in-every-buffer
(when-let* ((project (treemacs--find-project-for-path magit-root))
(dom-node (treemacs-find-in-dom (treemacs-project->path project))))
(push (cons (treemacs-project->path project) 'force-refresh)
(treemacs-dom-node->refresh-flag dom-node))
(treemacs--start-filewatch-timer))))
(defun treemacs-magit--extended-git-mode-update (magit-root)
"Update the project at the given MAGIT-ROOT.
This runs due to a commit or stash action, so we know that no files have
actually been added or deleted. This allows us to forego rebuilding the entire
project structure just to be sure we caught everything. Instead we grab the
current git status and just go through the lines as they are right now."
;; we run a single git process to update every buffer, so we need to gather
;; the visible dirs in every buffer
;; this collection may contain duplicates, but they are removed in python
(-let [visible-dirs nil]
(treemacs-run-in-every-buffer
(dolist (dir (-some->> magit-root
(treemacs-find-in-dom)
(treemacs-dom-node->children)
(-map #'treemacs-dom-node->key)))
(when (stringp dir)
(push dir visible-dirs))))
(pfuture-callback `(,treemacs-python-executable
"-O" "-S"
,treemacs--git-status.py
,magit-root
,(number-to-string treemacs-max-git-entries)
,treemacs-git-command-pipe
,@visible-dirs)
:directory magit-root
:on-success
(progn
(ignore status)
(treemacs-magit--update-callback magit-root pfuture-buffer)))))
(defun treemacs-magit--update-callback (magit-root pfuture-buffer)
"Run the update as a pfuture callback.
Will update nodes under MAGIT-ROOT with output in PFUTURE-BUFFER."
(let ((ht (read (pfuture-output-from-buffer pfuture-buffer))))
(treemacs-run-in-every-buffer
(let ((dom-node (or (treemacs-find-in-dom magit-root)
(when-let* ((project
(seq-find
(lambda (pr) (treemacs-is-path (treemacs-project->path pr) :in magit-root))
(treemacs-workspace->projects (treemacs-current-workspace)))))
(treemacs-find-in-dom (treemacs-project->path project))))))
(when (and dom-node
(treemacs-dom-node->position dom-node)
(treemacs-is-node-expanded? (treemacs-dom-node->position dom-node))
(null (treemacs-dom-node->refresh-flag dom-node)))
(save-excursion
(goto-char (treemacs-dom-node->position dom-node))
(forward-line 1)
(let* ((node (treemacs-node-at-point))
(start-depth (-some-> node (treemacs-button-get :depth)))
(curr-depth start-depth)
(path (-some-> node (treemacs-button-get :key))))
(treemacs-with-writable-buffer
(while (and node
(>= curr-depth start-depth))
(when (and (stringp path)
(file-exists-p path))
(treemacs--git-face-quick-change
(treemacs-button-get node :key)
(or (ht-get ht path)
(if (memq (treemacs-button-get node :state)
'(file-node-open file-node-closed))
'treemacs-git-unmodified-face
'treemacs-directory-face)))
(put-text-property (treemacs-button-start node) (treemacs-button-end node) 'face
(or (ht-get ht path)
(if (memq (treemacs-button-get node :state)
'(file-node-open file-node-closed))
'treemacs-git-unmodified-face
'treemacs-directory-face))))
(forward-line 1)
(if (eobp)
(setf node nil)
(setf node (treemacs-node-at-point)
path (-some-> node (treemacs-button-get :path))
curr-depth (-some-> node (treemacs-button-get :depth)))))))))))))
(unless (featurep 'treemacs-magit)
(add-hook 'magit-post-commit-hook #'treemacs-magit--schedule-update)
(add-hook 'git-commit-post-finish-hook #'treemacs-magit--schedule-update)
(add-hook 'magit-post-stage-hook #'treemacs-magit--schedule-update)
(add-hook 'magit-post-unstage-hook #'treemacs-magit--schedule-update))
;;;; Git Commit Diff
(defvar treemacs--git-commit-diff.py)
(defvar treemacs--commit-diff-ann-source)
(defconst treemacs--commit-diff-update-commands
(list "pull" "push" "commit" "merge" "rebase" "cherry-pick" "fetch" "checkout")
"List of git commands that change local/remote commit status info.
Relevant for integrating with `treemacs-git-commit-diff-mode'.")
(defun treemacs--update-commit-diff-after-magit-process (process &rest _)
"Update commit diffs after completion of a magit git PROCESS."
(when (memq (process-status process) '(exit signal))
(let* ((args (process-command process))
(command (car (nthcdr (1+ (length magit-git-global-arguments)) args))))
(when (member command treemacs--commit-diff-update-commands)
(-let [path (process-get process 'default-dir)]
(pfuture-callback `(,treemacs-python-executable "-O" ,treemacs--git-commit-diff.py ,path)
:directory path
:on-success
(-let [out (-> (pfuture-callback-output)
(treemacs-string-trim-right)
(read))]
(treemacs-run-in-every-buffer
(-when-let* ((project (treemacs--find-project-for-path path))
(project-path (treemacs-project->path project)))
(if out
(treemacs-set-annotation-suffix
project-path out treemacs--commit-diff-ann-source)
(treemacs-remove-annotation-suffix project-path treemacs--commit-diff-ann-source))
(treemacs-apply-single-annotation project-path))))))))))
(defun treemacs--magit-commit-diff-setup ()
"Enable or disable magit advice for `treemacs-git-commit-diff-mode'."
(if (bound-and-true-p treemacs-git-commit-diff-mode)
(advice-add #'magit-process-sentinel :after #'treemacs--update-commit-diff-after-magit-process)
(advice-remove #'magit-process-sentinel #'treemacs--update-commit-diff-after-magit-process)))
(unless (featurep 'treemacs-magit)
(add-hook 'treemacs-git-commit-diff-mode-hook #'treemacs--magit-commit-diff-setup)
(when (bound-and-true-p treemacs-git-commit-diff-mode)
(advice-add #'magit-process-sentinel :after #'treemacs--update-commit-diff-after-magit-process)))
(provide 'treemacs-magit)
;;; treemacs-magit.el ends here
``` | /content/code_sandbox/src/extra/treemacs-magit.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 2,249 |
```emacs lisp
;;; treemacs-icons-dired.el --- Treemacs icons for dired -*- lexical-binding: t -*-
;; Author: Alexander Miller <alexanderm@web.de>
;; Package-Requires: ((treemacs "0.0") (emacs "26.1"))
;; Version: 0
;; Homepage: path_to_url
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;;; Treemacs icons for Dired. Code is based on all-the-icons-dired.el
;;; Code:
(require 'treemacs)
(require 'hl-line)
(require 'dired)
(require 'pcase)
(eval-when-compile
(require 'treemacs-macros))
(defvar treemacs-icons-dired--ranger-adjust nil)
(with-eval-after-load 'ranger (setf treemacs-icons-dired--ranger-adjust t))
(defvar-local treemacs-icons-dired-displayed nil
"Flags whether icons have been added.")
(defvar-local treemacs-icons-dired--covered-subdirs nil
"List of subdirs icons were already added for.")
(defun treemacs-icons-dired--display ()
"Display the icons of files in a Dired buffer."
(when (and (display-graphic-p)
(not treemacs-icons-dired-displayed)
dired-subdir-alist)
(setq-local treemacs-icons-dired-displayed t)
(setq-local treemacs-icons (treemacs-theme->gui-icons treemacs--current-theme))
(pcase-dolist (`(,path . ,pos) dired-subdir-alist)
(treemacs-icons-dired--display-icons-for-subdir path pos))))
(defun treemacs-icons-dired--display-icons-for-subdir (path pos)
"Display icons for subdir PATH at given POS."
(unless (member path treemacs-icons-dired--covered-subdirs)
(add-to-list 'treemacs-icons-dired--covered-subdirs path)
(treemacs-with-writable-buffer
(save-excursion
(goto-char pos)
(dired-goto-next-file)
(treemacs-block
(while (not (eobp))
(if (dired-move-to-filename nil)
(let* ((file (dired-get-filename nil t))
(icon (if (file-directory-p file)
(treemacs-icon-for-dir file 'closed)
(treemacs-icon-for-file file))))
(insert icon))
(treemacs-return nil))
(forward-line 1) ))))))
(defun treemacs-icons-dired--insert-subdir-advice (&rest args)
"Advice to Dired & Dired+ insert-subdir commands.
Will add icons for the subdir in the `car' of ARGS."
(let* ((path (file-name-as-directory (car args)))
(pos (cdr (assoc path dired-subdir-alist))))
(when pos
(treemacs-icons-dired--display-icons-for-subdir path pos))))
(advice-add #'dired-insert-subdir :after #'treemacs-icons-dired--insert-subdir-advice)
(with-eval-after-load 'dired+
(when (fboundp 'diredp-insert-subdirs)
(advice-add #'diredp-insert-subdirs :after #'treemacs-icons-dired--insert-subdir-advice)))
(defun treemacs-icons-dired--kill-subdir-advice (&rest _args)
"Advice to Dired kill-subdir commands.
Will remove the killed subdir from `treemacs-icons-dired--covered-subdirs'."
(setf treemacs-icons-dired--covered-subdirs (delete (dired-current-directory) treemacs-icons-dired--covered-subdirs)))
(advice-add #'dired-kill-subdir :before #'treemacs-icons-dired--kill-subdir-advice)
(defun treemacs-icons-dired--reset (&rest _args)
"Reset metadata on revert."
(setq-local treemacs-icons-dired--covered-subdirs nil)
(setq-local treemacs-icons-dired-displayed nil))
(defun treemacs-icons-dired--add-icon-for-new-entry (file &rest _)
"Add an icon for a new single FILE added by Dired."
(let (buffer-read-only)
(insert (if (file-directory-p file)
(treemacs-icon-for-dir file 'closed)
(treemacs-icon-for-file file)))))
(defun treemacs-icons-dired--set-tab-width ()
"Set the local `tab-width' to 1.
Necessary for the all-the-icons based themes."
(setq-local tab-width 1))
(defun treemacs-icons-dired--setup ()
"Setup for the minor-mode."
(add-hook 'dired-after-readin-hook #'treemacs-icons-dired--display)
(add-hook 'dired-mode-hook #'treemacs--select-icon-set)
(add-hook 'dired-mode-hook #'treemacs-icons-dired--set-tab-width)
(advice-add 'dired-revert :before #'treemacs-icons-dired--reset)
(advice-add 'ranger-setup :before #'treemacs--select-icon-set)
(advice-add 'dired-add-entry :after #'treemacs-icons-dired--add-icon-for-new-entry)
(dolist (buffer (buffer-list))
(with-current-buffer buffer
(when (derived-mode-p 'dired-mode)
(treemacs-icons-dired--set-tab-width)
(treemacs--select-icon-set)
(treemacs-icons-dired--display)))))
(defun treemacs-icons-dired--teardown ()
"Tear-down for the minor-mode."
(remove-hook 'dired-after-readin-hook #'treemacs-icons-dired--display)
(remove-hook 'dired-mode-hook #'treemacs--select-icon-set)
(remove-hook 'dired-mode-hook #'treemacs-icons-dired--set-tab-width)
(advice-remove 'dired-revert #'treemacs-icons-dired--reset)
(advice-remove 'ranger-setup #'treemacs--select-icon-set)
(advice-remove 'dired-add-entry #'treemacs-icons-dired--add-icon-for-new-entry)
(dolist (buffer (buffer-list))
(with-current-buffer buffer
(when (derived-mode-p 'dired-mode)
(dired-revert)))))
;;;###autoload
(define-minor-mode treemacs-icons-dired-mode
"Display treemacs icons for each file in a Dired buffer."
:require 'treemacs-icons-dired
:init-value nil
:global t
:group 'treemacs
(if treemacs-icons-dired-mode
(treemacs-icons-dired--setup)
(treemacs-icons-dired--teardown)))
;;;###autoload
(defun treemacs-icons-dired-enable-once ()
"Enable `treemacs-icons-dired-mode' and remove self from `dired-mode-hook'.
This function is meant to be used as a single-use toggle added to
`dired-mode-hook' to enable icons for Dired only once, without having to use
\"with-eval-after-load \\='dired\", since Dired tends to be loaded early."
(treemacs-icons-dired-mode)
(remove-hook 'dired-mode-hook #'treemacs-icons-dired-enable-once))
(provide 'treemacs-icons-dired)
;;; treemacs-icons-dired.el ends here
``` | /content/code_sandbox/src/extra/treemacs-icons-dired.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 1,633 |
```emacs lisp
;;; treemacs-all-the-icons.el --- all-the-icons integration for treemacs -*- lexical-binding: t -*-
;; Author: Eric Dallo <ercdll1337@gmail.com>
;; Package-Requires: ((emacs "26.1") (all-the-icons "4.0.1") (treemacs "0.0"))
;; Version: 0
;; Homepage: path_to_url
;; This program is free software; you can redistribute it and/or modify
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; along with this program. If not, see <path_to_url
;;; Commentary:
;;; all-the-icons integration.
;;
;;; Code:
(require 'all-the-icons)
(require 'treemacs)
(defface treemacs-all-the-icons-root-face
'((t (:inherit font-lock-string-face)))
"Face used for the root icon in all-the-icons theme."
:group 'treemacs-faces)
(defface treemacs-all-the-icons-file-face
'((t (:inherit font-lock-doc-face)))
"Face used for the directory and file icons in all-the-icons theme."
:group 'treemacs-faces)
(defvar treemacs-all-the-icons-tab (if (bound-and-true-p treemacs-all-the-icons-tab-font)
(propertize "\t" 'face `((:family ,treemacs-all-the-icons-tab-font)))
"\t"))
(treemacs-create-theme "all-the-icons"
:config
(progn
(dolist (item all-the-icons-extension-icon-alist)
(let ((extensions (list (nth 0 item)))
(fn (nth 1 item))
(key (nth 2 item))
(plist (nthcdr 3 item)))
(treemacs-create-icon
:icon (format " %s%s" (apply fn key plist) treemacs-all-the-icons-tab)
:extensions extensions)))
;; directory and other icons
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-octicon "repo" :height 1.2 :v-adjust -0.1 :face 'treemacs-all-the-icons-root-face) treemacs-all-the-icons-tab)
:extensions (root-closed root-open)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s%s%s" (all-the-icons-octicon "chevron-down" :height 0.75 :v-adjust 0.1 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab (all-the-icons-octicon "file-directory" :v-adjust 0 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (dir-open)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s%s%s" (all-the-icons-octicon "chevron-right" :height 0.75 :v-adjust 0.1 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab (all-the-icons-octicon "file-directory" :v-adjust 0 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (dir-closed)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s%s%s" (all-the-icons-octicon "chevron-down" :height 0.75 :v-adjust 0.1 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab (all-the-icons-octicon "package" :v-adjust 0 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (tag-open)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s%s%s" (all-the-icons-octicon "chevron-right" :height 0.75 :v-adjust 0.1 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab (all-the-icons-octicon "package" :v-adjust 0 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (tag-closed)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-octicon "tag" :height 0.9 :v-adjust 0 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (tag-leaf)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-octicon "flame" :v-adjust 0 :face 'all-the-icons-red) treemacs-all-the-icons-tab)
:extensions (error)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-octicon "stop" :v-adjust 0 :face 'all-the-icons-yellow) treemacs-all-the-icons-tab)
:extensions (warning)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-octicon "info" :height 0.75 :v-adjust 0.1 :face 'all-the-icons-blue) treemacs-all-the-icons-tab)
:extensions (info)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-material "mail" :height 0.75 :v-adjust 0.1 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (mail)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-octicon "bookmark" :height 0.75 :v-adjust 0.1 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (bookmark)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-material "computer" :height 0.75 :v-adjust 0.1 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (screen)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-material "home" :height 0.75 :v-adjust 0.1 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (house)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-material "menu" :height 0.75 :v-adjust 0.1 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (list)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-material "repeat" :height 0.75 :v-adjust 0.1 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (repeat)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-faicon "suitcase" :height 0.75 :v-adjust 0.1 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (suitcase)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-material "close" :height 0.75 :v-adjust 0.1 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (close)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-octicon "calendar" :height 0.75 :v-adjust 0.1 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (calendar)
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format "%s%s" (all-the-icons-faicon "briefcase" :height 0.75 :v-adjust 0.1 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (briefcase)
:fallback 'same-as-icon)
;; file icons - remove icon if the extension appears in all-the-icons-icon-extension-alist
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "access" :v-adjust 0 :face 'all-the-icons-red) treemacs-all-the-icons-tab) :extensions ("accdb" "accdt") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "actionscript" :v-adjust 0 :face 'all-the-icons-red) treemacs-all-the-icons-tab) :extensions ("actionscript") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "ansible" :v-adjust 0 :face 'all-the-icons-dsilver) treemacs-all-the-icons-tab) :extensions ("ansible") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "antlr" :v-adjust 0 :face 'all-the-icons-orange) treemacs-all-the-icons-tab) :extensions ("antlr") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "apple" :v-adjust 0 :face 'all-the-icons-lsilver) treemacs-all-the-icons-tab) :extensions ("applescript") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "appveyor" :v-adjust 0 :face 'all-the-icons-lblue) treemacs-all-the-icons-tab) :extensions ("appveyor.yml") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "arduino" :v-adjust 0 :face 'all-the-icons-dgreen) treemacs-all-the-icons-tab) :extensions ("ino" "pde") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-material "audiotrack" :v-adjust 0 :face 'all-the-icons-lblue) treemacs-all-the-icons-tab) :extensions ("midi") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "babel" :v-adjust 0 :face 'all-the-icons-yellow) treemacs-all-the-icons-tab) :extensions ("babelignore" "babelrc.js" "babelrc.json" "babel.config.js") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "bazel" :v-adjust 0 :face 'all-the-icons-green) treemacs-all-the-icons-tab) :extensions ("bazelrc" "bazel") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-alltheicon "bower" :v-adjust 0 :face 'all-the-icons-orange) treemacs-all-the-icons-tab) :extensions ("bower.json") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "bundler" :v-adjust 0 :face 'all-the-icons-lblue) treemacs-all-the-icons-tab) :extensions ("gemfile" "gemfile.lock") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-octicon "gear" :v-adjust 0 :face 'all-the-icons-lsilver) treemacs-all-the-icons-tab) :extensions ("bat") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-alltheicon "cplusplus" :v-adjust 0 :face 'all-the-icons-purple) treemacs-all-the-icons-tab) :extensions ("tpp") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-alltheicon "clojure" :v-adjust 0 :face 'all-the-icons-blue) treemacs-all-the-icons-tab) :extensions ("edn") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "cmake" :v-adjust 0 :face 'all-the-icons-green) treemacs-all-the-icons-tab) :extensions ("cmake-cache") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "cobol" :v-adjust 0 :face 'all-the-icons-dblue) treemacs-all-the-icons-tab) :extensions ("cobol") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-alltheicon "coffeescript" :v-adjust 0 :face 'all-the-icons-dorange) treemacs-all-the-icons-tab) :extensions ("coffeescript") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-faicon "certificate" :v-adjust 0 :face 'all-the-icons-yellow) treemacs-all-the-icons-tab) :extensions ("csr" "crt" "cer" "der" "pfx" "p7b" "p7r" "src" "crl" "sst" "stl") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-octicon "gear" :v-adjust 0 :face 'all-the-icons-lsilver) treemacs-all-the-icons-tab) :extensions ("conf" "properties" "config" "cfg" "xdefaults" "xresources" "terminalrc" "ledgerrc") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "cython" :v-adjust 0 :face 'all-the-icons-dblue) treemacs-all-the-icons-tab) :extensions ("cython") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-alltheicon "dlang" :v-adjust 0 :face 'all-the-icons-red) treemacs-all-the-icons-tab) :extensions ("d" "dscript" "dml" "diet") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-octicon "diff" :v-adjust 0 :face 'all-the-icons-lsilver) treemacs-all-the-icons-tab) :extensions ("diff") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "dockerfile" :v-adjust 0 :face 'all-the-icons-blue) treemacs-all-the-icons-tab) :extensions ("docker-compose.yml") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "editorconfig" :v-adjust 0 :face 'all-the-icons-lsilver) treemacs-all-the-icons-tab) :extensions ("editorconfig") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-faicon "wrench" :v-adjust 0 :face 'all-the-icons-lpurple) treemacs-all-the-icons-tab) :extensions ("envrc") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "eslint" :v-adjust 0 :face 'all-the-icons-lpurple) treemacs-all-the-icons-tab) :extensions ("eslintrc" "eslintcache") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-octicon "file-binary" :v-adjust 0 :face 'all-the-icons-lsilver) treemacs-all-the-icons-tab) :extensions ("exe" "obj" "so" "o") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-alltheicon "elixir" :v-adjust 0 :face 'all-the-icons-dpurple) treemacs-all-the-icons-tab) :extensions ("heex") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "cucumber" :v-adjust 0 :face 'all-the-icons-dgreen) treemacs-all-the-icons-tab) :extensions ("feature") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "fortran" :v-adjust 0 :face 'all-the-icons-lsilver) treemacs-all-the-icons-tab) :extensions ("fortran" "fortran-modern" "fortranfreeform") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "fsharp" :v-adjust 0 :face 'all-the-icons-lblue) treemacs-all-the-icons-tab) :extensions ("fsharp") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "godot" :v-adjust 0 :face 'all-the-icons-dblue) treemacs-all-the-icons-tab) :extensions ("gdscript") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-alltheicon "git" :height 0.85 :v-adjust 0 :face 'all-the-icons-red) treemacs-all-the-icons-tab) :extensions ("gitmodules" "gitconfig" "gitignore" "gitattributes") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "graphql" :v-adjust 0 :face 'all-the-icons-pink) treemacs-all-the-icons-tab) :extensions ("graphql") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "jenkins" :v-adjust 0 :face 'all-the-icons-lsilver) treemacs-all-the-icons-tab) :extensions ("jenkins") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-alltheicon "java" :v-adjust 0 :face 'all-the-icons-orange) treemacs-all-the-icons-tab) :extensions ("jar") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-faicon "balance-scale" :v-adjust 0 :face 'all-the-icons-purple) treemacs-all-the-icons-tab) :extensions ("ledger") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-octicon "key" :v-adjust 0 :face 'all-the-icons-yellow) treemacs-all-the-icons-tab) :extensions ("license") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-material "translate" :v-adjust 0 :face 'all-the-icons-blue) treemacs-all-the-icons-tab) :extensions ("locale") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-material "lock" :v-adjust 0 :face 'all-the-icons-dred) treemacs-all-the-icons-tab) :extensions ("lock") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "gnu" :v-adjust 0 :face 'all-the-icons-dsilver) treemacs-all-the-icons-tab) :extensions ("makefile") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "meson" :v-adjust 0 :face 'all-the-icons-green) treemacs-all-the-icons-tab) :extensions ("meson") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "ocaml" :v-adjust 0 :face 'all-the-icons-lorange) treemacs-all-the-icons-tab) :extensions ("merlin" "ocaml") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-faicon "file-video-o" :v-adjust 0 :face 'all-the-icons-lgreen) treemacs-all-the-icons-tab) :extensions ("avi") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "nginx" :v-adjust 0 :face 'all-the-icons-green) treemacs-all-the-icons-tab) :extensions ("nginx.conf") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "npm" :v-adjust 0 :face 'all-the-icons-red) treemacs-all-the-icons-tab) :extensions ("npmignore" "npmrc" "package.json" "package-lock.json" "npm-shrinwrap.json") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "delphi" :v-adjust 0 :face 'all-the-icons-red) treemacs-all-the-icons-tab) :extensions ("pascal" "objectpascal") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "patch" :v-adjust 0 :face 'all-the-icons-orange) treemacs-all-the-icons-tab) :extensions ("patch") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-alltheicon "perl" :v-adjust 0 :face 'all-the-icons-dblue) treemacs-all-the-icons-tab) :extensions ("perl") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "phpunit" :v-adjust 0 :face 'all-the-icons-blue) treemacs-all-the-icons-tab) :extensions ("phpunit" "phpunit.xml") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-alltheicon "postgresql" :v-adjust 0 :face 'all-the-icons-dblue) treemacs-all-the-icons-tab) :extensions ("pgsql") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "powerpoint" :v-adjust 0 :face 'all-the-icons-orange) treemacs-all-the-icons-tab) :extensions ("pot" "potx" "potm" "ppsx" "ppsm" "pptx" "pptm" "pa" "ppa" "ppam" "sldm" "sldx") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-alltheicon "prolog" :v-adjust 0 :face 'all-the-icons-orange) treemacs-all-the-icons-tab) :extensions ("prolog") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "purescript" :v-adjust 0 :face 'all-the-icons-lblue) treemacs-all-the-icons-tab) :extensions ("purs") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "racket" :v-adjust 0 :face 'all-the-icons-dred) treemacs-all-the-icons-tab) :extensions ("racket" "rktd" "rktl" "scrbl" "scribble" "plt") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "sqlite" :v-adjust 0 :face 'all-the-icons-blue) treemacs-all-the-icons-tab) :extensions ("sqlite" "db3" "sqlite3") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "swagger" :v-adjust 0 :face 'all-the-icons-green) treemacs-all-the-icons-tab) :extensions ("swagger") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-alltheicon "terminal" :v-adjust 0 :face 'all-the-icons-dgreen) treemacs-all-the-icons-tab)
:extensions ("zshrc" "zshenv" "zprofile" "zlogin" "zlogout" "bash"
"bash_profile" "bash_login" "profile" "bash_aliases")
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "tsx-alt" :v-adjust 0 :face 'all-the-icons-lgreen) treemacs-all-the-icons-tab) :extensions ("tsx") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "excel" :v-adjust 0 :face 'all-the-icons-green) treemacs-all-the-icons-tab) :extensions ("ods" "fods") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "wasm" :v-adjust 0 :face 'all-the-icons-lpurple) treemacs-all-the-icons-tab) :extensions ("wasm" "wat") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-faicon "font" :v-adjust 0 :face 'all-the-icons-lsilver) treemacs-all-the-icons-tab) :extensions ("ttf" "otf" "eot" "pfa" "pfb" "sfd") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-material "code" :v-adjust 0 :face 'all-the-icons-lpurple) treemacs-all-the-icons-tab) :extensions ("xsl") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-fileicon "yarn" :v-adjust 0 :face 'all-the-icons-dblue) treemacs-all-the-icons-tab) :extensions ("yarn.lock" "yarnrc" "yarnclean" "yarn-integrity" "yarn-metadata.json" "yarnignore") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-octicon "file-media" :v-adjust 0 :face 'all-the-icons-orange) treemacs-all-the-icons-tab)
:extensions ("tif" "tiff" "bmp" "psd" "ai" "eps" "indd") :fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-octicon "file-code" :v-adjust 0 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions ("cask" "ideavimrc" "inputrc"
"toml" "tridactylrc" "vh" "vimperatorrc"
"vimrc" "vrapperrc")
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-octicon "book" :v-adjust 0 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions ("lrf" "lrx" "cbr" "cbz" "cb7" "cbt" "cba" "chm" "djvu"
"doc" "docx" "pdb" "pdb" "fb2" "xeb" "ceb" "inf" "azw"
"azw3" "kf8" "kfx" "lit" "prc" "mobi" "exe" "or"
"pkg" "opf" "txt" "pdb" "ps" "rtf" "pdg" "xml" "tr2"
"tr3" "oxps" "xps")
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-octicon "file-text" :v-adjust 0 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions ("markdown" "rst" "CONTRIBUTE" "LICENSE" "README" "CHANGELOG")
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-octicon "file-binary" :v-adjust 0 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions ("class" "exe" "obj" "so" "o" "out" "pyc")
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-octicon "file-zip" :v-adjust 0 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions ("tar" "rar" "tgz")
:fallback 'same-as-icon)
(treemacs-create-icon :icon (format " %s%s" (all-the-icons-octicon "file-text" :v-adjust 0 :face 'treemacs-all-the-icons-file-face) treemacs-all-the-icons-tab)
:extensions (fallback)
:fallback 'same-as-icon)))
(provide 'treemacs-all-the-icons)
;;; treemacs-all-the-icons.el ends here
``` | /content/code_sandbox/src/extra/treemacs-all-the-icons.el | emacs lisp | 2016-07-17T21:13:35 | 2024-08-16T10:41:21 | treemacs | Alexander-Miller/treemacs | 2,068 | 6,804 |
```javascript
const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-react', '@babel/preset-env']
}
}
},
{
test: /\.scss$/,
loader: 'style-loader!css-loader!sass-loader'
}
]
},
plugins: [
new MiniCssExtractPlugin({ filename: 'style.css'})
]
}
``` | /content/code_sandbox/webpack.config.js | javascript | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 166 |
```javascript
/* global document */
import React from 'react'
import { render } from 'react-dom'
import DownloadPanel from './components/DownloadPanel'
import './stylesheets/shared.scss'
render(
<DownloadPanel />,
document.getElementById('app')
)
``` | /content/code_sandbox/src/main.js | javascript | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 51 |
```javascript
#!/usr/bin/env node
const http = require('http')
const querystring = require('querystring')
const postData = querystring.stringify({
'url': 'path_to_url
})
const req = http.request(
{
host: 'localhost',
port: '3000',
path: '/download',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
},
(res) => {
const { statusCode } = res
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`)
})
res.on('end', () => {
console.log('No more data in response.')
if (statusCode !== 200) {
console.log(`Got status ${statusCode}`)
process.exit(1)
}
console.log('Yay it works')
})
}
).on('error', (e) => {
console.error(`Got error: ${e.message}`)
process.exit(1)
})
req.write(postData)
req.end()
``` | /content/code_sandbox/test/e2e.js | javascript | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 234 |
```javascript
/* global localStorage */
function getItem (key) {
return JSON.parse(localStorage.getItem(key))
}
function setItem (key, value) {
localStorage.setItem(key, JSON.stringify(value))
}
function removeItem (key) {
localStorage.removeItem(key)
}
module.exports = {
getItem,
setItem,
removeItem
}
``` | /content/code_sandbox/src/javascripts/localStorage.js | javascript | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 68 |
```scss
@import "./shared";
.downloadPanel {
align-content: center;
align-items: flex-center;
display: flex;
flex-wrap: wrap;
height: 100vh;
justify-content: center;
padding: 0 20px;
}
``` | /content/code_sandbox/src/stylesheets/DownloadPanel.scss | scss | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 56 |
```scss
@import './shared';
.downloadForm {
align-items: center;
display: flex;
justify-content: center;
width: 100%;
&__input {
@include makePanel();
appearance: none;
flex: 0 1 500px;
font-size: 16px;
height: 20px;
margin-right: 10px;
padding: 10px;
&--error {
border: 1px solid $accent_primary;
color: $accent_primary;
}
}
&__btn {
@include makePanel();
background-color: $accent_primary;
color: $text_primary;
flex: 0 0 70px;
font-family: 'Open Sans', sans-serif;
font-size: 18px;
height: 40px;
padding-bottom: 3px;
outline: none;
&:active {
background-color: darken($accent_primary, 10%);
}
}
}
``` | /content/code_sandbox/src/stylesheets/DownloadForm.scss | scss | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 214 |
```javascript
/* global XMLHttpRequest */
function get (url) {
// Return a new promise.
return new Promise((resolve, reject) => {
// Do the usual XHR stuff
const req = new XMLHttpRequest()
req.open('GET', url)
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
req.onload = () => {
// This is called even on 404 etc
// so check the status
if (req.status === 200) {
// Resolve the promise with the response text
resolve(JSON.parse(req.response))
} else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText))
}
}
// Handle network errors
req.onerror = () => {
reject(Error('Network Error'))
}
// Make the request
req.send()
})
}
function post (url, params) {
// Return a new promise.
return new Promise((resolve, reject) => {
// Do the usual XHR stuff
const req = new XMLHttpRequest()
req.open('POST', url)
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
req.onload = () => {
// This is called even on 404 etc
// so check the status
if (req.status === 200) {
// Resolve the promise with the response text
resolve(JSON.parse(req.response))
} else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText))
}
}
// Handle network errors
req.onerror = () => {
reject(Error('Network Error'))
}
// Make the request
req.send(params)
})
}
module.exports = {
get,
post
}
``` | /content/code_sandbox/src/javascripts/helpers.js | javascript | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 383 |
```scss
@import "./shared";
.downloadList {
@include makePanel();
background: $background_secondary;
display: flex;
flex: 0 1 600px;
flex-wrap: wrap;
list-style-type: none;
margin-top: 20px;
max-height: 80%;
overflow-y: auto;
position:relative;
&__item {
display: flex;
flex: 1 0 300px;
padding: 10px;
width: 100%;
}
&__clear {
background: $background_secondary;
border-top: 1px solid $background_primary;
color: $text-secondary;
padding: 5px;
text-align: center;
width: 100%;
&:hover {
background: darken($background_secondary, 2%);
cursor: pointer;
}
}
&::-webkit-scrollbar {
width: 8px;
}
&::-webkit-scrollbar-track {
background: $background_secondary;
}
&::-webkit-scrollbar-thumb {
background: darken($background_primary, 2%);
}
}
.video {
&__name {
color: $text-secondary;
word-break: break-all;
word-wrap: break-word;
}
&__link {
font-size: 14px;
margin-left: auto;
a {
color: $text-secondary;
text-decoration: none;
&:hover {
text-decoration: underline;
}
&:visited {
color: $text-secondary;
}
}
}
}
``` | /content/code_sandbox/src/stylesheets/DownloadList.scss | scss | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 334 |
```javascript
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import '../stylesheets/DownloadForm.scss'
class DownloadForm extends Component {
componentDidMount () {
}
render () {
return (
<form className='downloadForm' onSubmit={this.props.onSubmit}>
<input className='downloadForm__input' type='text' />
<button className='downloadForm__btn'></button>
</form>
)
}
}
DownloadForm.propTypes = {
onSubmit: PropTypes.func
}
export default DownloadForm
``` | /content/code_sandbox/src/components/DownloadForm.js | javascript | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 113 |
```scss
@import url(path_to_url
$accent_primary: #cc181e;
$text_primary: #eeffff;
$text_secondary: #d3d0c8;
$background_primary: #202530;
$background_secondary: #2f343f;
@mixin makePanel() {
border: none;
border-radius: 2px;
box-shadow: 0 0 5px rgb(40,40,40);
outline: none;
}
* {
margin: 0;
padding: 0;
}
body {
background: $background_primary;
color: $text_primary;
font-family: 'Open Sans', sans-serif;
}
.spinner {
margin-left: auto;
margin-top: -3px;
text-align: center;
width: 60px;
}
.spinner > div {
animation: sk-bouncedelay 1.4s infinite ease-in-out both;
background-color: $text_secondary;
border-radius: 100%;
display: inline-block;
height: 8px;
margin-left: 5px;
width: 8px;
}
.spinner .bounce1 {
animation-delay: -0.32s;
}
.spinner .bounce2 {
animation-delay: -0.16s;
}
@keyframes sk-bouncedelay {
0%, 80%, 100% {
transform: scale(0);
} 40% {
transform: scale(1.0);
}
}
``` | /content/code_sandbox/src/stylesheets/shared.scss | scss | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 312 |
```javascript
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import '../stylesheets/DownloadList.scss'
class DownloadList extends Component {
componentDidMount () {
}
render () {
return (
<ul className='downloadList'>
{this.props.videos.map((video, index) =>
<li key={index} className='downloadList__item'>
<span className='video__name'>{video.name}</span>
{video.downloading
? (
<div className='spinner'>
<div className='bounce1' />
<div className='bounce2' />
<div className='bounce3' />
</div>
) : (
<span className='video__link'>
<a
onClick={this.props.onVideoDownloadClick}
data-orig={video.url}
href={`/request/${video.name}.${video.format}`}
download={`${video.name}.${video.format}`}
>Download</a>
</span>
)
}
</li>
)}
{this.props.videos.length === 0
? '' : <li className='downloadList__clear' onClick={this.props.onClearClick}>Clear all</li>
}
</ul>
)
}
}
DownloadList.propTypes = {
videos: PropTypes.array,
onClearClick: PropTypes.func,
onVideoDownloadClick: PropTypes.func
}
export default DownloadList
``` | /content/code_sandbox/src/components/DownloadList.js | javascript | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 299 |
```javascript
/* global document */
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { isURL } from 'validator'
import DownloadForm from './DownloadForm'
import DownloadList from './DownloadList'
import { post } from '../javascripts/helpers'
import localStorage from '../javascripts/localStorage'
import '../stylesheets/DownloadPanel.scss'
class DownloadPanel extends Component {
constructor (props) {
super(props)
console.log(localStorage.getItem('videos'))
const storedVideos = localStorage.getItem('videos')
this.state = { videos: storedVideos || [] }
this.handleSubmit = this.handleSubmit.bind(this)
this.handleClearClick = this.handleClearClick.bind(this)
this.handleVideoDownloadClick = this.handleVideoDownloadClick.bind(this)
}
handleClearClick () {
this.setState({ videos: [] })
localStorage.removeItem('videos')
}
handleVideoDownloadClick (e) {
const videos = this.state.videos
const videoUrl = e.target.getAttribute('data-orig')
const updatedVideos = videos.filter(video => video.url !== videoUrl)
this.setState({ videos: updatedVideos })
// Can't use this.state.videos because this is bound to the function
localStorage.setItem('videos', updatedVideos)
}
handleSubmit (e) {
e.preventDefault()
const urlInput = document.querySelector('.downloadForm__input')
const url = urlInput.value
if (url.length === 0) {
return
}
urlInput.value = ''
if (!isURL(url)) {
urlInput.classList.add('downloadForm__input--error')
urlInput.placeholder = 'Invalid URL'
setTimeout(() => {
urlInput.classList.remove('downloadForm__input--error')
urlInput.placeholder = ''
}, 2000)
return
}
// Provide instant feedback by adding as much as we know to state
let videos = this.state.videos
this.setState({ videos: [{
name: url,
url,
downloading: true
}, ...videos] })
post('/download', `url=${url}`).then(newVideo => {
videos = this.state.videos
const updatedVideos = videos.map(video =>
(video.url === newVideo.url ? Object.assign({}, video, newVideo) : video)
)
this.setState({ videos: updatedVideos })
localStorage.setItem('videos', this.state.videos)
}, error => {
console.log('Failed!', error)
})
}
render () {
return (
<div className='downloadPanel'>
<DownloadForm onSubmit={this.handleSubmit} />
<DownloadList
videos={this.state.videos}
onClearClick={this.handleClearClick}
onVideoDownloadClick={this.handleVideoDownloadClick}
/>
</div>
)
}
}
export default DownloadPanel
``` | /content/code_sandbox/src/components/DownloadPanel.js | javascript | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 599 |
```javascript
const Hapi = require('@hapi/hapi')
const Inert = require('@hapi/inert')
const mkdirp = require('mkdirp')
const path = require('path')
const youtube = require('./handlers/youtube')
const server = new Hapi.Server({
port: process.env.PORT || 3000,
routes: {
files: {
relativeTo: path.join(__dirname, '../../public')
}
}
})
const provision = async () => {
await server.register(Inert)
// TODO add notifications to app
// TODO remove duplicate downloads from ui
server.route({
method: 'GET',
path: '/{path*}',
handler: {
directory: {
path: '.',
listing: false,
index: true
}
}
})
server.route({
method: 'POST',
path: '/download',
handler: (request) => {
const url = request.payload.url
const options = {
path: path.join(__dirname, '../../public/temp'),
audioOnly: true
}
mkdirp(options.path, err => {
if (err) {
throw err
}
})
return youtube.download(url, options)
}
})
server.route({
method: 'GET',
path: '/request/{video}',
handler: (request, h) => {
const videoName = encodeURIComponent(request.params.video)
return h.file(path.join('temp', decodeURIComponent(videoName)))
}
})
await server.start()
console.log('Server running at:', server.info.uri)
}
provision()
``` | /content/code_sandbox/src/server/server.js | javascript | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 339 |
```javascript
const path = require('path')
const fs = require('fs')
const ffmpeg = require('fluent-ffmpeg')
const youtubeDl = require('@microlink/youtube-dl')
function exists (filename, cb) {
fs.access(filename, fs.F_OK, (err) => {
if (!err) {
cb(true)
} else {
cb(false)
}
})
}
function download (url, options = {
path: 'downloads',
audioOnly: false
}) {
return new Promise((resolve, reject) => {
let format = 'mp4'
if (options.audioOnly) {
format = 'mp3'
}
// TODO Add proper support for options
const video = youtubeDl(url,
// Optional arguments passed to youtube-dl.
['--format=18'],
// Additional options can be given for calling `child_process.execFile()`.
{ cwd: __dirname, maxBuffer: Infinity })
// Will be called when the download starts.
video.on('info', info => {
let filename = info._filename
filename = filename
.replace('.mp4', '')
.substring(0, filename.length - 16)
const filePath = path.join(options.path, `${filename}.${format}`)
exists(filePath, (doesExist) => {
const videoObj = {
name: filename,
url,
downloading: false,
format
}
if (!doesExist) {
// Convert to audio
ffmpeg({ source: video })
.on('end', () => {
resolve(videoObj)
})
.toFormat(format)
.save(filePath)
} else {
resolve(videoObj)
}
})
})
})
}
module.exports = {
download
}
``` | /content/code_sandbox/src/server/handlers/youtube.js | javascript | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 380 |
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ytdl - Webserver</title>
</head>
<body>
<div id="app"></div>
<script src="bundle.js"></script>
</body>
</html>
``` | /content/code_sandbox/public/index.html | html | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 82 |
```javascript
/******/ (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] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = 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;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(34);
var _DownloadPanel = __webpack_require__(172);
var _DownloadPanel2 = _interopRequireDefault(_DownloadPanel);
__webpack_require__(249);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* global document */
(0, _reactDom.render)(_react2.default.createElement(_DownloadPanel2.default, null), document.getElementById('app'));
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(2);
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule React
*/
'use strict';
var _assign = __webpack_require__(4);
var ReactChildren = __webpack_require__(5);
var ReactComponent = __webpack_require__(17);
var ReactPureComponent = __webpack_require__(20);
var ReactClass = __webpack_require__(21);
var ReactDOMFactories = __webpack_require__(26);
var ReactElement = __webpack_require__(9);
var ReactPropTypes = __webpack_require__(31);
var ReactVersion = __webpack_require__(32);
var onlyChild = __webpack_require__(33);
var warning = __webpack_require__(11);
var createElement = ReactElement.createElement;
var createFactory = ReactElement.createFactory;
var cloneElement = ReactElement.cloneElement;
if (process.env.NODE_ENV !== 'production') {
var ReactElementValidator = __webpack_require__(27);
createElement = ReactElementValidator.createElement;
createFactory = ReactElementValidator.createFactory;
cloneElement = ReactElementValidator.cloneElement;
}
var __spread = _assign;
if (process.env.NODE_ENV !== 'production') {
var warned = false;
__spread = function () {
process.env.NODE_ENV !== 'production' ? warning(warned, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See path_to_url for more details.') : void 0;
warned = true;
return _assign.apply(null, arguments);
};
}
var React = {
// Modern
Children: {
map: ReactChildren.map,
forEach: ReactChildren.forEach,
count: ReactChildren.count,
toArray: ReactChildren.toArray,
only: onlyChild
},
Component: ReactComponent,
PureComponent: ReactPureComponent,
createElement: createElement,
cloneElement: cloneElement,
isValidElement: ReactElement.isValidElement,
// Classic
PropTypes: ReactPropTypes,
createClass: ReactClass.createClass,
createFactory: createFactory,
createMixin: function (mixin) {
// Currently a noop. Will be used to validate and trace mixins.
return mixin;
},
// This looks DOM specific but these are actually isomorphic helpers
// since they are just generating DOM strings.
DOM: ReactDOMFactories,
version: ReactVersion,
// Deprecated hook for JSX spread, don't use this for anything.
__spread: __spread
};
module.exports = React;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 3 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
(function () {
try {
cachedSetTimeout = setTimeout;
} catch (e) {
cachedSetTimeout = function () {
throw new Error('setTimeout is not defined');
}
}
try {
cachedClearTimeout = clearTimeout;
} catch (e) {
cachedClearTimeout = function () {
throw new Error('clearTimeout is not defined');
}
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ },
/* 4 */
/***/ function(module, exports) {
'use strict';
/* eslint-disable no-unused-vars */
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// path_to_url
var test1 = new String('abc'); // eslint-disable-line
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// path_to_url
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// path_to_url
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (e) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (Object.getOwnPropertySymbols) {
symbols = Object.getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactChildren
*/
'use strict';
var PooledClass = __webpack_require__(6);
var ReactElement = __webpack_require__(9);
var emptyFunction = __webpack_require__(12);
var traverseAllChildren = __webpack_require__(14);
var twoArgumentPooler = PooledClass.twoArgumentPooler;
var fourArgumentPooler = PooledClass.fourArgumentPooler;
var userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text) {
return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/');
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* traversal. Allows avoiding binding callbacks.
*
* @constructor ForEachBookKeeping
* @param {!function} forEachFunction Function to perform traversal with.
* @param {?*} forEachContext Context to perform context with.
*/
function ForEachBookKeeping(forEachFunction, forEachContext) {
this.func = forEachFunction;
this.context = forEachContext;
this.count = 0;
}
ForEachBookKeeping.prototype.destructor = function () {
this.func = null;
this.context = null;
this.count = 0;
};
PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
function forEachSingleChild(bookKeeping, child, name) {
var func = bookKeeping.func;
var context = bookKeeping.context;
func.call(context, child, bookKeeping.count++);
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* See path_to_url#react.children.foreach
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
if (children == null) {
return children;
}
var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
traverseAllChildren(children, forEachSingleChild, traverseContext);
ForEachBookKeeping.release(traverseContext);
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* mapping. Allows avoiding binding callbacks.
*
* @constructor MapBookKeeping
* @param {!*} mapResult Object containing the ordered map of results.
* @param {!function} mapFunction Function to perform mapping with.
* @param {?*} mapContext Context to perform mapping with.
*/
function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) {
this.result = mapResult;
this.keyPrefix = keyPrefix;
this.func = mapFunction;
this.context = mapContext;
this.count = 0;
}
MapBookKeeping.prototype.destructor = function () {
this.result = null;
this.keyPrefix = null;
this.func = null;
this.context = null;
this.count = 0;
};
PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler);
function mapSingleChildIntoContext(bookKeeping, child, childKey) {
var result = bookKeeping.result;
var keyPrefix = bookKeeping.keyPrefix;
var func = bookKeeping.func;
var context = bookKeeping.context;
var mappedChild = func.call(context, child, bookKeeping.count++);
if (Array.isArray(mappedChild)) {
mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument);
} else if (mappedChild != null) {
if (ReactElement.isValidElement(mappedChild)) {
mappedChild = ReactElement.cloneAndReplaceKey(mappedChild,
// Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey);
}
result.push(mappedChild);
}
}
function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
var escapedPrefix = '';
if (prefix != null) {
escapedPrefix = escapeUserProvidedKey(prefix) + '/';
}
var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context);
traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
MapBookKeeping.release(traverseContext);
}
/**
* Maps children that are typically specified as `props.children`.
*
* See path_to_url#react.children.map
*
* The provided mapFunction(child, key, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, func, context);
return result;
}
function forEachSingleChildDummy(traverseContext, child, name) {
return null;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* See path_to_url#react.children.count
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children, context) {
return traverseAllChildren(children, forEachSingleChildDummy, null);
}
/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*
* See path_to_url#react.children.toarray
*/
function toArray(children) {
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument);
return result;
}
var ReactChildren = {
forEach: forEachChildren,
map: mapChildren,
mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal,
count: countChildren,
toArray: toArray
};
module.exports = ReactChildren;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule PooledClass
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
/**
* Static poolers. Several custom versions for each potential number of
* arguments. A completely generic pooler is easy to implement, but would
* require accessing the `arguments` object. In each of these, `this` refers to
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
var oneArgumentPooler = function (copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
};
var twoArgumentPooler = function (a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
var threeArgumentPooler = function (a1, a2, a3) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3);
return instance;
} else {
return new Klass(a1, a2, a3);
}
};
var fourArgumentPooler = function (a1, a2, a3, a4) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4);
return instance;
} else {
return new Klass(a1, a2, a3, a4);
}
};
var fiveArgumentPooler = function (a1, a2, a3, a4, a5) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4, a5);
return instance;
} else {
return new Klass(a1, a2, a3, a4, a5);
}
};
var standardReleaser = function (instance) {
var Klass = this;
!(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0;
instance.destructor();
if (Klass.instancePool.length < Klass.poolSize) {
Klass.instancePool.push(instance);
}
};
var DEFAULT_POOL_SIZE = 10;
var DEFAULT_POOLER = oneArgumentPooler;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
* you give this may have a `poolSize` property, and will look for a
* prototypical `destructor` on instances.
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
var addPoolingTo = function (CopyConstructor, pooler) {
var NewKlass = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
};
var PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: oneArgumentPooler,
twoArgumentPooler: twoArgumentPooler,
threeArgumentPooler: threeArgumentPooler,
fourArgumentPooler: fourArgumentPooler,
fiveArgumentPooler: fiveArgumentPooler
};
module.exports = PooledClass;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 7 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule reactProdInvariant
*
*/
'use strict';
/**
* WARNING: DO NOT manually require this module.
* This is a replacement for `invariant(...)` used by the error code system
* and will _only_ be required by the corresponding babel pass.
* It always throws.
*/
function reactProdInvariant(code) {
var argCount = arguments.length - 1;
var message = 'Minified React error #' + code + '; visit ' + 'path_to_url + code;
for (var argIdx = 0; argIdx < argCount; argIdx++) {
message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]);
}
message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.';
var error = new Error(message);
error.name = 'Invariant Violation';
error.framesToPop = 1; // we don't care about reactProdInvariant's own frame
throw error;
}
module.exports = reactProdInvariant;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if (process.env.NODE_ENV !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactElement
*/
'use strict';
var _assign = __webpack_require__(4);
var ReactCurrentOwner = __webpack_require__(10);
var warning = __webpack_require__(11);
var canDefineProperty = __webpack_require__(13);
var hasOwnProperty = Object.prototype.hasOwnProperty;
// The Symbol used to tag the ReactElement type. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
var specialPropKeyWarningShown, specialPropRefWarningShown;
function hasValidRef(config) {
if (process.env.NODE_ENV !== 'production') {
if (hasOwnProperty.call(config, 'ref')) {
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.ref !== undefined;
}
function hasValidKey(config) {
if (process.env.NODE_ENV !== 'production') {
if (hasOwnProperty.call(config, 'key')) {
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.key !== undefined;
}
function defineKeyPropWarningGetter(props, displayName) {
var warnAboutAccessingKey = function () {
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
process.env.NODE_ENV !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (path_to_url displayName) : void 0;
}
};
warnAboutAccessingKey.isReactWarning = true;
Object.defineProperty(props, 'key', {
get: warnAboutAccessingKey,
configurable: true
});
}
function defineRefPropWarningGetter(props, displayName) {
var warnAboutAccessingRef = function () {
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
process.env.NODE_ENV !== 'production' ? warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (path_to_url displayName) : void 0;
}
};
warnAboutAccessingRef.isReactWarning = true;
Object.defineProperty(props, 'ref', {
get: warnAboutAccessingRef,
configurable: true
});
}
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, no instanceof check
* will work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} key
* @param {string|object} ref
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @param {*} owner
* @param {*} props
* @internal
*/
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allow us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
if (process.env.NODE_ENV !== 'production') {
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {};
var shadowChildren = Array.isArray(props.children) ? props.children.slice(0) : props.children;
// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
if (canDefineProperty) {
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
});
// self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
});
Object.defineProperty(element, '_shadowChildren', {
configurable: false,
enumerable: false,
writable: false,
value: shadowChildren
});
// Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
} else {
element._store.validated = false;
element._self = self;
element._shadowChildren = shadowChildren;
element._source = source;
}
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
};
/**
* Create and return a new ReactElement of the given type.
* See path_to_url#react.createelement
*/
ReactElement.createElement = function (type, config, children) {
var propName;
// Reserved names are extracted
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
if (config != null) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(
/* eslint-disable no-proto */
config.__proto__ == null || config.__proto__ === Object.prototype,
/* eslint-enable no-proto */
'React.createElement(...): Expected props argument to be a plain object. ' + 'Properties defined in its prototype chain will be ignored.') : void 0;
}
if (hasValidRef(config)) {
ref = config.ref;
}
if (hasValidKey(config)) {
key = '' + config.key;
}
self = config.__self === undefined ? null : config.__self;
source = config.__source === undefined ? null : config.__source;
// Remaining properties are added to a new props object
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
// Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
if (process.env.NODE_ENV !== 'production') {
if (key || ref) {
if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) {
var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
if (key) {
defineKeyPropWarningGetter(props, displayName);
}
if (ref) {
defineRefPropWarningGetter(props, displayName);
}
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
};
/**
* Return a function that produces ReactElements of a given type.
* See path_to_url#react.createfactory
*/
ReactElement.createFactory = function (type) {
var factory = ReactElement.createElement.bind(null, type);
// Expose the type on the factory and the prototype so that it can be
// easily accessed on elements. E.g. `<Foo />.type === Foo`.
// This should not be named `constructor` since this may not be the function
// that created the element, and it may not even be a constructor.
// Legacy hook TODO: Warn if this is accessed
factory.type = type;
return factory;
};
ReactElement.cloneAndReplaceKey = function (oldElement, newKey) {
var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
return newElement;
};
/**
* Clone and return a new ReactElement using element as the starting point.
* See path_to_url#react.cloneelement
*/
ReactElement.cloneElement = function (element, config, children) {
var propName;
// Original props are copied
var props = _assign({}, element.props);
// Reserved names are extracted
var key = element.key;
var ref = element.ref;
// Self is preserved since the owner is preserved.
var self = element._self;
// Source is preserved since cloneElement is unlikely to be targeted by a
// transpiler, and the original source is probably a better indicator of the
// true owner.
var source = element._source;
// Owner will be preserved, unless ref is overridden
var owner = element._owner;
if (config != null) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(
/* eslint-disable no-proto */
config.__proto__ == null || config.__proto__ === Object.prototype,
/* eslint-enable no-proto */
'React.cloneElement(...): Expected props argument to be a plain object. ' + 'Properties defined in its prototype chain will be ignored.') : void 0;
}
if (hasValidRef(config)) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (hasValidKey(config)) {
key = '' + config.key;
}
// Remaining properties override existing props
var defaultProps;
if (element.type && element.type.defaultProps) {
defaultProps = element.type.defaultProps;
}
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
if (config[propName] === undefined && defaultProps !== undefined) {
// Resolve default props
props[propName] = defaultProps[propName];
} else {
props[propName] = config[propName];
}
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
};
/**
* Verifies the object is a ReactElement.
* See path_to_url#react.isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a valid component.
* @final
*/
ReactElement.isValidElement = function (object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
};
ReactElement.REACT_ELEMENT_TYPE = REACT_ELEMENT_TYPE;
module.exports = ReactElement;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 10 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactCurrentOwner
*/
'use strict';
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
module.exports = ReactCurrentOwner;
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var emptyFunction = __webpack_require__(12);
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
(function () {
var printWarning = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning = function warning(condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
})();
}
module.exports = warning;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 12 */
/***/ function(module, exports) {
"use strict";
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule canDefineProperty
*/
'use strict';
var canDefineProperty = false;
if (process.env.NODE_ENV !== 'production') {
try {
Object.defineProperty({}, 'x', { get: function () {} });
canDefineProperty = true;
} catch (x) {
// IE will fail on defineProperty
}
}
module.exports = canDefineProperty;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule traverseAllChildren
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactCurrentOwner = __webpack_require__(10);
var ReactElement = __webpack_require__(9);
var getIteratorFn = __webpack_require__(15);
var invariant = __webpack_require__(8);
var KeyEscapeUtils = __webpack_require__(16);
var warning = __webpack_require__(11);
var SEPARATOR = '.';
var SUBSEPARATOR = ':';
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var didWarnAboutMaps = false;
/**
* Generate a key string that identifies a component within a set.
*
* @param {*} component A component that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getComponentKey(component, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (component && typeof component === 'object' && component.key != null) {
// Explicit key
return KeyEscapeUtils.escape(component.key);
}
// Implicit key determined by the index in the set
return index.toString(36);
}
/**
* @param {?*} children Children tree container.
* @param {!string} nameSoFar Name of the key path so far.
* @param {!function} callback Callback to invoke with each child found.
* @param {?*} traverseContext Used to pass information throughout the traversal
* process.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) {
callback(traverseContext, children,
// If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows.
nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getComponentKey(child, i);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
var iteratorFn = getIteratorFn(children);
if (iteratorFn) {
var iterator = iteratorFn.call(children);
var step;
if (iteratorFn !== children.entries) {
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getComponentKey(child, ii++);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
if (process.env.NODE_ENV !== 'production') {
var mapsAsChildrenAddendum = '';
if (ReactCurrentOwner.current) {
var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName();
if (mapsAsChildrenOwnerName) {
mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.';
}
}
process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0;
didWarnAboutMaps = true;
}
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
child = entry[1];
nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
}
}
} else if (type === 'object') {
var addendum = '';
if (process.env.NODE_ENV !== 'production') {
addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.';
if (children._isReactElement) {
addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.';
}
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
addendum += ' Check the render method of `' + name + '`.';
}
}
}
var childrenString = String(children);
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0;
}
}
return subtreeCount;
}
/**
* Traverses children that are typically specified as `props.children`, but
* might also be specified through attributes:
*
* - `traverseAllChildren(this.props.children, ...)`
* - `traverseAllChildren(this.props.leftPanelChildren, ...)`
*
* The `traverseContext` is an optional argument that is passed through the
* entire traversal. It can be used to store accumulations or anything else that
* the callback might find relevant.
*
* @param {?*} children Children tree object.
* @param {!function} callback To invoke upon traversing each child.
* @param {?*} traverseContext Context for traversal.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildren(children, callback, traverseContext) {
if (children == null) {
return 0;
}
return traverseAllChildrenImpl(children, '', callback, traverseContext);
}
module.exports = traverseAllChildren;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 15 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getIteratorFn
*
*/
'use strict';
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
module.exports = getIteratorFn;
/***/ },
/* 16 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule KeyEscapeUtils
*
*/
'use strict';
/**
* Escape and wrap key so it is safe to use as a reactid
*
* @param {string} key to be escaped.
* @return {string} the escaped key.
*/
function escape(key) {
var escapeRegex = /[=:]/g;
var escaperLookup = {
'=': '=0',
':': '=2'
};
var escapedString = ('' + key).replace(escapeRegex, function (match) {
return escaperLookup[match];
});
return '$' + escapedString;
}
/**
* Unescape and unwrap key for human-readable display
*
* @param {string} key to unescape.
* @return {string} the unescaped key.
*/
function unescape(key) {
var unescapeRegex = /(=0|=2)/g;
var unescaperLookup = {
'=0': '=',
'=2': ':'
};
var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1);
return ('' + keySubstring).replace(unescapeRegex, function (match) {
return unescaperLookup[match];
});
}
var KeyEscapeUtils = {
escape: escape,
unescape: unescape
};
module.exports = KeyEscapeUtils;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponent
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactNoopUpdateQueue = __webpack_require__(18);
var canDefineProperty = __webpack_require__(13);
var emptyObject = __webpack_require__(19);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
/**
* Base class helpers for the updating state of a component.
*/
function ReactComponent(props, context, updater) {
this.props = props;
this.context = context;
this.refs = emptyObject;
// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
ReactComponent.prototype.isReactComponent = {};
/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
ReactComponent.prototype.setState = function (partialState, callback) {
!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0;
this.updater.enqueueSetState(this, partialState);
if (callback) {
this.updater.enqueueCallback(this, callback, 'setState');
}
};
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
ReactComponent.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this);
if (callback) {
this.updater.enqueueCallback(this, callback, 'forceUpdate');
}
};
/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
if (process.env.NODE_ENV !== 'production') {
var deprecatedAPIs = {
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'path_to_url
};
var defineDeprecationWarning = function (methodName, info) {
if (canDefineProperty) {
Object.defineProperty(ReactComponent.prototype, methodName, {
get: function () {
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : void 0;
return undefined;
}
});
}
};
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
module.exports = ReactComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNoopUpdateQueue
*/
'use strict';
var warning = __webpack_require__(11);
function warnNoop(publicInstance, callerName) {
if (process.env.NODE_ENV !== 'production') {
var constructor = publicInstance.constructor;
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0;
}
}
/**
* This is the abstract API for an update queue.
*/
var ReactNoopUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
return false;
},
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @internal
*/
enqueueCallback: function (publicInstance, callback) {},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
enqueueForceUpdate: function (publicInstance) {
warnNoop(publicInstance, 'forceUpdate');
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState) {
warnNoop(publicInstance, 'replaceState');
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @internal
*/
enqueueSetState: function (publicInstance, partialState) {
warnNoop(publicInstance, 'setState');
}
};
module.exports = ReactNoopUpdateQueue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var emptyObject = {};
if (process.env.NODE_ENV !== 'production') {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPureComponent
*/
'use strict';
var _assign = __webpack_require__(4);
var ReactComponent = __webpack_require__(17);
var ReactNoopUpdateQueue = __webpack_require__(18);
var emptyObject = __webpack_require__(19);
/**
* Base class helpers for the updating state of a component.
*/
function ReactPureComponent(props, context, updater) {
// Duplicated from ReactComponent.
this.props = props;
this.context = context;
this.refs = emptyObject;
// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
function ComponentDummy() {}
ComponentDummy.prototype = ReactComponent.prototype;
ReactPureComponent.prototype = new ComponentDummy();
ReactPureComponent.prototype.constructor = ReactPureComponent;
// Avoid an extra prototype jump for these methods.
_assign(ReactPureComponent.prototype, ReactComponent.prototype);
ReactPureComponent.prototype.isPureReactComponent = true;
module.exports = ReactPureComponent;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactClass
*/
'use strict';
var _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var ReactComponent = __webpack_require__(17);
var ReactElement = __webpack_require__(9);
var ReactPropTypeLocations = __webpack_require__(22);
var ReactPropTypeLocationNames = __webpack_require__(24);
var ReactNoopUpdateQueue = __webpack_require__(18);
var emptyObject = __webpack_require__(19);
var invariant = __webpack_require__(8);
var keyMirror = __webpack_require__(23);
var keyOf = __webpack_require__(25);
var warning = __webpack_require__(11);
var MIXINS_KEY = keyOf({ mixins: null });
/**
* Policies that describe methods in `ReactClassInterface`.
*/
var SpecPolicy = keyMirror({
/**
* These methods may be defined only once by the class specification or mixin.
*/
DEFINE_ONCE: null,
/**
* These methods may be defined by both the class specification and mixins.
* Subsequent definitions will be chained. These methods must return void.
*/
DEFINE_MANY: null,
/**
* These methods are overriding the base class.
*/
OVERRIDE_BASE: null,
/**
* These methods are similar to DEFINE_MANY, except we assume they return
* objects. We try to merge the keys of the return values of all the mixed in
* functions. If there is a key conflict we throw.
*/
DEFINE_MANY_MERGED: null
});
var injectedMixins = [];
/**
* Composite components are higher-level components that compose other composite
* or host components.
*
* To create a new type of `ReactClass`, pass a specification of
* your new class to `React.createClass`. The only requirement of your class
* specification is that you implement a `render` method.
*
* var MyComponent = React.createClass({
* render: function() {
* return <div>Hello World</div>;
* }
* });
*
* The class specification supports a specific protocol of methods that have
* special meaning (e.g. `render`). See `ReactClassInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will be available on the prototype.
*
* @interface ReactClassInterface
* @internal
*/
var ReactClassInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: SpecPolicy.DEFINE_MANY,
/**
* An object containing properties and methods that should be defined on
* the component's constructor instead of its prototype (static methods).
*
* @type {object}
* @optional
*/
statics: SpecPolicy.DEFINE_MANY,
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: SpecPolicy.DEFINE_MANY,
// ==== Definition methods ====
/**
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
*
* @return {object}
* @optional
*/
getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: SpecPolicy.DEFINE_MANY_MERGED,
/**
* @return {object}
* @optional
*/
getChildContext: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @nosideeffects
* @required
*/
render: SpecPolicy.DEFINE_ONCE,
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps, nextContext) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: SpecPolicy.DEFINE_MANY,
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props, state and/or context.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props/state/context will not require a component
* update.
*
* shouldComponentUpdate: function(nextProps, nextState, nextContext) {
* return !equal(nextProps, this.props) ||
* !equal(nextState, this.state) ||
* !equal(nextContext, this.context);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: SpecPolicy.DEFINE_ONCE,
/**
* Invoked when the component is about to update due to a transition from
* `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
* and `nextContext`.
*
* Use this as an opportunity to perform preparation before an update occurs.
*
* NOTE: You **cannot** use `this.setState()` in this method.
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @param {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {?object} prevContext
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: SpecPolicy.DEFINE_MANY,
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: SpecPolicy.OVERRIDE_BASE
};
/**
* Mapping from class specification keys to special processing functions.
*
* Although these are declared like instance properties in the specification
* when defining classes using `React.createClass`, they are actually static
* and are accessible on the constructor instead of the prototype. Despite
* being static, they must be defined outside of the "statics" key under
* which all other static methods are defined.
*/
var RESERVED_SPEC_KEYS = {
displayName: function (Constructor, displayName) {
Constructor.displayName = displayName;
},
mixins: function (Constructor, mixins) {
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
mixSpecIntoComponent(Constructor, mixins[i]);
}
}
},
childContextTypes: function (Constructor, childContextTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext);
}
Constructor.childContextTypes = _assign({}, Constructor.childContextTypes, childContextTypes);
},
contextTypes: function (Constructor, contextTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context);
}
Constructor.contextTypes = _assign({}, Constructor.contextTypes, contextTypes);
},
/**
* Special case getDefaultProps which should move into statics but requires
* automatic merging.
*/
getDefaultProps: function (Constructor, getDefaultProps) {
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps);
} else {
Constructor.getDefaultProps = getDefaultProps;
}
},
propTypes: function (Constructor, propTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop);
}
Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes);
},
statics: function (Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
},
autobind: function () {} };
// noop
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
// use a warning instead of an invariant so components
// don't show up in prod but only in __DEV__
process.env.NODE_ENV !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : void 0;
}
}
}
function validateMethodOverride(isAlreadyDefined, name) {
var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactClassMixin.hasOwnProperty(name)) {
!(specPolicy === SpecPolicy.OVERRIDE_BASE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.', name) : _prodInvariant('73', name) : void 0;
}
// Disallow defining methods more than once unless explicitly allowed.
if (isAlreadyDefined) {
!(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('74', name) : void 0;
}
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building React classes.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
if (process.env.NODE_ENV !== 'production') {
var typeofSpec = typeof spec;
var isMixinValid = typeofSpec === 'object' && spec !== null;
process.env.NODE_ENV !== 'production' ? warning(isMixinValid, '%s: You\'re attempting to include a mixin that is either null ' + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec) : void 0;
}
return;
}
!(typeof spec !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component class or function as a mixin. Instead, just use a regular object.') : _prodInvariant('75') : void 0;
!!ReactElement.isValidElement(spec) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component as a mixin. Instead, just use a regular object.') : _prodInvariant('76') : void 0;
var proto = Constructor.prototype;
var autoBindPairs = proto.__reactAutoBindPairs;
// By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
if (spec.hasOwnProperty(MIXINS_KEY)) {
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
}
for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
}
if (name === MIXINS_KEY) {
// We have already handled mixins in a special case above.
continue;
}
var property = spec[name];
var isAlreadyDefined = proto.hasOwnProperty(name);
validateMethodOverride(isAlreadyDefined, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactClass methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
var isFunction = typeof property === 'function';
var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false;
if (shouldAutoBind) {
autoBindPairs.push(name, property);
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
// These cases should already be caught by validateMethodOverride.
!(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.', specPolicy, name) : _prodInvariant('77', specPolicy, name) : void 0;
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === SpecPolicy.DEFINE_MANY) {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if (process.env.NODE_ENV !== 'production') {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}
function mixStaticSpecIntoComponent(Constructor, statics) {
if (!statics) {
return;
}
for (var name in statics) {
var property = statics[name];
if (!statics.hasOwnProperty(name)) {
continue;
}
var isReserved = name in RESERVED_SPEC_KEYS;
!!isReserved ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.', name) : _prodInvariant('78', name) : void 0;
var isInherited = name in Constructor;
!!isInherited ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('79', name) : void 0;
Constructor[name] = property;
}
}
/**
* Merge two objects, but throw if both contain the same key.
*
* @param {object} one The first object, which is mutated.
* @param {object} two The second object
* @return {object} one after it has been mutated to contain everything in two.
*/
function mergeIntoWithNoDuplicateKeys(one, two) {
!(one && two && typeof one === 'object' && typeof two === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : _prodInvariant('80') : void 0;
for (var key in two) {
if (two.hasOwnProperty(key)) {
!(one[key] === undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.', key) : _prodInvariant('81', key) : void 0;
one[key] = two[key];
}
}
return one;
}
/**
* Creates a function that invokes two functions and merges their return values.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createMergedResultFunction(one, two) {
return function mergedResult() {
var a = one.apply(this, arguments);
var b = two.apply(this, arguments);
if (a == null) {
return b;
} else if (b == null) {
return a;
}
var c = {};
mergeIntoWithNoDuplicateKeys(c, a);
mergeIntoWithNoDuplicateKeys(c, b);
return c;
};
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function chainedFunction() {
one.apply(this, arguments);
two.apply(this, arguments);
};
}
/**
* Binds a method to the component.
*
* @param {object} component Component whose method is going to be bound.
* @param {function} method Method to be bound.
* @return {function} The bound method.
*/
function bindAutoBindMethod(component, method) {
var boundMethod = method.bind(component);
if (process.env.NODE_ENV !== 'production') {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function (newThis) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
// User is trying to bind() an autobound method; we effectively will
// ignore the value of "this" that the user is trying to use, so
// let's warn.
if (newThis !== component && newThis !== null) {
process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : void 0;
} else if (!args.length) {
process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : void 0;
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
/**
* Binds all auto-bound methods in a component.
*
* @param {object} component Component whose method is going to be bound.
*/
function bindAutoBindMethods(component) {
var pairs = component.__reactAutoBindPairs;
for (var i = 0; i < pairs.length; i += 2) {
var autoBindKey = pairs[i];
var method = pairs[i + 1];
component[autoBindKey] = bindAutoBindMethod(component, method);
}
}
/**
* Add more to the ReactClass base class. These are all legacy features and
* therefore not already part of the modern ReactComponent.
*/
var ReactClassMixin = {
/**
* TODO: This will be deprecated because state should always keep a consistent
* type signature and the only use case for this, is to avoid that.
*/
replaceState: function (newState, callback) {
this.updater.enqueueReplaceState(this, newState);
if (callback) {
this.updater.enqueueCallback(this, callback, 'replaceState');
}
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function () {
return this.updater.isMounted(this);
}
};
var ReactClassComponent = function () {};
_assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin);
/**
* Module for creating composite components.
*
* @class ReactClass
*/
var ReactClass = {
/**
* Creates a composite component class given a class specification.
* See path_to_url#react.createclass
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
createClass: function (spec) {
var Constructor = function (props, context, updater) {
// This constructor gets overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: path_to_url : void 0;
}
// Wire up auto-binding
if (this.__reactAutoBindPairs.length) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (initialState === undefined && this.getInitialState._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : _prodInvariant('82', Constructor.displayName || 'ReactCompositeComponent') : void 0;
this.state = initialState;
};
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor;
Constructor.prototype.__reactAutoBindPairs = [];
injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));
mixSpecIntoComponent(Constructor, spec);
// Initialize the defaultProps property after all mixins have been merged.
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
}
if (process.env.NODE_ENV !== 'production') {
// This is a tag to indicate that the use of these method names is ok,
// since it's used with createClass. If it's not, then it's likely a
// mistake so we'll warn you to use the static property, property
// initializer or constructor respectively.
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps.isReactClassApproved = {};
}
if (Constructor.prototype.getInitialState) {
Constructor.prototype.getInitialState.isReactClassApproved = {};
}
}
!Constructor.prototype.render ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : _prodInvariant('83') : void 0;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : void 0;
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactClassInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
return Constructor;
},
injection: {
injectMixin: function (mixin) {
injectedMixins.push(mixin);
}
}
};
module.exports = ReactClass;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPropTypeLocations
*/
'use strict';
var keyMirror = __webpack_require__(23);
var ReactPropTypeLocations = keyMirror({
prop: null,
context: null,
childContext: null
});
module.exports = ReactPropTypeLocations;
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks static-only
*/
'use strict';
var invariant = __webpack_require__(8);
/**
* Constructs an enumeration with keys equal to their value.
*
* For example:
*
* var COLORS = keyMirror({blue: null, red: null});
* var myColor = COLORS.blue;
* var isColorValid = !!COLORS[myColor];
*
* The last line could not be performed if the values of the generated enum were
* not equal to their keys.
*
* Input: {key1: val1, key2: val2}
* Output: {key1: key1, key2: key2}
*
* @param {object} obj
* @return {object}
*/
var keyMirror = function keyMirror(obj) {
var ret = {};
var key;
!(obj instanceof Object && !Array.isArray(obj)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : void 0;
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPropTypeLocationNames
*/
'use strict';
var ReactPropTypeLocationNames = {};
if (process.env.NODE_ENV !== 'production') {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
}
module.exports = ReactPropTypeLocationNames;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 25 */
/***/ function(module, exports) {
"use strict";
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/**
* Allows extraction of a minified key. Let's the build system minify keys
* without losing the ability to dynamically use key strings as values
* themselves. Pass in an object with a single key/val pair and it will return
* you the string key of that single record. Suppose you want to grab the
* value for a key 'className' inside of an object. Key/val minification may
* have aliased that key to be 'xa12'. keyOf({className: null}) will return
* 'xa12' in that case. Resolve keys you want to use once at startup time, then
* reuse those resolutions.
*/
var keyOf = function keyOf(oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMFactories
*/
'use strict';
var ReactElement = __webpack_require__(9);
/**
* Create a factory that creates HTML tag elements.
*
* @private
*/
var createDOMFactory = ReactElement.createFactory;
if (process.env.NODE_ENV !== 'production') {
var ReactElementValidator = __webpack_require__(27);
createDOMFactory = ReactElementValidator.createFactory;
}
/**
* Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
* This is also accessible via `React.DOM`.
*
* @public
*/
var ReactDOMFactories = {
a: createDOMFactory('a'),
abbr: createDOMFactory('abbr'),
address: createDOMFactory('address'),
area: createDOMFactory('area'),
article: createDOMFactory('article'),
aside: createDOMFactory('aside'),
audio: createDOMFactory('audio'),
b: createDOMFactory('b'),
base: createDOMFactory('base'),
bdi: createDOMFactory('bdi'),
bdo: createDOMFactory('bdo'),
big: createDOMFactory('big'),
blockquote: createDOMFactory('blockquote'),
body: createDOMFactory('body'),
br: createDOMFactory('br'),
button: createDOMFactory('button'),
canvas: createDOMFactory('canvas'),
caption: createDOMFactory('caption'),
cite: createDOMFactory('cite'),
code: createDOMFactory('code'),
col: createDOMFactory('col'),
colgroup: createDOMFactory('colgroup'),
data: createDOMFactory('data'),
datalist: createDOMFactory('datalist'),
dd: createDOMFactory('dd'),
del: createDOMFactory('del'),
details: createDOMFactory('details'),
dfn: createDOMFactory('dfn'),
dialog: createDOMFactory('dialog'),
div: createDOMFactory('div'),
dl: createDOMFactory('dl'),
dt: createDOMFactory('dt'),
em: createDOMFactory('em'),
embed: createDOMFactory('embed'),
fieldset: createDOMFactory('fieldset'),
figcaption: createDOMFactory('figcaption'),
figure: createDOMFactory('figure'),
footer: createDOMFactory('footer'),
form: createDOMFactory('form'),
h1: createDOMFactory('h1'),
h2: createDOMFactory('h2'),
h3: createDOMFactory('h3'),
h4: createDOMFactory('h4'),
h5: createDOMFactory('h5'),
h6: createDOMFactory('h6'),
head: createDOMFactory('head'),
header: createDOMFactory('header'),
hgroup: createDOMFactory('hgroup'),
hr: createDOMFactory('hr'),
html: createDOMFactory('html'),
i: createDOMFactory('i'),
iframe: createDOMFactory('iframe'),
img: createDOMFactory('img'),
input: createDOMFactory('input'),
ins: createDOMFactory('ins'),
kbd: createDOMFactory('kbd'),
keygen: createDOMFactory('keygen'),
label: createDOMFactory('label'),
legend: createDOMFactory('legend'),
li: createDOMFactory('li'),
link: createDOMFactory('link'),
main: createDOMFactory('main'),
map: createDOMFactory('map'),
mark: createDOMFactory('mark'),
menu: createDOMFactory('menu'),
menuitem: createDOMFactory('menuitem'),
meta: createDOMFactory('meta'),
meter: createDOMFactory('meter'),
nav: createDOMFactory('nav'),
noscript: createDOMFactory('noscript'),
object: createDOMFactory('object'),
ol: createDOMFactory('ol'),
optgroup: createDOMFactory('optgroup'),
option: createDOMFactory('option'),
output: createDOMFactory('output'),
p: createDOMFactory('p'),
param: createDOMFactory('param'),
picture: createDOMFactory('picture'),
pre: createDOMFactory('pre'),
progress: createDOMFactory('progress'),
q: createDOMFactory('q'),
rp: createDOMFactory('rp'),
rt: createDOMFactory('rt'),
ruby: createDOMFactory('ruby'),
s: createDOMFactory('s'),
samp: createDOMFactory('samp'),
script: createDOMFactory('script'),
section: createDOMFactory('section'),
select: createDOMFactory('select'),
small: createDOMFactory('small'),
source: createDOMFactory('source'),
span: createDOMFactory('span'),
strong: createDOMFactory('strong'),
style: createDOMFactory('style'),
sub: createDOMFactory('sub'),
summary: createDOMFactory('summary'),
sup: createDOMFactory('sup'),
table: createDOMFactory('table'),
tbody: createDOMFactory('tbody'),
td: createDOMFactory('td'),
textarea: createDOMFactory('textarea'),
tfoot: createDOMFactory('tfoot'),
th: createDOMFactory('th'),
thead: createDOMFactory('thead'),
time: createDOMFactory('time'),
title: createDOMFactory('title'),
tr: createDOMFactory('tr'),
track: createDOMFactory('track'),
u: createDOMFactory('u'),
ul: createDOMFactory('ul'),
'var': createDOMFactory('var'),
video: createDOMFactory('video'),
wbr: createDOMFactory('wbr'),
// SVG
circle: createDOMFactory('circle'),
clipPath: createDOMFactory('clipPath'),
defs: createDOMFactory('defs'),
ellipse: createDOMFactory('ellipse'),
g: createDOMFactory('g'),
image: createDOMFactory('image'),
line: createDOMFactory('line'),
linearGradient: createDOMFactory('linearGradient'),
mask: createDOMFactory('mask'),
path: createDOMFactory('path'),
pattern: createDOMFactory('pattern'),
polygon: createDOMFactory('polygon'),
polyline: createDOMFactory('polyline'),
radialGradient: createDOMFactory('radialGradient'),
rect: createDOMFactory('rect'),
stop: createDOMFactory('stop'),
svg: createDOMFactory('svg'),
text: createDOMFactory('text'),
tspan: createDOMFactory('tspan')
};
module.exports = ReactDOMFactories;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactElementValidator
*/
/**
* ReactElementValidator provides a wrapper around a element factory
* which validates the props passed to the element. This is intended to be
* used only in DEV and could be replaced by a static type checker for languages
* that support it.
*/
'use strict';
var ReactCurrentOwner = __webpack_require__(10);
var ReactComponentTreeHook = __webpack_require__(28);
var ReactElement = __webpack_require__(9);
var ReactPropTypeLocations = __webpack_require__(22);
var checkReactTypeSpec = __webpack_require__(29);
var canDefineProperty = __webpack_require__(13);
var getIteratorFn = __webpack_require__(15);
var warning = __webpack_require__(11);
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {};
function getCurrentComponentErrorInfo(parentType) {
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
info = ' Check the top-level render call using <' + parentName + '>.';
}
}
return info;
}
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it. Error statuses are cached so a warning
* will only be shown once.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var memoizer = ownerHasKeyUseWarning.uniqueKey || (ownerHasKeyUseWarning.uniqueKey = {});
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (memoizer[currentComponentErrorInfo]) {
return;
}
memoizer[currentComponentErrorInfo] = true;
// Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwner = '';
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
childOwner = ' It was passed a child from ' + element._owner.getName() + '.';
}
process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s See path_to_url for more information.%s', currentComponentErrorInfo, childOwner, ReactComponentTreeHook.getCurrentStackAddendum(element)) : void 0;
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
if (typeof node !== 'object') {
return;
}
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (ReactElement.isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (ReactElement.isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
// Entry iterators provide implicit keys.
if (iteratorFn) {
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (ReactElement.isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
var componentClass = element.type;
if (typeof componentClass !== 'function') {
return;
}
var name = componentClass.displayName || componentClass.name;
if (componentClass.propTypes) {
checkReactTypeSpec(componentClass.propTypes, element.props, ReactPropTypeLocations.prop, name, element, null);
}
if (typeof componentClass.getDefaultProps === 'function') {
process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0;
}
}
var ReactElementValidator = {
createElement: function (type, props, children) {
var validType = typeof type === 'string' || typeof type === 'function';
// We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
process.env.NODE_ENV !== 'production' ? warning(false, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : void 0;
}
var element = ReactElement.createElement.apply(this, arguments);
// The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
}
// Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
}
validatePropTypes(element);
return element;
},
createFactory: function (type) {
var validatedFactory = ReactElementValidator.createElement.bind(null, type);
// Legacy hook TODO: Warn if this is accessed
validatedFactory.type = type;
if (process.env.NODE_ENV !== 'production') {
if (canDefineProperty) {
Object.defineProperty(validatedFactory, 'type', {
enumerable: false,
get: function () {
process.env.NODE_ENV !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : void 0;
Object.defineProperty(this, 'type', {
value: type
});
return type;
}
});
}
}
return validatedFactory;
},
cloneElement: function (element, props, children) {
var newElement = ReactElement.cloneElement.apply(this, arguments);
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], newElement.type);
}
validatePropTypes(newElement);
return newElement;
}
};
module.exports = ReactElementValidator;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponentTreeHook
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactCurrentOwner = __webpack_require__(10);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
function isNative(fn) {
// Based on isNative() from Lodash
var funcToString = Function.prototype.toString;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var reIsNative = RegExp('^' + funcToString
// Take an example native function source for comparison
.call(hasOwnProperty)
// Strip regex characters so we can use it for regex
.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
// Remove hasOwnProperty from the template to make it generic
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
try {
var source = funcToString.call(fn);
return reIsNative.test(source);
} catch (err) {
return false;
}
}
var canUseCollections =
// Array.from
typeof Array.from === 'function' &&
// Map
typeof Map === 'function' && isNative(Map) &&
// Map.prototype.keys
Map.prototype != null && typeof Map.prototype.keys === 'function' && isNative(Map.prototype.keys) &&
// Set
typeof Set === 'function' && isNative(Set) &&
// Set.prototype.keys
Set.prototype != null && typeof Set.prototype.keys === 'function' && isNative(Set.prototype.keys);
var itemMap;
var rootIDSet;
var itemByKey;
var rootByKey;
if (canUseCollections) {
itemMap = new Map();
rootIDSet = new Set();
} else {
itemByKey = {};
rootByKey = {};
}
var unmountedIDs = [];
// Use non-numeric keys to prevent V8 performance issues:
// path_to_url
function getKeyFromID(id) {
return '.' + id;
}
function getIDFromKey(key) {
return parseInt(key.substr(1), 10);
}
function get(id) {
if (canUseCollections) {
return itemMap.get(id);
} else {
var key = getKeyFromID(id);
return itemByKey[key];
}
}
function remove(id) {
if (canUseCollections) {
itemMap['delete'](id);
} else {
var key = getKeyFromID(id);
delete itemByKey[key];
}
}
function create(id, element, parentID) {
var item = {
element: element,
parentID: parentID,
text: null,
childIDs: [],
isMounted: false,
updateCount: 0
};
if (canUseCollections) {
itemMap.set(id, item);
} else {
var key = getKeyFromID(id);
itemByKey[key] = item;
}
}
function addRoot(id) {
if (canUseCollections) {
rootIDSet.add(id);
} else {
var key = getKeyFromID(id);
rootByKey[key] = true;
}
}
function removeRoot(id) {
if (canUseCollections) {
rootIDSet['delete'](id);
} else {
var key = getKeyFromID(id);
delete rootByKey[key];
}
}
function getRegisteredIDs() {
if (canUseCollections) {
return Array.from(itemMap.keys());
} else {
return Object.keys(itemByKey).map(getIDFromKey);
}
}
function getRootIDs() {
if (canUseCollections) {
return Array.from(rootIDSet.keys());
} else {
return Object.keys(rootByKey).map(getIDFromKey);
}
}
function purgeDeep(id) {
var item = get(id);
if (item) {
var childIDs = item.childIDs;
remove(id);
childIDs.forEach(purgeDeep);
}
}
function describeComponentFrame(name, source, ownerName) {
return '\n in ' + name + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : '');
}
function getDisplayName(element) {
if (element == null) {
return '#empty';
} else if (typeof element === 'string' || typeof element === 'number') {
return '#text';
} else if (typeof element.type === 'string') {
return element.type;
} else {
return element.type.displayName || element.type.name || 'Unknown';
}
}
function describeID(id) {
var name = ReactComponentTreeHook.getDisplayName(id);
var element = ReactComponentTreeHook.getElement(id);
var ownerID = ReactComponentTreeHook.getOwnerID(id);
var ownerName;
if (ownerID) {
ownerName = ReactComponentTreeHook.getDisplayName(ownerID);
}
process.env.NODE_ENV !== 'production' ? warning(element, 'ReactComponentTreeHook: Missing React element for debugID %s when ' + 'building stack', id) : void 0;
return describeComponentFrame(name, element && element._source, ownerName);
}
var ReactComponentTreeHook = {
onSetChildren: function (id, nextChildIDs) {
var item = get(id);
item.childIDs = nextChildIDs;
for (var i = 0; i < nextChildIDs.length; i++) {
var nextChildID = nextChildIDs[i];
var nextChild = get(nextChildID);
!nextChild ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected hook events to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('140') : void 0;
!(nextChild.childIDs != null || typeof nextChild.element !== 'object' || nextChild.element == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onSetChildren() to fire for a container child before its parent includes it in onSetChildren().') : _prodInvariant('141') : void 0;
!nextChild.isMounted ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('71') : void 0;
if (nextChild.parentID == null) {
nextChild.parentID = id;
// TODO: This shouldn't be necessary but mounting a new root during in
// componentWillMount currently causes not-yet-mounted components to
// be purged from our tree data so their parent ID is missing.
}
!(nextChild.parentID === id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onBeforeMountComponent() parent and onSetChildren() to be consistent (%s has parents %s and %s).', nextChildID, nextChild.parentID, id) : _prodInvariant('142', nextChildID, nextChild.parentID, id) : void 0;
}
},
onBeforeMountComponent: function (id, element, parentID) {
create(id, element, parentID);
},
onBeforeUpdateComponent: function (id, element) {
var item = get(id);
if (!item || !item.isMounted) {
// We may end up here as a result of setState() in componentWillUnmount().
// In this case, ignore the element.
return;
}
item.element = element;
},
onMountComponent: function (id) {
var item = get(id);
item.isMounted = true;
var isRoot = item.parentID === 0;
if (isRoot) {
addRoot(id);
}
},
onUpdateComponent: function (id) {
var item = get(id);
if (!item || !item.isMounted) {
// We may end up here as a result of setState() in componentWillUnmount().
// In this case, ignore the element.
return;
}
item.updateCount++;
},
onUnmountComponent: function (id) {
var item = get(id);
if (item) {
// We need to check if it exists.
// `item` might not exist if it is inside an error boundary, and a sibling
// error boundary child threw while mounting. Then this instance never
// got a chance to mount, but it still gets an unmounting event during
// the error boundary cleanup.
item.isMounted = false;
var isRoot = item.parentID === 0;
if (isRoot) {
removeRoot(id);
}
}
unmountedIDs.push(id);
},
purgeUnmountedComponents: function () {
if (ReactComponentTreeHook._preventPurging) {
// Should only be used for testing.
return;
}
for (var i = 0; i < unmountedIDs.length; i++) {
var id = unmountedIDs[i];
purgeDeep(id);
}
unmountedIDs.length = 0;
},
isMounted: function (id) {
var item = get(id);
return item ? item.isMounted : false;
},
getCurrentStackAddendum: function (topElement) {
var info = '';
if (topElement) {
var type = topElement.type;
var name = typeof type === 'function' ? type.displayName || type.name : type;
var owner = topElement._owner;
info += describeComponentFrame(name || 'Unknown', topElement._source, owner && owner.getName());
}
var currentOwner = ReactCurrentOwner.current;
var id = currentOwner && currentOwner._debugID;
info += ReactComponentTreeHook.getStackAddendumByID(id);
return info;
},
getStackAddendumByID: function (id) {
var info = '';
while (id) {
info += describeID(id);
id = ReactComponentTreeHook.getParentID(id);
}
return info;
},
getChildIDs: function (id) {
var item = get(id);
return item ? item.childIDs : [];
},
getDisplayName: function (id) {
var element = ReactComponentTreeHook.getElement(id);
if (!element) {
return null;
}
return getDisplayName(element);
},
getElement: function (id) {
var item = get(id);
return item ? item.element : null;
},
getOwnerID: function (id) {
var element = ReactComponentTreeHook.getElement(id);
if (!element || !element._owner) {
return null;
}
return element._owner._debugID;
},
getParentID: function (id) {
var item = get(id);
return item ? item.parentID : null;
},
getSource: function (id) {
var item = get(id);
var element = item ? item.element : null;
var source = element != null ? element._source : null;
return source;
},
getText: function (id) {
var element = ReactComponentTreeHook.getElement(id);
if (typeof element === 'string') {
return element;
} else if (typeof element === 'number') {
return '' + element;
} else {
return null;
}
},
getUpdateCount: function (id) {
var item = get(id);
return item ? item.updateCount : 0;
},
getRegisteredIDs: getRegisteredIDs,
getRootIDs: getRootIDs
};
module.exports = ReactComponentTreeHook;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule checkReactTypeSpec
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactPropTypeLocationNames = __webpack_require__(24);
var ReactPropTypesSecret = __webpack_require__(30);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
var ReactComponentTreeHook;
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') {
// Temporary hack.
// Inline requires don't work well with Jest:
// path_to_url
// Remove the inline requires when we don't need them anymore:
// path_to_url
ReactComponentTreeHook = __webpack_require__(28);
}
var loggedTypeFailures = {};
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?object} element The React element that is being type-checked
* @param {?number} debugID The React component instance that is being type-checked
* @private
*/
function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) {
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
!(typeof typeSpecs[typeSpecName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0;
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0;
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var componentStackInfo = '';
if (process.env.NODE_ENV !== 'production') {
if (!ReactComponentTreeHook) {
ReactComponentTreeHook = __webpack_require__(28);
}
if (debugID !== null) {
componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID);
} else if (element !== null) {
componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element);
}
}
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0;
}
}
}
}
module.exports = checkReactTypeSpec;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 30 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPropTypesSecret
*/
'use strict';
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPropTypes
*/
'use strict';
var ReactElement = __webpack_require__(9);
var ReactPropTypeLocationNames = __webpack_require__(24);
var ReactPropTypesSecret = __webpack_require__(30);
var emptyFunction = __webpack_require__(12);
var getIteratorFn = __webpack_require__(15);
var warning = __webpack_require__(11);
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* path_to_url
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
if (process.env.NODE_ENV !== 'production') {
var manualPropTypeCallCache = {};
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (process.env.NODE_ENV !== 'production') {
if (secret !== ReactPropTypesSecret && typeof console !== 'undefined') {
var cacheKey = componentName + ':' + propName;
if (!manualPropTypeCallCache[cacheKey]) {
process.env.NODE_ENV !== 'production' ? warning(false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will not work in the next major version. You may be ' + 'seeing this warning due to a third-party PropTypes library. ' + 'See path_to_url for details.', propFullName, componentName) : void 0;
manualPropTypeCallCache[cacheKey] = true;
}
}
}
if (props[propName] == null) {
var locationName = ReactPropTypeLocationNames[location];
if (isRequired) {
return new PropTypeError('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
var locationName = ReactPropTypeLocationNames[location];
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturns(null));
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var locationName = ReactPropTypeLocationNames[location];
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!ReactElement.isValidElement(propValue)) {
var locationName = ReactPropTypeLocationNames[location];
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var locationName = ReactPropTypeLocationNames[location];
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
var valuesString = JSON.stringify(expectedValues);
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || ReactElement.isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
module.exports = ReactPropTypes;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 32 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactVersion
*/
'use strict';
module.exports = '15.3.1';
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule onlyChild
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactElement = __webpack_require__(9);
var invariant = __webpack_require__(8);
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection.
*
* See path_to_url#react.children.only
*
* The current implementation of this function assumes that a single child gets
* passed without a wrapper, but the purpose of this helper function is to
* abstract away the particular structure of children.
*
* @param {?object} children Child collection structure.
* @return {ReactElement} The first and only `ReactElement` contained in the
* structure.
*/
function onlyChild(children) {
!ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React.Children.only expected to receive a single React element child.') : _prodInvariant('143') : void 0;
return children;
}
module.exports = onlyChild;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(35);
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOM
*/
/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/
'use strict';
var ReactDOMComponentTree = __webpack_require__(36);
var ReactDefaultInjection = __webpack_require__(39);
var ReactMount = __webpack_require__(162);
var ReactReconciler = __webpack_require__(59);
var ReactUpdates = __webpack_require__(56);
var ReactVersion = __webpack_require__(32);
var findDOMNode = __webpack_require__(167);
var getHostComponentFromComposite = __webpack_require__(168);
var renderSubtreeIntoContainer = __webpack_require__(169);
var warning = __webpack_require__(11);
ReactDefaultInjection.inject();
var ReactDOM = {
findDOMNode: findDOMNode,
render: ReactMount.render,
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
version: ReactVersion,
/* eslint-disable camelcase */
unstable_batchedUpdates: ReactUpdates.batchedUpdates,
unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer
};
// Inject the runtime into a devtools global hook regardless of browser.
// Allows for debugging when the hook is injected on the page.
/* eslint-enable camelcase */
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
ComponentTree: {
getClosestInstanceFromNode: ReactDOMComponentTree.getClosestInstanceFromNode,
getNodeFromInstance: function (inst) {
// inst is an internal instance (but could be a composite)
if (inst._renderedComponent) {
inst = getHostComponentFromComposite(inst);
}
if (inst) {
return ReactDOMComponentTree.getNodeFromInstance(inst);
} else {
return null;
}
}
},
Mount: ReactMount,
Reconciler: ReactReconciler
});
}
if (process.env.NODE_ENV !== 'production') {
var ExecutionEnvironment = __webpack_require__(49);
if (ExecutionEnvironment.canUseDOM && window.top === window.self) {
// First check if devtools is not installed
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
// If we're in Chrome or Firefox, provide a download link if not installed.
if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
// Firefox does not have the issue with devtools loaded over file://
var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 && navigator.userAgent.indexOf('Firefox') === -1;
console.debug('Download the React DevTools ' + (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') + 'for a better development experience: ' + 'path_to_url
}
}
var testFunc = function testFn() {};
process.env.NODE_ENV !== 'production' ? warning((testFunc.name || testFunc.toString()).indexOf('testFn') !== -1, 'It looks like you\'re using a minified copy of the development build ' + 'of React. When deploying React apps to production, make sure to use ' + 'the production build which skips development warnings and is faster. ' + 'See path_to_url for more details.') : void 0;
// If we're in IE8, check to see if we are in compatibility mode and provide
// information on preventing compatibility mode
var ieCompatibilityMode = document.documentMode && document.documentMode < 8;
process.env.NODE_ENV !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : void 0;
var expectedFeatures = [
// shims
Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim];
for (var i = 0; i < expectedFeatures.length; i++) {
if (!expectedFeatures[i]) {
process.env.NODE_ENV !== 'production' ? warning(false, 'One or more ES5 shims expected by React are not available: ' + 'path_to_url : void 0;
break;
}
}
}
}
if (process.env.NODE_ENV !== 'production') {
var ReactInstrumentation = __webpack_require__(62);
var ReactDOMUnknownPropertyHook = __webpack_require__(170);
var ReactDOMNullInputValuePropHook = __webpack_require__(171);
ReactInstrumentation.debugTool.addHook(ReactDOMUnknownPropertyHook);
ReactInstrumentation.debugTool.addHook(ReactDOMNullInputValuePropHook);
}
module.exports = ReactDOM;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMComponentTree
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var DOMProperty = __webpack_require__(37);
var ReactDOMComponentFlags = __webpack_require__(38);
var invariant = __webpack_require__(8);
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var Flags = ReactDOMComponentFlags;
var internalInstanceKey = '__reactInternalInstance$' + Math.random().toString(36).slice(2);
/**
* Drill down (through composites and empty components) until we get a host or
* host text component.
*
* This is pretty polymorphic but unavoidable with the current structure we have
* for `_renderedChildren`.
*/
function getRenderedHostOrTextFromComponent(component) {
var rendered;
while (rendered = component._renderedComponent) {
component = rendered;
}
return component;
}
/**
* Populate `_hostNode` on the rendered host/text component with the given
* DOM node. The passed `inst` can be a composite.
*/
function precacheNode(inst, node) {
var hostInst = getRenderedHostOrTextFromComponent(inst);
hostInst._hostNode = node;
node[internalInstanceKey] = hostInst;
}
function uncacheNode(inst) {
var node = inst._hostNode;
if (node) {
delete node[internalInstanceKey];
inst._hostNode = null;
}
}
/**
* Populate `_hostNode` on each child of `inst`, assuming that the children
* match up with the DOM (element) children of `node`.
*
* We cache entire levels at once to avoid an n^2 problem where we access the
* children of a node sequentially and have to walk from the start to our target
* node every time.
*
* Since we update `_renderedChildren` and the actual DOM at (slightly)
* different times, we could race here and see a newer `_renderedChildren` than
* the DOM nodes we see. To avoid this, ReactMultiChild calls
* `prepareToManageChildren` before we change `_renderedChildren`, at which
* time the container's child nodes are always cached (until it unmounts).
*/
function precacheChildNodes(inst, node) {
if (inst._flags & Flags.hasCachedChildNodes) {
return;
}
var children = inst._renderedChildren;
var childNode = node.firstChild;
outer: for (var name in children) {
if (!children.hasOwnProperty(name)) {
continue;
}
var childInst = children[name];
var childID = getRenderedHostOrTextFromComponent(childInst)._domID;
if (childID === 0) {
// We're currently unmounting this child in ReactMultiChild; skip it.
continue;
}
// We assume the child nodes are in the same order as the child instances.
for (; childNode !== null; childNode = childNode.nextSibling) {
if (childNode.nodeType === 1 && childNode.getAttribute(ATTR_NAME) === String(childID) || childNode.nodeType === 8 && childNode.nodeValue === ' react-text: ' + childID + ' ' || childNode.nodeType === 8 && childNode.nodeValue === ' react-empty: ' + childID + ' ') {
precacheNode(childInst, childNode);
continue outer;
}
}
// We reached the end of the DOM children without finding an ID match.
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unable to find element with ID %s.', childID) : _prodInvariant('32', childID) : void 0;
}
inst._flags |= Flags.hasCachedChildNodes;
}
/**
* Given a DOM node, return the closest ReactDOMComponent or
* ReactDOMTextComponent instance ancestor.
*/
function getClosestInstanceFromNode(node) {
if (node[internalInstanceKey]) {
return node[internalInstanceKey];
}
// Walk up the tree until we find an ancestor whose instance we have cached.
var parents = [];
while (!node[internalInstanceKey]) {
parents.push(node);
if (node.parentNode) {
node = node.parentNode;
} else {
// Top of the tree. This node must not be part of a React tree (or is
// unmounted, potentially).
return null;
}
}
var closest;
var inst;
for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) {
closest = inst;
if (parents.length) {
precacheChildNodes(inst, node);
}
}
return closest;
}
/**
* Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
* instance, or null if the node was not rendered by this React.
*/
function getInstanceFromNode(node) {
var inst = getClosestInstanceFromNode(node);
if (inst != null && inst._hostNode === node) {
return inst;
} else {
return null;
}
}
/**
* Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
* DOM node.
*/
function getNodeFromInstance(inst) {
// Without this first invariant, passing a non-DOM-component triggers the next
// invariant for a missing parent, which is super confusing.
!(inst._hostNode !== undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0;
if (inst._hostNode) {
return inst._hostNode;
}
// Walk up the tree until we find an ancestor whose DOM node we have cached.
var parents = [];
while (!inst._hostNode) {
parents.push(inst);
!inst._hostParent ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React DOM tree root should always have a node reference.') : _prodInvariant('34') : void 0;
inst = inst._hostParent;
}
// Now parents contains each ancestor that does *not* have a cached native
// node, and `inst` is the deepest ancestor that does.
for (; parents.length; inst = parents.pop()) {
precacheChildNodes(inst, inst._hostNode);
}
return inst._hostNode;
}
var ReactDOMComponentTree = {
getClosestInstanceFromNode: getClosestInstanceFromNode,
getInstanceFromNode: getInstanceFromNode,
getNodeFromInstance: getNodeFromInstance,
precacheChildNodes: precacheChildNodes,
precacheNode: precacheNode,
uncacheNode: uncacheNode
};
module.exports = ReactDOMComponentTree;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMProperty
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
function checkMask(value, bitmask) {
return (value & bitmask) === bitmask;
}
var DOMPropertyInjection = {
/**
* Mapping from normalized, camelcased property names to a configuration that
* specifies how the associated DOM property should be accessed or rendered.
*/
MUST_USE_PROPERTY: 0x1,
HAS_BOOLEAN_VALUE: 0x4,
HAS_NUMERIC_VALUE: 0x8,
HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8,
HAS_OVERLOADED_BOOLEAN_VALUE: 0x20,
/**
* Inject some specialized knowledge about the DOM. This takes a config object
* with the following properties:
*
* isCustomAttribute: function that given an attribute name will return true
* if it can be inserted into the DOM verbatim. Useful for data-* or aria-*
* attributes where it's impossible to enumerate all of the possible
* attribute names,
*
* Properties: object mapping DOM property name to one of the
* DOMPropertyInjection constants or null. If your attribute isn't in here,
* it won't get written to the DOM.
*
* DOMAttributeNames: object mapping React attribute name to the DOM
* attribute name. Attribute names not specified use the **lowercase**
* normalized name.
*
* DOMAttributeNamespaces: object mapping React attribute name to the DOM
* attribute namespace URL. (Attribute names not specified use no namespace.)
*
* DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.
* Property names not specified use the normalized name.
*
* DOMMutationMethods: Properties that require special mutation methods. If
* `value` is undefined, the mutation method should unset the property.
*
* @param {object} domPropertyConfig the config as described above.
*/
injectDOMPropertyConfig: function (domPropertyConfig) {
var Injection = DOMPropertyInjection;
var Properties = domPropertyConfig.Properties || {};
var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {};
var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};
var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {};
var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};
if (domPropertyConfig.isCustomAttribute) {
DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute);
}
for (var propName in Properties) {
!!DOMProperty.properties.hasOwnProperty(propName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property \'%s\' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.', propName) : _prodInvariant('48', propName) : void 0;
var lowerCased = propName.toLowerCase();
var propConfig = Properties[propName];
var propertyInfo = {
attributeName: lowerCased,
attributeNamespace: null,
propertyName: propName,
mutationMethod: null,
mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY),
hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE),
hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE),
hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE),
hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE)
};
!(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s', propName) : _prodInvariant('50', propName) : void 0;
if (process.env.NODE_ENV !== 'production') {
DOMProperty.getPossibleStandardName[lowerCased] = propName;
}
if (DOMAttributeNames.hasOwnProperty(propName)) {
var attributeName = DOMAttributeNames[propName];
propertyInfo.attributeName = attributeName;
if (process.env.NODE_ENV !== 'production') {
DOMProperty.getPossibleStandardName[attributeName] = propName;
}
}
if (DOMAttributeNamespaces.hasOwnProperty(propName)) {
propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName];
}
if (DOMPropertyNames.hasOwnProperty(propName)) {
propertyInfo.propertyName = DOMPropertyNames[propName];
}
if (DOMMutationMethods.hasOwnProperty(propName)) {
propertyInfo.mutationMethod = DOMMutationMethods[propName];
}
DOMProperty.properties[propName] = propertyInfo;
}
}
};
/* eslint-disable max-len */
var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';
/* eslint-enable max-len */
/**
* DOMProperty exports lookup objects that can be used like functions:
*
* > DOMProperty.isValid['id']
* true
* > DOMProperty.isValid['foobar']
* undefined
*
* Although this may be confusing, it performs better in general.
*
* @see path_to_url
* @see path_to_url
*/
var DOMProperty = {
ID_ATTRIBUTE_NAME: 'data-reactid',
ROOT_ATTRIBUTE_NAME: 'data-reactroot',
ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR,
ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040',
/**
* Map from property "standard name" to an object with info about how to set
* the property in the DOM. Each object contains:
*
* attributeName:
* Used when rendering markup or with `*Attribute()`.
* attributeNamespace
* propertyName:
* Used on DOM node instances. (This includes properties that mutate due to
* external factors.)
* mutationMethod:
* If non-null, used instead of the property or `setAttribute()` after
* initial render.
* mustUseProperty:
* Whether the property must be accessed and mutated as an object property.
* hasBooleanValue:
* Whether the property should be removed when set to a falsey value.
* hasNumericValue:
* Whether the property must be numeric or parse as a numeric and should be
* removed when set to a falsey value.
* hasPositiveNumericValue:
* Whether the property must be positive numeric or parse as a positive
* numeric and should be removed when set to a falsey value.
* hasOverloadedBooleanValue:
* Whether the property can be used as a flag as well as with a value.
* Removed when strictly equal to false; present without a value when
* strictly equal to true; present with a value otherwise.
*/
properties: {},
/**
* Mapping from lowercase property names to the properly cased version, used
* to warn in the case of missing properties. Available only in __DEV__.
* @type {Object}
*/
getPossibleStandardName: process.env.NODE_ENV !== 'production' ? {} : null,
/**
* All of the isCustomAttribute() functions that have been injected.
*/
_isCustomAttributeFunctions: [],
/**
* Checks whether a property name is a custom attribute.
* @method
*/
isCustomAttribute: function (attributeName) {
for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) {
var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i];
if (isCustomAttributeFn(attributeName)) {
return true;
}
}
return false;
},
injection: DOMPropertyInjection
};
module.exports = DOMProperty;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 38 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMComponentFlags
*/
'use strict';
var ReactDOMComponentFlags = {
hasCachedChildNodes: 1 << 0
};
module.exports = ReactDOMComponentFlags;
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDefaultInjection
*/
'use strict';
var BeforeInputEventPlugin = __webpack_require__(40);
var ChangeEventPlugin = __webpack_require__(55);
var DefaultEventPluginOrder = __webpack_require__(73);
var EnterLeaveEventPlugin = __webpack_require__(74);
var HTMLDOMPropertyConfig = __webpack_require__(79);
var ReactComponentBrowserEnvironment = __webpack_require__(80);
var ReactDOMComponent = __webpack_require__(94);
var ReactDOMComponentTree = __webpack_require__(36);
var ReactDOMEmptyComponent = __webpack_require__(133);
var ReactDOMTreeTraversal = __webpack_require__(134);
var ReactDOMTextComponent = __webpack_require__(135);
var ReactDefaultBatchingStrategy = __webpack_require__(136);
var ReactEventListener = __webpack_require__(137);
var ReactInjection = __webpack_require__(140);
var ReactReconcileTransaction = __webpack_require__(141);
var SVGDOMPropertyConfig = __webpack_require__(149);
var SelectEventPlugin = __webpack_require__(150);
var SimpleEventPlugin = __webpack_require__(151);
var alreadyInjected = false;
function inject() {
if (alreadyInjected) {
// TODO: This is currently true because these injections are shared between
// the client and the server package. They should be built independently
// and not share any injection state. Then this problem will be solved.
return;
}
alreadyInjected = true;
ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener);
/**
* Inject modules for resolving DOM hierarchy and plugin ordering.
*/
ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder);
ReactInjection.EventPluginUtils.injectComponentTree(ReactDOMComponentTree);
ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal);
/**
* Some important event plugins included by default (without having to require
* them).
*/
ReactInjection.EventPluginHub.injectEventPluginsByName({
SimpleEventPlugin: SimpleEventPlugin,
EnterLeaveEventPlugin: EnterLeaveEventPlugin,
ChangeEventPlugin: ChangeEventPlugin,
SelectEventPlugin: SelectEventPlugin,
BeforeInputEventPlugin: BeforeInputEventPlugin
});
ReactInjection.HostComponent.injectGenericComponentClass(ReactDOMComponent);
ReactInjection.HostComponent.injectTextComponentClass(ReactDOMTextComponent);
ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
ReactInjection.EmptyComponent.injectEmptyComponentFactory(function (instantiate) {
return new ReactDOMEmptyComponent(instantiate);
});
ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction);
ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy);
ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
}
module.exports = {
inject: inject
};
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule BeforeInputEventPlugin
*/
'use strict';
var EventConstants = __webpack_require__(41);
var EventPropagators = __webpack_require__(42);
var ExecutionEnvironment = __webpack_require__(49);
var FallbackCompositionState = __webpack_require__(50);
var SyntheticCompositionEvent = __webpack_require__(52);
var SyntheticInputEvent = __webpack_require__(54);
var keyOf = __webpack_require__(25);
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
var START_KEYCODE = 229;
var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window;
var documentMode = null;
if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) {
documentMode = document.documentMode;
}
// Webkit offers a very useful `textInput` event that can be used to
// directly represent `beforeInput`. The IE `textinput` event is not as
// useful, so we don't use it.
var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto();
// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. Japanese ideographic
// spaces, for instance (\u3000) are not recorded correctly.
var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
/**
* Opera <= 12 includes TextEvent in window, but does not fire
* text input events. Rely on keypress instead.
*/
function isPresto() {
var opera = window.opera;
return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12;
}
var SPACEBAR_CODE = 32;
var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
var topLevelTypes = EventConstants.topLevelTypes;
// Events and their corresponding property names.
var eventTypes = {
beforeInput: {
phasedRegistrationNames: {
bubbled: keyOf({ onBeforeInput: null }),
captured: keyOf({ onBeforeInputCapture: null })
},
dependencies: [topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste]
},
compositionEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionEnd: null }),
captured: keyOf({ onCompositionEndCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
},
compositionStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionStart: null }),
captured: keyOf({ onCompositionStartCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
},
compositionUpdate: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionUpdate: null }),
captured: keyOf({ onCompositionUpdateCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
}
};
// Track whether we've ever handled a keypress on the space key.
var hasSpaceKeypress = false;
/**
* Return whether a native keypress event is assumed to be a command.
* This is required because Firefox fires `keypress` events for key commands
* (cut, copy, select-all, etc.) even though no character is inserted.
*/
function isKeypressCommand(nativeEvent) {
return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
// ctrlKey && altKey is equivalent to AltGr, and is not a command.
!(nativeEvent.ctrlKey && nativeEvent.altKey);
}
/**
* Translate native top level events into event types.
*
* @param {string} topLevelType
* @return {object}
*/
function getCompositionEventType(topLevelType) {
switch (topLevelType) {
case topLevelTypes.topCompositionStart:
return eventTypes.compositionStart;
case topLevelTypes.topCompositionEnd:
return eventTypes.compositionEnd;
case topLevelTypes.topCompositionUpdate:
return eventTypes.compositionUpdate;
}
}
/**
* Does our fallback best-guess model think this event signifies that
* composition has begun?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionStart(topLevelType, nativeEvent) {
return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE;
}
/**
* Does our fallback mode think that this event is the end of composition?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionEnd(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topKeyUp:
// Command keys insert or clear IME input.
return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
case topLevelTypes.topKeyDown:
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return nativeEvent.keyCode !== START_KEYCODE;
case topLevelTypes.topKeyPress:
case topLevelTypes.topMouseDown:
case topLevelTypes.topBlur:
// Events are not possible without cancelling IME.
return true;
default:
return false;
}
}
/**
* Google Input Tools provides composition data via a CustomEvent,
* with the `data` property populated in the `detail` object. If this
* is available on the event object, use it. If not, this is a plain
* composition event and we have nothing special to extract.
*
* @param {object} nativeEvent
* @return {?string}
*/
function getDataFromCustomEvent(nativeEvent) {
var detail = nativeEvent.detail;
if (typeof detail === 'object' && 'data' in detail) {
return detail.data;
}
return null;
}
// Track the current IME composition fallback object, if any.
var currentComposition = null;
/**
* @return {?object} A SyntheticCompositionEvent.
*/
function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var eventType;
var fallbackData;
if (canUseCompositionEvent) {
eventType = getCompositionEventType(topLevelType);
} else if (!currentComposition) {
if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionStart;
}
} else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionEnd;
}
if (!eventType) {
return null;
}
if (useFallbackCompositionData) {
// The current composition is stored statically and must not be
// overwritten while composition continues.
if (!currentComposition && eventType === eventTypes.compositionStart) {
currentComposition = FallbackCompositionState.getPooled(nativeEventTarget);
} else if (eventType === eventTypes.compositionEnd) {
if (currentComposition) {
fallbackData = currentComposition.getData();
}
}
}
var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);
if (fallbackData) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = fallbackData;
} else {
var customData = getDataFromCustomEvent(nativeEvent);
if (customData !== null) {
event.data = customData;
}
}
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The string corresponding to this `beforeInput` event.
*/
function getNativeBeforeInputChars(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topCompositionEnd:
return getDataFromCustomEvent(nativeEvent);
case topLevelTypes.topKeyPress:
/**
* If native `textInput` events are available, our goal is to make
* use of them. However, there is a special case: the spacebar key.
* In Webkit, preventing default on a spacebar `textInput` event
* cancels character insertion, but it *also* causes the browser
* to fall back to its default spacebar behavior of scrolling the
* page.
*
* Tracking at:
* path_to_url
*
* To avoid this issue, use the keypress event as if no `textInput`
* event is available.
*/
var which = nativeEvent.which;
if (which !== SPACEBAR_CODE) {
return null;
}
hasSpaceKeypress = true;
return SPACEBAR_CHAR;
case topLevelTypes.topTextInput:
// Record the characters to be added to the DOM.
var chars = nativeEvent.data;
// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately. Android Chrome
// doesn't give us keycodes, so we need to blacklist it.
if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
return null;
}
return chars;
default:
// For other native event types, do nothing.
return null;
}
}
/**
* For browsers that do not provide the `textInput` event, extract the
* appropriate string to use for SyntheticInputEvent.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The fallback string for this `beforeInput` event.
*/
function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
// If we are currently composing (IME) and using a fallback to do so,
// try to extract the composed characters from the fallback object.
if (currentComposition) {
if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) {
var chars = currentComposition.getData();
FallbackCompositionState.release(currentComposition);
currentComposition = null;
return chars;
}
return null;
}
switch (topLevelType) {
case topLevelTypes.topPaste:
// If a paste event occurs after a keypress, throw out the input
// chars. Paste events should not lead to BeforeInput events.
return null;
case topLevelTypes.topKeyPress:
/**
* As of v27, Firefox may fire keypress events even when no character
* will be inserted. A few possibilities:
*
* - `which` is `0`. Arrow keys, Esc key, etc.
*
* - `which` is the pressed key code, but no char is available.
* Ex: 'AltGr + d` in Polish. There is no modified character for
* this key combination and no character is inserted into the
* document, but FF fires the keypress for char code `100` anyway.
* No `input` event will occur.
*
* - `which` is the pressed key code, but a command combination is
* being used. Ex: `Cmd+C`. No character is inserted, and no
* `input` event will occur.
*/
if (nativeEvent.which && !isKeypressCommand(nativeEvent)) {
return String.fromCharCode(nativeEvent.which);
}
return null;
case topLevelTypes.topCompositionEnd:
return useFallbackCompositionData ? null : nativeEvent.data;
default:
return null;
}
}
/**
* Extract a SyntheticInputEvent for `beforeInput`, based on either native
* `textInput` or fallback behavior.
*
* @return {?object} A SyntheticInputEvent.
*/
function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var chars;
if (canUseTextInputEvent) {
chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
} else {
chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
}
// If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return null;
}
var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);
event.data = chars;
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
/**
* Create an `onBeforeInput` event to match
* path_to_url#events-inputevents.
*
* This event plugin is based on the native `textInput` event
* available in Chrome, Safari, Opera, and IE. This event fires after
* `onKeyPress` and `onCompositionEnd`, but before `onInput`.
*
* `beforeInput` is spec'd but not implemented in any browsers, and
* the `input` event does not provide any useful information about what has
* actually been added, contrary to the spec. Thus, `textInput` is the best
* available event to identify the characters that have actually been inserted
* into the target node.
*
* This plugin is also responsible for emitting `composition` events, thus
* allowing us to share composition fallback code for both `beforeInput` and
* `composition` event types.
*/
var BeforeInputEventPlugin = {
eventTypes: eventTypes,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)];
}
};
module.exports = BeforeInputEventPlugin;
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventConstants
*/
'use strict';
var keyMirror = __webpack_require__(23);
var PropagationPhases = keyMirror({ bubbled: null, captured: null });
/**
* Types of raw signals from the browser caught at the top level.
*/
var topLevelTypes = keyMirror({
topAbort: null,
topAnimationEnd: null,
topAnimationIteration: null,
topAnimationStart: null,
topBlur: null,
topCanPlay: null,
topCanPlayThrough: null,
topChange: null,
topClick: null,
topCompositionEnd: null,
topCompositionStart: null,
topCompositionUpdate: null,
topContextMenu: null,
topCopy: null,
topCut: null,
topDoubleClick: null,
topDrag: null,
topDragEnd: null,
topDragEnter: null,
topDragExit: null,
topDragLeave: null,
topDragOver: null,
topDragStart: null,
topDrop: null,
topDurationChange: null,
topEmptied: null,
topEncrypted: null,
topEnded: null,
topError: null,
topFocus: null,
topInput: null,
topInvalid: null,
topKeyDown: null,
topKeyPress: null,
topKeyUp: null,
topLoad: null,
topLoadedData: null,
topLoadedMetadata: null,
topLoadStart: null,
topMouseDown: null,
topMouseMove: null,
topMouseOut: null,
topMouseOver: null,
topMouseUp: null,
topPaste: null,
topPause: null,
topPlay: null,
topPlaying: null,
topProgress: null,
topRateChange: null,
topReset: null,
topScroll: null,
topSeeked: null,
topSeeking: null,
topSelectionChange: null,
topStalled: null,
topSubmit: null,
topSuspend: null,
topTextInput: null,
topTimeUpdate: null,
topTouchCancel: null,
topTouchEnd: null,
topTouchMove: null,
topTouchStart: null,
topTransitionEnd: null,
topVolumeChange: null,
topWaiting: null,
topWheel: null
});
var EventConstants = {
topLevelTypes: topLevelTypes,
PropagationPhases: PropagationPhases
};
module.exports = EventConstants;
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPropagators
*/
'use strict';
var EventConstants = __webpack_require__(41);
var EventPluginHub = __webpack_require__(43);
var EventPluginUtils = __webpack_require__(45);
var accumulateInto = __webpack_require__(47);
var forEachAccumulated = __webpack_require__(48);
var warning = __webpack_require__(11);
var PropagationPhases = EventConstants.PropagationPhases;
var getListener = EventPluginHub.getListener;
/**
* Some event types have a notion of different registration names for different
* "phases" of propagation. This finds listeners by a given phase.
*/
function listenerAtPhase(inst, event, propagationPhase) {
var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(inst, registrationName);
}
/**
* Tags a `SyntheticEvent` with dispatched listeners. Creating this function
* here, allows us to not have to bind or create functions for each event.
* Mutating the event's members allows us to not have to create a wrapping
* "dispatch" object that pairs the event with the listener.
*/
function accumulateDirectionalDispatches(inst, upwards, event) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(inst, 'Dispatching inst must not be null') : void 0;
}
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured;
var listener = listenerAtPhase(inst, event, phase);
if (listener) {
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
}
}
/**
* Collect dispatches (must be entirely collected before dispatching - see unit
* tests). Lazily allocate the array to conserve memory. We must loop through
* each event and perform the traversal for each one. We cannot perform a
* single traversal for the entire collection of events because each event may
* have a different target.
*/
function accumulateTwoPhaseDispatchesSingle(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
}
}
/**
* Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
*/
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
var targetInst = event._targetInst;
var parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null;
EventPluginUtils.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event);
}
}
/**
* Accumulates without regard to direction, does not look for phased
* registration names. Same as `accumulateDirectDispatchesSingle` but without
* requiring that the `dispatchMarker` be the same as the dispatched ID.
*/
function accumulateDispatches(inst, ignoredDirection, event) {
if (event && event.dispatchConfig.registrationName) {
var registrationName = event.dispatchConfig.registrationName;
var listener = getListener(inst, registrationName);
if (listener) {
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
}
}
}
/**
* Accumulates dispatches on an `SyntheticEvent`, but only for the
* `dispatchMarker`.
* @param {SyntheticEvent} event
*/
function accumulateDirectDispatchesSingle(event) {
if (event && event.dispatchConfig.registrationName) {
accumulateDispatches(event._targetInst, null, event);
}
}
function accumulateTwoPhaseDispatches(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
}
function accumulateTwoPhaseDispatchesSkipTarget(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
}
function accumulateEnterLeaveDispatches(leave, enter, from, to) {
EventPluginUtils.traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
}
function accumulateDirectDispatches(events) {
forEachAccumulated(events, accumulateDirectDispatchesSingle);
}
/**
* A small set of propagation patterns, each of which will accept a small amount
* of information, and generate a set of "dispatch ready event objects" - which
* are sets of events that have already been annotated with a set of dispatched
* listener functions/ids. The API is designed this way to discourage these
* propagation strategies from actually executing the dispatches, since we
* always want to collect the entire set of dispatches before executing event a
* single one.
*
* @constructor EventPropagators
*/
var EventPropagators = {
accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches
};
module.exports = EventPropagators;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPluginHub
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var EventPluginRegistry = __webpack_require__(44);
var EventPluginUtils = __webpack_require__(45);
var ReactErrorUtils = __webpack_require__(46);
var accumulateInto = __webpack_require__(47);
var forEachAccumulated = __webpack_require__(48);
var invariant = __webpack_require__(8);
/**
* Internal store for event listeners
*/
var listenerBank = {};
/**
* Internal queue of events that have accumulated their dispatches and are
* waiting to have their dispatches executed.
*/
var eventQueue = null;
/**
* Dispatches an event and releases it back into the pool, unless persistent.
*
* @param {?object} event Synthetic event to be dispatched.
* @param {boolean} simulated If the event is simulated (changes exn behavior)
* @private
*/
var executeDispatchesAndRelease = function (event, simulated) {
if (event) {
EventPluginUtils.executeDispatchesInOrder(event, simulated);
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
};
var executeDispatchesAndReleaseSimulated = function (e) {
return executeDispatchesAndRelease(e, true);
};
var executeDispatchesAndReleaseTopLevel = function (e) {
return executeDispatchesAndRelease(e, false);
};
var getDictionaryKey = function (inst) {
// Prevents V8 performance issue:
// path_to_url
return '.' + inst._rootNodeID;
};
/**
* This is a unified interface for event plugins to be installed and configured.
*
* Event plugins can implement the following properties:
*
* `extractEvents` {function(string, DOMEventTarget, string, object): *}
* Required. When a top-level event is fired, this method is expected to
* extract synthetic events that will in turn be queued and dispatched.
*
* `eventTypes` {object}
* Optional, plugins that fire events must publish a mapping of registration
* names that are used to register listeners. Values of this mapping must
* be objects that contain `registrationName` or `phasedRegistrationNames`.
*
* `executeDispatch` {function(object, function, string)}
* Optional, allows plugins to override how an event gets dispatched. By
* default, the listener is simply invoked.
*
* Each plugin that is injected into `EventsPluginHub` is immediately operable.
*
* @public
*/
var EventPluginHub = {
/**
* Methods for injecting dependencies.
*/
injection: {
/**
* @param {array} InjectedEventPluginOrder
* @public
*/
injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder,
/**
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
*/
injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName
},
/**
* Stores `listener` at `listenerBank[registrationName][key]`. Is idempotent.
*
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {function} listener The callback to store.
*/
putListener: function (inst, registrationName, listener) {
!(typeof listener === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : _prodInvariant('94', registrationName, typeof listener) : void 0;
var key = getDictionaryKey(inst);
var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {});
bankForRegistrationName[key] = listener;
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.didPutListener) {
PluginModule.didPutListener(inst, registrationName, listener);
}
},
/**
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
getListener: function (inst, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
var key = getDictionaryKey(inst);
return bankForRegistrationName && bankForRegistrationName[key];
},
/**
* Deletes a listener from the registration bank.
*
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
*/
deleteListener: function (inst, registrationName) {
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(inst, registrationName);
}
var bankForRegistrationName = listenerBank[registrationName];
// TODO: This should never be null -- when is it?
if (bankForRegistrationName) {
var key = getDictionaryKey(inst);
delete bankForRegistrationName[key];
}
},
/**
* Deletes all listeners for the DOM element with the supplied ID.
*
* @param {object} inst The instance, which is the source of events.
*/
deleteAllListeners: function (inst) {
var key = getDictionaryKey(inst);
for (var registrationName in listenerBank) {
if (!listenerBank.hasOwnProperty(registrationName)) {
continue;
}
if (!listenerBank[registrationName][key]) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(inst, registrationName);
}
delete listenerBank[registrationName][key];
}
},
/**
* Allows registered plugins an opportunity to extract events from top-level
* native browser events.
*
* @return {*} An accumulation of synthetic events.
* @internal
*/
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var events;
var plugins = EventPluginRegistry.plugins;
for (var i = 0; i < plugins.length; i++) {
// Not every plugin in the ordering may be loaded at runtime.
var possiblePlugin = plugins[i];
if (possiblePlugin) {
var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
if (extractedEvents) {
events = accumulateInto(events, extractedEvents);
}
}
}
return events;
},
/**
* Enqueues a synthetic event that should be dispatched when
* `processEventQueue` is invoked.
*
* @param {*} events An accumulation of synthetic events.
* @internal
*/
enqueueEvents: function (events) {
if (events) {
eventQueue = accumulateInto(eventQueue, events);
}
},
/**
* Dispatches all synthetic events on the event queue.
*
* @internal
*/
processEventQueue: function (simulated) {
// Set `eventQueue` to null before processing it so that we can tell if more
// events get enqueued while processing.
var processingEventQueue = eventQueue;
eventQueue = null;
if (simulated) {
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated);
} else {
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
}
!!eventQueue ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : _prodInvariant('95') : void 0;
// This would be a good time to rethrow if any of the event handlers threw.
ReactErrorUtils.rethrowCaughtError();
},
/**
* These are needed for tests only. Do not use!
*/
__purge: function () {
listenerBank = {};
},
__getListenerBank: function () {
return listenerBank;
}
};
module.exports = EventPluginHub;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPluginRegistry
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
/**
* Injectable ordering of event plugins.
*/
var EventPluginOrder = null;
/**
* Injectable mapping from names to event plugin modules.
*/
var namesToPlugins = {};
/**
* Recomputes the plugin list using the injected plugins and plugin ordering.
*
* @private
*/
function recomputePluginOrdering() {
if (!EventPluginOrder) {
// Wait until an `EventPluginOrder` is injected.
return;
}
for (var pluginName in namesToPlugins) {
var PluginModule = namesToPlugins[pluginName];
var pluginIndex = EventPluginOrder.indexOf(pluginName);
!(pluginIndex > -1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : _prodInvariant('96', pluginName) : void 0;
if (EventPluginRegistry.plugins[pluginIndex]) {
continue;
}
!PluginModule.extractEvents ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : _prodInvariant('97', pluginName) : void 0;
EventPluginRegistry.plugins[pluginIndex] = PluginModule;
var publishedEvents = PluginModule.eventTypes;
for (var eventName in publishedEvents) {
!publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : _prodInvariant('98', eventName, pluginName) : void 0;
}
}
}
/**
* Publishes an event so that it can be dispatched by the supplied plugin.
*
* @param {object} dispatchConfig Dispatch configuration for the event.
* @param {object} PluginModule Plugin publishing the event.
* @return {boolean} True if the event was successfully published.
* @private
*/
function publishEventForPlugin(dispatchConfig, PluginModule, eventName) {
!!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : _prodInvariant('99', eventName) : void 0;
EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig;
var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
if (phasedRegistrationNames) {
for (var phaseName in phasedRegistrationNames) {
if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
var phasedRegistrationName = phasedRegistrationNames[phaseName];
publishRegistrationName(phasedRegistrationName, PluginModule, eventName);
}
}
return true;
} else if (dispatchConfig.registrationName) {
publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName);
return true;
}
return false;
}
/**
* Publishes a registration name that is used to identify dispatched events and
* can be used with `EventPluginHub.putListener` to register listeners.
*
* @param {string} registrationName Registration name to add.
* @param {object} PluginModule Plugin publishing the event.
* @private
*/
function publishRegistrationName(registrationName, PluginModule, eventName) {
!!EventPluginRegistry.registrationNameModules[registrationName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : _prodInvariant('100', registrationName) : void 0;
EventPluginRegistry.registrationNameModules[registrationName] = PluginModule;
EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies;
if (process.env.NODE_ENV !== 'production') {
var lowerCasedName = registrationName.toLowerCase();
EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName;
if (registrationName === 'onDoubleClick') {
EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName;
}
}
}
/**
* Registers plugins so that they can extract and dispatch events.
*
* @see {EventPluginHub}
*/
var EventPluginRegistry = {
/**
* Ordered list of injected plugins.
*/
plugins: [],
/**
* Mapping from event name to dispatch config
*/
eventNameDispatchConfigs: {},
/**
* Mapping from registration name to plugin module
*/
registrationNameModules: {},
/**
* Mapping from registration name to event name
*/
registrationNameDependencies: {},
/**
* Mapping from lowercase registration names to the properly cased version,
* used to warn in the case of missing event handlers. Available
* only in __DEV__.
* @type {Object}
*/
possibleRegistrationNames: process.env.NODE_ENV !== 'production' ? {} : null,
/**
* Injects an ordering of plugins (by plugin name). This allows the ordering
* to be decoupled from injection of the actual plugins so that ordering is
* always deterministic regardless of packaging, on-the-fly injection, etc.
*
* @param {array} InjectedEventPluginOrder
* @internal
* @see {EventPluginHub.injection.injectEventPluginOrder}
*/
injectEventPluginOrder: function (InjectedEventPluginOrder) {
!!EventPluginOrder ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : _prodInvariant('101') : void 0;
// Clone the ordering so it cannot be dynamically mutated.
EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder);
recomputePluginOrdering();
},
/**
* Injects plugins to be used by `EventPluginHub`. The plugin names must be
* in the ordering injected by `injectEventPluginOrder`.
*
* Plugins can be injected as part of page initialization or on-the-fly.
*
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
* @internal
* @see {EventPluginHub.injection.injectEventPluginsByName}
*/
injectEventPluginsByName: function (injectedNamesToPlugins) {
var isOrderingDirty = false;
for (var pluginName in injectedNamesToPlugins) {
if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
continue;
}
var PluginModule = injectedNamesToPlugins[pluginName];
if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) {
!!namesToPlugins[pluginName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : _prodInvariant('102', pluginName) : void 0;
namesToPlugins[pluginName] = PluginModule;
isOrderingDirty = true;
}
}
if (isOrderingDirty) {
recomputePluginOrdering();
}
},
/**
* Looks up the plugin for the supplied event.
*
* @param {object} event A synthetic event.
* @return {?object} The plugin that created the supplied event.
* @internal
*/
getPluginModuleForEvent: function (event) {
var dispatchConfig = event.dispatchConfig;
if (dispatchConfig.registrationName) {
return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null;
}
for (var phase in dispatchConfig.phasedRegistrationNames) {
if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]];
if (PluginModule) {
return PluginModule;
}
}
return null;
},
/**
* Exposed for unit testing.
* @private
*/
_resetEventPlugins: function () {
EventPluginOrder = null;
for (var pluginName in namesToPlugins) {
if (namesToPlugins.hasOwnProperty(pluginName)) {
delete namesToPlugins[pluginName];
}
}
EventPluginRegistry.plugins.length = 0;
var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs;
for (var eventName in eventNameDispatchConfigs) {
if (eventNameDispatchConfigs.hasOwnProperty(eventName)) {
delete eventNameDispatchConfigs[eventName];
}
}
var registrationNameModules = EventPluginRegistry.registrationNameModules;
for (var registrationName in registrationNameModules) {
if (registrationNameModules.hasOwnProperty(registrationName)) {
delete registrationNameModules[registrationName];
}
}
if (process.env.NODE_ENV !== 'production') {
var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames;
for (var lowerCasedName in possibleRegistrationNames) {
if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) {
delete possibleRegistrationNames[lowerCasedName];
}
}
}
}
};
module.exports = EventPluginRegistry;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPluginUtils
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var EventConstants = __webpack_require__(41);
var ReactErrorUtils = __webpack_require__(46);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
/**
* Injected dependencies:
*/
/**
* - `ComponentTree`: [required] Module that can convert between React instances
* and actual node references.
*/
var ComponentTree;
var TreeTraversal;
var injection = {
injectComponentTree: function (Injected) {
ComponentTree = Injected;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0;
}
},
injectTreeTraversal: function (Injected) {
TreeTraversal = Injected;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, 'EventPluginUtils.injection.injectTreeTraversal(...): Injected ' + 'module is missing isAncestor or getLowestCommonAncestor.') : void 0;
}
}
};
var topLevelTypes = EventConstants.topLevelTypes;
function isEndish(topLevelType) {
return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel;
}
function isMoveish(topLevelType) {
return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove;
}
function isStartish(topLevelType) {
return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart;
}
var validateEventDispatches;
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches = function (event) {
var dispatchListeners = event._dispatchListeners;
var dispatchInstances = event._dispatchInstances;
var listenersIsArr = Array.isArray(dispatchListeners);
var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
var instancesIsArr = Array.isArray(dispatchInstances);
var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
process.env.NODE_ENV !== 'production' ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : void 0;
};
}
/**
* Dispatch the event to the listener.
* @param {SyntheticEvent} event SyntheticEvent to handle
* @param {boolean} simulated If the event is simulated (changes exn behavior)
* @param {function} listener Application-level callback
* @param {*} inst Internal component instance
*/
function executeDispatch(event, simulated, listener, inst) {
var type = event.type || 'unknown-event';
event.currentTarget = EventPluginUtils.getNodeFromInstance(inst);
if (simulated) {
ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event);
} else {
ReactErrorUtils.invokeGuardedCallback(type, listener, event);
}
event.currentTarget = null;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(event, simulated) {
var dispatchListeners = event._dispatchListeners;
var dispatchInstances = event._dispatchInstances;
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and Instances are two parallel arrays that are always in sync.
executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]);
}
} else if (dispatchListeners) {
executeDispatch(event, simulated, dispatchListeners, dispatchInstances);
}
event._dispatchListeners = null;
event._dispatchInstances = null;
}
/**
* Standard/simple iteration through an event's collected dispatches, but stops
* at the first dispatch execution returning true, and returns that id.
*
* @return {?string} id of the first dispatch execution who's listener returns
* true, or null if no listener returned true.
*/
function executeDispatchesInOrderStopAtTrueImpl(event) {
var dispatchListeners = event._dispatchListeners;
var dispatchInstances = event._dispatchInstances;
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and Instances are two parallel arrays that are always in sync.
if (dispatchListeners[i](event, dispatchInstances[i])) {
return dispatchInstances[i];
}
}
} else if (dispatchListeners) {
if (dispatchListeners(event, dispatchInstances)) {
return dispatchInstances;
}
}
return null;
}
/**
* @see executeDispatchesInOrderStopAtTrueImpl
*/
function executeDispatchesInOrderStopAtTrue(event) {
var ret = executeDispatchesInOrderStopAtTrueImpl(event);
event._dispatchInstances = null;
event._dispatchListeners = null;
return ret;
}
/**
* Execution of a "direct" dispatch - there must be at most one dispatch
* accumulated on the event or it is considered an error. It doesn't really make
* sense for an event with multiple dispatches (bubbled) to keep track of the
* return values at each dispatch execution, but it does tend to make sense when
* dealing with "direct" dispatches.
*
* @return {*} The return value of executing the single dispatch.
*/
function executeDirectDispatch(event) {
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches(event);
}
var dispatchListener = event._dispatchListeners;
var dispatchInstance = event._dispatchInstances;
!!Array.isArray(dispatchListener) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : _prodInvariant('103') : void 0;
event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null;
var res = dispatchListener ? dispatchListener(event) : null;
event.currentTarget = null;
event._dispatchListeners = null;
event._dispatchInstances = null;
return res;
}
/**
* @param {SyntheticEvent} event
* @return {boolean} True iff number of dispatches accumulated is greater than 0.
*/
function hasDispatches(event) {
return !!event._dispatchListeners;
}
/**
* General utilities that are useful in creating custom Event Plugins.
*/
var EventPluginUtils = {
isEndish: isEndish,
isMoveish: isMoveish,
isStartish: isStartish,
executeDirectDispatch: executeDirectDispatch,
executeDispatchesInOrder: executeDispatchesInOrder,
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
hasDispatches: hasDispatches,
getInstanceFromNode: function (node) {
return ComponentTree.getInstanceFromNode(node);
},
getNodeFromInstance: function (node) {
return ComponentTree.getNodeFromInstance(node);
},
isAncestor: function (a, b) {
return TreeTraversal.isAncestor(a, b);
},
getLowestCommonAncestor: function (a, b) {
return TreeTraversal.getLowestCommonAncestor(a, b);
},
getParentInstance: function (inst) {
return TreeTraversal.getParentInstance(inst);
},
traverseTwoPhase: function (target, fn, arg) {
return TreeTraversal.traverseTwoPhase(target, fn, arg);
},
traverseEnterLeave: function (from, to, fn, argFrom, argTo) {
return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo);
},
injection: injection
};
module.exports = EventPluginUtils;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactErrorUtils
*/
'use strict';
var caughtError = null;
/**
* Call a function while guarding against errors that happens within it.
*
* @param {?String} name of the guard to use for logging or debugging
* @param {Function} func The function to invoke
* @param {*} a First argument
* @param {*} b Second argument
*/
function invokeGuardedCallback(name, func, a, b) {
try {
return func(a, b);
} catch (x) {
if (caughtError === null) {
caughtError = x;
}
return undefined;
}
}
var ReactErrorUtils = {
invokeGuardedCallback: invokeGuardedCallback,
/**
* Invoked by ReactTestUtils.Simulate so that any errors thrown by the event
* handler are sure to be rethrown by rethrowCaughtError.
*/
invokeGuardedCallbackWithCatch: invokeGuardedCallback,
/**
* During execution of guarded functions we will capture the first error which
* we will rethrow to be handled by the top level error handler.
*/
rethrowCaughtError: function () {
if (caughtError) {
var error = caughtError;
caughtError = null;
throw error;
}
}
};
if (process.env.NODE_ENV !== 'production') {
/**
* To help development we can get better devtools integration by simulating a
* real browser event.
*/
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
var fakeNode = document.createElement('react');
ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) {
var boundFunc = func.bind(null, a, b);
var evtType = 'react-' + name;
fakeNode.addEventListener(evtType, boundFunc, false);
var evt = document.createEvent('Event');
evt.initEvent(evtType, false, false);
fakeNode.dispatchEvent(evt);
fakeNode.removeEventListener(evtType, boundFunc, false);
};
}
}
module.exports = ReactErrorUtils;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule accumulateInto
*
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
/**
* Accumulates items that must not be null or undefined into the first one. This
* is used to conserve memory by avoiding array allocations, and thus sacrifices
* API cleanness. Since `current` can be null before being passed in and not
* null after this function, make sure to assign it back to `current`:
*
* `a = accumulateInto(a, b);`
*
* This API should be sparingly used. Try `accumulate` for something cleaner.
*
* @return {*|array<*>} An accumulation of items.
*/
function accumulateInto(current, next) {
!(next != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : _prodInvariant('30') : void 0;
if (current == null) {
return next;
}
// Both are not empty. Warning: Never call x.concat(y) when you are not
// certain that x is an Array (x could be a string with concat method).
if (Array.isArray(current)) {
if (Array.isArray(next)) {
current.push.apply(current, next);
return current;
}
current.push(next);
return current;
}
if (Array.isArray(next)) {
// A bit too dangerous to mutate `next`.
return [current].concat(next);
}
return [current, next];
}
module.exports = accumulateInto;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 48 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule forEachAccumulated
*
*/
'use strict';
/**
* @param {array} arr an "accumulation" of items which is either an Array or
* a single item. Useful when paired with the `accumulate` module. This is a
* simple utility that allows us to reason about a collection of items, but
* handling the case when there is exactly one item (and we do not need to
* allocate an array).
*/
function forEachAccumulated(arr, cb, scope) {
if (Array.isArray(arr)) {
arr.forEach(cb, scope);
} else if (arr) {
cb.call(scope, arr);
}
}
module.exports = forEachAccumulated;
/***/ },
/* 49 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/**
* Simple, lightweight module assisting with the detection and context of
* Worker. Helps avoid circular dependencies and allows code to reason about
* whether or not they are in a Worker, even if they never include the main
* `ReactWorker` dependency.
*/
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
/***/ },
/* 50 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule FallbackCompositionState
*/
'use strict';
var _assign = __webpack_require__(4);
var PooledClass = __webpack_require__(6);
var getTextContentAccessor = __webpack_require__(51);
/**
* This helper class stores information about text content of a target node,
* allowing comparison of content before and after a given event.
*
* Identify the node where selection currently begins, then observe
* both its text content and its current position in the DOM. Since the
* browser may natively replace the target node during composition, we can
* use its position to find its replacement.
*
* @param {DOMEventTarget} root
*/
function FallbackCompositionState(root) {
this._root = root;
this._startText = this.getText();
this._fallbackText = null;
}
_assign(FallbackCompositionState.prototype, {
destructor: function () {
this._root = null;
this._startText = null;
this._fallbackText = null;
},
/**
* Get current text of input.
*
* @return {string}
*/
getText: function () {
if ('value' in this._root) {
return this._root.value;
}
return this._root[getTextContentAccessor()];
},
/**
* Determine the differing substring between the initially stored
* text content and the current content.
*
* @return {string}
*/
getData: function () {
if (this._fallbackText) {
return this._fallbackText;
}
var start;
var startValue = this._startText;
var startLength = startValue.length;
var end;
var endValue = this.getText();
var endLength = endValue.length;
for (start = 0; start < startLength; start++) {
if (startValue[start] !== endValue[start]) {
break;
}
}
var minEnd = startLength - start;
for (end = 1; end <= minEnd; end++) {
if (startValue[startLength - end] !== endValue[endLength - end]) {
break;
}
}
var sliceTail = end > 1 ? 1 - end : undefined;
this._fallbackText = endValue.slice(start, sliceTail);
return this._fallbackText;
}
});
PooledClass.addPoolingTo(FallbackCompositionState);
module.exports = FallbackCompositionState;
/***/ },
/* 51 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getTextContentAccessor
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(49);
var contentKey = null;
/**
* Gets the key used to access text content on a DOM node.
*
* @return {?string} Key used to access text content.
* @internal
*/
function getTextContentAccessor() {
if (!contentKey && ExecutionEnvironment.canUseDOM) {
// Prefer textContent to innerText because many browsers support both but
// SVG <text> elements don't support innerText even when <div> does.
contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText';
}
return contentKey;
}
module.exports = getTextContentAccessor;
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticCompositionEvent
*/
'use strict';
var SyntheticEvent = __webpack_require__(53);
/**
* @interface Event
* @see path_to_url#events-compositionevents
*/
var CompositionEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface);
module.exports = SyntheticCompositionEvent;
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticEvent
*/
'use strict';
var _assign = __webpack_require__(4);
var PooledClass = __webpack_require__(6);
var emptyFunction = __webpack_require__(12);
var warning = __webpack_require__(11);
var didWarnForAddedNewProperty = false;
var isProxySupported = typeof Proxy === 'function';
var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances'];
/**
* @interface Event
* @see path_to_url
*/
var EventInterface = {
type: null,
target: null,
// currentTarget is set when dispatching; no use in copying it here
currentTarget: emptyFunction.thatReturnsNull,
eventPhase: null,
bubbles: null,
cancelable: null,
timeStamp: function (event) {
return event.timeStamp || Date.now();
},
defaultPrevented: null,
isTrusted: null
};
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {*} targetInst Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @param {DOMEventTarget} nativeEventTarget Target node.
*/
function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
if (process.env.NODE_ENV !== 'production') {
// these have a getter/setter for warnings
delete this.nativeEvent;
delete this.preventDefault;
delete this.stopPropagation;
}
this.dispatchConfig = dispatchConfig;
this._targetInst = targetInst;
this.nativeEvent = nativeEvent;
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (!Interface.hasOwnProperty(propName)) {
continue;
}
if (process.env.NODE_ENV !== 'production') {
delete this[propName]; // this has a getter/setter for warnings
}
var normalize = Interface[propName];
if (normalize) {
this[propName] = normalize(nativeEvent);
} else {
if (propName === 'target') {
this.target = nativeEventTarget;
} else {
this[propName] = nativeEvent[propName];
}
}
}
var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
if (defaultPrevented) {
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
} else {
this.isDefaultPrevented = emptyFunction.thatReturnsFalse;
}
this.isPropagationStopped = emptyFunction.thatReturnsFalse;
return this;
}
_assign(SyntheticEvent.prototype, {
preventDefault: function () {
this.defaultPrevented = true;
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
},
stopPropagation: function () {
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.stopPropagation) {
event.stopPropagation();
} else if (typeof event.cancelBubble !== 'unknown') {
// eslint-disable-line valid-typeof
// The ChangeEventPlugin registers a "propertychange" event for
// IE. This event does not support bubbling or cancelling, and
// any references to cancelBubble throw "Member not found". A
// typeof check of "unknown" circumvents this issue (and is also
// IE specific).
event.cancelBubble = true;
}
this.isPropagationStopped = emptyFunction.thatReturnsTrue;
},
/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/
persist: function () {
this.isPersistent = emptyFunction.thatReturnsTrue;
},
/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/
isPersistent: emptyFunction.thatReturnsFalse,
/**
* `PooledClass` looks for `destructor` on each instance it releases.
*/
destructor: function () {
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (process.env.NODE_ENV !== 'production') {
Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
} else {
this[propName] = null;
}
}
for (var i = 0; i < shouldBeReleasedProperties.length; i++) {
this[shouldBeReleasedProperties[i]] = null;
}
if (process.env.NODE_ENV !== 'production') {
Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction));
Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction));
}
}
});
SyntheticEvent.Interface = EventInterface;
if (process.env.NODE_ENV !== 'production') {
if (isProxySupported) {
/*eslint-disable no-func-assign */
SyntheticEvent = new Proxy(SyntheticEvent, {
construct: function (target, args) {
return this.apply(target, Object.create(target.prototype), args);
},
apply: function (constructor, that, args) {
return new Proxy(constructor.apply(that, args), {
set: function (target, prop, value) {
if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) {
process.env.NODE_ENV !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re adding a new property in the synthetic event object. ' + 'The property is never released. See ' + 'path_to_url for more information.') : void 0;
didWarnForAddedNewProperty = true;
}
target[prop] = value;
return true;
}
});
}
});
/*eslint-enable no-func-assign */
}
}
/**
* Helper to reduce boilerplate when creating subclasses.
*
* @param {function} Class
* @param {?object} Interface
*/
SyntheticEvent.augmentClass = function (Class, Interface) {
var Super = this;
var E = function () {};
E.prototype = Super.prototype;
var prototype = new E();
_assign(prototype, Class.prototype);
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.Interface = _assign({}, Super.Interface, Interface);
Class.augmentClass = Super.augmentClass;
PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler);
};
PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler);
module.exports = SyntheticEvent;
/**
* Helper to nullify syntheticEvent instance properties when destructing
*
* @param {object} SyntheticEvent
* @param {String} propName
* @return {object} defineProperty object
*/
function getPooledWarningPropertyDefinition(propName, getVal) {
var isFunction = typeof getVal === 'function';
return {
configurable: true,
set: set,
get: get
};
function set(val) {
var action = isFunction ? 'setting the method' : 'setting the property';
warn(action, 'This is effectively a no-op');
return val;
}
function get() {
var action = isFunction ? 'accessing the method' : 'accessing the property';
var result = isFunction ? 'This is a no-op function' : 'This is set to null';
warn(action, result);
return getVal;
}
function warn(action, result) {
var warningCondition = false;
process.env.NODE_ENV !== 'production' ? warning(warningCondition, 'This synthetic event is reused for performance reasons. If you\'re seeing this, ' + 'you\'re %s `%s` on a released/nullified synthetic event. %s. ' + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See path_to_url for more information.', action, propName, result) : void 0;
}
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticInputEvent
*/
'use strict';
var SyntheticEvent = __webpack_require__(53);
/**
* @interface Event
* @see path_to_url
* /#events-inputevents
*/
var InputEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface);
module.exports = SyntheticInputEvent;
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ChangeEventPlugin
*/
'use strict';
var EventConstants = __webpack_require__(41);
var EventPluginHub = __webpack_require__(43);
var EventPropagators = __webpack_require__(42);
var ExecutionEnvironment = __webpack_require__(49);
var ReactDOMComponentTree = __webpack_require__(36);
var ReactUpdates = __webpack_require__(56);
var SyntheticEvent = __webpack_require__(53);
var getEventTarget = __webpack_require__(70);
var isEventSupported = __webpack_require__(71);
var isTextInputElement = __webpack_require__(72);
var keyOf = __webpack_require__(25);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
change: {
phasedRegistrationNames: {
bubbled: keyOf({ onChange: null }),
captured: keyOf({ onChangeCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange]
}
};
/**
* For IE shims
*/
var activeElement = null;
var activeElementInst = null;
var activeElementValue = null;
var activeElementValueProp = null;
/**
* SECTION: handle `change` event
*/
function shouldUseChangeEvent(elem) {
var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
}
var doesChangeEventBubble = false;
if (ExecutionEnvironment.canUseDOM) {
// See `handleChange` comment below
doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8);
}
function manualDispatchChangeEvent(nativeEvent) {
var event = SyntheticEvent.getPooled(eventTypes.change, activeElementInst, nativeEvent, getEventTarget(nativeEvent));
EventPropagators.accumulateTwoPhaseDispatches(event);
// If change and propertychange bubbled, we'd just bind to it like all the
// other events and have it go through ReactBrowserEventEmitter. Since it
// doesn't, we manually listen for the events and so we have to enqueue and
// process the abstract event manually.
//
// Batching is necessary here in order to ensure that all event handlers run
// before the next rerender (including event handlers attached to ancestor
// elements instead of directly on the input). Without this, controlled
// components don't work properly in conjunction with event bubbling because
// the component is rerendered and the value reverted before all the event
// handlers can run. See path_to_url
ReactUpdates.batchedUpdates(runEventInBatch, event);
}
function runEventInBatch(event) {
EventPluginHub.enqueueEvents(event);
EventPluginHub.processEventQueue(false);
}
function startWatchingForChangeEventIE8(target, targetInst) {
activeElement = target;
activeElementInst = targetInst;
activeElement.attachEvent('onchange', manualDispatchChangeEvent);
}
function stopWatchingForChangeEventIE8() {
if (!activeElement) {
return;
}
activeElement.detachEvent('onchange', manualDispatchChangeEvent);
activeElement = null;
activeElementInst = null;
}
function getTargetInstForChangeEvent(topLevelType, targetInst) {
if (topLevelType === topLevelTypes.topChange) {
return targetInst;
}
}
function handleEventsForChangeEventIE8(topLevelType, target, targetInst) {
if (topLevelType === topLevelTypes.topFocus) {
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForChangeEventIE8();
startWatchingForChangeEventIE8(target, targetInst);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForChangeEventIE8();
}
}
/**
* SECTION: handle `input` event
*/
var isInputEventSupported = false;
if (ExecutionEnvironment.canUseDOM) {
// IE9 claims to support the input event but fails to trigger it when
// deleting text, so we ignore its input events.
// IE10+ fire input events to often, such when a placeholder
// changes or when an input with a placeholder is focused.
isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 11);
}
/**
* (For IE <=11) Replacement getter/setter for the `value` property that gets
* set on the active element.
*/
var newValueProp = {
get: function () {
return activeElementValueProp.get.call(this);
},
set: function (val) {
// Cast to a string so we can do equality checks.
activeElementValue = '' + val;
activeElementValueProp.set.call(this, val);
}
};
/**
* (For IE <=11) Starts tracking propertychange events on the passed-in element
* and override the value property so that we can distinguish user events from
* value changes in JS.
*/
function startWatchingForValueChange(target, targetInst) {
activeElement = target;
activeElementInst = targetInst;
activeElementValue = target.value;
activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value');
// Not guarded in a canDefineProperty check: IE8 supports defineProperty only
// on DOM elements
Object.defineProperty(activeElement, 'value', newValueProp);
if (activeElement.attachEvent) {
activeElement.attachEvent('onpropertychange', handlePropertyChange);
} else {
activeElement.addEventListener('propertychange', handlePropertyChange, false);
}
}
/**
* (For IE <=11) Removes the event listeners from the currently-tracked element,
* if any exists.
*/
function stopWatchingForValueChange() {
if (!activeElement) {
return;
}
// delete restores the original property definition
delete activeElement.value;
if (activeElement.detachEvent) {
activeElement.detachEvent('onpropertychange', handlePropertyChange);
} else {
activeElement.removeEventListener('propertychange', handlePropertyChange, false);
}
activeElement = null;
activeElementInst = null;
activeElementValue = null;
activeElementValueProp = null;
}
/**
* (For IE <=11) Handles a propertychange event, sending a `change` event if
* the value of the active element has changed.
*/
function handlePropertyChange(nativeEvent) {
if (nativeEvent.propertyName !== 'value') {
return;
}
var value = nativeEvent.srcElement.value;
if (value === activeElementValue) {
return;
}
activeElementValue = value;
manualDispatchChangeEvent(nativeEvent);
}
/**
* If a `change` event should be fired, returns the target's ID.
*/
function getTargetInstForInputEvent(topLevelType, targetInst) {
if (topLevelType === topLevelTypes.topInput) {
// In modern browsers (i.e., not IE8 or IE9), the input event is exactly
// what we want so fall through here and trigger an abstract event
return targetInst;
}
}
function handleEventsForInputEventIE(topLevelType, target, targetInst) {
if (topLevelType === topLevelTypes.topFocus) {
// In IE8, we can capture almost all .value changes by adding a
// propertychange handler and looking for events with propertyName
// equal to 'value'
// In IE9-11, propertychange fires for most input events but is buggy and
// doesn't fire when text is deleted, but conveniently, selectionchange
// appears to fire in all of the remaining cases so we catch those and
// forward the event if the value has changed
// In either case, we don't want to call the event handler if the value
// is changed from JS so we redefine a setter for `.value` that updates
// our activeElementValue variable, allowing us to ignore those changes
//
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForValueChange();
startWatchingForValueChange(target, targetInst);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForValueChange();
}
}
// For IE8 and IE9.
function getTargetInstForInputEventIE(topLevelType, targetInst) {
if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) {
// On the selectionchange event, the target is just document which isn't
// helpful for us so just check activeElement instead.
//
// 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
// propertychange on the first input event after setting `value` from a
// script and fires only keydown, keypress, keyup. Catching keyup usually
// gets it and catching keydown lets us fire an event for the first
// keystroke if user does a key repeat (it'll be a little delayed: right
// before the second keystroke). Other input methods (e.g., paste) seem to
// fire selectionchange normally.
if (activeElement && activeElement.value !== activeElementValue) {
activeElementValue = activeElement.value;
return activeElementInst;
}
}
}
/**
* SECTION: handle `click` event
*/
function shouldUseClickEvent(elem) {
// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
}
function getTargetInstForClickEvent(topLevelType, targetInst) {
if (topLevelType === topLevelTypes.topClick) {
return targetInst;
}
}
/**
* This plugin creates an `onChange` event that normalizes change events
* across form elements. This event fires at a time when it's possible to
* change the element's value without seeing a flicker.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - select
*/
var ChangeEventPlugin = {
eventTypes: eventTypes,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window;
var getTargetInstFunc, handleEventFunc;
if (shouldUseChangeEvent(targetNode)) {
if (doesChangeEventBubble) {
getTargetInstFunc = getTargetInstForChangeEvent;
} else {
handleEventFunc = handleEventsForChangeEventIE8;
}
} else if (isTextInputElement(targetNode)) {
if (isInputEventSupported) {
getTargetInstFunc = getTargetInstForInputEvent;
} else {
getTargetInstFunc = getTargetInstForInputEventIE;
handleEventFunc = handleEventsForInputEventIE;
}
} else if (shouldUseClickEvent(targetNode)) {
getTargetInstFunc = getTargetInstForClickEvent;
}
if (getTargetInstFunc) {
var inst = getTargetInstFunc(topLevelType, targetInst);
if (inst) {
var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, nativeEventTarget);
event.type = 'change';
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
if (handleEventFunc) {
handleEventFunc(topLevelType, targetNode, targetInst);
}
}
};
module.exports = ChangeEventPlugin;
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactUpdates
*/
'use strict';
var _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var CallbackQueue = __webpack_require__(57);
var PooledClass = __webpack_require__(6);
var ReactFeatureFlags = __webpack_require__(58);
var ReactReconciler = __webpack_require__(59);
var Transaction = __webpack_require__(69);
var invariant = __webpack_require__(8);
var dirtyComponents = [];
var updateBatchNumber = 0;
var asapCallbackQueue = CallbackQueue.getPooled();
var asapEnqueued = false;
var batchingStrategy = null;
function ensureInjected() {
!(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching strategy') : _prodInvariant('123') : void 0;
}
var NESTED_UPDATES = {
initialize: function () {
this.dirtyComponentsLength = dirtyComponents.length;
},
close: function () {
if (this.dirtyComponentsLength !== dirtyComponents.length) {
// Additional updates were enqueued by componentDidUpdate handlers or
// similar; before our own UPDATE_QUEUEING wrapper closes, we want to run
// these new updates so that if A's componentDidUpdate calls setState on
// B, B will update before the callback A's updater provided when calling
// setState.
dirtyComponents.splice(0, this.dirtyComponentsLength);
flushBatchedUpdates();
} else {
dirtyComponents.length = 0;
}
}
};
var UPDATE_QUEUEING = {
initialize: function () {
this.callbackQueue.reset();
},
close: function () {
this.callbackQueue.notifyAll();
}
};
var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING];
function ReactUpdatesFlushTransaction() {
this.reinitializeTransaction();
this.dirtyComponentsLength = null;
this.callbackQueue = CallbackQueue.getPooled();
this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(
/* useCreateElement */true);
}
_assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, {
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
destructor: function () {
this.dirtyComponentsLength = null;
CallbackQueue.release(this.callbackQueue);
this.callbackQueue = null;
ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);
this.reconcileTransaction = null;
},
perform: function (method, scope, a) {
// Essentially calls `this.reconcileTransaction.perform(method, scope, a)`
// with this transaction's wrappers around it.
return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a);
}
});
PooledClass.addPoolingTo(ReactUpdatesFlushTransaction);
function batchedUpdates(callback, a, b, c, d, e) {
ensureInjected();
batchingStrategy.batchedUpdates(callback, a, b, c, d, e);
}
/**
* Array comparator for ReactComponents by mount ordering.
*
* @param {ReactComponent} c1 first component you're comparing
* @param {ReactComponent} c2 second component you're comparing
* @return {number} Return value usable by Array.prototype.sort().
*/
function mountOrderComparator(c1, c2) {
return c1._mountOrder - c2._mountOrder;
}
function runBatchedUpdates(transaction) {
var len = transaction.dirtyComponentsLength;
!(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to match dirty-components array length (%s).', len, dirtyComponents.length) : _prodInvariant('124', len, dirtyComponents.length) : void 0;
// Since reconciling a component higher in the owner hierarchy usually (not
// always -- see shouldComponentUpdate()) will reconcile children, reconcile
// them before their children by sorting the array.
dirtyComponents.sort(mountOrderComparator);
// Any updates enqueued while reconciling must be performed after this entire
// batch. Otherwise, if dirtyComponents is [A, B] where A has children B and
// C, B could update twice in a single batch if C's render enqueues an update
// to B (since B would have already updated, we should skip it, and the only
// way we can know to do so is by checking the batch counter).
updateBatchNumber++;
for (var i = 0; i < len; i++) {
// If a component is unmounted before pending changes apply, it will still
// be here, but we assume that it has cleared its _pendingCallbacks and
// that performUpdateIfNecessary is a noop.
var component = dirtyComponents[i];
// If performUpdateIfNecessary happens to enqueue any new updates, we
// shouldn't execute the callbacks until the next render happens, so
// stash the callbacks first
var callbacks = component._pendingCallbacks;
component._pendingCallbacks = null;
var markerName;
if (ReactFeatureFlags.logTopLevelRenders) {
var namedComponent = component;
// Duck type TopLevelWrapper. This is probably always true.
if (component._currentElement.props === component._renderedComponent._currentElement) {
namedComponent = component._renderedComponent;
}
markerName = 'React update: ' + namedComponent.getName();
console.time(markerName);
}
ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber);
if (markerName) {
console.timeEnd(markerName);
}
if (callbacks) {
for (var j = 0; j < callbacks.length; j++) {
transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance());
}
}
}
}
var flushBatchedUpdates = function () {
// ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents
// array and perform any updates enqueued by mount-ready handlers (i.e.,
// componentDidUpdate) but we need to check here too in order to catch
// updates enqueued by setState callbacks and asap calls.
while (dirtyComponents.length || asapEnqueued) {
if (dirtyComponents.length) {
var transaction = ReactUpdatesFlushTransaction.getPooled();
transaction.perform(runBatchedUpdates, null, transaction);
ReactUpdatesFlushTransaction.release(transaction);
}
if (asapEnqueued) {
asapEnqueued = false;
var queue = asapCallbackQueue;
asapCallbackQueue = CallbackQueue.getPooled();
queue.notifyAll();
CallbackQueue.release(queue);
}
}
};
/**
* Mark a component as needing a rerender, adding an optional callback to a
* list of functions which will be executed once the rerender occurs.
*/
function enqueueUpdate(component) {
ensureInjected();
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (This is called by each top-level update
// function, like setState, forceUpdate, etc.; creation and
// destruction of top-level components is guarded in ReactMount.)
if (!batchingStrategy.isBatchingUpdates) {
batchingStrategy.batchedUpdates(enqueueUpdate, component);
return;
}
dirtyComponents.push(component);
if (component._updateBatchNumber == null) {
component._updateBatchNumber = updateBatchNumber + 1;
}
}
/**
* Enqueue a callback to be run at the end of the current batching cycle. Throws
* if no updates are currently being performed.
*/
function asap(callback, context) {
!batchingStrategy.isBatchingUpdates ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context whereupdates are not being batched.') : _prodInvariant('125') : void 0;
asapCallbackQueue.enqueue(callback, context);
asapEnqueued = true;
}
var ReactUpdatesInjection = {
injectReconcileTransaction: function (ReconcileTransaction) {
!ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : _prodInvariant('126') : void 0;
ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
},
injectBatchingStrategy: function (_batchingStrategy) {
!_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : _prodInvariant('127') : void 0;
!(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : _prodInvariant('128') : void 0;
!(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : _prodInvariant('129') : void 0;
batchingStrategy = _batchingStrategy;
}
};
var ReactUpdates = {
/**
* React references `ReactReconcileTransaction` using this property in order
* to allow dependency injection.
*
* @internal
*/
ReactReconcileTransaction: null,
batchedUpdates: batchedUpdates,
enqueueUpdate: enqueueUpdate,
flushBatchedUpdates: flushBatchedUpdates,
injection: ReactUpdatesInjection,
asap: asap
};
module.exports = ReactUpdates;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CallbackQueue
*/
'use strict';
var _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var PooledClass = __webpack_require__(6);
var invariant = __webpack_require__(8);
/**
* A specialized pseudo-event module to help keep track of components waiting to
* be notified when their DOM representations are available for use.
*
* This implements `PooledClass`, so you should never need to instantiate this.
* Instead, use `CallbackQueue.getPooled()`.
*
* @class ReactMountReady
* @implements PooledClass
* @internal
*/
function CallbackQueue() {
this._callbacks = null;
this._contexts = null;
}
_assign(CallbackQueue.prototype, {
/**
* Enqueues a callback to be invoked when `notifyAll` is invoked.
*
* @param {function} callback Invoked when `notifyAll` is invoked.
* @param {?object} context Context to call `callback` with.
* @internal
*/
enqueue: function (callback, context) {
this._callbacks = this._callbacks || [];
this._contexts = this._contexts || [];
this._callbacks.push(callback);
this._contexts.push(context);
},
/**
* Invokes all enqueued callbacks and clears the queue. This is invoked after
* the DOM representation of a component has been created or updated.
*
* @internal
*/
notifyAll: function () {
var callbacks = this._callbacks;
var contexts = this._contexts;
if (callbacks) {
!(callbacks.length === contexts.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : _prodInvariant('24') : void 0;
this._callbacks = null;
this._contexts = null;
for (var i = 0; i < callbacks.length; i++) {
callbacks[i].call(contexts[i]);
}
callbacks.length = 0;
contexts.length = 0;
}
},
checkpoint: function () {
return this._callbacks ? this._callbacks.length : 0;
},
rollback: function (len) {
if (this._callbacks) {
this._callbacks.length = len;
this._contexts.length = len;
}
},
/**
* Resets the internal queue.
*
* @internal
*/
reset: function () {
this._callbacks = null;
this._contexts = null;
},
/**
* `PooledClass` looks for this.
*/
destructor: function () {
this.reset();
}
});
PooledClass.addPoolingTo(CallbackQueue);
module.exports = CallbackQueue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 58 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactFeatureFlags
*
*/
'use strict';
var ReactFeatureFlags = {
// When true, call console.time() before and .timeEnd() after each top-level
// render (both initial renders and updates). Useful when looking at prod-mode
// timeline profiles in Chrome, for example.
logTopLevelRenders: false
};
module.exports = ReactFeatureFlags;
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactReconciler
*/
'use strict';
var ReactRef = __webpack_require__(60);
var ReactInstrumentation = __webpack_require__(62);
var warning = __webpack_require__(11);
/**
* Helper to call ReactRef.attachRefs with this composite component, split out
* to avoid allocations in the transaction mount-ready queue.
*/
function attachRefs() {
ReactRef.attachRefs(this, this._currentElement);
}
var ReactReconciler = {
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactComponent} internalInstance
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?object} the containing host component instance
* @param {?object} info about the host container
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (internalInstance, transaction, hostParent, hostContainerInfo, context, parentDebugID // 0 in production and for roots
) {
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onBeforeMountComponent(internalInstance._debugID, internalInstance._currentElement, parentDebugID);
}
}
var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context, parentDebugID);
if (internalInstance._currentElement && internalInstance._currentElement.ref != null) {
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
}
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID);
}
}
return markup;
},
/**
* Returns a value that can be passed to
* ReactComponentEnvironment.replaceNodeWithMarkup.
*/
getHostNode: function (internalInstance) {
return internalInstance.getHostNode();
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function (internalInstance, safely) {
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onBeforeUnmountComponent(internalInstance._debugID);
}
}
ReactRef.detachRefs(internalInstance, internalInstance._currentElement);
internalInstance.unmountComponent(safely);
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID);
}
}
},
/**
* Update a component using a new element.
*
* @param {ReactComponent} internalInstance
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @internal
*/
receiveComponent: function (internalInstance, nextElement, transaction, context) {
var prevElement = internalInstance._currentElement;
if (nextElement === prevElement && context === internalInstance._context) {
// Since elements are immutable after the owner is rendered,
// we can do a cheap identity compare here to determine if this is a
// superfluous reconcile. It's possible for state to be mutable but such
// change should trigger an update of the owner which would recreate
// the element. We explicitly check for the existence of an owner since
// it's possible for an element created outside a composite to be
// deeply mutated and reused.
// TODO: Bailing out early is just a perf optimization right?
// TODO: Removing the return statement should affect correctness?
return;
}
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement);
}
}
var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement);
if (refsChanged) {
ReactRef.detachRefs(internalInstance, prevElement);
}
internalInstance.receiveComponent(nextElement, transaction, context);
if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) {
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
}
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);
}
}
},
/**
* Flush any dirty changes in a component.
*
* @param {ReactComponent} internalInstance
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function (internalInstance, transaction, updateBatchNumber) {
if (internalInstance._updateBatchNumber !== updateBatchNumber) {
// The component's enqueued batch number should always be the current
// batch or the following one.
process.env.NODE_ENV !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0;
return;
}
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement);
}
}
internalInstance.performUpdateIfNecessary(transaction);
if (process.env.NODE_ENV !== 'production') {
if (internalInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID);
}
}
}
};
module.exports = ReactReconciler;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactRef
*/
'use strict';
var ReactOwner = __webpack_require__(61);
var ReactRef = {};
function attachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(component.getPublicInstance());
} else {
// Legacy ref
ReactOwner.addComponentAsRefTo(component, ref, owner);
}
}
function detachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(null);
} else {
// Legacy ref
ReactOwner.removeComponentAsRefFrom(component, ref, owner);
}
}
ReactRef.attachRefs = function (instance, element) {
if (element === null || element === false) {
return;
}
var ref = element.ref;
if (ref != null) {
attachRef(ref, instance, element._owner);
}
};
ReactRef.shouldUpdateRefs = function (prevElement, nextElement) {
// If either the owner or a `ref` has changed, make sure the newest owner
// has stored a reference to `this`, and the previous owner (if different)
// has forgotten the reference to `this`. We use the element instead
// of the public this.props because the post processing cannot determine
// a ref. The ref conceptually lives on the element.
// TODO: Should this even be possible? The owner cannot change because
// it's forbidden by shouldUpdateReactComponent. The ref can change
// if you swap the keys of but not the refs. Reconsider where this check
// is made. It probably belongs where the key checking and
// instantiateReactComponent is done.
var prevEmpty = prevElement === null || prevElement === false;
var nextEmpty = nextElement === null || nextElement === false;
return (
// This has a few false positives w/r/t empty components.
prevEmpty || nextEmpty || nextElement.ref !== prevElement.ref ||
// If owner changes but we have an unchanged function ref, don't update refs
typeof nextElement.ref === 'string' && nextElement._owner !== prevElement._owner
);
};
ReactRef.detachRefs = function (instance, element) {
if (element === null || element === false) {
return;
}
var ref = element.ref;
if (ref != null) {
detachRef(ref, instance, element._owner);
}
};
module.exports = ReactRef;
/***/ },
/* 61 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactOwner
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
/**
* ReactOwners are capable of storing references to owned components.
*
* All components are capable of //being// referenced by owner components, but
* only ReactOwner components are capable of //referencing// owned components.
* The named reference is known as a "ref".
*
* Refs are available when mounted and updated during reconciliation.
*
* var MyComponent = React.createClass({
* render: function() {
* return (
* <div onClick={this.handleClick}>
* <CustomComponent ref="custom" />
* </div>
* );
* },
* handleClick: function() {
* this.refs.custom.handleClick();
* },
* componentDidMount: function() {
* this.refs.custom.initialize();
* }
* });
*
* Refs should rarely be used. When refs are used, they should only be done to
* control data that is not handled by React's data flow.
*
* @class ReactOwner
*/
var ReactOwner = {
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid owner.
* @final
*/
isValidOwner: function (object) {
return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function');
},
/**
* Adds a component by ref to an owner component.
*
* @param {ReactComponent} component Component to reference.
* @param {string} ref Name by which to refer to the component.
* @param {ReactOwner} owner Component on which to record the ref.
* @final
* @internal
*/
addComponentAsRefTo: function (component, ref, owner) {
!ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: path_to_url : _prodInvariant('119') : void 0;
owner.attachRef(ref, component);
},
/**
* Removes a component by ref from an owner component.
*
* @param {ReactComponent} component Component to dereference.
* @param {string} ref Name of the ref to remove.
* @param {ReactOwner} owner Component on which the ref is recorded.
* @final
* @internal
*/
removeComponentAsRefFrom: function (component, ref, owner) {
!ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might be removing a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: path_to_url : _prodInvariant('120') : void 0;
var ownerPublicInstance = owner.getPublicInstance();
// Check that `component`'s owner is still alive and that `component` is still the current ref
// because we do not want to detach the ref if another component stole it.
if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) {
owner.detachRef(ref);
}
}
};
module.exports = ReactOwner;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 62 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInstrumentation
*/
'use strict';
var debugTool = null;
if (process.env.NODE_ENV !== 'production') {
var ReactDebugTool = __webpack_require__(63);
debugTool = ReactDebugTool;
}
module.exports = { debugTool: debugTool };
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDebugTool
*/
'use strict';
var ReactInvalidSetStateWarningHook = __webpack_require__(64);
var ReactHostOperationHistoryHook = __webpack_require__(65);
var ReactComponentTreeHook = __webpack_require__(28);
var ReactChildrenMutationWarningHook = __webpack_require__(66);
var ExecutionEnvironment = __webpack_require__(49);
var performanceNow = __webpack_require__(67);
var warning = __webpack_require__(11);
var hooks = [];
var didHookThrowForEvent = {};
function callHook(event, fn, context, arg1, arg2, arg3, arg4, arg5) {
try {
fn.call(context, arg1, arg2, arg3, arg4, arg5);
} catch (e) {
process.env.NODE_ENV !== 'production' ? warning(didHookThrowForEvent[event], 'Exception thrown by hook while handling %s: %s', event, e + '\n' + e.stack) : void 0;
didHookThrowForEvent[event] = true;
}
}
function emitEvent(event, arg1, arg2, arg3, arg4, arg5) {
for (var i = 0; i < hooks.length; i++) {
var hook = hooks[i];
var fn = hook[event];
if (fn) {
callHook(event, fn, hook, arg1, arg2, arg3, arg4, arg5);
}
}
}
var isProfiling = false;
var flushHistory = [];
var lifeCycleTimerStack = [];
var currentFlushNesting = 0;
var currentFlushMeasurements = null;
var currentFlushStartTime = null;
var currentTimerDebugID = null;
var currentTimerStartTime = null;
var currentTimerNestedFlushDuration = null;
var currentTimerType = null;
var lifeCycleTimerHasWarned = false;
function clearHistory() {
ReactComponentTreeHook.purgeUnmountedComponents();
ReactHostOperationHistoryHook.clearHistory();
}
function getTreeSnapshot(registeredIDs) {
return registeredIDs.reduce(function (tree, id) {
var ownerID = ReactComponentTreeHook.getOwnerID(id);
var parentID = ReactComponentTreeHook.getParentID(id);
tree[id] = {
displayName: ReactComponentTreeHook.getDisplayName(id),
text: ReactComponentTreeHook.getText(id),
updateCount: ReactComponentTreeHook.getUpdateCount(id),
childIDs: ReactComponentTreeHook.getChildIDs(id),
// Text nodes don't have owners but this is close enough.
ownerID: ownerID || ReactComponentTreeHook.getOwnerID(parentID),
parentID: parentID
};
return tree;
}, {});
}
function resetMeasurements() {
var previousStartTime = currentFlushStartTime;
var previousMeasurements = currentFlushMeasurements || [];
var previousOperations = ReactHostOperationHistoryHook.getHistory();
if (currentFlushNesting === 0) {
currentFlushStartTime = null;
currentFlushMeasurements = null;
clearHistory();
return;
}
if (previousMeasurements.length || previousOperations.length) {
var registeredIDs = ReactComponentTreeHook.getRegisteredIDs();
flushHistory.push({
duration: performanceNow() - previousStartTime,
measurements: previousMeasurements || [],
operations: previousOperations || [],
treeSnapshot: getTreeSnapshot(registeredIDs)
});
}
clearHistory();
currentFlushStartTime = performanceNow();
currentFlushMeasurements = [];
}
function checkDebugID(debugID) {
var allowRoot = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
if (allowRoot && debugID === 0) {
return;
}
if (!debugID) {
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDebugTool: debugID may not be empty.') : void 0;
}
}
function beginLifeCycleTimer(debugID, timerType) {
if (currentFlushNesting === 0) {
return;
}
if (currentTimerType && !lifeCycleTimerHasWarned) {
process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'Did not expect %s timer to start while %s timer is still in ' + 'progress for %s instance.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0;
lifeCycleTimerHasWarned = true;
}
currentTimerStartTime = performanceNow();
currentTimerNestedFlushDuration = 0;
currentTimerDebugID = debugID;
currentTimerType = timerType;
}
function endLifeCycleTimer(debugID, timerType) {
if (currentFlushNesting === 0) {
return;
}
if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) {
process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'We did not expect %s timer to stop while %s timer is still in ' + 'progress for %s instance. Please report this as a bug in React.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0;
lifeCycleTimerHasWarned = true;
}
if (isProfiling) {
currentFlushMeasurements.push({
timerType: timerType,
instanceID: debugID,
duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration
});
}
currentTimerStartTime = null;
currentTimerNestedFlushDuration = null;
currentTimerDebugID = null;
currentTimerType = null;
}
function pauseCurrentLifeCycleTimer() {
var currentTimer = {
startTime: currentTimerStartTime,
nestedFlushStartTime: performanceNow(),
debugID: currentTimerDebugID,
timerType: currentTimerType
};
lifeCycleTimerStack.push(currentTimer);
currentTimerStartTime = null;
currentTimerNestedFlushDuration = null;
currentTimerDebugID = null;
currentTimerType = null;
}
function resumeCurrentLifeCycleTimer() {
var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop();
var startTime = _lifeCycleTimerStack$.startTime;
var nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime;
var debugID = _lifeCycleTimerStack$.debugID;
var timerType = _lifeCycleTimerStack$.timerType;
var nestedFlushDuration = performanceNow() - nestedFlushStartTime;
currentTimerStartTime = startTime;
currentTimerNestedFlushDuration += nestedFlushDuration;
currentTimerDebugID = debugID;
currentTimerType = timerType;
}
var ReactDebugTool = {
addHook: function (hook) {
hooks.push(hook);
},
removeHook: function (hook) {
for (var i = 0; i < hooks.length; i++) {
if (hooks[i] === hook) {
hooks.splice(i, 1);
i--;
}
}
},
isProfiling: function () {
return isProfiling;
},
beginProfiling: function () {
if (isProfiling) {
return;
}
isProfiling = true;
flushHistory.length = 0;
resetMeasurements();
ReactDebugTool.addHook(ReactHostOperationHistoryHook);
},
endProfiling: function () {
if (!isProfiling) {
return;
}
isProfiling = false;
resetMeasurements();
ReactDebugTool.removeHook(ReactHostOperationHistoryHook);
},
getFlushHistory: function () {
return flushHistory;
},
onBeginFlush: function () {
currentFlushNesting++;
resetMeasurements();
pauseCurrentLifeCycleTimer();
emitEvent('onBeginFlush');
},
onEndFlush: function () {
resetMeasurements();
currentFlushNesting--;
resumeCurrentLifeCycleTimer();
emitEvent('onEndFlush');
},
onBeginLifeCycleTimer: function (debugID, timerType) {
checkDebugID(debugID);
emitEvent('onBeginLifeCycleTimer', debugID, timerType);
beginLifeCycleTimer(debugID, timerType);
},
onEndLifeCycleTimer: function (debugID, timerType) {
checkDebugID(debugID);
endLifeCycleTimer(debugID, timerType);
emitEvent('onEndLifeCycleTimer', debugID, timerType);
},
onError: function (debugID) {
if (currentTimerDebugID != null) {
endLifeCycleTimer(currentTimerDebugID, currentTimerType);
}
emitEvent('onError', debugID);
},
onBeginProcessingChildContext: function () {
emitEvent('onBeginProcessingChildContext');
},
onEndProcessingChildContext: function () {
emitEvent('onEndProcessingChildContext');
},
onHostOperation: function (debugID, type, payload) {
checkDebugID(debugID);
emitEvent('onHostOperation', debugID, type, payload);
},
onSetState: function () {
emitEvent('onSetState');
},
onSetChildren: function (debugID, childDebugIDs) {
checkDebugID(debugID);
childDebugIDs.forEach(checkDebugID);
emitEvent('onSetChildren', debugID, childDebugIDs);
},
onBeforeMountComponent: function (debugID, element, parentDebugID) {
checkDebugID(debugID);
checkDebugID(parentDebugID, true);
emitEvent('onBeforeMountComponent', debugID, element, parentDebugID);
},
onMountComponent: function (debugID) {
checkDebugID(debugID);
emitEvent('onMountComponent', debugID);
},
onBeforeUpdateComponent: function (debugID, element) {
checkDebugID(debugID);
emitEvent('onBeforeUpdateComponent', debugID, element);
},
onUpdateComponent: function (debugID) {
checkDebugID(debugID);
emitEvent('onUpdateComponent', debugID);
},
onBeforeUnmountComponent: function (debugID) {
checkDebugID(debugID);
emitEvent('onBeforeUnmountComponent', debugID);
},
onUnmountComponent: function (debugID) {
checkDebugID(debugID);
emitEvent('onUnmountComponent', debugID);
},
onTestEvent: function () {
emitEvent('onTestEvent');
}
};
// TODO remove these when RN/www gets updated
ReactDebugTool.addDevtool = ReactDebugTool.addHook;
ReactDebugTool.removeDevtool = ReactDebugTool.removeHook;
ReactDebugTool.addHook(ReactInvalidSetStateWarningHook);
ReactDebugTool.addHook(ReactComponentTreeHook);
ReactDebugTool.addHook(ReactChildrenMutationWarningHook);
var url = ExecutionEnvironment.canUseDOM && window.location.href || '';
if (/[?&]react_perf\b/.test(url)) {
ReactDebugTool.beginProfiling();
}
module.exports = ReactDebugTool;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInvalidSetStateWarningHook
*/
'use strict';
var warning = __webpack_require__(11);
if (process.env.NODE_ENV !== 'production') {
var processingChildContext = false;
var warnInvalidSetState = function () {
process.env.NODE_ENV !== 'production' ? warning(!processingChildContext, 'setState(...): Cannot call setState() inside getChildContext()') : void 0;
};
}
var ReactInvalidSetStateWarningHook = {
onBeginProcessingChildContext: function () {
processingChildContext = true;
},
onEndProcessingChildContext: function () {
processingChildContext = false;
},
onSetState: function () {
warnInvalidSetState();
}
};
module.exports = ReactInvalidSetStateWarningHook;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 65 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactHostOperationHistoryHook
*/
'use strict';
var history = [];
var ReactHostOperationHistoryHook = {
onHostOperation: function (debugID, type, payload) {
history.push({
instanceID: debugID,
type: type,
payload: payload
});
},
clearHistory: function () {
if (ReactHostOperationHistoryHook._preventClearing) {
// Should only be used for tests.
return;
}
history = [];
},
getHistory: function () {
return history;
}
};
module.exports = ReactHostOperationHistoryHook;
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactChildrenMutationWarningHook
*/
'use strict';
var ReactComponentTreeHook = __webpack_require__(28);
var warning = __webpack_require__(11);
function handleElement(debugID, element) {
if (element == null) {
return;
}
if (element._shadowChildren === undefined) {
return;
}
if (element._shadowChildren === element.props.children) {
return;
}
var isMutated = false;
if (Array.isArray(element._shadowChildren)) {
if (element._shadowChildren.length === element.props.children.length) {
for (var i = 0; i < element._shadowChildren.length; i++) {
if (element._shadowChildren[i] !== element.props.children[i]) {
isMutated = true;
}
}
} else {
isMutated = true;
}
}
if (!Array.isArray(element._shadowChildren) || isMutated) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Component\'s children should not be mutated.%s', ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0;
}
}
var ReactChildrenMutationWarningHook = {
onMountComponent: function (debugID) {
handleElement(debugID, ReactComponentTreeHook.getElement(debugID));
},
onUpdateComponent: function (debugID) {
handleElement(debugID, ReactComponentTreeHook.getElement(debugID));
}
};
module.exports = ReactChildrenMutationWarningHook;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var performance = __webpack_require__(68);
var performanceNow;
/**
* Detect if we can use `window.performance.now()` and gracefully fallback to
* `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now
* because of Facebook's testing infrastructure.
*/
if (performance.now) {
performanceNow = function performanceNow() {
return performance.now();
};
} else {
performanceNow = function performanceNow() {
return Date.now();
};
}
module.exports = performanceNow;
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(49);
var performance;
if (ExecutionEnvironment.canUseDOM) {
performance = window.performance || window.msPerformance || window.webkitPerformance;
}
module.exports = performance || {};
/***/ },
/* 69 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Transaction
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
/**
* `Transaction` creates a black box that is able to wrap any method such that
* certain invariants are maintained before and after the method is invoked
* (Even if an exception is thrown while invoking the wrapped method). Whoever
* instantiates a transaction can provide enforcers of the invariants at
* creation time. The `Transaction` class itself will supply one additional
* automatic invariant for you - the invariant that any transaction instance
* should not be run while it is already being run. You would typically create a
* single instance of a `Transaction` for reuse multiple times, that potentially
* is used to wrap several different methods. Wrappers are extremely simple -
* they only require implementing two methods.
*
* <pre>
* wrappers (injected at creation time)
* + +
* | |
* +-----------------|--------|--------------+
* | v | |
* | +---------------+ | |
* | +--| wrapper1 |---|----+ |
* | | +---------------+ v | |
* | | +-------------+ | |
* | | +----| wrapper2 |--------+ |
* | | | +-------------+ | | |
* | | | | | |
* | v v v v | wrapper
* | +---+ +---+ +---------+ +---+ +---+ | invariants
* perform(anyMethod) | | | | | | | | | | | | maintained
* +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|-------->
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +---+ +---+ +---------+ +---+ +---+ |
* | initialize close |
* +-----------------------------------------+
* </pre>
*
* Use cases:
* - Preserving the input selection ranges before/after reconciliation.
* Restoring selection even in the event of an unexpected error.
* - Deactivating events while rearranging the DOM, preventing blurs/focuses,
* while guaranteeing that afterwards, the event system is reactivated.
* - Flushing a queue of collected DOM mutations to the main UI thread after a
* reconciliation takes place in a worker thread.
* - Invoking any collected `componentDidUpdate` callbacks after rendering new
* content.
* - (Future use case): Wrapping particular flushes of the `ReactWorker` queue
* to preserve the `scrollTop` (an automatic scroll aware DOM).
* - (Future use case): Layout calculations before and after DOM updates.
*
* Transactional plugin API:
* - A module that has an `initialize` method that returns any precomputation.
* - and a `close` method that accepts the precomputation. `close` is invoked
* when the wrapped process is completed, or has failed.
*
* @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules
* that implement `initialize` and `close`.
* @return {Transaction} Single transaction for reuse in thread.
*
* @class Transaction
*/
var Mixin = {
/**
* Sets up this instance so that it is prepared for collecting metrics. Does
* so such that this setup method may be used on an instance that is already
* initialized, in a way that does not consume additional memory upon reuse.
* That can be useful if you decide to make your subclass of this mixin a
* "PooledClass".
*/
reinitializeTransaction: function () {
this.transactionWrappers = this.getTransactionWrappers();
if (this.wrapperInitData) {
this.wrapperInitData.length = 0;
} else {
this.wrapperInitData = [];
}
this._isInTransaction = false;
},
_isInTransaction: false,
/**
* @abstract
* @return {Array<TransactionWrapper>} Array of transaction wrappers.
*/
getTransactionWrappers: null,
isInTransaction: function () {
return !!this._isInTransaction;
},
/**
* Executes the function within a safety window. Use this for the top level
* methods that result in large amounts of computation/mutations that would
* need to be safety checked. The optional arguments helps prevent the need
* to bind in many cases.
*
* @param {function} method Member of scope to call.
* @param {Object} scope Scope to invoke from.
* @param {Object?=} a Argument to pass to the method.
* @param {Object?=} b Argument to pass to the method.
* @param {Object?=} c Argument to pass to the method.
* @param {Object?=} d Argument to pass to the method.
* @param {Object?=} e Argument to pass to the method.
* @param {Object?=} f Argument to pass to the method.
*
* @return {*} Return value from `method`.
*/
perform: function (method, scope, a, b, c, d, e, f) {
!!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.') : _prodInvariant('27') : void 0;
var errorThrown;
var ret;
try {
this._isInTransaction = true;
// Catching errors makes debugging more difficult, so we start with
// errorThrown set to true before setting it to false after calling
// close -- if it's still set to true in the finally block, it means
// one of these calls threw.
errorThrown = true;
this.initializeAll(0);
ret = method.call(scope, a, b, c, d, e, f);
errorThrown = false;
} finally {
try {
if (errorThrown) {
// If `method` throws, prefer to show that stack trace over any thrown
// by invoking `closeAll`.
try {
this.closeAll(0);
} catch (err) {}
} else {
// Since `method` didn't throw, we don't want to silence the exception
// here.
this.closeAll(0);
}
} finally {
this._isInTransaction = false;
}
}
return ret;
},
initializeAll: function (startIndex) {
var transactionWrappers = this.transactionWrappers;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
try {
// Catching errors makes debugging more difficult, so we start with the
// OBSERVED_ERROR state before overwriting it with the real return value
// of initialize -- if it's still set to OBSERVED_ERROR in the finally
// block, it means wrapper.initialize threw.
this.wrapperInitData[i] = Transaction.OBSERVED_ERROR;
this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null;
} finally {
if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) {
// The initializer for wrapper i threw an error; initialize the
// remaining wrappers but silence any exceptions from them to ensure
// that the first error is the one to bubble up.
try {
this.initializeAll(i + 1);
} catch (err) {}
}
}
}
},
/**
* Invokes each of `this.transactionWrappers.close[i]` functions, passing into
* them the respective return values of `this.transactionWrappers.init[i]`
* (`close`rs that correspond to initializers that failed will not be
* invoked).
*/
closeAll: function (startIndex) {
!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : _prodInvariant('28') : void 0;
var transactionWrappers = this.transactionWrappers;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
var initData = this.wrapperInitData[i];
var errorThrown;
try {
// Catching errors makes debugging more difficult, so we start with
// errorThrown set to true before setting it to false after calling
// close -- if it's still set to true in the finally block, it means
// wrapper.close threw.
errorThrown = true;
if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) {
wrapper.close.call(this, initData);
}
errorThrown = false;
} finally {
if (errorThrown) {
// The closer for wrapper i threw an error; close the remaining
// wrappers but silence any exceptions from them to ensure that the
// first error is the one to bubble up.
try {
this.closeAll(i + 1);
} catch (e) {}
}
}
}
this.wrapperInitData.length = 0;
}
};
var Transaction = {
Mixin: Mixin,
/**
* Token to look for to determine if an error occurred.
*/
OBSERVED_ERROR: {}
};
module.exports = Transaction;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 70 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventTarget
*/
'use strict';
/**
* Gets the target node from a native browser event by accounting for
* inconsistencies in browser DOM APIs.
*
* @param {object} nativeEvent Native browser event.
* @return {DOMEventTarget} Target node.
*/
function getEventTarget(nativeEvent) {
var target = nativeEvent.target || nativeEvent.srcElement || window;
// Normalize SVG <use> element events #4963
if (target.correspondingUseElement) {
target = target.correspondingUseElement;
}
// Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see path_to_url
return target.nodeType === 3 ? target.parentNode : target;
}
module.exports = getEventTarget;
/***/ },
/* 71 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule isEventSupported
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(49);
var useHasFeature;
if (ExecutionEnvironment.canUseDOM) {
useHasFeature = document.implementation && document.implementation.hasFeature &&
// always returns true in newer browsers as per the standard.
// @see path_to_url#dom-domimplementation-hasfeature
document.implementation.hasFeature('', '') !== true;
}
/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
function isEventSupported(eventNameSuffix, capture) {
if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) {
return false;
}
var eventName = 'on' + eventNameSuffix;
var isSupported = eventName in document;
if (!isSupported) {
var element = document.createElement('div');
element.setAttribute(eventName, 'return;');
isSupported = typeof element[eventName] === 'function';
}
if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') {
// This is the only way to test support for the `wheel` event in IE9+.
isSupported = document.implementation.hasFeature('Events.wheel', '3.0');
}
return isSupported;
}
module.exports = isEventSupported;
/***/ },
/* 72 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule isTextInputElement
*
*/
'use strict';
/**
* @see path_to_url#input-type-attr-summary
*/
var supportedInputTypes = {
'color': true,
'date': true,
'datetime': true,
'datetime-local': true,
'email': true,
'month': true,
'number': true,
'password': true,
'range': true,
'search': true,
'tel': true,
'text': true,
'time': true,
'url': true,
'week': true
};
function isTextInputElement(elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
if (nodeName === 'input') {
return !!supportedInputTypes[elem.type];
}
if (nodeName === 'textarea') {
return true;
}
return false;
}
module.exports = isTextInputElement;
/***/ },
/* 73 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DefaultEventPluginOrder
*/
'use strict';
var keyOf = __webpack_require__(25);
/**
* Module that is injectable into `EventPluginHub`, that specifies a
* deterministic ordering of `EventPlugin`s. A convenient way to reason about
* plugins, without having to package every one of them. This is better than
* having plugins be ordered in the same order that they are injected because
* that ordering would be influenced by the packaging order.
* `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
* preventing default on events is convenient in `SimpleEventPlugin` handlers.
*/
var DefaultEventPluginOrder = [keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null })];
module.exports = DefaultEventPluginOrder;
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EnterLeaveEventPlugin
*/
'use strict';
var EventConstants = __webpack_require__(41);
var EventPropagators = __webpack_require__(42);
var ReactDOMComponentTree = __webpack_require__(36);
var SyntheticMouseEvent = __webpack_require__(75);
var keyOf = __webpack_require__(25);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
mouseEnter: {
registrationName: keyOf({ onMouseEnter: null }),
dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver]
},
mouseLeave: {
registrationName: keyOf({ onMouseLeave: null }),
dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver]
}
};
var EnterLeaveEventPlugin = {
eventTypes: eventTypes,
/**
* For almost every interaction we care about, there will be both a top-level
* `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
* we do not extract duplicate events. However, moving the mouse into the
* browser from outside will not fire a `mouseout` event. In this case, we use
* the `mouseover` top-level event.
*/
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
return null;
}
if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) {
// Must not be a mouse in or mouse out - ignoring.
return null;
}
var win;
if (nativeEventTarget.window === nativeEventTarget) {
// `nativeEventTarget` is probably a window object.
win = nativeEventTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc = nativeEventTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
var from;
var to;
if (topLevelType === topLevelTypes.topMouseOut) {
from = targetInst;
var related = nativeEvent.relatedTarget || nativeEvent.toElement;
to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null;
} else {
// Moving to a node from outside the window.
from = null;
to = targetInst;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
var fromNode = from == null ? win : ReactDOMComponentTree.getNodeFromInstance(from);
var toNode = to == null ? win : ReactDOMComponentTree.getNodeFromInstance(to);
var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget);
leave.type = 'mouseleave';
leave.target = fromNode;
leave.relatedTarget = toNode;
var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget);
enter.type = 'mouseenter';
enter.target = toNode;
enter.relatedTarget = fromNode;
EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to);
return [leave, enter];
}
};
module.exports = EnterLeaveEventPlugin;
/***/ },
/* 75 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticMouseEvent
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(76);
var ViewportMetrics = __webpack_require__(77);
var getEventModifierState = __webpack_require__(78);
/**
* @interface MouseEvent
* @see path_to_url
*/
var MouseEventInterface = {
screenX: null,
screenY: null,
clientX: null,
clientY: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
getModifierState: getEventModifierState,
button: function (event) {
// Webkit, Firefox, IE9+
// which: 1 2 3
// button: 0 1 2 (standard)
var button = event.button;
if ('which' in event) {
return button;
}
// IE<9
// which: undefined
// button: 0 0 0
// button: 1 4 2 (onmouseup)
return button === 2 ? 2 : button === 4 ? 1 : 0;
},
buttons: null,
relatedTarget: function (event) {
return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
},
// "Proprietary" Interface.
pageX: function (event) {
return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft;
},
pageY: function (event) {
return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
module.exports = SyntheticMouseEvent;
/***/ },
/* 76 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticUIEvent
*/
'use strict';
var SyntheticEvent = __webpack_require__(53);
var getEventTarget = __webpack_require__(70);
/**
* @interface UIEvent
* @see path_to_url
*/
var UIEventInterface = {
view: function (event) {
if (event.view) {
return event.view;
}
var target = getEventTarget(event);
if (target.window === target) {
// target is a window object
return target;
}
var doc = target.ownerDocument;
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
if (doc) {
return doc.defaultView || doc.parentWindow;
} else {
return window;
}
},
detail: function (event) {
return event.detail || 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
module.exports = SyntheticUIEvent;
/***/ },
/* 77 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ViewportMetrics
*/
'use strict';
var ViewportMetrics = {
currentScrollLeft: 0,
currentScrollTop: 0,
refreshScrollValues: function (scrollPosition) {
ViewportMetrics.currentScrollLeft = scrollPosition.x;
ViewportMetrics.currentScrollTop = scrollPosition.y;
}
};
module.exports = ViewportMetrics;
/***/ },
/* 78 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventModifierState
*/
'use strict';
/**
* Translation from modifier key to the associated property in the event.
* @see path_to_url#keys-Modifiers
*/
var modifierKeyToProp = {
'Alt': 'altKey',
'Control': 'ctrlKey',
'Meta': 'metaKey',
'Shift': 'shiftKey'
};
// IE8 does not implement getModifierState so we simply map it to the only
// modifier keys exposed by the event itself, does not support Lock-keys.
// Currently, all major browsers except Chrome seems to support Lock-keys.
function modifierStateGetter(keyArg) {
var syntheticEvent = this;
var nativeEvent = syntheticEvent.nativeEvent;
if (nativeEvent.getModifierState) {
return nativeEvent.getModifierState(keyArg);
}
var keyProp = modifierKeyToProp[keyArg];
return keyProp ? !!nativeEvent[keyProp] : false;
}
function getEventModifierState(nativeEvent) {
return modifierStateGetter;
}
module.exports = getEventModifierState;
/***/ },
/* 79 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule HTMLDOMPropertyConfig
*/
'use strict';
var DOMProperty = __webpack_require__(37);
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;
var HTMLDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$')),
Properties: {
/**
* Standard Properties
*/
accept: 0,
acceptCharset: 0,
accessKey: 0,
action: 0,
allowFullScreen: HAS_BOOLEAN_VALUE,
allowTransparency: 0,
alt: 0,
async: HAS_BOOLEAN_VALUE,
autoComplete: 0,
// autoFocus is polyfilled/normalized by AutoFocusUtils
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
capture: HAS_BOOLEAN_VALUE,
cellPadding: 0,
cellSpacing: 0,
charSet: 0,
challenge: 0,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
cite: 0,
classID: 0,
className: 0,
cols: HAS_POSITIVE_NUMERIC_VALUE,
colSpan: 0,
content: 0,
contentEditable: 0,
contextMenu: 0,
controls: HAS_BOOLEAN_VALUE,
coords: 0,
crossOrigin: 0,
data: 0, // For `<object />` acts as `src`.
dateTime: 0,
'default': HAS_BOOLEAN_VALUE,
defer: HAS_BOOLEAN_VALUE,
dir: 0,
disabled: HAS_BOOLEAN_VALUE,
download: HAS_OVERLOADED_BOOLEAN_VALUE,
draggable: 0,
encType: 0,
form: 0,
formAction: 0,
formEncType: 0,
formMethod: 0,
formNoValidate: HAS_BOOLEAN_VALUE,
formTarget: 0,
frameBorder: 0,
headers: 0,
height: 0,
hidden: HAS_BOOLEAN_VALUE,
high: 0,
href: 0,
hrefLang: 0,
htmlFor: 0,
httpEquiv: 0,
icon: 0,
id: 0,
inputMode: 0,
integrity: 0,
is: 0,
keyParams: 0,
keyType: 0,
kind: 0,
label: 0,
lang: 0,
list: 0,
loop: HAS_BOOLEAN_VALUE,
low: 0,
manifest: 0,
marginHeight: 0,
marginWidth: 0,
max: 0,
maxLength: 0,
media: 0,
mediaGroup: 0,
method: 0,
min: 0,
minLength: 0,
// Caution; `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`.
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: 0,
nonce: 0,
noValidate: HAS_BOOLEAN_VALUE,
open: HAS_BOOLEAN_VALUE,
optimum: 0,
pattern: 0,
placeholder: 0,
poster: 0,
preload: 0,
profile: 0,
radioGroup: 0,
readOnly: HAS_BOOLEAN_VALUE,
referrerPolicy: 0,
rel: 0,
required: HAS_BOOLEAN_VALUE,
reversed: HAS_BOOLEAN_VALUE,
role: 0,
rows: HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: HAS_NUMERIC_VALUE,
sandbox: 0,
scope: 0,
scoped: HAS_BOOLEAN_VALUE,
scrolling: 0,
seamless: HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
shape: 0,
size: HAS_POSITIVE_NUMERIC_VALUE,
sizes: 0,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: 0,
src: 0,
srcDoc: 0,
srcLang: 0,
srcSet: 0,
start: HAS_NUMERIC_VALUE,
step: 0,
style: 0,
summary: 0,
tabIndex: 0,
target: 0,
title: 0,
// Setting .type throws on non-<input> tags
type: 0,
useMap: 0,
value: 0,
width: 0,
wmode: 0,
wrap: 0,
/**
* RDFa Properties
*/
about: 0,
datatype: 0,
inlist: 0,
prefix: 0,
// property is also supported for OpenGraph in meta tags.
property: 0,
resource: 0,
'typeof': 0,
vocab: 0,
/**
* Non-standard Properties
*/
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: 0,
autoCorrect: 0,
// autoSave allows WebKit/Blink to persist values of input fields on page reloads
autoSave: 0,
// color is for Safari mask-icon link
color: 0,
// itemProp, itemScope, itemType are for
// Microdata support. See path_to_url
itemProp: 0,
itemScope: HAS_BOOLEAN_VALUE,
itemType: 0,
// itemID and itemRef are for Microdata support as well but
// only specified in the WHATWG spec document. See
// path_to_url#microdata-dom-api
itemID: 0,
itemRef: 0,
// results show looking glass icon and recent searches on input
// search fields in WebKit/Blink
results: 0,
// IE-only attribute that specifies security restrictions on an iframe
// as an alternative to the sandbox attribute on IE<10
security: 0,
// IE-only attribute that controls focus behavior
unselectable: 0
},
DOMAttributeNames: {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
},
DOMPropertyNames: {}
};
module.exports = HTMLDOMPropertyConfig;
/***/ },
/* 80 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponentBrowserEnvironment
*/
'use strict';
var DOMChildrenOperations = __webpack_require__(81);
var ReactDOMIDOperations = __webpack_require__(93);
/**
* Abstracts away all functionality of the reconciler that requires knowledge of
* the browser context. TODO: These callers should be refactored to avoid the
* need for this injection.
*/
var ReactComponentBrowserEnvironment = {
processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates,
replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup
};
module.exports = ReactComponentBrowserEnvironment;
/***/ },
/* 81 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMChildrenOperations
*/
'use strict';
var DOMLazyTree = __webpack_require__(82);
var Danger = __webpack_require__(88);
var ReactMultiChildUpdateTypes = __webpack_require__(92);
var ReactDOMComponentTree = __webpack_require__(36);
var ReactInstrumentation = __webpack_require__(62);
var createMicrosoftUnsafeLocalFunction = __webpack_require__(85);
var setInnerHTML = __webpack_require__(84);
var setTextContent = __webpack_require__(86);
function getNodeAfter(parentNode, node) {
// Special case for text components, which return [open, close] comments
// from getHostNode.
if (Array.isArray(node)) {
node = node[1];
}
return node ? node.nextSibling : parentNode.firstChild;
}
/**
* Inserts `childNode` as a child of `parentNode` at the `index`.
*
* @param {DOMElement} parentNode Parent node in which to insert.
* @param {DOMElement} childNode Child node to insert.
* @param {number} index Index at which to insert the child.
* @internal
*/
var insertChildAt = createMicrosoftUnsafeLocalFunction(function (parentNode, childNode, referenceNode) {
// We rely exclusively on `insertBefore(node, null)` instead of also using
// `appendChild(node)`. (Using `undefined` is not allowed by all browsers so
// we are careful to use `null`.)
parentNode.insertBefore(childNode, referenceNode);
});
function insertLazyTreeChildAt(parentNode, childTree, referenceNode) {
DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode);
}
function moveChild(parentNode, childNode, referenceNode) {
if (Array.isArray(childNode)) {
moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode);
} else {
insertChildAt(parentNode, childNode, referenceNode);
}
}
function removeChild(parentNode, childNode) {
if (Array.isArray(childNode)) {
var closingComment = childNode[1];
childNode = childNode[0];
removeDelimitedText(parentNode, childNode, closingComment);
parentNode.removeChild(closingComment);
}
parentNode.removeChild(childNode);
}
function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) {
var node = openingComment;
while (true) {
var nextNode = node.nextSibling;
insertChildAt(parentNode, node, referenceNode);
if (node === closingComment) {
break;
}
node = nextNode;
}
}
function removeDelimitedText(parentNode, startNode, closingComment) {
while (true) {
var node = startNode.nextSibling;
if (node === closingComment) {
// The closing comment is removed by ReactMultiChild.
break;
} else {
parentNode.removeChild(node);
}
}
}
function replaceDelimitedText(openingComment, closingComment, stringText) {
var parentNode = openingComment.parentNode;
var nodeAfterComment = openingComment.nextSibling;
if (nodeAfterComment === closingComment) {
// There are no text nodes between the opening and closing comments; insert
// a new one if stringText isn't empty.
if (stringText) {
insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment);
}
} else {
if (stringText) {
// Set the text content of the first node after the opening comment, and
// remove all following nodes up until the closing comment.
setTextContent(nodeAfterComment, stringText);
removeDelimitedText(parentNode, nodeAfterComment, closingComment);
} else {
removeDelimitedText(parentNode, openingComment, closingComment);
}
}
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID, 'replace text', stringText);
}
}
var dangerouslyReplaceNodeWithMarkup = Danger.dangerouslyReplaceNodeWithMarkup;
if (process.env.NODE_ENV !== 'production') {
dangerouslyReplaceNodeWithMarkup = function (oldChild, markup, prevInstance) {
Danger.dangerouslyReplaceNodeWithMarkup(oldChild, markup);
if (prevInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onHostOperation(prevInstance._debugID, 'replace with', markup.toString());
} else {
var nextInstance = ReactDOMComponentTree.getInstanceFromNode(markup.node);
if (nextInstance._debugID !== 0) {
ReactInstrumentation.debugTool.onHostOperation(nextInstance._debugID, 'mount', markup.toString());
}
}
};
}
/**
* Operations for updating with DOM children.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup,
replaceDelimitedText: replaceDelimitedText,
/**
* Updates a component's children by processing a series of updates. The
* update configurations are each expected to have a `parentNode` property.
*
* @param {array<object>} updates List of update configurations.
* @internal
*/
processUpdates: function (parentNode, updates) {
if (process.env.NODE_ENV !== 'production') {
var parentNodeDebugID = ReactDOMComponentTree.getInstanceFromNode(parentNode)._debugID;
}
for (var k = 0; k < updates.length; k++) {
var update = updates[k];
switch (update.type) {
case ReactMultiChildUpdateTypes.INSERT_MARKUP:
insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode));
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'insert child', { toIndex: update.toIndex, content: update.content.toString() });
}
break;
case ReactMultiChildUpdateTypes.MOVE_EXISTING:
moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode));
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'move child', { fromIndex: update.fromIndex, toIndex: update.toIndex });
}
break;
case ReactMultiChildUpdateTypes.SET_MARKUP:
setInnerHTML(parentNode, update.content);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'replace children', update.content.toString());
}
break;
case ReactMultiChildUpdateTypes.TEXT_CONTENT:
setTextContent(parentNode, update.content);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'replace text', update.content.toString());
}
break;
case ReactMultiChildUpdateTypes.REMOVE_NODE:
removeChild(parentNode, update.fromNode);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'remove child', { fromIndex: update.fromIndex });
}
break;
}
}
}
};
module.exports = DOMChildrenOperations;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 82 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMLazyTree
*/
'use strict';
var DOMNamespaces = __webpack_require__(83);
var setInnerHTML = __webpack_require__(84);
var createMicrosoftUnsafeLocalFunction = __webpack_require__(85);
var setTextContent = __webpack_require__(86);
var ELEMENT_NODE_TYPE = 1;
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
/**
* In IE (8-11) and Edge, appending nodes with no children is dramatically
* faster than appending a full subtree, so we essentially queue up the
* .appendChild calls here and apply them so each node is added to its parent
* before any children are added.
*
* In other browsers, doing so is slower or neutral compared to the other order
* (in Firefox, twice as slow) so we only do this inversion in IE.
*
* See path_to_url
*/
var enableLazy = typeof document !== 'undefined' && typeof document.documentMode === 'number' || typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && /\bEdge\/\d/.test(navigator.userAgent);
function insertTreeChildren(tree) {
if (!enableLazy) {
return;
}
var node = tree.node;
var children = tree.children;
if (children.length) {
for (var i = 0; i < children.length; i++) {
insertTreeBefore(node, children[i], null);
}
} else if (tree.html != null) {
setInnerHTML(node, tree.html);
} else if (tree.text != null) {
setTextContent(node, tree.text);
}
}
var insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (parentNode, tree, referenceNode) {
// DocumentFragments aren't actually part of the DOM after insertion so
// appending children won't update the DOM. We need to ensure the fragment
// is properly populated first, breaking out of our lazy approach for just
// this level. Also, some <object> plugins (like Flash Player) will read
// <param> nodes immediately upon insertion into the DOM, so <object>
// must also be populated prior to insertion into the DOM.
if (tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE || tree.node.nodeType === ELEMENT_NODE_TYPE && tree.node.nodeName.toLowerCase() === 'object' && (tree.node.namespaceURI == null || tree.node.namespaceURI === DOMNamespaces.html)) {
insertTreeChildren(tree);
parentNode.insertBefore(tree.node, referenceNode);
} else {
parentNode.insertBefore(tree.node, referenceNode);
insertTreeChildren(tree);
}
});
function replaceChildWithTree(oldNode, newTree) {
oldNode.parentNode.replaceChild(newTree.node, oldNode);
insertTreeChildren(newTree);
}
function queueChild(parentTree, childTree) {
if (enableLazy) {
parentTree.children.push(childTree);
} else {
parentTree.node.appendChild(childTree.node);
}
}
function queueHTML(tree, html) {
if (enableLazy) {
tree.html = html;
} else {
setInnerHTML(tree.node, html);
}
}
function queueText(tree, text) {
if (enableLazy) {
tree.text = text;
} else {
setTextContent(tree.node, text);
}
}
function toString() {
return this.node.nodeName;
}
function DOMLazyTree(node) {
return {
node: node,
children: [],
html: null,
text: null,
toString: toString
};
}
DOMLazyTree.insertTreeBefore = insertTreeBefore;
DOMLazyTree.replaceChildWithTree = replaceChildWithTree;
DOMLazyTree.queueChild = queueChild;
DOMLazyTree.queueHTML = queueHTML;
DOMLazyTree.queueText = queueText;
module.exports = DOMLazyTree;
/***/ },
/* 83 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMNamespaces
*/
'use strict';
var DOMNamespaces = {
html: 'path_to_url
mathml: 'path_to_url
svg: 'path_to_url
};
module.exports = DOMNamespaces;
/***/ },
/* 84 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule setInnerHTML
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(49);
var DOMNamespaces = __webpack_require__(83);
var WHITESPACE_TEST = /^[ \r\n\t\f]/;
var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/;
var createMicrosoftUnsafeLocalFunction = __webpack_require__(85);
// SVG temp container for IE lacking innerHTML
var reusableSVGContainer;
/**
* Set the innerHTML property of a node, ensuring that whitespace is preserved
* even in IE8.
*
* @param {DOMElement} node
* @param {string} html
* @internal
*/
var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
// IE does not have innerHTML for SVG nodes, so instead we inject the
// new markup in a temp node and then move the child nodes across into
// the target node
if (node.namespaceURI === DOMNamespaces.svg && !('innerHTML' in node)) {
reusableSVGContainer = reusableSVGContainer || document.createElement('div');
reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>';
var newNodes = reusableSVGContainer.firstChild.childNodes;
for (var i = 0; i < newNodes.length; i++) {
node.appendChild(newNodes[i]);
}
} else {
node.innerHTML = html;
}
});
if (ExecutionEnvironment.canUseDOM) {
// IE8: When updating a just created node with innerHTML only leading
// whitespace is removed. When updating an existing node with innerHTML
// whitespace in root TextNodes is also collapsed.
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
// Feature detection; only IE8 is known to behave improperly like this.
var testElement = document.createElement('div');
testElement.innerHTML = ' ';
if (testElement.innerHTML === '') {
setInnerHTML = function (node, html) {
// Magic theory: IE8 supposedly differentiates between added and updated
// nodes when processing innerHTML, innerHTML on updated nodes suffers
// from worse whitespace behavior. Re-adding a node like this triggers
// the initial and more favorable whitespace behavior.
// TODO: What to do on a detached node?
if (node.parentNode) {
node.parentNode.replaceChild(node, node);
}
// We also implement a workaround for non-visible tags disappearing into
// thin air on IE8, this only happens if there is no visible text
// in-front of the non-visible tags. Piggyback on the whitespace fix
// and simply check if any non-visible tags appear in the source.
if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) {
// Recover leading whitespace by temporarily prepending any character.
// \uFEFF has the potential advantage of being zero-width/invisible.
// UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode
// in hopes that this is preserved even if "\uFEFF" is transformed to
// the actual Unicode character (by Babel, for example).
// path_to_url#L216
node.innerHTML = String.fromCharCode(0xFEFF) + html;
// deleteData leaves an empty `TextNode` which offsets the index of all
// children. Definitely want to avoid this.
var textNode = node.firstChild;
if (textNode.data.length === 1) {
node.removeChild(textNode);
} else {
textNode.deleteData(0, 1);
}
} else {
node.innerHTML = html;
}
};
}
testElement = null;
}
module.exports = setInnerHTML;
/***/ },
/* 85 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule createMicrosoftUnsafeLocalFunction
*/
/* globals MSApp */
'use strict';
/**
* Create a function which has 'unsafe' privileges (required by windows8 apps)
*/
var createMicrosoftUnsafeLocalFunction = function (func) {
if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
return function (arg0, arg1, arg2, arg3) {
MSApp.execUnsafeLocalFunction(function () {
return func(arg0, arg1, arg2, arg3);
});
};
} else {
return func;
}
};
module.exports = createMicrosoftUnsafeLocalFunction;
/***/ },
/* 86 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule setTextContent
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(49);
var escapeTextContentForBrowser = __webpack_require__(87);
var setInnerHTML = __webpack_require__(84);
/**
* Set the textContent property of a node, ensuring that whitespace is preserved
* even in IE8. innerText is a poor substitute for textContent and, among many
* issues, inserts <br> instead of the literal newline chars. innerHTML behaves
* as it should.
*
* @param {DOMElement} node
* @param {string} text
* @internal
*/
var setTextContent = function (node, text) {
if (text) {
var firstChild = node.firstChild;
if (firstChild && firstChild === node.lastChild && firstChild.nodeType === 3) {
firstChild.nodeValue = text;
return;
}
}
node.textContent = text;
};
if (ExecutionEnvironment.canUseDOM) {
if (!('textContent' in document.documentElement)) {
setTextContent = function (node, text) {
setInnerHTML(node, escapeTextContentForBrowser(text));
};
}
}
module.exports = setTextContent;
/***/ },
/* 87 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* 'Software'), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @providesModule escapeTextContentForBrowser
*/
'use strict';
// code copied and modified from escape-html
/**
* Module variables.
* @private
*/
var matchHtmlRegExp = /["'&<>]/;
/**
* Escape special characters in the given string of html.
*
* @param {string} string The string to escape for inserting into HTML
* @return {string}
* @public
*/
function escapeHtml(string) {
var str = '' + string;
var match = matchHtmlRegExp.exec(str);
if (!match) {
return str;
}
var escape;
var html = '';
var index = 0;
var lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34:
// "
escape = '"';
break;
case 38:
// &
escape = '&';
break;
case 39:
// '
escape = '''; // modified from escape-html; used to be '''
break;
case 60:
// <
escape = '<';
break;
case 62:
// >
escape = '>';
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
}
lastIndex = index + 1;
html += escape;
}
return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
}
// end code copied and modified from escape-html
/**
* Escapes text to prevent scripting attacks.
*
* @param {*} text Text value to escape.
* @return {string} An escaped string.
*/
function escapeTextContentForBrowser(text) {
if (typeof text === 'boolean' || typeof text === 'number') {
// this shortcircuit helps perf for types that we know will never have
// special characters, especially given that this function is used often
// for numeric dom ids.
return '' + text;
}
return escapeHtml(text);
}
module.exports = escapeTextContentForBrowser;
/***/ },
/* 88 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Danger
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var DOMLazyTree = __webpack_require__(82);
var ExecutionEnvironment = __webpack_require__(49);
var createNodesFromMarkup = __webpack_require__(89);
var emptyFunction = __webpack_require__(12);
var invariant = __webpack_require__(8);
var Danger = {
/**
* Replaces a node with a string of markup at its current position within its
* parent. The markup must render into a single root node.
*
* @param {DOMElement} oldChild Child node to replace.
* @param {string} markup Markup to render in place of the child node.
* @internal
*/
dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) {
!ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('56') : void 0;
!markup ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : _prodInvariant('57') : void 0;
!(oldChild.nodeName !== 'HTML') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See ReactDOMServer.renderToString().') : _prodInvariant('58') : void 0;
if (typeof markup === 'string') {
var newChild = createNodesFromMarkup(markup, emptyFunction)[0];
oldChild.parentNode.replaceChild(newChild, oldChild);
} else {
DOMLazyTree.replaceChildWithTree(oldChild, markup);
}
}
};
module.exports = Danger;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 89 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
/*eslint-disable fb-www/unsafe-html*/
var ExecutionEnvironment = __webpack_require__(49);
var createArrayFromMixed = __webpack_require__(90);
var getMarkupWrap = __webpack_require__(91);
var invariant = __webpack_require__(8);
/**
* Dummy container used to render all markup.
*/
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Pattern used by `getNodeName`.
*/
var nodeNamePattern = /^\s*<(\w+)/;
/**
* Extracts the `nodeName` of the first element in a string of markup.
*
* @param {string} markup String of markup.
* @return {?string} Node name of the supplied markup.
*/
function getNodeName(markup) {
var nodeNameMatch = markup.match(nodeNamePattern);
return nodeNameMatch && nodeNameMatch[1].toLowerCase();
}
/**
* Creates an array containing the nodes rendered from the supplied markup. The
* optionally supplied `handleScript` function will be invoked once for each
* <script> element that is rendered. If no `handleScript` function is supplied,
* an exception is thrown if any <script> elements are rendered.
*
* @param {string} markup A string of valid HTML markup.
* @param {?function} handleScript Invoked once for each rendered <script>.
* @return {array<DOMElement|DOMTextNode>} An array of rendered nodes.
*/
function createNodesFromMarkup(markup, handleScript) {
var node = dummyNode;
!!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : void 0;
var nodeName = getNodeName(markup);
var wrap = nodeName && getMarkupWrap(nodeName);
if (wrap) {
node.innerHTML = wrap[1] + markup + wrap[2];
var wrapDepth = wrap[0];
while (wrapDepth--) {
node = node.lastChild;
}
} else {
node.innerHTML = markup;
}
var scripts = node.getElementsByTagName('script');
if (scripts.length) {
!handleScript ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : void 0;
createArrayFromMixed(scripts).forEach(handleScript);
}
var nodes = Array.from(node.childNodes);
while (node.lastChild) {
node.removeChild(node.lastChild);
}
return nodes;
}
module.exports = createNodesFromMarkup;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 90 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var invariant = __webpack_require__(8);
/**
* Convert array-like objects to arrays.
*
* This API assumes the caller knows the contents of the data type. For less
* well defined inputs use createArrayFromMixed.
*
* @param {object|function|filelist} obj
* @return {array}
*/
function toArray(obj) {
var length = obj.length;
// Some browsers builtin objects can report typeof 'function' (e.g. NodeList
// in old versions of Safari).
!(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : void 0;
!(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : void 0;
!(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : void 0;
!(typeof obj.callee !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant(false) : void 0;
// Old IE doesn't give collections access to hasOwnProperty. Assume inputs
// without method will throw during the slice call and skip straight to the
// fallback.
if (obj.hasOwnProperty) {
try {
return Array.prototype.slice.call(obj);
} catch (e) {
// IE < 9 does not support Array#slice on collections objects
}
}
// Fall back to copying key by key. This assumes all keys have a value,
// so will not preserve sparsely populated inputs.
var ret = Array(length);
for (var ii = 0; ii < length; ii++) {
ret[ii] = obj[ii];
}
return ret;
}
/**
* Perform a heuristic test to determine if an object is "array-like".
*
* A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
* Joshu replied: "Mu."
*
* This function determines if its argument has "array nature": it returns
* true if the argument is an actual array, an `arguments' object, or an
* HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
*
* It will return false for other array-like objects like Filelist.
*
* @param {*} obj
* @return {boolean}
*/
function hasArrayNature(obj) {
return (
// not null/false
!!obj && (
// arrays are objects, NodeLists are functions in Safari
typeof obj == 'object' || typeof obj == 'function') &&
// quacks like an array
'length' in obj &&
// not window
!('setInterval' in obj) &&
// no DOM node should be considered an array-like
// a 'select' element has 'length' and 'item' properties on IE8
typeof obj.nodeType != 'number' && (
// a real array
Array.isArray(obj) ||
// arguments
'callee' in obj ||
// HTMLCollection/NodeList
'item' in obj)
);
}
/**
* Ensure that the argument is an array by wrapping it in an array if it is not.
* Creates a copy of the argument if it is already an array.
*
* This is mostly useful idiomatically:
*
* var createArrayFromMixed = require('createArrayFromMixed');
*
* function takesOneOrMoreThings(things) {
* things = createArrayFromMixed(things);
* ...
* }
*
* This allows you to treat `things' as an array, but accept scalars in the API.
*
* If you need to convert an array-like object, like `arguments`, into an array
* use toArray instead.
*
* @param {*} obj
* @return {array}
*/
function createArrayFromMixed(obj) {
if (!hasArrayNature(obj)) {
return [obj];
} else if (Array.isArray(obj)) {
return obj.slice();
} else {
return toArray(obj);
}
}
module.exports = createArrayFromMixed;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 91 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/*eslint-disable fb-www/unsafe-html */
var ExecutionEnvironment = __webpack_require__(49);
var invariant = __webpack_require__(8);
/**
* Dummy container used to detect which wraps are necessary.
*/
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Some browsers cannot use `innerHTML` to render certain elements standalone,
* so we wrap them, render the wrapped nodes, then extract the desired node.
*
* In IE8, certain elements cannot render alone, so wrap all elements ('*').
*/
var shouldWrap = {};
var selectWrap = [1, '<select multiple="true">', '</select>'];
var tableWrap = [1, '<table>', '</table>'];
var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
var svgWrap = [1, '<svg xmlns="path_to_url">', '</svg>'];
var markupWrap = {
'*': [1, '?<div>', '</div>'],
'area': [1, '<map>', '</map>'],
'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
'legend': [1, '<fieldset>', '</fieldset>'],
'param': [1, '<object>', '</object>'],
'tr': [2, '<table><tbody>', '</tbody></table>'],
'optgroup': selectWrap,
'option': selectWrap,
'caption': tableWrap,
'colgroup': tableWrap,
'tbody': tableWrap,
'tfoot': tableWrap,
'thead': tableWrap,
'td': trWrap,
'th': trWrap
};
// Initialize the SVG elements since we know they'll always need to be wrapped
// consistently. If they are created inside a <div> they will be initialized in
// the wrong namespace (and will not display).
var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan'];
svgElements.forEach(function (nodeName) {
markupWrap[nodeName] = svgWrap;
shouldWrap[nodeName] = true;
});
/**
* Gets the markup wrap configuration for the supplied `nodeName`.
*
* NOTE: This lazily detects which wraps are necessary for the current browser.
*
* @param {string} nodeName Lowercase `nodeName`.
* @return {?array} Markup wrap configuration, if applicable.
*/
function getMarkupWrap(nodeName) {
!!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : void 0;
if (!markupWrap.hasOwnProperty(nodeName)) {
nodeName = '*';
}
if (!shouldWrap.hasOwnProperty(nodeName)) {
if (nodeName === '*') {
dummyNode.innerHTML = '<link />';
} else {
dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>';
}
shouldWrap[nodeName] = !dummyNode.firstChild;
}
return shouldWrap[nodeName] ? markupWrap[nodeName] : null;
}
module.exports = getMarkupWrap;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 92 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMultiChildUpdateTypes
*/
'use strict';
var keyMirror = __webpack_require__(23);
/**
* When a component's children are updated, a series of update configuration
* objects are created in order to batch and serialize the required changes.
*
* Enumerates all the possible types of update configurations.
*
* @internal
*/
var ReactMultiChildUpdateTypes = keyMirror({
INSERT_MARKUP: null,
MOVE_EXISTING: null,
REMOVE_NODE: null,
SET_MARKUP: null,
TEXT_CONTENT: null
});
module.exports = ReactMultiChildUpdateTypes;
/***/ },
/* 93 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMIDOperations
*/
'use strict';
var DOMChildrenOperations = __webpack_require__(81);
var ReactDOMComponentTree = __webpack_require__(36);
/**
* Operations used to process updates to DOM nodes.
*/
var ReactDOMIDOperations = {
/**
* Updates a component's children by processing a series of updates.
*
* @param {array<object>} updates List of update configurations.
* @internal
*/
dangerouslyProcessChildrenUpdates: function (parentInst, updates) {
var node = ReactDOMComponentTree.getNodeFromInstance(parentInst);
DOMChildrenOperations.processUpdates(node, updates);
}
};
module.exports = ReactDOMIDOperations;
/***/ },
/* 94 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMComponent
*/
/* global hasOwnProperty:true */
'use strict';
var _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var AutoFocusUtils = __webpack_require__(95);
var CSSPropertyOperations = __webpack_require__(97);
var DOMLazyTree = __webpack_require__(82);
var DOMNamespaces = __webpack_require__(83);
var DOMProperty = __webpack_require__(37);
var DOMPropertyOperations = __webpack_require__(105);
var EventConstants = __webpack_require__(41);
var EventPluginHub = __webpack_require__(43);
var EventPluginRegistry = __webpack_require__(44);
var ReactBrowserEventEmitter = __webpack_require__(107);
var ReactDOMButton = __webpack_require__(110);
var ReactDOMComponentFlags = __webpack_require__(38);
var ReactDOMComponentTree = __webpack_require__(36);
var ReactDOMInput = __webpack_require__(112);
var ReactDOMOption = __webpack_require__(114);
var ReactDOMSelect = __webpack_require__(115);
var ReactDOMTextarea = __webpack_require__(116);
var ReactInstrumentation = __webpack_require__(62);
var ReactMultiChild = __webpack_require__(117);
var ReactServerRenderingTransaction = __webpack_require__(129);
var emptyFunction = __webpack_require__(12);
var escapeTextContentForBrowser = __webpack_require__(87);
var invariant = __webpack_require__(8);
var isEventSupported = __webpack_require__(71);
var keyOf = __webpack_require__(25);
var shallowEqual = __webpack_require__(124);
var validateDOMNesting = __webpack_require__(132);
var warning = __webpack_require__(11);
var Flags = ReactDOMComponentFlags;
var deleteListener = EventPluginHub.deleteListener;
var getNode = ReactDOMComponentTree.getNodeFromInstance;
var listenTo = ReactBrowserEventEmitter.listenTo;
var registrationNameModules = EventPluginRegistry.registrationNameModules;
// For quickly matching children type, to test if can be treated as content.
var CONTENT_TYPES = { 'string': true, 'number': true };
var STYLE = keyOf({ style: null });
var HTML = keyOf({ __html: null });
var RESERVED_PROPS = {
children: null,
dangerouslySetInnerHTML: null,
suppressContentEditableWarning: null
};
// Node type for document fragments (Node.DOCUMENT_FRAGMENT_NODE).
var DOC_FRAGMENT_TYPE = 11;
function getDeclarationErrorAddendum(internalInstance) {
if (internalInstance) {
var owner = internalInstance._currentElement._owner || null;
if (owner) {
var name = owner.getName();
if (name) {
return ' This DOM node was rendered by `' + name + '`.';
}
}
}
return '';
}
function friendlyStringify(obj) {
if (typeof obj === 'object') {
if (Array.isArray(obj)) {
return '[' + obj.map(friendlyStringify).join(', ') + ']';
} else {
var pairs = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key);
pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key]));
}
}
return '{' + pairs.join(', ') + '}';
}
} else if (typeof obj === 'string') {
return JSON.stringify(obj);
} else if (typeof obj === 'function') {
return '[function object]';
}
// Differs from JSON.stringify in that undefined because undefined and that
// inf and nan don't become null
return String(obj);
}
var styleMutationWarning = {};
function checkAndWarnForMutatedStyle(style1, style2, component) {
if (style1 == null || style2 == null) {
return;
}
if (shallowEqual(style1, style2)) {
return;
}
var componentName = component._tag;
var owner = component._currentElement._owner;
var ownerName;
if (owner) {
ownerName = owner.getName();
}
var hash = ownerName + '|' + componentName;
if (styleMutationWarning.hasOwnProperty(hash)) {
return;
}
styleMutationWarning[hash] = true;
process.env.NODE_ENV !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : void 0;
}
/**
* @param {object} component
* @param {?object} props
*/
function assertValidProps(component, props) {
if (!props) {
return;
}
// Note the use of `==` which checks for null or undefined.
if (voidElementTags[component._tag]) {
!(props.children == null && props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : _prodInvariant('137', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : void 0;
}
if (props.dangerouslySetInnerHTML != null) {
!(props.children == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : _prodInvariant('60') : void 0;
!(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit path_to_url for more information.') : _prodInvariant('61') : void 0;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : void 0;
process.env.NODE_ENV !== 'production' ? warning(props.suppressContentEditableWarning || !props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : void 0;
process.env.NODE_ENV !== 'production' ? warning(props.onFocusIn == null && props.onFocusOut == null, 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.') : void 0;
}
!(props.style == null || typeof props.style === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + \'em\'}} when using JSX.%s', getDeclarationErrorAddendum(component)) : _prodInvariant('62', getDeclarationErrorAddendum(component)) : void 0;
}
function enqueuePutListener(inst, registrationName, listener, transaction) {
if (transaction instanceof ReactServerRenderingTransaction) {
return;
}
if (process.env.NODE_ENV !== 'production') {
// IE8 has no API for event capturing and the `onScroll` event doesn't
// bubble.
process.env.NODE_ENV !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : void 0;
}
var containerInfo = inst._hostContainerInfo;
var isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOC_FRAGMENT_TYPE;
var doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument;
listenTo(registrationName, doc);
transaction.getReactMountReady().enqueue(putListener, {
inst: inst,
registrationName: registrationName,
listener: listener
});
}
function putListener() {
var listenerToPut = this;
EventPluginHub.putListener(listenerToPut.inst, listenerToPut.registrationName, listenerToPut.listener);
}
function inputPostMount() {
var inst = this;
ReactDOMInput.postMountWrapper(inst);
}
function textareaPostMount() {
var inst = this;
ReactDOMTextarea.postMountWrapper(inst);
}
function optionPostMount() {
var inst = this;
ReactDOMOption.postMountWrapper(inst);
}
var setContentChildForInstrumentation = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
setContentChildForInstrumentation = function (content) {
var hasExistingContent = this._contentDebugID != null;
var debugID = this._debugID;
// This ID represents the inlined child that has no backing instance:
var contentDebugID = -debugID;
if (content == null) {
if (hasExistingContent) {
ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID);
}
this._contentDebugID = null;
return;
}
this._contentDebugID = contentDebugID;
if (hasExistingContent) {
ReactInstrumentation.debugTool.onBeforeUpdateComponent(contentDebugID, content);
ReactInstrumentation.debugTool.onUpdateComponent(contentDebugID);
} else {
ReactInstrumentation.debugTool.onBeforeMountComponent(contentDebugID, content, debugID);
ReactInstrumentation.debugTool.onMountComponent(contentDebugID);
ReactInstrumentation.debugTool.onSetChildren(debugID, [contentDebugID]);
}
};
}
// There are so many media events, it makes sense to just
// maintain a list rather than create a `trapBubbledEvent` for each
var mediaEvents = {
topAbort: 'abort',
topCanPlay: 'canplay',
topCanPlayThrough: 'canplaythrough',
topDurationChange: 'durationchange',
topEmptied: 'emptied',
topEncrypted: 'encrypted',
topEnded: 'ended',
topError: 'error',
topLoadedData: 'loadeddata',
topLoadedMetadata: 'loadedmetadata',
topLoadStart: 'loadstart',
topPause: 'pause',
topPlay: 'play',
topPlaying: 'playing',
topProgress: 'progress',
topRateChange: 'ratechange',
topSeeked: 'seeked',
topSeeking: 'seeking',
topStalled: 'stalled',
topSuspend: 'suspend',
topTimeUpdate: 'timeupdate',
topVolumeChange: 'volumechange',
topWaiting: 'waiting'
};
function trapBubbledEventsLocal() {
var inst = this;
// If a component renders to null or if another component fatals and causes
// the state of the tree to be corrupted, `node` here can be null.
!inst._rootNodeID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Must be mounted to trap events') : _prodInvariant('63') : void 0;
var node = getNode(inst);
!node ? process.env.NODE_ENV !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : _prodInvariant('64') : void 0;
switch (inst._tag) {
case 'iframe':
case 'object':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)];
break;
case 'video':
case 'audio':
inst._wrapperState.listeners = [];
// Create listener for each media event
for (var event in mediaEvents) {
if (mediaEvents.hasOwnProperty(event)) {
inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node));
}
}
break;
case 'source':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node)];
break;
case 'img':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)];
break;
case 'form':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)];
break;
case 'input':
case 'select':
case 'textarea':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topInvalid, 'invalid', node)];
break;
}
}
function postUpdateSelectWrapper() {
ReactDOMSelect.postUpdateWrapper(this);
}
// For HTML, certain tags should omit their close tag. We keep a whitelist for
// those special-case tags.
var omittedCloseTags = {
'area': true,
'base': true,
'br': true,
'col': true,
'embed': true,
'hr': true,
'img': true,
'input': true,
'keygen': true,
'link': true,
'meta': true,
'param': true,
'source': true,
'track': true,
'wbr': true
};
// NOTE: menuitem's close tag should be omitted, but that causes problems.
var newlineEatingTags = {
'listing': true,
'pre': true,
'textarea': true
};
// For HTML, certain tags cannot have children. This has the same purpose as
// `omittedCloseTags` except that `menuitem` should still have its closing tag.
var voidElementTags = _assign({
'menuitem': true
}, omittedCloseTags);
// We accept any tag to be rendered but since this gets injected into arbitrary
// HTML, we want to make sure that it's a safe tag.
// path_to_url#NT-Name
var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
var validatedTagCache = {};
var hasOwnProperty = {}.hasOwnProperty;
function validateDangerousTag(tag) {
if (!hasOwnProperty.call(validatedTagCache, tag)) {
!VALID_TAG_REGEX.test(tag) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : _prodInvariant('65', tag) : void 0;
validatedTagCache[tag] = true;
}
}
function isCustomComponent(tagName, props) {
return tagName.indexOf('-') >= 0 || props.is != null;
}
var globalIdCounter = 1;
/**
* Creates a new React class that is idempotent and capable of containing other
* React components. It accepts event listeners and DOM properties that are
* valid according to `DOMProperty`.
*
* - Event listeners: `onClick`, `onMouseDown`, etc.
* - DOM properties: `className`, `name`, `title`, etc.
*
* The `style` property functions differently from the DOM API. It accepts an
* object mapping of style properties to values.
*
* @constructor ReactDOMComponent
* @extends ReactMultiChild
*/
function ReactDOMComponent(element) {
var tag = element.type;
validateDangerousTag(tag);
this._currentElement = element;
this._tag = tag.toLowerCase();
this._namespaceURI = null;
this._renderedChildren = null;
this._previousStyle = null;
this._previousStyleCopy = null;
this._hostNode = null;
this._hostParent = null;
this._rootNodeID = 0;
this._domID = 0;
this._hostContainerInfo = null;
this._wrapperState = null;
this._topLevelWrapper = null;
this._flags = 0;
if (process.env.NODE_ENV !== 'production') {
this._ancestorInfo = null;
setContentChildForInstrumentation.call(this, null);
}
}
ReactDOMComponent.displayName = 'ReactDOMComponent';
ReactDOMComponent.Mixin = {
/**
* Generates root tag markup then recurses. This method has side effects and
* is not idempotent.
*
* @internal
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?ReactDOMComponent} the parent component instance
* @param {?object} info about the host container
* @param {object} context
* @return {string} The computed markup.
*/
mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
this._rootNodeID = globalIdCounter++;
this._domID = hostContainerInfo._idCounter++;
this._hostParent = hostParent;
this._hostContainerInfo = hostContainerInfo;
var props = this._currentElement.props;
switch (this._tag) {
case 'audio':
case 'form':
case 'iframe':
case 'img':
case 'link':
case 'object':
case 'source':
case 'video':
this._wrapperState = {
listeners: null
};
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'button':
props = ReactDOMButton.getHostProps(this, props, hostParent);
break;
case 'input':
ReactDOMInput.mountWrapper(this, props, hostParent);
props = ReactDOMInput.getHostProps(this, props);
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'option':
ReactDOMOption.mountWrapper(this, props, hostParent);
props = ReactDOMOption.getHostProps(this, props);
break;
case 'select':
ReactDOMSelect.mountWrapper(this, props, hostParent);
props = ReactDOMSelect.getHostProps(this, props);
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'textarea':
ReactDOMTextarea.mountWrapper(this, props, hostParent);
props = ReactDOMTextarea.getHostProps(this, props);
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
}
assertValidProps(this, props);
// We create tags in the namespace of their parent container, except HTML
// tags get no namespace.
var namespaceURI;
var parentTag;
if (hostParent != null) {
namespaceURI = hostParent._namespaceURI;
parentTag = hostParent._tag;
} else if (hostContainerInfo._tag) {
namespaceURI = hostContainerInfo._namespaceURI;
parentTag = hostContainerInfo._tag;
}
if (namespaceURI == null || namespaceURI === DOMNamespaces.svg && parentTag === 'foreignobject') {
namespaceURI = DOMNamespaces.html;
}
if (namespaceURI === DOMNamespaces.html) {
if (this._tag === 'svg') {
namespaceURI = DOMNamespaces.svg;
} else if (this._tag === 'math') {
namespaceURI = DOMNamespaces.mathml;
}
}
this._namespaceURI = namespaceURI;
if (process.env.NODE_ENV !== 'production') {
var parentInfo;
if (hostParent != null) {
parentInfo = hostParent._ancestorInfo;
} else if (hostContainerInfo._tag) {
parentInfo = hostContainerInfo._ancestorInfo;
}
if (parentInfo) {
// parentInfo should always be present except for the top-level
// component when server rendering
validateDOMNesting(this._tag, this, parentInfo);
}
this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this);
}
var mountImage;
if (transaction.useCreateElement) {
var ownerDocument = hostContainerInfo._ownerDocument;
var el;
if (namespaceURI === DOMNamespaces.html) {
if (this._tag === 'script') {
// Create the script via .innerHTML so its "parser-inserted" flag is
// set to true and it does not execute
var div = ownerDocument.createElement('div');
var type = this._currentElement.type;
div.innerHTML = '<' + type + '></' + type + '>';
el = div.removeChild(div.firstChild);
} else if (props.is) {
el = ownerDocument.createElement(this._currentElement.type, props.is);
} else {
// Separate else branch instead of using `props.is || undefined` above becuase of a Firefox bug.
// See discussion in path_to_url
// and discussion in path_to_url
el = ownerDocument.createElement(this._currentElement.type);
}
} else {
el = ownerDocument.createElementNS(namespaceURI, this._currentElement.type);
}
ReactDOMComponentTree.precacheNode(this, el);
this._flags |= Flags.hasCachedChildNodes;
if (!this._hostParent) {
DOMPropertyOperations.setAttributeForRoot(el);
}
this._updateDOMProperties(null, props, transaction);
var lazyTree = DOMLazyTree(el);
this._createInitialChildren(transaction, props, context, lazyTree);
mountImage = lazyTree;
} else {
var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props);
var tagContent = this._createContentMarkup(transaction, props, context);
if (!tagContent && omittedCloseTags[this._tag]) {
mountImage = tagOpen + '/>';
} else {
mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>';
}
}
switch (this._tag) {
case 'input':
transaction.getReactMountReady().enqueue(inputPostMount, this);
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
case 'textarea':
transaction.getReactMountReady().enqueue(textareaPostMount, this);
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
case 'select':
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
case 'button':
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
case 'option':
transaction.getReactMountReady().enqueue(optionPostMount, this);
break;
}
return mountImage;
},
/**
* Creates markup for the open tag and all attributes.
*
* This method has side effects because events get registered.
*
* Iterating over object properties is faster than iterating over arrays.
* @see path_to_url
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} props
* @return {string} Markup of opening tag.
*/
_createOpenTagMarkupAndPutListeners: function (transaction, props) {
var ret = '<' + this._currentElement.type;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (registrationNameModules.hasOwnProperty(propKey)) {
if (propValue) {
enqueuePutListener(this, propKey, propValue, transaction);
}
} else {
if (propKey === STYLE) {
if (propValue) {
if (process.env.NODE_ENV !== 'production') {
// See `_updateDOMProperties`. style block
this._previousStyle = propValue;
}
propValue = this._previousStyleCopy = _assign({}, props.style);
}
propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this);
}
var markup = null;
if (this._tag != null && isCustomComponent(this._tag, props)) {
if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue);
}
} else {
markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
}
if (markup) {
ret += ' ' + markup;
}
}
}
// For static pages, no need to put React ID and checksum. Saves lots of
// bytes.
if (transaction.renderToStaticMarkup) {
return ret;
}
if (!this._hostParent) {
ret += ' ' + DOMPropertyOperations.createMarkupForRoot();
}
ret += ' ' + DOMPropertyOperations.createMarkupForID(this._domID);
return ret;
},
/**
* Creates markup for the content between the tags.
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} props
* @param {object} context
* @return {string} Content markup.
*/
_createContentMarkup: function (transaction, props, context) {
var ret = '';
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
ret = innerHTML.__html;
}
} else {
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null;
var childrenToUse = contentToUse != null ? null : props.children;
if (contentToUse != null) {
// TODO: Validate that text is allowed as a child of this node
ret = escapeTextContentForBrowser(contentToUse);
if (process.env.NODE_ENV !== 'production') {
setContentChildForInstrumentation.call(this, contentToUse);
}
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(childrenToUse, transaction, context);
ret = mountImages.join('');
}
}
if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') {
// text/html ignores the first character in these tags if it's a newline
// Prefer to break application/xml over text/html (for now) by adding
// a newline specifically to get eaten by the parser. (Alternately for
// textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
// \r is normalized out by HTMLTextAreaElement#value.)
// See: <path_to_url#newlines-in-textarea-and-pre>
// See: <path_to_url#element-restrictions>
// See: <path_to_url#newlines>
// See: Parsing of "textarea" "listing" and "pre" elements
// from <path_to_url#parsing-main-inbody>
return '\n' + ret;
} else {
return ret;
}
},
_createInitialChildren: function (transaction, props, context, lazyTree) {
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
DOMLazyTree.queueHTML(lazyTree, innerHTML.__html);
}
} else {
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null;
var childrenToUse = contentToUse != null ? null : props.children;
if (contentToUse != null) {
// TODO: Validate that text is allowed as a child of this node
if (process.env.NODE_ENV !== 'production') {
setContentChildForInstrumentation.call(this, contentToUse);
}
DOMLazyTree.queueText(lazyTree, contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(childrenToUse, transaction, context);
for (var i = 0; i < mountImages.length; i++) {
DOMLazyTree.queueChild(lazyTree, mountImages[i]);
}
}
}
},
/**
* Receives a next element and updates the component.
*
* @internal
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} context
*/
receiveComponent: function (nextElement, transaction, context) {
var prevElement = this._currentElement;
this._currentElement = nextElement;
this.updateComponent(transaction, prevElement, nextElement, context);
},
/**
* Updates a DOM component after it has already been allocated and
* attached to the DOM. Reconciles the root DOM node, then recurses.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevElement
* @param {ReactElement} nextElement
* @internal
* @overridable
*/
updateComponent: function (transaction, prevElement, nextElement, context) {
var lastProps = prevElement.props;
var nextProps = this._currentElement.props;
switch (this._tag) {
case 'button':
lastProps = ReactDOMButton.getHostProps(this, lastProps);
nextProps = ReactDOMButton.getHostProps(this, nextProps);
break;
case 'input':
lastProps = ReactDOMInput.getHostProps(this, lastProps);
nextProps = ReactDOMInput.getHostProps(this, nextProps);
break;
case 'option':
lastProps = ReactDOMOption.getHostProps(this, lastProps);
nextProps = ReactDOMOption.getHostProps(this, nextProps);
break;
case 'select':
lastProps = ReactDOMSelect.getHostProps(this, lastProps);
nextProps = ReactDOMSelect.getHostProps(this, nextProps);
break;
case 'textarea':
lastProps = ReactDOMTextarea.getHostProps(this, lastProps);
nextProps = ReactDOMTextarea.getHostProps(this, nextProps);
break;
}
assertValidProps(this, nextProps);
this._updateDOMProperties(lastProps, nextProps, transaction);
this._updateDOMChildren(lastProps, nextProps, transaction, context);
switch (this._tag) {
case 'input':
// Update the wrapper around inputs *after* updating props. This has to
// happen after `_updateDOMProperties`. Otherwise HTML5 input validations
// raise warnings and prevent the new value from being assigned.
ReactDOMInput.updateWrapper(this);
break;
case 'textarea':
ReactDOMTextarea.updateWrapper(this);
break;
case 'select':
// <select> value update needs to occur after <option> children
// reconciliation
transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
break;
}
},
/**
* Reconciles the properties by detecting differences in property values and
* updating the DOM as necessary. This function is probably the single most
* critical path for performance optimization.
*
* TODO: Benchmark whether checking for changed values in memory actually
* improves performance (especially statically positioned elements).
* TODO: Benchmark the effects of putting this at the top since 99% of props
* do not change for a given reconciliation.
* TODO: Benchmark areas that can be improved with caching.
*
* @private
* @param {object} lastProps
* @param {object} nextProps
* @param {?DOMElement} node
*/
_updateDOMProperties: function (lastProps, nextProps, transaction) {
var propKey;
var styleName;
var styleUpdates;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
continue;
}
if (propKey === STYLE) {
var lastStyle = this._previousStyleCopy;
for (styleName in lastStyle) {
if (lastStyle.hasOwnProperty(styleName)) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
this._previousStyleCopy = null;
} else if (registrationNameModules.hasOwnProperty(propKey)) {
if (lastProps[propKey]) {
// Only call deleteListener if there was a listener previously or
// else willDeleteListener gets called when there wasn't actually a
// listener (e.g., onClick={null})
deleteListener(this, propKey);
}
} else if (isCustomComponent(this._tag, lastProps)) {
if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
DOMPropertyOperations.deleteValueForAttribute(getNode(this), propKey);
}
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey);
}
}
for (propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps != null ? lastProps[propKey] : undefined;
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
continue;
}
if (propKey === STYLE) {
if (nextProp) {
if (process.env.NODE_ENV !== 'production') {
checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this);
this._previousStyle = nextProp;
}
nextProp = this._previousStyleCopy = _assign({}, nextProp);
} else {
this._previousStyleCopy = null;
}
if (lastProp) {
// Unset styles on `lastProp` but not on `nextProp`.
for (styleName in lastProp) {
if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
// Update styles that changed since `lastProp`.
for (styleName in nextProp) {
if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = nextProp[styleName];
}
}
} else {
// Relies on `updateStylesByID` not mutating `styleUpdates`.
styleUpdates = nextProp;
}
} else if (registrationNameModules.hasOwnProperty(propKey)) {
if (nextProp) {
enqueuePutListener(this, propKey, nextProp, transaction);
} else if (lastProp) {
deleteListener(this, propKey);
}
} else if (isCustomComponent(this._tag, nextProps)) {
if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
DOMPropertyOperations.setValueForAttribute(getNode(this), propKey, nextProp);
}
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
var node = getNode(this);
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertently setting to a string. This
// brings us in line with the same behavior we have on initial render.
if (nextProp != null) {
DOMPropertyOperations.setValueForProperty(node, propKey, nextProp);
} else {
DOMPropertyOperations.deleteValueForProperty(node, propKey);
}
}
}
if (styleUpdates) {
CSSPropertyOperations.setValueForStyles(getNode(this), styleUpdates, this);
}
},
/**
* Reconciles the children with the various properties that affect the
* children content.
*
* @param {object} lastProps
* @param {object} nextProps
* @param {ReactReconcileTransaction} transaction
* @param {object} context
*/
_updateDOMChildren: function (lastProps, nextProps, transaction, context) {
var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null;
var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null;
var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html;
var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html;
// Note the use of `!=` which checks for null or undefined.
var lastChildren = lastContent != null ? null : lastProps.children;
var nextChildren = nextContent != null ? null : nextProps.children;
// If we're switching from children to content/html or vice versa, remove
// the old content
var lastHasContentOrHtml = lastContent != null || lastHtml != null;
var nextHasContentOrHtml = nextContent != null || nextHtml != null;
if (lastChildren != null && nextChildren == null) {
this.updateChildren(null, transaction, context);
} else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
this.updateTextContent('');
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onSetChildren(this._debugID, []);
}
}
if (nextContent != null) {
if (lastContent !== nextContent) {
this.updateTextContent('' + nextContent);
if (process.env.NODE_ENV !== 'production') {
setContentChildForInstrumentation.call(this, nextContent);
}
}
} else if (nextHtml != null) {
if (lastHtml !== nextHtml) {
this.updateMarkup('' + nextHtml);
}
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onSetChildren(this._debugID, []);
}
} else if (nextChildren != null) {
if (process.env.NODE_ENV !== 'production') {
setContentChildForInstrumentation.call(this, null);
}
this.updateChildren(nextChildren, transaction, context);
}
},
getHostNode: function () {
return getNode(this);
},
/**
* Destroys all event registrations for this instance. Does not remove from
* the DOM. That must be done by the parent.
*
* @internal
*/
unmountComponent: function (safely) {
switch (this._tag) {
case 'audio':
case 'form':
case 'iframe':
case 'img':
case 'link':
case 'object':
case 'source':
case 'video':
var listeners = this._wrapperState.listeners;
if (listeners) {
for (var i = 0; i < listeners.length; i++) {
listeners[i].remove();
}
}
break;
case 'html':
case 'head':
case 'body':
/**
* Components like <html> <head> and <body> can't be removed or added
* easily in a cross-browser way, however it's valuable to be able to
* take advantage of React's reconciliation for styling and <title>
* management. So we just document it and throw in dangerous cases.
*/
true ? process.env.NODE_ENV !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.', this._tag) : _prodInvariant('66', this._tag) : void 0;
break;
}
this.unmountChildren(safely);
ReactDOMComponentTree.uncacheNode(this);
EventPluginHub.deleteAllListeners(this);
this._rootNodeID = 0;
this._domID = 0;
this._wrapperState = null;
if (process.env.NODE_ENV !== 'production') {
setContentChildForInstrumentation.call(this, null);
}
},
getPublicInstance: function () {
return getNode(this);
}
};
_assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin);
module.exports = ReactDOMComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 95 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule AutoFocusUtils
*/
'use strict';
var ReactDOMComponentTree = __webpack_require__(36);
var focusNode = __webpack_require__(96);
var AutoFocusUtils = {
focusDOMComponent: function () {
focusNode(ReactDOMComponentTree.getNodeFromInstance(this));
}
};
module.exports = AutoFocusUtils;
/***/ },
/* 96 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* @param {DOMElement} node input/textarea to focus
*/
function focusNode(node) {
// IE8 can throw "Can't move focus to the control because it is invisible,
// not enabled, or of a type that does not accept the focus." for all kinds of
// reasons that are too expensive and fragile to test.
try {
node.focus();
} catch (e) {}
}
module.exports = focusNode;
/***/ },
/* 97 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CSSPropertyOperations
*/
'use strict';
var CSSProperty = __webpack_require__(98);
var ExecutionEnvironment = __webpack_require__(49);
var ReactInstrumentation = __webpack_require__(62);
var camelizeStyleName = __webpack_require__(99);
var dangerousStyleValue = __webpack_require__(101);
var hyphenateStyleName = __webpack_require__(102);
var memoizeStringOnly = __webpack_require__(104);
var warning = __webpack_require__(11);
var processStyleName = memoizeStringOnly(function (styleName) {
return hyphenateStyleName(styleName);
});
var hasShorthandPropertyBug = false;
var styleFloatAccessor = 'cssFloat';
if (ExecutionEnvironment.canUseDOM) {
var tempStyle = document.createElement('div').style;
try {
// IE8 throws "Invalid argument." if resetting shorthand style properties.
tempStyle.font = '';
} catch (e) {
hasShorthandPropertyBug = true;
}
// IE8 only supports accessing cssFloat (standard) as styleFloat
if (document.documentElement.style.cssFloat === undefined) {
styleFloatAccessor = 'styleFloat';
}
}
if (process.env.NODE_ENV !== 'production') {
// 'msTransform' is correct, but the other prefixes should be capitalized
var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
// style values shouldn't contain a semicolon
var badStyleValueWithSemicolonPattern = /;\s*$/;
var warnedStyleNames = {};
var warnedStyleValues = {};
var warnedForNaNValue = false;
var warnHyphenatedStyleName = function (name, owner) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?%s', name, camelizeStyleName(name), checkRenderMessage(owner)) : void 0;
};
var warnBadVendoredStyleName = function (name, owner) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?%s', name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)) : void 0;
};
var warnStyleValueWithSemicolon = function (name, value, owner) {
if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
return;
}
warnedStyleValues[value] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon.%s ' + 'Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, '')) : void 0;
};
var warnStyleValueIsNaN = function (name, value, owner) {
if (warnedForNaNValue) {
return;
}
warnedForNaNValue = true;
process.env.NODE_ENV !== 'production' ? warning(false, '`NaN` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)) : void 0;
};
var checkRenderMessage = function (owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
};
/**
* @param {string} name
* @param {*} value
* @param {ReactDOMComponent} component
*/
var warnValidStyle = function (name, value, component) {
var owner;
if (component) {
owner = component._currentElement._owner;
}
if (name.indexOf('-') > -1) {
warnHyphenatedStyleName(name, owner);
} else if (badVendoredStyleNamePattern.test(name)) {
warnBadVendoredStyleName(name, owner);
} else if (badStyleValueWithSemicolonPattern.test(value)) {
warnStyleValueWithSemicolon(name, value, owner);
}
if (typeof value === 'number' && isNaN(value)) {
warnStyleValueIsNaN(name, value, owner);
}
};
}
/**
* Operations for dealing with CSS properties.
*/
var CSSPropertyOperations = {
/**
* Serializes a mapping of style properties for use as inline styles:
*
* > createMarkupForStyles({width: '200px', height: 0})
* "width:200px;height:0;"
*
* Undefined values are ignored so that declarative programming is easier.
* The result should be HTML-escaped before insertion into the DOM.
*
* @param {object} styles
* @param {ReactDOMComponent} component
* @return {?string}
*/
createMarkupForStyles: function (styles, component) {
var serialized = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
if (process.env.NODE_ENV !== 'production') {
warnValidStyle(styleName, styleValue, component);
}
if (styleValue != null) {
serialized += processStyleName(styleName) + ':';
serialized += dangerousStyleValue(styleName, styleValue, component) + ';';
}
}
return serialized || null;
},
/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
* @param {ReactDOMComponent} component
*/
setValueForStyles: function (node, styles, component) {
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(component._debugID, 'update styles', styles);
}
var style = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
if (process.env.NODE_ENV !== 'production') {
warnValidStyle(styleName, styles[styleName], component);
}
var styleValue = dangerousStyleValue(styleName, styles[styleName], component);
if (styleName === 'float' || styleName === 'cssFloat') {
styleName = styleFloatAccessor;
}
if (styleValue) {
style[styleName] = styleValue;
} else {
var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName];
if (expansion) {
// Shorthand property that IE8 won't like unsetting, so unset each
// component to placate it
for (var individualStyleName in expansion) {
style[individualStyleName] = '';
}
} else {
style[styleName] = '';
}
}
}
}
};
module.exports = CSSPropertyOperations;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 98 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CSSProperty
*/
'use strict';
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
animationIterationCount: true,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
gridRow: true,
gridColumn: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true
};
/**
* @param {string} prefix vendor-specific prefix, eg: Webkit
* @param {string} key style name, eg: transitionDuration
* @return {string} style name prefixed with `prefix`, properly camelCased, eg:
* WebkitTransitionDuration
*/
function prefixKey(prefix, key) {
return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
* Support style names that may come passed in prefixed by adding permutations
* of vendor prefixes.
*/
var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function (prop) {
prefixes.forEach(function (prefix) {
isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
});
});
/**
* Most style properties can be unset by doing .style[prop] = '' but IE8
* doesn't like doing that with shorthand properties so for the properties that
* IE8 breaks on, which are listed here, we instead unset each of the
* individual properties. See path_to_url
* The 4-value 'clock' properties like margin, padding, border-width seem to
* behave without any problems. Curiously, list-style works too without any
* special prodding.
*/
var shorthandPropertyExpansions = {
background: {
backgroundAttachment: true,
backgroundColor: true,
backgroundImage: true,
backgroundPositionX: true,
backgroundPositionY: true,
backgroundRepeat: true
},
backgroundPosition: {
backgroundPositionX: true,
backgroundPositionY: true
},
border: {
borderWidth: true,
borderStyle: true,
borderColor: true
},
borderBottom: {
borderBottomWidth: true,
borderBottomStyle: true,
borderBottomColor: true
},
borderLeft: {
borderLeftWidth: true,
borderLeftStyle: true,
borderLeftColor: true
},
borderRight: {
borderRightWidth: true,
borderRightStyle: true,
borderRightColor: true
},
borderTop: {
borderTopWidth: true,
borderTopStyle: true,
borderTopColor: true
},
font: {
fontStyle: true,
fontVariant: true,
fontWeight: true,
fontSize: true,
lineHeight: true,
fontFamily: true
},
outline: {
outlineWidth: true,
outlineStyle: true,
outlineColor: true
}
};
var CSSProperty = {
isUnitlessNumber: isUnitlessNumber,
shorthandPropertyExpansions: shorthandPropertyExpansions
};
module.exports = CSSProperty;
/***/ },
/* 99 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
'use strict';
var camelize = __webpack_require__(100);
var msPattern = /^-ms-/;
/**
* Camelcases a hyphenated CSS property name, for example:
*
* > camelizeStyleName('background-color')
* < "backgroundColor"
* > camelizeStyleName('-moz-transition')
* < "MozTransition"
* > camelizeStyleName('-ms-transition')
* < "msTransition"
*
* As Andi Smith suggests
* (path_to_url an `-ms` prefix
* is converted to lowercase `ms`.
*
* @param {string} string
* @return {string}
*/
function camelizeStyleName(string) {
return camelize(string.replace(msPattern, 'ms-'));
}
module.exports = camelizeStyleName;
/***/ },
/* 100 */
/***/ function(module, exports) {
"use strict";
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var _hyphenPattern = /-(.)/g;
/**
* Camelcases a hyphenated string, for example:
*
* > camelize('background-color')
* < "backgroundColor"
*
* @param {string} string
* @return {string}
*/
function camelize(string) {
return string.replace(_hyphenPattern, function (_, character) {
return character.toUpperCase();
});
}
module.exports = camelize;
/***/ },
/* 101 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule dangerousStyleValue
*/
'use strict';
var CSSProperty = __webpack_require__(98);
var warning = __webpack_require__(11);
var isUnitlessNumber = CSSProperty.isUnitlessNumber;
var styleWarnings = {};
/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @param {ReactDOMComponent} component
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value, component) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// path_to_url
// path_to_url
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty = value == null || typeof value === 'boolean' || value === '';
if (isEmpty) {
return '';
}
var isNonNumeric = isNaN(value);
if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
return '' + value; // cast to string
}
if (typeof value === 'string') {
if (process.env.NODE_ENV !== 'production') {
// Allow '0' to pass through without warning. 0 is already special and
// doesn't require units, so we don't need to warn about it.
if (component && value !== '0') {
var owner = component._currentElement._owner;
var ownerName = owner ? owner.getName() : null;
if (ownerName && !styleWarnings[ownerName]) {
styleWarnings[ownerName] = {};
}
var warned = false;
if (ownerName) {
var warnings = styleWarnings[ownerName];
warned = warnings[name];
if (!warned) {
warnings[name] = true;
}
}
if (!warned) {
process.env.NODE_ENV !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value) : void 0;
}
}
}
value = value.trim();
}
return value + 'px';
}
module.exports = dangerousStyleValue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 102 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
'use strict';
var hyphenate = __webpack_require__(103);
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (path_to_url#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, '-ms-');
}
module.exports = hyphenateStyleName;
/***/ },
/* 103 */
/***/ function(module, exports) {
'use strict';
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* For CSS style names, use `hyphenateStyleName` instead which works properly
* with all vendor prefixes, including `ms`.
*
* @param {string} string
* @return {string}
*/
function hyphenate(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
module.exports = hyphenate;
/***/ },
/* 104 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
* @typechecks static-only
*/
'use strict';
/**
* Memoizes the return value of a function that accepts one string argument.
*/
function memoizeStringOnly(callback) {
var cache = {};
return function (string) {
if (!cache.hasOwnProperty(string)) {
cache[string] = callback.call(this, string);
}
return cache[string];
};
}
module.exports = memoizeStringOnly;
/***/ },
/* 105 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMPropertyOperations
*/
'use strict';
var DOMProperty = __webpack_require__(37);
var ReactDOMComponentTree = __webpack_require__(36);
var ReactInstrumentation = __webpack_require__(62);
var quoteAttributeValueForBrowser = __webpack_require__(106);
var warning = __webpack_require__(11);
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$');
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
if (validatedAttributeNameCache.hasOwnProperty(attributeName)) {
return true;
}
if (illegalAttributeNameCache.hasOwnProperty(attributeName)) {
return false;
}
if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
validatedAttributeNameCache[attributeName] = true;
return true;
}
illegalAttributeNameCache[attributeName] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : void 0;
return false;
}
function shouldIgnoreValue(propertyInfo, value) {
return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false;
}
/**
* Operations for dealing with DOM properties.
*/
var DOMPropertyOperations = {
/**
* Creates markup for the ID property.
*
* @param {string} id Unescaped ID.
* @return {string} Markup string.
*/
createMarkupForID: function (id) {
return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id);
},
setAttributeForID: function (node, id) {
node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id);
},
createMarkupForRoot: function () {
return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""';
},
setAttributeForRoot: function (node) {
node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, '');
},
/**
* Creates markup for a property.
*
* @param {string} name
* @param {*} value
* @return {?string} Markup string, or null if the property was invalid.
*/
createMarkupForProperty: function (name, value) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
if (shouldIgnoreValue(propertyInfo, value)) {
return '';
}
var attributeName = propertyInfo.attributeName;
if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
return attributeName + '=""';
}
return attributeName + '=' + quoteAttributeValueForBrowser(value);
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
}
return null;
},
/**
* Creates markup for a custom property.
*
* @param {string} name
* @param {*} value
* @return {string} Markup string, or empty string if the property was invalid.
*/
createMarkupForCustomAttribute: function (name, value) {
if (!isAttributeNameSafe(name) || value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
},
/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/
setValueForProperty: function (node, name, value) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, value);
} else if (shouldIgnoreValue(propertyInfo, value)) {
this.deleteValueForProperty(node, name);
return;
} else if (propertyInfo.mustUseProperty) {
// Contrary to `setAttribute`, object properties are properly
// `toString`ed by IE8/9.
node[propertyInfo.propertyName] = value;
} else {
var attributeName = propertyInfo.attributeName;
var namespace = propertyInfo.attributeNamespace;
// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
if (namespace) {
node.setAttributeNS(namespace, attributeName, '' + value);
} else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
node.setAttribute(attributeName, '');
} else {
node.setAttribute(attributeName, '' + value);
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
DOMPropertyOperations.setValueForAttribute(node, name, value);
return;
}
if (process.env.NODE_ENV !== 'production') {
var payload = {};
payload[name] = value;
ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'update attribute', payload);
}
},
setValueForAttribute: function (node, name, value) {
if (!isAttributeNameSafe(name)) {
return;
}
if (value == null) {
node.removeAttribute(name);
} else {
node.setAttribute(name, '' + value);
}
if (process.env.NODE_ENV !== 'production') {
var payload = {};
payload[name] = value;
ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'update attribute', payload);
}
},
/**
* Deletes an attributes from a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForAttribute: function (node, name) {
node.removeAttribute(name);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'remove attribute', name);
}
},
/**
* Deletes the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForProperty: function (node, name) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, undefined);
} else if (propertyInfo.mustUseProperty) {
var propName = propertyInfo.propertyName;
if (propertyInfo.hasBooleanValue) {
node[propName] = false;
} else {
node[propName] = '';
}
} else {
node.removeAttribute(propertyInfo.attributeName);
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.removeAttribute(name);
}
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'remove attribute', name);
}
}
};
module.exports = DOMPropertyOperations;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 106 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule quoteAttributeValueForBrowser
*/
'use strict';
var escapeTextContentForBrowser = __webpack_require__(87);
/**
* Escapes attribute value to prevent scripting attacks.
*
* @param {*} value Value to escape.
* @return {string} An escaped string.
*/
function quoteAttributeValueForBrowser(value) {
return '"' + escapeTextContentForBrowser(value) + '"';
}
module.exports = quoteAttributeValueForBrowser;
/***/ },
/* 107 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactBrowserEventEmitter
*/
'use strict';
var _assign = __webpack_require__(4);
var EventConstants = __webpack_require__(41);
var EventPluginRegistry = __webpack_require__(44);
var ReactEventEmitterMixin = __webpack_require__(108);
var ViewportMetrics = __webpack_require__(77);
var getVendorPrefixedEventName = __webpack_require__(109);
var isEventSupported = __webpack_require__(71);
/**
* Summary of `ReactBrowserEventEmitter` event handling:
*
* - Top-level delegation is used to trap most native browser events. This
* may only occur in the main thread and is the responsibility of
* ReactEventListener, which is injected and can therefore support pluggable
* event sources. This is the only work that occurs in the main thread.
*
* - We normalize and de-duplicate events to account for browser quirks. This
* may be done in the worker thread.
*
* - Forward these native events (with the associated top-level type used to
* trap it) to `EventPluginHub`, which in turn will ask plugins if they want
* to extract any synthetic events.
*
* - The `EventPluginHub` will then process each event by annotating them with
* "dispatches", a sequence of listeners and IDs that care about that event.
*
* - The `EventPluginHub` then dispatches the events.
*
* Overview of React and the event system:
*
* +------------+ .
* | DOM | .
* +------------+ .
* | .
* v .
* +------------+ .
* | ReactEvent | .
* | Listener | .
* +------------+ . +-----------+
* | . +--------+|SimpleEvent|
* | . | |Plugin |
* +-----|------+ . v +-----------+
* | | | . +--------------+ +------------+
* | +-----------.--->|EventPluginHub| | Event |
* | | . | | +-----------+ | Propagators|
* | ReactEvent | . | | |TapEvent | |------------|
* | Emitter | . | |<---+|Plugin | |other plugin|
* | | . | | +-----------+ | utilities |
* | +-----------.--->| | +------------+
* | | | . +--------------+
* +-----|------+ . ^ +-----------+
* | . | |Enter/Leave|
* + . +-------+|Plugin |
* +-------------+ . +-----------+
* | application | .
* |-------------| .
* | | .
* | | .
* +-------------+ .
* .
* React Core . General Purpose Event Plugin System
*/
var hasEventPageXY;
var alreadyListeningTo = {};
var isMonitoringScrollValue = false;
var reactTopListenersCounter = 0;
// For events like 'submit' which don't consistently bubble (which we trap at a
// lower node than `document`), binding at `document` would cause duplicate
// events so we don't include them here
var topEventMapping = {
topAbort: 'abort',
topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend',
topAnimationIteration: getVendorPrefixedEventName('animationiteration') || 'animationiteration',
topAnimationStart: getVendorPrefixedEventName('animationstart') || 'animationstart',
topBlur: 'blur',
topCanPlay: 'canplay',
topCanPlayThrough: 'canplaythrough',
topChange: 'change',
topClick: 'click',
topCompositionEnd: 'compositionend',
topCompositionStart: 'compositionstart',
topCompositionUpdate: 'compositionupdate',
topContextMenu: 'contextmenu',
topCopy: 'copy',
topCut: 'cut',
topDoubleClick: 'dblclick',
topDrag: 'drag',
topDragEnd: 'dragend',
topDragEnter: 'dragenter',
topDragExit: 'dragexit',
topDragLeave: 'dragleave',
topDragOver: 'dragover',
topDragStart: 'dragstart',
topDrop: 'drop',
topDurationChange: 'durationchange',
topEmptied: 'emptied',
topEncrypted: 'encrypted',
topEnded: 'ended',
topError: 'error',
topFocus: 'focus',
topInput: 'input',
topKeyDown: 'keydown',
topKeyPress: 'keypress',
topKeyUp: 'keyup',
topLoadedData: 'loadeddata',
topLoadedMetadata: 'loadedmetadata',
topLoadStart: 'loadstart',
topMouseDown: 'mousedown',
topMouseMove: 'mousemove',
topMouseOut: 'mouseout',
topMouseOver: 'mouseover',
topMouseUp: 'mouseup',
topPaste: 'paste',
topPause: 'pause',
topPlay: 'play',
topPlaying: 'playing',
topProgress: 'progress',
topRateChange: 'ratechange',
topScroll: 'scroll',
topSeeked: 'seeked',
topSeeking: 'seeking',
topSelectionChange: 'selectionchange',
topStalled: 'stalled',
topSuspend: 'suspend',
topTextInput: 'textInput',
topTimeUpdate: 'timeupdate',
topTouchCancel: 'touchcancel',
topTouchEnd: 'touchend',
topTouchMove: 'touchmove',
topTouchStart: 'touchstart',
topTransitionEnd: getVendorPrefixedEventName('transitionend') || 'transitionend',
topVolumeChange: 'volumechange',
topWaiting: 'waiting',
topWheel: 'wheel'
};
/**
* To ensure no conflicts with other potential React instances on the page
*/
var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2);
function getListeningForDocument(mountAt) {
// In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty`
// directly.
if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) {
mountAt[topListenersIDKey] = reactTopListenersCounter++;
alreadyListeningTo[mountAt[topListenersIDKey]] = {};
}
return alreadyListeningTo[mountAt[topListenersIDKey]];
}
/**
* `ReactBrowserEventEmitter` is used to attach top-level event listeners. For
* example:
*
* EventPluginHub.putListener('myID', 'onClick', myFunction);
*
* This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
*
* @internal
*/
var ReactBrowserEventEmitter = _assign({}, ReactEventEmitterMixin, {
/**
* Injectable event backend
*/
ReactEventListener: null,
injection: {
/**
* @param {object} ReactEventListener
*/
injectReactEventListener: function (ReactEventListener) {
ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel);
ReactBrowserEventEmitter.ReactEventListener = ReactEventListener;
}
},
/**
* Sets whether or not any created callbacks should be enabled.
*
* @param {boolean} enabled True if callbacks should be enabled.
*/
setEnabled: function (enabled) {
if (ReactBrowserEventEmitter.ReactEventListener) {
ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled);
}
},
/**
* @return {boolean} True if callbacks are enabled.
*/
isEnabled: function () {
return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled());
},
/**
* We listen for bubbled touch events on the document object.
*
* Firefox v8.01 (and possibly others) exhibited strange behavior when
* mounting `onmousemove` events at some node that was not the document
* element. The symptoms were that if your mouse is not moving over something
* contained within that mount point (for example on the background) the
* top-level listeners for `onmousemove` won't be called. However, if you
* register the `mousemove` on the document object, then it will of course
* catch all `mousemove`s. This along with iOS quirks, justifies restricting
* top-level listeners to the document object only, at least for these
* movement types of events and possibly all events.
*
* @see path_to_url
*
* Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
* they bubble to document.
*
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {object} contentDocumentHandle Document which owns the container
*/
listenTo: function (registrationName, contentDocumentHandle) {
var mountAt = contentDocumentHandle;
var isListening = getListeningForDocument(mountAt);
var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName];
var topLevelTypes = EventConstants.topLevelTypes;
for (var i = 0; i < dependencies.length; i++) {
var dependency = dependencies[i];
if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
if (dependency === topLevelTypes.topWheel) {
if (isEventSupported('wheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt);
} else if (isEventSupported('mousewheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt);
} else {
// Firefox needs to capture a different mouse scroll event.
// @see path_to_url
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt);
}
} else if (dependency === topLevelTypes.topScroll) {
if (isEventSupported('scroll', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt);
} else {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE);
}
} else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) {
if (isEventSupported('focus', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt);
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt);
} else if (isEventSupported('focusin')) {
// IE has `focusin` and `focusout` events which bubble.
// @see path_to_url
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt);
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt);
}
// to make sure blur and focus event listeners are only attached once
isListening[topLevelTypes.topBlur] = true;
isListening[topLevelTypes.topFocus] = true;
} else if (topEventMapping.hasOwnProperty(dependency)) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt);
}
isListening[dependency] = true;
}
}
},
trapBubbledEvent: function (topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle);
},
trapCapturedEvent: function (topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle);
},
/**
* Listens to window scroll and resize events. We cache scroll values so that
* application code can access them without triggering reflows.
*
* ViewportMetrics is only used by SyntheticMouse/TouchEvent and only when
* pageX/pageY isn't supported (legacy browsers).
*
* NOTE: Scroll events do not bubble.
*
* @see path_to_url
*/
ensureScrollValueMonitoring: function () {
if (hasEventPageXY === undefined) {
hasEventPageXY = document.createEvent && 'pageX' in document.createEvent('MouseEvent');
}
if (!hasEventPageXY && !isMonitoringScrollValue) {
var refresh = ViewportMetrics.refreshScrollValues;
ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh);
isMonitoringScrollValue = true;
}
}
});
module.exports = ReactBrowserEventEmitter;
/***/ },
/* 108 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEventEmitterMixin
*/
'use strict';
var EventPluginHub = __webpack_require__(43);
function runEventQueueInBatch(events) {
EventPluginHub.enqueueEvents(events);
EventPluginHub.processEventQueue(false);
}
var ReactEventEmitterMixin = {
/**
* Streams a fired top-level event to `EventPluginHub` where plugins have the
* opportunity to create `ReactEvent`s to be dispatched.
*/
handleTopLevel: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var events = EventPluginHub.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
runEventQueueInBatch(events);
}
};
module.exports = ReactEventEmitterMixin;
/***/ },
/* 109 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getVendorPrefixedEventName
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(49);
/**
* Generate a mapping of standard vendor prefixes using the defined style property and event name.
*
* @param {string} styleProp
* @param {string} eventName
* @returns {object}
*/
function makePrefixMap(styleProp, eventName) {
var prefixes = {};
prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
prefixes['Webkit' + styleProp] = 'webkit' + eventName;
prefixes['Moz' + styleProp] = 'moz' + eventName;
prefixes['ms' + styleProp] = 'MS' + eventName;
prefixes['O' + styleProp] = 'o' + eventName.toLowerCase();
return prefixes;
}
/**
* A list of event names to a configurable list of vendor prefixes.
*/
var vendorPrefixes = {
animationend: makePrefixMap('Animation', 'AnimationEnd'),
animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
animationstart: makePrefixMap('Animation', 'AnimationStart'),
transitionend: makePrefixMap('Transition', 'TransitionEnd')
};
/**
* Event names that have already been detected and prefixed (if applicable).
*/
var prefixedEventNames = {};
/**
* Element to check for prefixes on.
*/
var style = {};
/**
* Bootstrap if a DOM exists.
*/
if (ExecutionEnvironment.canUseDOM) {
style = document.createElement('div').style;
// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are usable, and if not remove them from the map.
if (!('AnimationEvent' in window)) {
delete vendorPrefixes.animationend.animation;
delete vendorPrefixes.animationiteration.animation;
delete vendorPrefixes.animationstart.animation;
}
// Same as above
if (!('TransitionEvent' in window)) {
delete vendorPrefixes.transitionend.transition;
}
}
/**
* Attempts to determine the correct vendor prefixed event name.
*
* @param {string} eventName
* @returns {string}
*/
function getVendorPrefixedEventName(eventName) {
if (prefixedEventNames[eventName]) {
return prefixedEventNames[eventName];
} else if (!vendorPrefixes[eventName]) {
return eventName;
}
var prefixMap = vendorPrefixes[eventName];
for (var styleProp in prefixMap) {
if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
return prefixedEventNames[eventName] = prefixMap[styleProp];
}
}
return '';
}
module.exports = getVendorPrefixedEventName;
/***/ },
/* 110 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMButton
*/
'use strict';
var DisabledInputUtils = __webpack_require__(111);
/**
* Implements a <button> host component that does not receive mouse events
* when `disabled` is set.
*/
var ReactDOMButton = {
getHostProps: DisabledInputUtils.getHostProps
};
module.exports = ReactDOMButton;
/***/ },
/* 111 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DisabledInputUtils
*/
'use strict';
var disableableMouseListenerNames = {
onClick: true,
onDoubleClick: true,
onMouseDown: true,
onMouseMove: true,
onMouseUp: true,
onClickCapture: true,
onDoubleClickCapture: true,
onMouseDownCapture: true,
onMouseMoveCapture: true,
onMouseUpCapture: true
};
/**
* Implements a host component that does not receive mouse events
* when `disabled` is set.
*/
var DisabledInputUtils = {
getHostProps: function (inst, props) {
if (!props.disabled) {
return props;
}
// Copy the props, except the mouse listeners
var hostProps = {};
for (var key in props) {
if (!disableableMouseListenerNames[key] && props.hasOwnProperty(key)) {
hostProps[key] = props[key];
}
}
return hostProps;
}
};
module.exports = DisabledInputUtils;
/***/ },
/* 112 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMInput
*/
'use strict';
var _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var DisabledInputUtils = __webpack_require__(111);
var DOMPropertyOperations = __webpack_require__(105);
var LinkedValueUtils = __webpack_require__(113);
var ReactDOMComponentTree = __webpack_require__(36);
var ReactUpdates = __webpack_require__(56);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
var didWarnValueLink = false;
var didWarnCheckedLink = false;
var didWarnValueDefaultValue = false;
var didWarnCheckedDefaultChecked = false;
var didWarnControlledToUncontrolled = false;
var didWarnUncontrolledToControlled = false;
function forceUpdateIfMounted() {
if (this._rootNodeID) {
// DOM component is still mounted; update
ReactDOMInput.updateWrapper(this);
}
}
function isControlled(props) {
var usesChecked = props.type === 'checkbox' || props.type === 'radio';
return usesChecked ? props.checked !== undefined : props.value !== undefined;
}
/**
* Implements an <input> host component that allows setting these optional
* props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
*
* If `checked` or `value` are not supplied (or null/undefined), user actions
* that affect the checked state or value will trigger updates to the element.
*
* If they are supplied (and not null/undefined), the rendered element will not
* trigger updates to the element. Instead, the props must change in order for
* the rendered element to be updated.
*
* The rendered element will be initialized as unchecked (or `defaultChecked`)
* with an empty value (or `defaultValue`).
*
* @see path_to_url
*/
var ReactDOMInput = {
getHostProps: function (inst, props) {
var value = LinkedValueUtils.getValue(props);
var checked = LinkedValueUtils.getChecked(props);
var hostProps = _assign({
// Make sure we set .type before any other properties (setting .value
// before .type means .value is lost in IE11 and below)
type: undefined,
// Make sure we set .step before .value (setting .value before .step
// means .value is rounded on mount, based upon step precision)
step: undefined,
// Make sure we set .min & .max before .value (to ensure proper order
// in corner cases such as min or max deriving from value, e.g. Issue #7170)
min: undefined,
max: undefined
}, DisabledInputUtils.getHostProps(inst, props), {
defaultChecked: undefined,
defaultValue: undefined,
value: value != null ? value : inst._wrapperState.initialValue,
checked: checked != null ? checked : inst._wrapperState.initialChecked,
onChange: inst._wrapperState.onChange
});
return hostProps;
},
mountWrapper: function (inst, props) {
if (process.env.NODE_ENV !== 'production') {
LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner);
var owner = inst._currentElement._owner;
if (props.valueLink !== undefined && !didWarnValueLink) {
process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0;
didWarnValueLink = true;
}
if (props.checkedLink !== undefined && !didWarnCheckedLink) {
process.env.NODE_ENV !== 'production' ? warning(false, '`checkedLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0;
didWarnCheckedLink = true;
}
if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'path_to_url owner && owner.getName() || 'A component', props.type) : void 0;
didWarnCheckedDefaultChecked = true;
}
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'path_to_url owner && owner.getName() || 'A component', props.type) : void 0;
didWarnValueDefaultValue = true;
}
}
var defaultValue = props.defaultValue;
inst._wrapperState = {
initialChecked: props.checked != null ? props.checked : props.defaultChecked,
initialValue: props.value != null ? props.value : defaultValue,
listeners: null,
onChange: _handleChange.bind(inst)
};
if (process.env.NODE_ENV !== 'production') {
inst._wrapperState.controlled = isControlled(props);
}
},
updateWrapper: function (inst) {
var props = inst._currentElement.props;
if (process.env.NODE_ENV !== 'production') {
var controlled = isControlled(props);
var owner = inst._currentElement._owner;
if (!inst._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: path_to_url owner && owner.getName() || 'A component', props.type) : void 0;
didWarnUncontrolledToControlled = true;
}
if (inst._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: path_to_url owner && owner.getName() || 'A component', props.type) : void 0;
didWarnControlledToUncontrolled = true;
}
}
// TODO: Shouldn't this be getChecked(props)?
var checked = props.checked;
if (checked != null) {
DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'checked', checked || false);
}
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
var value = LinkedValueUtils.getValue(props);
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
var newValue = '' + value;
// To avoid side effects (such as losing text selection), only set value if changed
if (newValue !== node.value) {
node.value = newValue;
}
} else {
if (props.value == null && props.defaultValue != null) {
node.defaultValue = '' + props.defaultValue;
}
if (props.checked == null && props.defaultChecked != null) {
node.defaultChecked = !!props.defaultChecked;
}
}
},
postMountWrapper: function (inst) {
var props = inst._currentElement.props;
// This is in postMount because we need access to the DOM node, which is not
// available until after the component has mounted.
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
// Detach value from defaultValue. We won't do anything if we're working on
// submit or reset inputs as those values & defaultValues are linked. They
// are not resetable nodes so this operation doesn't matter and actually
// removes browser-default values (eg "Submit Query") when no value is
// provided.
switch (props.type) {
case 'submit':
case 'reset':
break;
case 'color':
case 'date':
case 'datetime':
case 'datetime-local':
case 'month':
case 'time':
case 'week':
// This fixes the no-show issue on iOS Safari and Android Chrome:
// path_to_url
node.value = '';
node.value = node.defaultValue;
break;
default:
node.value = node.value;
break;
}
// Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
// this is needed to work around a chrome bug where setting defaultChecked
// will sometimes influence the value of checked (even after detachment).
// Reference: path_to_url
// We need to temporarily unset name to avoid disrupting radio button groups.
var name = node.name;
if (name !== '') {
node.name = '';
}
node.defaultChecked = !node.defaultChecked;
node.defaultChecked = !node.defaultChecked;
if (name !== '') {
node.name = name;
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
// Here we use asap to wait until all updates have propagated, which
// is important when using controlled components within layers:
// path_to_url
ReactUpdates.asap(forceUpdateIfMounted, this);
var name = props.name;
if (props.type === 'radio' && name != null) {
var rootNode = ReactDOMComponentTree.getNodeFromInstance(this);
var queryRoot = rootNode;
while (queryRoot.parentNode) {
queryRoot = queryRoot.parentNode;
}
// If `rootNode.form` was non-null, then we could try `form.elements`,
// but that sometimes behaves strangely in IE8. We could also try using
// `form.getElementsByName`, but that will only return direct children
// and won't include inputs that use the HTML5 `form=` attribute. Since
// the input might not even be in a form, let's just use the global
// `querySelectorAll` to ensure we don't miss anything.
var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
for (var i = 0; i < group.length; i++) {
var otherNode = group[i];
if (otherNode === rootNode || otherNode.form !== rootNode.form) {
continue;
}
// This will throw if radio buttons rendered by different copies of React
// and the same name are rendered into the same form (same as #1939).
// That's probably okay; we don't support it just as we don't support
// mixing React radio buttons with non-React ones.
var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode);
!otherInstance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : _prodInvariant('90') : void 0;
// If this is a controlled radio button group, forcing the input that
// was previously checked to update will cause it to be come re-checked
// as appropriate.
ReactUpdates.asap(forceUpdateIfMounted, otherInstance);
}
}
return returnValue;
}
module.exports = ReactDOMInput;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 113 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule LinkedValueUtils
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactPropTypes = __webpack_require__(31);
var ReactPropTypeLocations = __webpack_require__(22);
var ReactPropTypesSecret = __webpack_require__(30);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
var hasReadOnlyValue = {
'button': true,
'checkbox': true,
'image': true,
'hidden': true,
'radio': true,
'reset': true,
'submit': true
};
function _assertSingleLink(inputProps) {
!(inputProps.checkedLink == null || inputProps.valueLink == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use checkedLink, you probably don\'t want to use valueLink and vice versa.') : _prodInvariant('87') : void 0;
}
function _assertValueLink(inputProps) {
_assertSingleLink(inputProps);
!(inputProps.value == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want to use value or onChange, you probably don\'t want to use valueLink.') : _prodInvariant('88') : void 0;
}
function _assertCheckedLink(inputProps) {
_assertSingleLink(inputProps);
!(inputProps.checked == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. If you want to use checked or onChange, you probably don\'t want to use checkedLink') : _prodInvariant('89') : void 0;
}
var propTypes = {
value: function (props, propName, componentName) {
if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) {
return null;
}
return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
},
checked: function (props, propName, componentName) {
if (!props[propName] || props.onChange || props.readOnly || props.disabled) {
return null;
}
return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
},
onChange: ReactPropTypes.func
};
var loggedTypeFailures = {};
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Provide a linked `value` attribute for controlled forms. You should not use
* this outside of the ReactDOM controlled form components.
*/
var LinkedValueUtils = {
checkPropTypes: function (tagName, props, owner) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop, null, ReactPropTypesSecret);
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var addendum = getDeclarationErrorAddendum(owner);
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : void 0;
}
}
},
/**
* @param {object} inputProps Props for form component
* @return {*} current value of the input either from value prop or link.
*/
getValue: function (inputProps) {
if (inputProps.valueLink) {
_assertValueLink(inputProps);
return inputProps.valueLink.value;
}
return inputProps.value;
},
/**
* @param {object} inputProps Props for form component
* @return {*} current checked status of the input either from checked prop
* or link.
*/
getChecked: function (inputProps) {
if (inputProps.checkedLink) {
_assertCheckedLink(inputProps);
return inputProps.checkedLink.value;
}
return inputProps.checked;
},
/**
* @param {object} inputProps Props for form component
* @param {SyntheticEvent} event change event to handle
*/
executeOnChange: function (inputProps, event) {
if (inputProps.valueLink) {
_assertValueLink(inputProps);
return inputProps.valueLink.requestChange(event.target.value);
} else if (inputProps.checkedLink) {
_assertCheckedLink(inputProps);
return inputProps.checkedLink.requestChange(event.target.checked);
} else if (inputProps.onChange) {
return inputProps.onChange.call(undefined, event);
}
}
};
module.exports = LinkedValueUtils;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 114 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMOption
*/
'use strict';
var _assign = __webpack_require__(4);
var ReactChildren = __webpack_require__(5);
var ReactDOMComponentTree = __webpack_require__(36);
var ReactDOMSelect = __webpack_require__(115);
var warning = __webpack_require__(11);
var didWarnInvalidOptionChildren = false;
function flattenChildren(children) {
var content = '';
// Flatten children and warn if they aren't strings or numbers;
// invalid types are ignored.
ReactChildren.forEach(children, function (child) {
if (child == null) {
return;
}
if (typeof child === 'string' || typeof child === 'number') {
content += child;
} else if (!didWarnInvalidOptionChildren) {
didWarnInvalidOptionChildren = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : void 0;
}
});
return content;
}
/**
* Implements an <option> host component that warns when `selected` is set.
*/
var ReactDOMOption = {
mountWrapper: function (inst, props, hostParent) {
// TODO (yungsters): Remove support for `selected` in <option>.
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : void 0;
}
// Look up whether this option is 'selected'
var selectValue = null;
if (hostParent != null) {
var selectParent = hostParent;
if (selectParent._tag === 'optgroup') {
selectParent = selectParent._hostParent;
}
if (selectParent != null && selectParent._tag === 'select') {
selectValue = ReactDOMSelect.getSelectValueContext(selectParent);
}
}
// If the value is null (e.g., no specified value or after initial mount)
// or missing (e.g., for <datalist>), we don't change props.selected
var selected = null;
if (selectValue != null) {
var value;
if (props.value != null) {
value = props.value + '';
} else {
value = flattenChildren(props.children);
}
selected = false;
if (Array.isArray(selectValue)) {
// multiple
for (var i = 0; i < selectValue.length; i++) {
if ('' + selectValue[i] === value) {
selected = true;
break;
}
}
} else {
selected = '' + selectValue === value;
}
}
inst._wrapperState = { selected: selected };
},
postMountWrapper: function (inst) {
// value="" should make a value attribute (#6219)
var props = inst._currentElement.props;
if (props.value != null) {
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
node.setAttribute('value', props.value);
}
},
getHostProps: function (inst, props) {
var hostProps = _assign({ selected: undefined, children: undefined }, props);
// Read state only from initial mount because <select> updates value
// manually; we need the initial state only for server rendering
if (inst._wrapperState.selected != null) {
hostProps.selected = inst._wrapperState.selected;
}
var content = flattenChildren(props.children);
if (content) {
hostProps.children = content;
}
return hostProps;
}
};
module.exports = ReactDOMOption;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 115 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMSelect
*/
'use strict';
var _assign = __webpack_require__(4);
var DisabledInputUtils = __webpack_require__(111);
var LinkedValueUtils = __webpack_require__(113);
var ReactDOMComponentTree = __webpack_require__(36);
var ReactUpdates = __webpack_require__(56);
var warning = __webpack_require__(11);
var didWarnValueLink = false;
var didWarnValueDefaultValue = false;
function updateOptionsIfPendingUpdateAndMounted() {
if (this._rootNodeID && this._wrapperState.pendingUpdate) {
this._wrapperState.pendingUpdate = false;
var props = this._currentElement.props;
var value = LinkedValueUtils.getValue(props);
if (value != null) {
updateOptions(this, Boolean(props.multiple), value);
}
}
}
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
var valuePropNames = ['value', 'defaultValue'];
/**
* Validation function for `value` and `defaultValue`.
* @private
*/
function checkSelectPropTypes(inst, props) {
var owner = inst._currentElement._owner;
LinkedValueUtils.checkPropTypes('select', props, owner);
if (props.valueLink !== undefined && !didWarnValueLink) {
process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `select` is deprecated; set `value` and `onChange` instead.') : void 0;
didWarnValueLink = true;
}
for (var i = 0; i < valuePropNames.length; i++) {
var propName = valuePropNames[i];
if (props[propName] == null) {
continue;
}
var isArray = Array.isArray(props[propName]);
if (props.multiple && !isArray) {
process.env.NODE_ENV !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : void 0;
} else if (!props.multiple && isArray) {
process.env.NODE_ENV !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : void 0;
}
}
}
/**
* @param {ReactDOMComponent} inst
* @param {boolean} multiple
* @param {*} propValue A stringable (with `multiple`, a list of stringables).
* @private
*/
function updateOptions(inst, multiple, propValue) {
var selectedValue, i;
var options = ReactDOMComponentTree.getNodeFromInstance(inst).options;
if (multiple) {
selectedValue = {};
for (i = 0; i < propValue.length; i++) {
selectedValue['' + propValue[i]] = true;
}
for (i = 0; i < options.length; i++) {
var selected = selectedValue.hasOwnProperty(options[i].value);
if (options[i].selected !== selected) {
options[i].selected = selected;
}
}
} else {
// Do not set `select.value` as exact behavior isn't consistent across all
// browsers for all cases.
selectedValue = '' + propValue;
for (i = 0; i < options.length; i++) {
if (options[i].value === selectedValue) {
options[i].selected = true;
return;
}
}
if (options.length) {
options[0].selected = true;
}
}
}
/**
* Implements a <select> host component that allows optionally setting the
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
* stringable. If `multiple` is true, the prop must be an array of stringables.
*
* If `value` is not supplied (or null/undefined), user actions that change the
* selected option will trigger updates to the rendered options.
*
* If it is supplied (and not null/undefined), the rendered options will not
* update in response to user actions. Instead, the `value` prop must change in
* order for the rendered options to update.
*
* If `defaultValue` is provided, any options with the supplied values will be
* selected.
*/
var ReactDOMSelect = {
getHostProps: function (inst, props) {
return _assign({}, DisabledInputUtils.getHostProps(inst, props), {
onChange: inst._wrapperState.onChange,
value: undefined
});
},
mountWrapper: function (inst, props) {
if (process.env.NODE_ENV !== 'production') {
checkSelectPropTypes(inst, props);
}
var value = LinkedValueUtils.getValue(props);
inst._wrapperState = {
pendingUpdate: false,
initialValue: value != null ? value : props.defaultValue,
listeners: null,
onChange: _handleChange.bind(inst),
wasMultiple: Boolean(props.multiple)
};
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'path_to_url : void 0;
didWarnValueDefaultValue = true;
}
},
getSelectValueContext: function (inst) {
// ReactDOMOption looks at this initial value so the initial generated
// markup has correct `selected` attributes
return inst._wrapperState.initialValue;
},
postUpdateWrapper: function (inst) {
var props = inst._currentElement.props;
// After the initial mount, we control selected-ness manually so don't pass
// this value down
inst._wrapperState.initialValue = undefined;
var wasMultiple = inst._wrapperState.wasMultiple;
inst._wrapperState.wasMultiple = Boolean(props.multiple);
var value = LinkedValueUtils.getValue(props);
if (value != null) {
inst._wrapperState.pendingUpdate = false;
updateOptions(inst, Boolean(props.multiple), value);
} else if (wasMultiple !== Boolean(props.multiple)) {
// For simplicity, reapply `defaultValue` if `multiple` is toggled.
if (props.defaultValue != null) {
updateOptions(inst, Boolean(props.multiple), props.defaultValue);
} else {
// Revert the select back to its default unselected state.
updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : '');
}
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
if (this._rootNodeID) {
this._wrapperState.pendingUpdate = true;
}
ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this);
return returnValue;
}
module.exports = ReactDOMSelect;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 116 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMTextarea
*/
'use strict';
var _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var DisabledInputUtils = __webpack_require__(111);
var LinkedValueUtils = __webpack_require__(113);
var ReactDOMComponentTree = __webpack_require__(36);
var ReactUpdates = __webpack_require__(56);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
var didWarnValueLink = false;
var didWarnValDefaultVal = false;
function forceUpdateIfMounted() {
if (this._rootNodeID) {
// DOM component is still mounted; update
ReactDOMTextarea.updateWrapper(this);
}
}
/**
* Implements a <textarea> host component that allows setting `value`, and
* `defaultValue`. This differs from the traditional DOM API because value is
* usually set as PCDATA children.
*
* If `value` is not supplied (or null/undefined), user actions that affect the
* value will trigger updates to the element.
*
* If `value` is supplied (and not null/undefined), the rendered element will
* not trigger updates to the element. Instead, the `value` prop must change in
* order for the rendered element to be updated.
*
* The rendered element will be initialized with an empty value, the prop
* `defaultValue` if specified, or the children content (deprecated).
*/
var ReactDOMTextarea = {
getHostProps: function (inst, props) {
!(props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : _prodInvariant('91') : void 0;
// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated. We could add a check in setTextContent
// to only set the value if/when the value differs from the node value (which would
// completely solve this IE9 bug), but Sebastian+Ben seemed to like this solution.
// The value can be a boolean or object so that's why it's forced to be a string.
var hostProps = _assign({}, DisabledInputUtils.getHostProps(inst, props), {
value: undefined,
defaultValue: undefined,
children: '' + inst._wrapperState.initialValue,
onChange: inst._wrapperState.onChange
});
return hostProps;
},
mountWrapper: function (inst, props) {
if (process.env.NODE_ENV !== 'production') {
LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner);
if (props.valueLink !== undefined && !didWarnValueLink) {
process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `textarea` is deprecated; set `value` and `onChange` instead.') : void 0;
didWarnValueLink = true;
}
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'path_to_url : void 0;
didWarnValDefaultVal = true;
}
}
var value = LinkedValueUtils.getValue(props);
var initialValue = value;
// Only bother fetching default value if we're going to use it
if (value == null) {
var defaultValue = props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
var children = props.children;
if (children != null) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : void 0;
}
!(defaultValue == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : _prodInvariant('92') : void 0;
if (Array.isArray(children)) {
!(children.length <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : _prodInvariant('93') : void 0;
children = children[0];
}
defaultValue = '' + children;
}
if (defaultValue == null) {
defaultValue = '';
}
initialValue = defaultValue;
}
inst._wrapperState = {
initialValue: '' + initialValue,
listeners: null,
onChange: _handleChange.bind(inst)
};
},
updateWrapper: function (inst) {
var props = inst._currentElement.props;
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
var value = LinkedValueUtils.getValue(props);
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
var newValue = '' + value;
// To avoid side effects (such as losing text selection), only set value if changed
if (newValue !== node.value) {
node.value = newValue;
}
if (props.defaultValue == null) {
node.defaultValue = newValue;
}
}
if (props.defaultValue != null) {
node.defaultValue = props.defaultValue;
}
},
postMountWrapper: function (inst) {
// This is in postMount because we need access to the DOM node, which is not
// available until after the component has mounted.
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
// Warning: node.value may be the empty string at this point (IE11) if placeholder is set.
node.value = node.textContent; // Detach value from defaultValue
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
ReactUpdates.asap(forceUpdateIfMounted, this);
return returnValue;
}
module.exports = ReactDOMTextarea;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 117 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMultiChild
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactComponentEnvironment = __webpack_require__(118);
var ReactInstanceMap = __webpack_require__(119);
var ReactInstrumentation = __webpack_require__(62);
var ReactMultiChildUpdateTypes = __webpack_require__(92);
var ReactCurrentOwner = __webpack_require__(10);
var ReactReconciler = __webpack_require__(59);
var ReactChildReconciler = __webpack_require__(120);
var emptyFunction = __webpack_require__(12);
var flattenChildren = __webpack_require__(128);
var invariant = __webpack_require__(8);
/**
* Make an update for markup to be rendered and inserted at a supplied index.
*
* @param {string} markup Markup that renders into an element.
* @param {number} toIndex Destination index.
* @private
*/
function makeInsertMarkup(markup, afterNode, toIndex) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
content: markup,
fromIndex: null,
fromNode: null,
toIndex: toIndex,
afterNode: afterNode
};
}
/**
* Make an update for moving an existing element to another index.
*
* @param {number} fromIndex Source index of the existing element.
* @param {number} toIndex Destination index of the element.
* @private
*/
function makeMove(child, afterNode, toIndex) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
content: null,
fromIndex: child._mountIndex,
fromNode: ReactReconciler.getHostNode(child),
toIndex: toIndex,
afterNode: afterNode
};
}
/**
* Make an update for removing an element at an index.
*
* @param {number} fromIndex Index of the element to remove.
* @private
*/
function makeRemove(child, node) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.REMOVE_NODE,
content: null,
fromIndex: child._mountIndex,
fromNode: node,
toIndex: null,
afterNode: null
};
}
/**
* Make an update for setting the markup of a node.
*
* @param {string} markup Markup that renders into an element.
* @private
*/
function makeSetMarkup(markup) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.SET_MARKUP,
content: markup,
fromIndex: null,
fromNode: null,
toIndex: null,
afterNode: null
};
}
/**
* Make an update for setting the text content.
*
* @param {string} textContent Text content to set.
* @private
*/
function makeTextContent(textContent) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.TEXT_CONTENT,
content: textContent,
fromIndex: null,
fromNode: null,
toIndex: null,
afterNode: null
};
}
/**
* Push an update, if any, onto the queue. Creates a new queue if none is
* passed and always returns the queue. Mutative.
*/
function enqueue(queue, update) {
if (update) {
queue = queue || [];
queue.push(update);
}
return queue;
}
/**
* Processes any enqueued updates.
*
* @private
*/
function processQueue(inst, updateQueue) {
ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue);
}
var setChildrenForInstrumentation = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
var getDebugID = function (inst) {
if (!inst._debugID) {
// Check for ART-like instances. TODO: This is silly/gross.
var internal;
if (internal = ReactInstanceMap.get(inst)) {
inst = internal;
}
}
return inst._debugID;
};
setChildrenForInstrumentation = function (children) {
var debugID = getDebugID(this);
// TODO: React Native empty components are also multichild.
// This means they still get into this method but don't have _debugID.
if (debugID !== 0) {
ReactInstrumentation.debugTool.onSetChildren(debugID, children ? Object.keys(children).map(function (key) {
return children[key]._debugID;
}) : []);
}
};
}
/**
* ReactMultiChild are capable of reconciling multiple children.
*
* @class ReactMultiChild
* @internal
*/
var ReactMultiChild = {
/**
* Provides common functionality for components that must reconcile multiple
* children. This is used by `ReactDOMComponent` to mount, update, and
* unmount child components.
*
* @lends {ReactMultiChild.prototype}
*/
Mixin: {
_reconcilerInstantiateChildren: function (nestedChildren, transaction, context) {
if (process.env.NODE_ENV !== 'production') {
var selfDebugID = getDebugID(this);
if (this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner;
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context, selfDebugID);
} finally {
ReactCurrentOwner.current = null;
}
}
}
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
},
_reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context) {
var nextChildren;
var selfDebugID = 0;
if (process.env.NODE_ENV !== 'production') {
selfDebugID = getDebugID(this);
if (this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner;
nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID);
} finally {
ReactCurrentOwner.current = null;
}
ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID);
return nextChildren;
}
}
nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID);
ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID);
return nextChildren;
},
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildren Nested child maps.
* @return {array} An array of mounted representations.
* @internal
*/
mountChildren: function (nestedChildren, transaction, context) {
var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context);
this._renderedChildren = children;
var mountImages = [];
var index = 0;
for (var name in children) {
if (children.hasOwnProperty(name)) {
var child = children[name];
var selfDebugID = 0;
if (process.env.NODE_ENV !== 'production') {
selfDebugID = getDebugID(this);
}
var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._hostContainerInfo, context, selfDebugID);
child._mountIndex = index++;
mountImages.push(mountImage);
}
}
if (process.env.NODE_ENV !== 'production') {
setChildrenForInstrumentation.call(this, children);
}
return mountImages;
},
/**
* Replaces any rendered children with a text content string.
*
* @param {string} nextContent String of content.
* @internal
*/
updateTextContent: function (nextContent) {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren, false);
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0;
}
}
// Set new text content.
var updates = [makeTextContent(nextContent)];
processQueue(this, updates);
},
/**
* Replaces any rendered children with a markup string.
*
* @param {string} nextMarkup String of markup.
* @internal
*/
updateMarkup: function (nextMarkup) {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren, false);
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0;
}
}
var updates = [makeSetMarkup(nextMarkup)];
processQueue(this, updates);
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function (nextNestedChildrenElements, transaction, context) {
// Hook used by React ART
this._updateChildren(nextNestedChildrenElements, transaction, context);
},
/**
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @final
* @protected
*/
_updateChildren: function (nextNestedChildrenElements, transaction, context) {
var prevChildren = this._renderedChildren;
var removedNodes = {};
var mountImages = [];
var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context);
if (!nextChildren && !prevChildren) {
return;
}
var updates = null;
var name;
// `nextIndex` will increment for each child in `nextChildren`, but
// `lastIndex` will be the last index visited in `prevChildren`.
var nextIndex = 0;
var lastIndex = 0;
// `nextMountIndex` will increment for each newly mounted child.
var nextMountIndex = 0;
var lastPlacedNode = null;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var nextChild = nextChildren[name];
if (prevChild === nextChild) {
updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex));
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
prevChild._mountIndex = nextIndex;
} else {
if (prevChild) {
// Update `lastIndex` before `_mountIndex` gets unset by unmounting.
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
// The `removedNodes` loop below will actually remove the child.
}
// The child must be instantiated before it's mounted.
updates = enqueue(updates, this._mountChildAtIndex(nextChild, mountImages[nextMountIndex], lastPlacedNode, nextIndex, transaction, context));
nextMountIndex++;
}
nextIndex++;
lastPlacedNode = ReactReconciler.getHostNode(nextChild);
}
// Remove children that are no longer present.
for (name in removedNodes) {
if (removedNodes.hasOwnProperty(name)) {
updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name]));
}
}
if (updates) {
processQueue(this, updates);
}
this._renderedChildren = nextChildren;
if (process.env.NODE_ENV !== 'production') {
setChildrenForInstrumentation.call(this, nextChildren);
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted. It does not actually perform any
* backend operations.
*
* @internal
*/
unmountChildren: function (safely) {
var renderedChildren = this._renderedChildren;
ReactChildReconciler.unmountChildren(renderedChildren, safely);
this._renderedChildren = null;
},
/**
* Moves a child component to the supplied index.
*
* @param {ReactComponent} child Component to move.
* @param {number} toIndex Destination index of the element.
* @param {number} lastIndex Last index visited of the siblings of `child`.
* @protected
*/
moveChild: function (child, afterNode, toIndex, lastIndex) {
// If the index of `child` is less than `lastIndex`, then it needs to
// be moved. Otherwise, we do not need to move it because a child will be
// inserted or moved before `child`.
if (child._mountIndex < lastIndex) {
return makeMove(child, afterNode, toIndex);
}
},
/**
* Creates a child component.
*
* @param {ReactComponent} child Component to create.
* @param {string} mountImage Markup to insert.
* @protected
*/
createChild: function (child, afterNode, mountImage) {
return makeInsertMarkup(mountImage, afterNode, child._mountIndex);
},
/**
* Removes a child component.
*
* @param {ReactComponent} child Child to remove.
* @protected
*/
removeChild: function (child, node) {
return makeRemove(child, node);
},
/**
* Mounts a child with the supplied name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to mount.
* @param {string} name Name of the child.
* @param {number} index Index at which to insert the child.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_mountChildAtIndex: function (child, mountImage, afterNode, index, transaction, context) {
child._mountIndex = index;
return this.createChild(child, afterNode, mountImage);
},
/**
* Unmounts a rendered child.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to unmount.
* @private
*/
_unmountChild: function (child, node) {
var update = this.removeChild(child, node);
child._mountIndex = null;
return update;
}
}
};
module.exports = ReactMultiChild;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 118 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponentEnvironment
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
var injected = false;
var ReactComponentEnvironment = {
/**
* Optionally injectable hook for swapping out mount images in the middle of
* the tree.
*/
replaceNodeWithMarkup: null,
/**
* Optionally injectable hook for processing a queue of child updates. Will
* later move into MultiChildComponents.
*/
processChildrenUpdates: null,
injection: {
injectEnvironment: function (environment) {
!!injected ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : _prodInvariant('104') : void 0;
ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup;
ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates;
injected = true;
}
}
};
module.exports = ReactComponentEnvironment;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 119 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInstanceMap
*/
'use strict';
/**
* `ReactInstanceMap` maintains a mapping from a public facing stateful
* instance (key) and the internal representation (value). This allows public
* methods to accept the user facing instance as an argument and map them back
* to internal methods.
*/
// TODO: Replace this with ES6: var ReactInstanceMap = new Map();
var ReactInstanceMap = {
/**
* This API should be called `delete` but we'd have to make sure to always
* transform these to strings for IE support. When this transform is fully
* supported we can rename it.
*/
remove: function (key) {
key._reactInternalInstance = undefined;
},
get: function (key) {
return key._reactInternalInstance;
},
has: function (key) {
return key._reactInternalInstance !== undefined;
},
set: function (key, value) {
key._reactInternalInstance = value;
}
};
module.exports = ReactInstanceMap;
/***/ },
/* 120 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactChildReconciler
*/
'use strict';
var ReactReconciler = __webpack_require__(59);
var instantiateReactComponent = __webpack_require__(121);
var KeyEscapeUtils = __webpack_require__(16);
var shouldUpdateReactComponent = __webpack_require__(125);
var traverseAllChildren = __webpack_require__(14);
var warning = __webpack_require__(11);
var ReactComponentTreeHook;
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') {
// Temporary hack.
// Inline requires don't work well with Jest:
// path_to_url
// Remove the inline requires when we don't need them anymore:
// path_to_url
ReactComponentTreeHook = __webpack_require__(28);
}
function instantiateChild(childInstances, child, name, selfDebugID) {
// We found a component instance.
var keyUnique = childInstances[name] === undefined;
if (process.env.NODE_ENV !== 'production') {
if (!ReactComponentTreeHook) {
ReactComponentTreeHook = __webpack_require__(28);
}
if (!keyUnique) {
process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0;
}
}
if (child != null && keyUnique) {
childInstances[name] = instantiateReactComponent(child, true);
}
}
/**
* ReactChildReconciler provides helpers for initializing or updating a set of
* children. Its output is suitable for passing it onto ReactMultiChild which
* does diffed reordering and insertion.
*/
var ReactChildReconciler = {
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildNodes Nested child maps.
* @return {?object} A set of child instances.
* @internal
*/
instantiateChildren: function (nestedChildNodes, transaction, context, selfDebugID // 0 in production and for roots
) {
if (nestedChildNodes == null) {
return null;
}
var childInstances = {};
if (process.env.NODE_ENV !== 'production') {
traverseAllChildren(nestedChildNodes, function (childInsts, child, name) {
return instantiateChild(childInsts, child, name, selfDebugID);
}, childInstances);
} else {
traverseAllChildren(nestedChildNodes, instantiateChild, childInstances);
}
return childInstances;
},
/**
* Updates the rendered children and returns a new set of children.
*
* @param {?object} prevChildren Previously initialized set of children.
* @param {?object} nextChildren Flat child element maps.
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @return {?object} A new set of child instances.
* @internal
*/
updateChildren: function (prevChildren, nextChildren, mountImages, removedNodes, transaction, hostParent, hostContainerInfo, context, selfDebugID // 0 in production and for roots
) {
// We currently don't have a way to track moves here but if we use iterators
// instead of for..in we can zip the iterators and check if an item has
// moved.
// TODO: If nothing has changed, return the prevChildren object so that we
// can quickly bailout if nothing has changed.
if (!nextChildren && !prevChildren) {
return;
}
var name;
var prevChild;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
prevChild = prevChildren && prevChildren[name];
var prevElement = prevChild && prevChild._currentElement;
var nextElement = nextChildren[name];
if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) {
ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context);
nextChildren[name] = prevChild;
} else {
if (prevChild) {
removedNodes[name] = ReactReconciler.getHostNode(prevChild);
ReactReconciler.unmountComponent(prevChild, false);
}
// The child must be instantiated before it's mounted.
var nextChildInstance = instantiateReactComponent(nextElement, true);
nextChildren[name] = nextChildInstance;
// Creating mount image now ensures refs are resolved in right order
// (see path_to_url for explanation).
var nextChildMountImage = ReactReconciler.mountComponent(nextChildInstance, transaction, hostParent, hostContainerInfo, context, selfDebugID);
mountImages.push(nextChildMountImage);
}
}
// Unmount children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) {
prevChild = prevChildren[name];
removedNodes[name] = ReactReconciler.getHostNode(prevChild);
ReactReconciler.unmountComponent(prevChild, false);
}
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @param {?object} renderedChildren Previously initialized set of children.
* @internal
*/
unmountChildren: function (renderedChildren, safely) {
for (var name in renderedChildren) {
if (renderedChildren.hasOwnProperty(name)) {
var renderedChild = renderedChildren[name];
ReactReconciler.unmountComponent(renderedChild, safely);
}
}
}
};
module.exports = ReactChildReconciler;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 121 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule instantiateReactComponent
*/
'use strict';
var _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var ReactCompositeComponent = __webpack_require__(122);
var ReactEmptyComponent = __webpack_require__(126);
var ReactHostComponent = __webpack_require__(127);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
// To avoid a cyclic dependency, we create the final class in this module
var ReactCompositeComponentWrapper = function (element) {
this.construct(element);
};
_assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, {
_instantiateReactComponent: instantiateReactComponent
});
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Check if the type reference is a known internal type. I.e. not a user
* provided composite type.
*
* @param {function} type
* @return {boolean} Returns true if this is a valid internal type.
*/
function isInternalComponentType(type) {
return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function';
}
var nextDebugID = 1;
/**
* Given a ReactNode, create an instance that will actually be mounted.
*
* @param {ReactNode} node
* @param {boolean} shouldHaveDebugID
* @return {object} A new instance of the element's constructor.
* @protected
*/
function instantiateReactComponent(node, shouldHaveDebugID) {
var instance;
if (node === null || node === false) {
instance = ReactEmptyComponent.create(instantiateReactComponent);
} else if (typeof node === 'object') {
var element = node;
!(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : _prodInvariant('130', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : void 0;
// Special case string values
if (typeof element.type === 'string') {
instance = ReactHostComponent.createInternalComponent(element);
} else if (isInternalComponentType(element.type)) {
// This is temporarily available for custom components that are not string
// representations. I.e. ART. Once those are updated to use the string
// representation, we can drop this code path.
instance = new element.type(element);
// We renamed this. Allow the old name for compat. :(
if (!instance.getHostNode) {
instance.getHostNode = instance.getNativeNode;
}
} else {
instance = new ReactCompositeComponentWrapper(element);
}
} else if (typeof node === 'string' || typeof node === 'number') {
instance = ReactHostComponent.createInstanceForText(node);
} else {
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : _prodInvariant('131', typeof node) : void 0;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.getHostNode === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : void 0;
}
// These two fields are used by the DOM and ART diffing algorithms
// respectively. Instead of using expandos on components, we should be
// storing the state needed by the diffing algorithms elsewhere.
instance._mountIndex = 0;
instance._mountImage = null;
if (process.env.NODE_ENV !== 'production') {
instance._debugID = shouldHaveDebugID ? nextDebugID++ : 0;
}
// Internal instances should fully constructed at this point, so they should
// not get any new fields added to them at this point.
if (process.env.NODE_ENV !== 'production') {
if (Object.preventExtensions) {
Object.preventExtensions(instance);
}
}
return instance;
}
module.exports = instantiateReactComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 122 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactCompositeComponent
*/
'use strict';
var _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var ReactComponentEnvironment = __webpack_require__(118);
var ReactCurrentOwner = __webpack_require__(10);
var ReactElement = __webpack_require__(9);
var ReactErrorUtils = __webpack_require__(46);
var ReactInstanceMap = __webpack_require__(119);
var ReactInstrumentation = __webpack_require__(62);
var ReactNodeTypes = __webpack_require__(123);
var ReactPropTypeLocations = __webpack_require__(22);
var ReactReconciler = __webpack_require__(59);
var checkReactTypeSpec = __webpack_require__(29);
var emptyObject = __webpack_require__(19);
var invariant = __webpack_require__(8);
var shallowEqual = __webpack_require__(124);
var shouldUpdateReactComponent = __webpack_require__(125);
var warning = __webpack_require__(11);
var CompositeTypes = {
ImpureClass: 0,
PureClass: 1,
StatelessFunctional: 2
};
function StatelessComponent(Component) {}
StatelessComponent.prototype.render = function () {
var Component = ReactInstanceMap.get(this)._currentElement.type;
var element = Component(this.props, this.context, this.updater);
warnIfInvalidElement(Component, element);
return element;
};
function warnIfInvalidElement(Component, element) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(element === null || element === false || ReactElement.isValidElement(element), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!Component.childContextTypes, '%s(...): childContextTypes cannot be defined on a functional component.', Component.displayName || Component.name || 'Component') : void 0;
}
}
function invokeComponentDidMountWithTimer() {
var publicInstance = this._instance;
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentDidMount');
}
publicInstance.componentDidMount();
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentDidMount');
}
}
function invokeComponentDidUpdateWithTimer(prevProps, prevState, prevContext) {
var publicInstance = this._instance;
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentDidUpdate');
}
publicInstance.componentDidUpdate(prevProps, prevState, prevContext);
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentDidUpdate');
}
}
function shouldConstruct(Component) {
return !!(Component.prototype && Component.prototype.isReactComponent);
}
function isPureComponent(Component) {
return !!(Component.prototype && Component.prototype.isPureReactComponent);
}
/**
* ------------------ The Life-Cycle of a Composite Component ------------------
*
* - constructor: Initialization of state. The instance is now retained.
* - componentWillMount
* - render
* - [children's constructors]
* - [children's componentWillMount and render]
* - [children's componentDidMount]
* - componentDidMount
*
* Update Phases:
* - componentWillReceiveProps (only called if parent updated)
* - shouldComponentUpdate
* - componentWillUpdate
* - render
* - [children's constructors or receive props phases]
* - componentDidUpdate
*
* - componentWillUnmount
* - [children's componentWillUnmount]
* - [children destroyed]
* - (destroyed): The instance is now blank, released by React and ready for GC.
*
* your_sha256_hash-------------
*/
/**
* An incrementing ID assigned to each component when it is mounted. This is
* used to enforce the order in which `ReactUpdates` updates dirty components.
*
* @private
*/
var nextMountID = 1;
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {ReactElement} element
* @final
* @internal
*/
construct: function (element) {
this._currentElement = element;
this._rootNodeID = 0;
this._compositeType = null;
this._instance = null;
this._hostParent = null;
this._hostContainerInfo = null;
// See ReactUpdateQueue
this._updateBatchNumber = null;
this._pendingElement = null;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._renderedNodeType = null;
this._renderedComponent = null;
this._context = null;
this._mountOrder = 0;
this._topLevelWrapper = null;
// See ReactUpdates and ReactUpdateQueue.
this._pendingCallbacks = null;
// ComponentWillUnmount shall only be called once
this._calledComponentWillUnmount = false;
if (process.env.NODE_ENV !== 'production') {
this._warnedAboutRefsInRender = false;
}
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?object} hostParent
* @param {?object} hostContainerInfo
* @param {?object} context
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
this._context = context;
this._mountOrder = nextMountID++;
this._hostParent = hostParent;
this._hostContainerInfo = hostContainerInfo;
var publicProps = this._currentElement.props;
var publicContext = this._processContext(context);
var Component = this._currentElement.type;
var updateQueue = transaction.getUpdateQueue();
// Initialize the public class
var doConstruct = shouldConstruct(Component);
var inst = this._constructComponent(doConstruct, publicProps, publicContext, updateQueue);
var renderedElement;
// Support functional components
if (!doConstruct && (inst == null || inst.render == null)) {
renderedElement = inst;
warnIfInvalidElement(Component, renderedElement);
!(inst === null || inst === false || ReactElement.isValidElement(inst)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : _prodInvariant('105', Component.displayName || Component.name || 'Component') : void 0;
inst = new StatelessComponent(Component);
this._compositeType = CompositeTypes.StatelessFunctional;
} else {
if (isPureComponent(Component)) {
this._compositeType = CompositeTypes.PureClass;
} else {
this._compositeType = CompositeTypes.ImpureClass;
}
}
if (process.env.NODE_ENV !== 'production') {
// This will throw later in _renderValidatedComponent, but add an early
// warning now to help debugging
if (inst.render == null) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', Component.displayName || Component.name || 'Component') : void 0;
}
var propsMutated = inst.props !== publicProps;
var componentName = Component.displayName || Component.name || 'Component';
process.env.NODE_ENV !== 'production' ? warning(inst.props === undefined || !propsMutated, '%s(...): When calling super() in `%s`, make sure to pass ' + 'up the same props that your component\'s constructor was passed.', componentName, componentName) : void 0;
}
// These should be set up in the constructor, but as a convenience for
// simpler class abstractions, we set them up after the fact.
inst.props = publicProps;
inst.context = publicContext;
inst.refs = emptyObject;
inst.updater = updateQueue;
this._instance = inst;
// Store a reference from the instance back to the internal representation
ReactInstanceMap.set(inst, this);
if (process.env.NODE_ENV !== 'production') {
// Since plain JS classes are defined without any special initialization
// logic, we can not catch common errors early. Therefore, we have to
// catch them here, at initialization time, instead.
process.env.NODE_ENV !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : void 0;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : void 0;
}
var initialState = inst.state;
if (initialState === undefined) {
inst.state = initialState = null;
}
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : _prodInvariant('106', this.getName() || 'ReactCompositeComponent') : void 0;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
var markup;
if (inst.unstable_handleError) {
markup = this.performInitialMountWithErrorHandling(renderedElement, hostParent, hostContainerInfo, transaction, context);
} else {
markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
}
if (inst.componentDidMount) {
if (process.env.NODE_ENV !== 'production') {
transaction.getReactMountReady().enqueue(invokeComponentDidMountWithTimer, this);
} else {
transaction.getReactMountReady().enqueue(inst.componentDidMount, inst);
}
}
return markup;
},
_constructComponent: function (doConstruct, publicProps, publicContext, updateQueue) {
if (process.env.NODE_ENV !== 'production') {
ReactCurrentOwner.current = this;
try {
return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue);
} finally {
ReactCurrentOwner.current = null;
}
} else {
return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue);
}
},
_constructComponentWithoutOwner: function (doConstruct, publicProps, publicContext, updateQueue) {
var Component = this._currentElement.type;
var instanceOrElement;
if (doConstruct) {
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'ctor');
}
}
instanceOrElement = new Component(publicProps, publicContext, updateQueue);
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'ctor');
}
}
} else {
// This can still be an instance in case of factory components
// but we'll count this as time spent rendering as the more common case.
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'render');
}
}
instanceOrElement = Component(publicProps, publicContext, updateQueue);
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'render');
}
}
}
return instanceOrElement;
},
performInitialMountWithErrorHandling: function (renderedElement, hostParent, hostContainerInfo, transaction, context) {
var markup;
var checkpoint = transaction.checkpoint();
try {
markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
} catch (e) {
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onError();
}
}
// Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint
transaction.rollback(checkpoint);
this._instance.unstable_handleError(e);
if (this._pendingStateQueue) {
this._instance.state = this._processPendingState(this._instance.props, this._instance.context);
}
checkpoint = transaction.checkpoint();
this._renderedComponent.unmountComponent(true);
transaction.rollback(checkpoint);
// Try again - we've informed the component about the error, so they can render an error message this time.
// If this throws again, the error will bubble up (and can be caught by a higher error boundary).
markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context);
}
return markup;
},
performInitialMount: function (renderedElement, hostParent, hostContainerInfo, transaction, context) {
var inst = this._instance;
if (inst.componentWillMount) {
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillMount');
}
}
inst.componentWillMount();
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillMount');
}
}
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingStateQueue` without triggering a re-render.
if (this._pendingStateQueue) {
inst.state = this._processPendingState(inst.props, inst.context);
}
}
// If not a stateless component, we now render
if (renderedElement === undefined) {
renderedElement = this._renderValidatedComponent();
}
var nodeType = ReactNodeTypes.getType(renderedElement);
this._renderedNodeType = nodeType;
var child = this._instantiateReactComponent(renderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */
);
this._renderedComponent = child;
var selfDebugID = 0;
if (process.env.NODE_ENV !== 'production') {
selfDebugID = this._debugID;
}
var markup = ReactReconciler.mountComponent(child, transaction, hostParent, hostContainerInfo, this._processChildContext(context), selfDebugID);
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onSetChildren(this._debugID, child._debugID !== 0 ? [child._debugID] : []);
}
}
return markup;
},
getHostNode: function () {
return ReactReconciler.getHostNode(this._renderedComponent);
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function (safely) {
if (!this._renderedComponent) {
return;
}
var inst = this._instance;
if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) {
inst._calledComponentWillUnmount = true;
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillUnmount');
}
}
if (safely) {
var name = this.getName() + '.componentWillUnmount()';
ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst));
} else {
inst.componentWillUnmount();
}
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillUnmount');
}
}
}
if (this._renderedComponent) {
ReactReconciler.unmountComponent(this._renderedComponent, safely);
this._renderedNodeType = null;
this._renderedComponent = null;
this._instance = null;
}
// Reset pending fields
// Even if this component is scheduled for another update in ReactUpdates,
// it would still be ignored because these fields are reset.
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._pendingCallbacks = null;
this._pendingElement = null;
// These fields do not really need to be reset since this object is no
// longer accessible.
this._context = null;
this._rootNodeID = 0;
this._topLevelWrapper = null;
// Delete the reference from the instance to this internal representation
// which allow the internals to be properly cleaned up even if the user
// leaks a reference to the public instance.
ReactInstanceMap.remove(inst);
// Some existing components rely on inst.props even after they've been
// destroyed (in event handlers).
// TODO: inst.props = null;
// TODO: inst.state = null;
// TODO: inst.context = null;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`
*
* @param {object} context
* @return {?object}
* @private
*/
_maskContext: function (context) {
var Component = this._currentElement.type;
var contextTypes = Component.contextTypes;
if (!contextTypes) {
return emptyObject;
}
var maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
return maskedContext;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`, and asserts that they are valid.
*
* @param {object} context
* @return {?object}
* @private
*/
_processContext: function (context) {
var maskedContext = this._maskContext(context);
if (process.env.NODE_ENV !== 'production') {
var Component = this._currentElement.type;
if (Component.contextTypes) {
this._checkContextTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context);
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function (currentContext) {
var Component = this._currentElement.type;
var inst = this._instance;
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onBeginProcessingChildContext();
}
var childContext = inst.getChildContext && inst.getChildContext();
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onEndProcessingChildContext();
}
if (childContext) {
!(typeof Component.childContextTypes === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().', this.getName() || 'ReactCompositeComponent') : _prodInvariant('107', this.getName() || 'ReactCompositeComponent') : void 0;
if (process.env.NODE_ENV !== 'production') {
this._checkContextTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext);
}
for (var name in childContext) {
!(name in Component.childContextTypes) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : _prodInvariant('108', this.getName() || 'ReactCompositeComponent', name) : void 0;
}
return _assign({}, currentContext, childContext);
}
return currentContext;
},
/**
* Assert that the context types are valid
*
* @param {object} typeSpecs Map of context field to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
_checkContextTypes: function (typeSpecs, values, location) {
checkReactTypeSpec(typeSpecs, values, location, this.getName(), null, this._debugID);
},
receiveComponent: function (nextElement, transaction, nextContext) {
var prevElement = this._currentElement;
var prevContext = this._context;
this._pendingElement = null;
this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext);
},
/**
* If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate`
* is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function (transaction) {
if (this._pendingElement != null) {
ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context);
} else if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context);
} else {
this._updateBatchNumber = null;
}
},
/**
* Perform an update to a mounted component. The componentWillReceiveProps and
* shouldComponentUpdate methods are called, then (assuming the update isn't
* skipped) the remaining update lifecycle methods are called and the DOM
* representation is updated.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevParentElement
* @param {ReactElement} nextParentElement
* @internal
* @overridable
*/
updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) {
var inst = this._instance;
!(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Attempted to update component `%s` that has already been unmounted (or failed to mount).', this.getName() || 'ReactCompositeComponent') : _prodInvariant('136', this.getName() || 'ReactCompositeComponent') : void 0;
var willReceive = false;
var nextContext;
// Determine if the context has changed or not
if (this._context === nextUnmaskedContext) {
nextContext = inst.context;
} else {
nextContext = this._processContext(nextUnmaskedContext);
willReceive = true;
}
var prevProps = prevParentElement.props;
var nextProps = nextParentElement.props;
// Not a simple state update but a props update
if (prevParentElement !== nextParentElement) {
willReceive = true;
}
// An update here will schedule an update but immediately set
// _pendingStateQueue which will ensure that any state updates gets
// immediately reconciled instead of waiting for the next batch.
if (willReceive && inst.componentWillReceiveProps) {
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillReceiveProps');
}
}
inst.componentWillReceiveProps(nextProps, nextContext);
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillReceiveProps');
}
}
}
var nextState = this._processPendingState(nextProps, nextContext);
var shouldUpdate = true;
if (!this._pendingForceUpdate) {
if (inst.shouldComponentUpdate) {
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'shouldComponentUpdate');
}
}
shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext);
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'shouldComponentUpdate');
}
}
} else {
if (this._compositeType === CompositeTypes.PureClass) {
shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState);
}
}
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(shouldUpdate !== undefined, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : void 0;
}
this._updateBatchNumber = null;
if (shouldUpdate) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext);
} else {
// If it's determined that a component should not update, we still want
// to set props and state but we shortcut the rest of the update.
this._currentElement = nextParentElement;
this._context = nextUnmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
}
},
_processPendingState: function (props, context) {
var inst = this._instance;
var queue = this._pendingStateQueue;
var replace = this._pendingReplaceState;
this._pendingReplaceState = false;
this._pendingStateQueue = null;
if (!queue) {
return inst.state;
}
if (replace && queue.length === 1) {
return queue[0];
}
var nextState = _assign({}, replace ? queue[0] : inst.state);
for (var i = replace ? 1 : 0; i < queue.length; i++) {
var partial = queue[i];
_assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial);
}
return nextState;
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {ReactElement} nextElement Next element
* @param {object} nextProps Next public object to set as properties.
* @param {?object} nextState Next object to set as state.
* @param {?object} nextContext Next public object to set as context.
* @param {ReactReconcileTransaction} transaction
* @param {?object} unmaskedContext
* @private
*/
_performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) {
var inst = this._instance;
var hasComponentDidUpdate = Boolean(inst.componentDidUpdate);
var prevProps;
var prevState;
var prevContext;
if (hasComponentDidUpdate) {
prevProps = inst.props;
prevState = inst.state;
prevContext = inst.context;
}
if (inst.componentWillUpdate) {
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillUpdate');
}
}
inst.componentWillUpdate(nextProps, nextState, nextContext);
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillUpdate');
}
}
}
this._currentElement = nextElement;
this._context = unmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
this._updateRenderedComponent(transaction, unmaskedContext);
if (hasComponentDidUpdate) {
if (process.env.NODE_ENV !== 'production') {
transaction.getReactMountReady().enqueue(invokeComponentDidUpdateWithTimer.bind(this, prevProps, prevState, prevContext), this);
} else {
transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst);
}
}
},
/**
* Call the component's `render` method and update the DOM accordingly.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_updateRenderedComponent: function (transaction, context) {
var prevComponentInstance = this._renderedComponent;
var prevRenderedElement = prevComponentInstance._currentElement;
var nextRenderedElement = this._renderValidatedComponent();
if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) {
ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context));
} else {
var oldHostNode = ReactReconciler.getHostNode(prevComponentInstance);
ReactReconciler.unmountComponent(prevComponentInstance, false);
var nodeType = ReactNodeTypes.getType(nextRenderedElement);
this._renderedNodeType = nodeType;
var child = this._instantiateReactComponent(nextRenderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */
);
this._renderedComponent = child;
var selfDebugID = 0;
if (process.env.NODE_ENV !== 'production') {
selfDebugID = this._debugID;
}
var nextMarkup = ReactReconciler.mountComponent(child, transaction, this._hostParent, this._hostContainerInfo, this._processChildContext(context), selfDebugID);
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onSetChildren(this._debugID, child._debugID !== 0 ? [child._debugID] : []);
}
}
this._replaceNodeWithMarkup(oldHostNode, nextMarkup, prevComponentInstance);
}
},
/**
* Overridden in shallow rendering.
*
* @protected
*/
_replaceNodeWithMarkup: function (oldHostNode, nextMarkup, prevInstance) {
ReactComponentEnvironment.replaceNodeWithMarkup(oldHostNode, nextMarkup, prevInstance);
},
/**
* @protected
*/
_renderValidatedComponentWithoutOwnerOrContext: function () {
var inst = this._instance;
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'render');
}
}
var renderedComponent = inst.render();
if (process.env.NODE_ENV !== 'production') {
if (this._debugID !== 0) {
ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'render');
}
}
if (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (renderedComponent === undefined && inst.render._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
renderedComponent = null;
}
}
return renderedComponent;
},
/**
* @private
*/
_renderValidatedComponent: function () {
var renderedComponent;
if (process.env.NODE_ENV !== 'production' || this._compositeType !== CompositeTypes.StatelessFunctional) {
ReactCurrentOwner.current = this;
try {
renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext();
} finally {
ReactCurrentOwner.current = null;
}
} else {
renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext();
}
!(
// TODO: An `isValidNode` function would probably be more appropriate
renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : _prodInvariant('109', this.getName() || 'ReactCompositeComponent') : void 0;
return renderedComponent;
},
/**
* Lazily allocates the refs object and stores `component` as `ref`.
*
* @param {string} ref Reference name.
* @param {component} component Component to store as `ref`.
* @final
* @private
*/
attachRef: function (ref, component) {
var inst = this.getPublicInstance();
!(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : _prodInvariant('110') : void 0;
var publicComponentInstance = component.getPublicInstance();
if (process.env.NODE_ENV !== 'production') {
var componentName = component && component.getName ? component.getName() : 'a component';
process.env.NODE_ENV !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : void 0;
}
var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs;
refs[ref] = publicComponentInstance;
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function (ref) {
var refs = this.getPublicInstance().refs;
delete refs[ref];
},
/**
* Get a text description of the component that can be used to identify it
* in error messages.
* @return {string} The name or null.
* @internal
*/
getName: function () {
var type = this._currentElement.type;
var constructor = this._instance && this._instance.constructor;
return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null;
},
/**
* Get the publicly accessible representation of this component - i.e. what
* is exposed by refs and returned by render. Can be null for stateless
* components.
*
* @return {ReactComponent} the public component instance.
* @internal
*/
getPublicInstance: function () {
var inst = this._instance;
if (this._compositeType === CompositeTypes.StatelessFunctional) {
return null;
}
return inst;
},
// Stub
_instantiateReactComponent: null
};
var ReactCompositeComponent = {
Mixin: ReactCompositeComponentMixin
};
module.exports = ReactCompositeComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 123 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNodeTypes
*
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactElement = __webpack_require__(9);
var invariant = __webpack_require__(8);
var ReactNodeTypes = {
HOST: 0,
COMPOSITE: 1,
EMPTY: 2,
getType: function (node) {
if (node === null || node === false) {
return ReactNodeTypes.EMPTY;
} else if (ReactElement.isValidElement(node)) {
if (typeof node.type === 'function') {
return ReactNodeTypes.COMPOSITE;
} else {
return ReactNodeTypes.HOST;
}
}
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unexpected node: %s', node) : _prodInvariant('26', node) : void 0;
}
};
module.exports = ReactNodeTypes;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 124 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*
*/
/*eslint-disable no-self-compare */
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* path_to_url
*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA, objB) {
if (is(objA, objB)) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
for (var i = 0; i < keysA.length; i++) {
if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
/***/ },
/* 125 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule shouldUpdateReactComponent
*/
'use strict';
/**
* Given a `prevElement` and `nextElement`, determines if the existing
* instance should be updated as opposed to being destroyed or replaced by a new
* instance. Both arguments are elements. This ensures that this logic can
* operate on stateless trees without any backing instance.
*
* @param {?object} prevElement
* @param {?object} nextElement
* @return {boolean} True if the existing instance should be updated.
* @protected
*/
function shouldUpdateReactComponent(prevElement, nextElement) {
var prevEmpty = prevElement === null || prevElement === false;
var nextEmpty = nextElement === null || nextElement === false;
if (prevEmpty || nextEmpty) {
return prevEmpty === nextEmpty;
}
var prevType = typeof prevElement;
var nextType = typeof nextElement;
if (prevType === 'string' || prevType === 'number') {
return nextType === 'string' || nextType === 'number';
} else {
return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key;
}
}
module.exports = shouldUpdateReactComponent;
/***/ },
/* 126 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEmptyComponent
*/
'use strict';
var emptyComponentFactory;
var ReactEmptyComponentInjection = {
injectEmptyComponentFactory: function (factory) {
emptyComponentFactory = factory;
}
};
var ReactEmptyComponent = {
create: function (instantiate) {
return emptyComponentFactory(instantiate);
}
};
ReactEmptyComponent.injection = ReactEmptyComponentInjection;
module.exports = ReactEmptyComponent;
/***/ },
/* 127 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactHostComponent
*/
'use strict';
var _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var invariant = __webpack_require__(8);
var genericComponentClass = null;
// This registry keeps track of wrapper classes around host tags.
var tagToComponentClass = {};
var textComponentClass = null;
var ReactHostComponentInjection = {
// This accepts a class that receives the tag string. This is a catch all
// that can render any kind of tag.
injectGenericComponentClass: function (componentClass) {
genericComponentClass = componentClass;
},
// This accepts a text component class that takes the text string to be
// rendered as props.
injectTextComponentClass: function (componentClass) {
textComponentClass = componentClass;
},
// This accepts a keyed object with classes as values. Each key represents a
// tag. That particular tag will use this class instead of the generic one.
injectComponentClasses: function (componentClasses) {
_assign(tagToComponentClass, componentClasses);
}
};
/**
* Get a host internal component class for a specific tag.
*
* @param {ReactElement} element The element to create.
* @return {function} The internal class constructor function.
*/
function createInternalComponent(element) {
!genericComponentClass ? process.env.NODE_ENV !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : _prodInvariant('111', element.type) : void 0;
return new genericComponentClass(element);
}
/**
* @param {ReactText} text
* @return {ReactComponent}
*/
function createInstanceForText(text) {
return new textComponentClass(text);
}
/**
* @param {ReactComponent} component
* @return {boolean}
*/
function isTextComponent(component) {
return component instanceof textComponentClass;
}
var ReactHostComponent = {
createInternalComponent: createInternalComponent,
createInstanceForText: createInstanceForText,
isTextComponent: isTextComponent,
injection: ReactHostComponentInjection
};
module.exports = ReactHostComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 128 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule flattenChildren
*
*/
'use strict';
var KeyEscapeUtils = __webpack_require__(16);
var traverseAllChildren = __webpack_require__(14);
var warning = __webpack_require__(11);
var ReactComponentTreeHook;
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') {
// Temporary hack.
// Inline requires don't work well with Jest:
// path_to_url
// Remove the inline requires when we don't need them anymore:
// path_to_url
ReactComponentTreeHook = __webpack_require__(28);
}
/**
* @param {function} traverseContext Context passed through traversal.
* @param {?ReactComponent} child React child component.
* @param {!string} name String name of key path to child.
* @param {number=} selfDebugID Optional debugID of the current internal instance.
*/
function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) {
// We found a component instance.
if (traverseContext && typeof traverseContext === 'object') {
var result = traverseContext;
var keyUnique = result[name] === undefined;
if (process.env.NODE_ENV !== 'production') {
if (!ReactComponentTreeHook) {
ReactComponentTreeHook = __webpack_require__(28);
}
if (!keyUnique) {
process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0;
}
}
if (keyUnique && child != null) {
result[name] = child;
}
}
}
/**
* Flattens children that are typically specified as `props.children`. Any null
* children will not be included in the resulting object.
* @return {!object} flattened children keyed by name.
*/
function flattenChildren(children, selfDebugID) {
if (children == null) {
return children;
}
var result = {};
if (process.env.NODE_ENV !== 'production') {
traverseAllChildren(children, function (traverseContext, child, name) {
return flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID);
}, result);
} else {
traverseAllChildren(children, flattenSingleChildIntoContext, result);
}
return result;
}
module.exports = flattenChildren;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 129 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactServerRenderingTransaction
*/
'use strict';
var _assign = __webpack_require__(4);
var PooledClass = __webpack_require__(6);
var Transaction = __webpack_require__(69);
var ReactInstrumentation = __webpack_require__(62);
var ReactServerUpdateQueue = __webpack_require__(130);
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [];
if (process.env.NODE_ENV !== 'production') {
TRANSACTION_WRAPPERS.push({
initialize: ReactInstrumentation.debugTool.onBeginFlush,
close: ReactInstrumentation.debugTool.onEndFlush
});
}
var noopCallbackQueue = {
enqueue: function () {}
};
/**
* @class ReactServerRenderingTransaction
* @param {boolean} renderToStaticMarkup
*/
function ReactServerRenderingTransaction(renderToStaticMarkup) {
this.reinitializeTransaction();
this.renderToStaticMarkup = renderToStaticMarkup;
this.useCreateElement = false;
this.updateQueue = new ReactServerUpdateQueue(this);
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array} Empty list of operation wrap procedures.
*/
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function () {
return noopCallbackQueue;
},
/**
* @return {object} The queue to collect React async events.
*/
getUpdateQueue: function () {
return this.updateQueue;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function () {},
checkpoint: function () {},
rollback: function () {}
};
_assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin);
PooledClass.addPoolingTo(ReactServerRenderingTransaction);
module.exports = ReactServerRenderingTransaction;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 130 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactServerUpdateQueue
*
*/
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ReactUpdateQueue = __webpack_require__(131);
var Transaction = __webpack_require__(69);
var warning = __webpack_require__(11);
function warnNoop(publicInstance, callerName) {
if (process.env.NODE_ENV !== 'production') {
var constructor = publicInstance.constructor;
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0;
}
}
/**
* This is the update queue used for server rendering.
* It delegates to ReactUpdateQueue while server rendering is in progress and
* switches to ReactNoopUpdateQueue after the transaction has completed.
* @class ReactServerUpdateQueue
* @param {Transaction} transaction
*/
var ReactServerUpdateQueue = function () {
/* :: transaction: Transaction; */
function ReactServerUpdateQueue(transaction) {
_classCallCheck(this, ReactServerUpdateQueue);
this.transaction = transaction;
}
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
ReactServerUpdateQueue.prototype.isMounted = function isMounted(publicInstance) {
return false;
};
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @internal
*/
ReactServerUpdateQueue.prototype.enqueueCallback = function enqueueCallback(publicInstance, callback, callerName) {
if (this.transaction.isInTransaction()) {
ReactUpdateQueue.enqueueCallback(publicInstance, callback, callerName);
}
};
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
ReactServerUpdateQueue.prototype.enqueueForceUpdate = function enqueueForceUpdate(publicInstance) {
if (this.transaction.isInTransaction()) {
ReactUpdateQueue.enqueueForceUpdate(publicInstance);
} else {
warnNoop(publicInstance, 'forceUpdate');
}
};
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object|function} completeState Next state.
* @internal
*/
ReactServerUpdateQueue.prototype.enqueueReplaceState = function enqueueReplaceState(publicInstance, completeState) {
if (this.transaction.isInTransaction()) {
ReactUpdateQueue.enqueueReplaceState(publicInstance, completeState);
} else {
warnNoop(publicInstance, 'replaceState');
}
};
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object|function} partialState Next partial state to be merged with state.
* @internal
*/
ReactServerUpdateQueue.prototype.enqueueSetState = function enqueueSetState(publicInstance, partialState) {
if (this.transaction.isInTransaction()) {
ReactUpdateQueue.enqueueSetState(publicInstance, partialState);
} else {
warnNoop(publicInstance, 'setState');
}
};
return ReactServerUpdateQueue;
}();
module.exports = ReactServerUpdateQueue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 131 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactUpdateQueue
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactCurrentOwner = __webpack_require__(10);
var ReactInstanceMap = __webpack_require__(119);
var ReactInstrumentation = __webpack_require__(62);
var ReactUpdates = __webpack_require__(56);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
function enqueueUpdate(internalInstance) {
ReactUpdates.enqueueUpdate(internalInstance);
}
function formatUnexpectedArgument(arg) {
var type = typeof arg;
if (type !== 'object') {
return type;
}
var displayName = arg.constructor && arg.constructor.name || type;
var keys = Object.keys(arg);
if (keys.length > 0 && keys.length < 20) {
return displayName + ' (keys: ' + keys.join(', ') + ')';
}
return displayName;
}
function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
var internalInstance = ReactInstanceMap.get(publicInstance);
if (!internalInstance) {
if (process.env.NODE_ENV !== 'production') {
var ctor = publicInstance.constructor;
// Only warn when we have a callerName. Otherwise we should be silent.
// We're probably calling from enqueueCallback. We don't want to warn
// there because we already warned for the corresponding lifecycle method.
process.env.NODE_ENV !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, ctor && (ctor.displayName || ctor.name) || 'ReactClass') : void 0;
}
return null;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition (such as ' + 'within `render` or another component\'s constructor). Render methods ' + 'should be a pure function of props and state; constructor ' + 'side-effects are an anti-pattern, but can be moved to ' + '`componentWillMount`.', callerName) : void 0;
}
return internalInstance;
}
/**
* ReactUpdateQueue allows for state updates to be scheduled into a later
* reconciliation step.
*/
var ReactUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
if (process.env.NODE_ENV !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0;
owner._warnedAboutRefsInRender = true;
}
}
var internalInstance = ReactInstanceMap.get(publicInstance);
if (internalInstance) {
// During componentWillMount and render this will still be null but after
// that will always render to something. At least for now. So we can use
// this hack.
return !!internalInstance._renderedComponent;
} else {
return false;
}
},
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @param {string} callerName Name of the calling function in the public API.
* @internal
*/
enqueueCallback: function (publicInstance, callback, callerName) {
ReactUpdateQueue.validateCallback(callback, callerName);
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
// Previously we would throw an error if we didn't have an internal
// instance. Since we want to make it a no-op instead, we mirror the same
// behavior we have in other enqueue* methods.
// We also need to ignore callbacks in componentWillMount. See
// enqueueUpdates.
if (!internalInstance) {
return null;
}
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
// TODO: The callback here is ignored when setState is called from
// componentWillMount. Either fix it or disallow doing so completely in
// favor of getInitialState. Alternatively, we can disallow
// componentWillMount during server-side rendering.
enqueueUpdate(internalInstance);
},
enqueueCallbackInternal: function (internalInstance, callback) {
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
enqueueUpdate(internalInstance);
},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
enqueueForceUpdate: function (publicInstance) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate');
if (!internalInstance) {
return;
}
internalInstance._pendingForceUpdate = true;
enqueueUpdate(internalInstance);
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState');
if (!internalInstance) {
return;
}
internalInstance._pendingStateQueue = [completeState];
internalInstance._pendingReplaceState = true;
enqueueUpdate(internalInstance);
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @internal
*/
enqueueSetState: function (publicInstance, partialState) {
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onSetState();
process.env.NODE_ENV !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : void 0;
}
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState');
if (!internalInstance) {
return;
}
var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []);
queue.push(partialState);
enqueueUpdate(internalInstance);
},
enqueueElementInternal: function (internalInstance, nextElement, nextContext) {
internalInstance._pendingElement = nextElement;
// TODO: introduce _pendingContext instead of setting it directly.
internalInstance._context = nextContext;
enqueueUpdate(internalInstance);
},
validateCallback: function (callback, callerName) {
!(!callback || typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.', callerName, formatUnexpectedArgument(callback)) : _prodInvariant('122', callerName, formatUnexpectedArgument(callback)) : void 0;
}
};
module.exports = ReactUpdateQueue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 132 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule validateDOMNesting
*/
'use strict';
var _assign = __webpack_require__(4);
var emptyFunction = __webpack_require__(12);
var warning = __webpack_require__(11);
var validateDOMNesting = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
// This validation code was written based on the HTML5 parsing spec:
// path_to_url#has-an-element-in-scope
//
// Note: this does not catch all invalid nesting, nor does it try to (as it's
// not clear what practical benefit doing so provides); instead, we warn only
// for cases where the parser will give a parse tree differing from what React
// intended. For example, <b><div></div></b> is invalid but we don't warn
// because it still parses correctly; we do warn for other cases like nested
// <p> tags where the beginning of the second element implicitly closes the
// first, causing a confusing mess.
// path_to_url#special
var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp'];
// path_to_url#has-an-element-in-scope
var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template',
// path_to_url#html-integration-point
// TODO: Distinguish by namespace here -- for <title>, including it here
// errs on the side of fewer warnings
'foreignObject', 'desc', 'title'];
// path_to_url#has-an-element-in-button-scope
var buttonScopeTags = inScopeTags.concat(['button']);
// path_to_url#generate-implied-end-tags
var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
var emptyAncestorInfo = {
current: null,
formTag: null,
aTagInScope: null,
buttonTagInScope: null,
nobrTagInScope: null,
pTagInButtonScope: null,
listItemTagAutoclosing: null,
dlItemTagAutoclosing: null
};
var updatedAncestorInfo = function (oldInfo, tag, instance) {
var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);
var info = { tag: tag, instance: instance };
if (inScopeTags.indexOf(tag) !== -1) {
ancestorInfo.aTagInScope = null;
ancestorInfo.buttonTagInScope = null;
ancestorInfo.nobrTagInScope = null;
}
if (buttonScopeTags.indexOf(tag) !== -1) {
ancestorInfo.pTagInButtonScope = null;
}
// See rules for 'li', 'dd', 'dt' start tags in
// path_to_url#parsing-main-inbody
if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
ancestorInfo.listItemTagAutoclosing = null;
ancestorInfo.dlItemTagAutoclosing = null;
}
ancestorInfo.current = info;
if (tag === 'form') {
ancestorInfo.formTag = info;
}
if (tag === 'a') {
ancestorInfo.aTagInScope = info;
}
if (tag === 'button') {
ancestorInfo.buttonTagInScope = info;
}
if (tag === 'nobr') {
ancestorInfo.nobrTagInScope = info;
}
if (tag === 'p') {
ancestorInfo.pTagInButtonScope = info;
}
if (tag === 'li') {
ancestorInfo.listItemTagAutoclosing = info;
}
if (tag === 'dd' || tag === 'dt') {
ancestorInfo.dlItemTagAutoclosing = info;
}
return ancestorInfo;
};
/**
* Returns whether
*/
var isTagValidWithParent = function (tag, parentTag) {
// First, let's check if we're in an unusual parsing mode...
switch (parentTag) {
// path_to_url#parsing-main-inselect
case 'select':
return tag === 'option' || tag === 'optgroup' || tag === '#text';
case 'optgroup':
return tag === 'option' || tag === '#text';
// Strictly speaking, seeing an <option> doesn't mean we're in a <select>
// but
case 'option':
return tag === '#text';
// path_to_url#parsing-main-intd
// path_to_url#parsing-main-incaption
// No special behavior since these rules fall back to "in body" mode for
// all except special table nodes which cause bad parsing behavior anyway.
// path_to_url#parsing-main-intr
case 'tr':
return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
// path_to_url#parsing-main-intbody
case 'tbody':
case 'thead':
case 'tfoot':
return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
// path_to_url#parsing-main-incolgroup
case 'colgroup':
return tag === 'col' || tag === 'template';
// path_to_url#parsing-main-intable
case 'table':
return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
// path_to_url#parsing-main-inhead
case 'head':
return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
// path_to_url#the-html-element
case 'html':
return tag === 'head' || tag === 'body';
case '#document':
return tag === 'html';
}
// Probably in the "in body" parsing mode, so we outlaw only tag combos
// where the parsing rules cause implicit opens or closes to be added.
// path_to_url#parsing-main-inbody
switch (tag) {
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
case 'rp':
case 'rt':
return impliedEndTags.indexOf(parentTag) === -1;
case 'body':
case 'caption':
case 'col':
case 'colgroup':
case 'frame':
case 'head':
case 'html':
case 'tbody':
case 'td':
case 'tfoot':
case 'th':
case 'thead':
case 'tr':
// These tags are only valid with a few parents that have special child
// parsing rules -- if we're down here, then none of those matched and
// so we allow it only if we don't know what the parent is, as all other
// cases are invalid.
return parentTag == null;
}
return true;
};
/**
* Returns whether
*/
var findInvalidAncestorForTag = function (tag, ancestorInfo) {
switch (tag) {
case 'address':
case 'article':
case 'aside':
case 'blockquote':
case 'center':
case 'details':
case 'dialog':
case 'dir':
case 'div':
case 'dl':
case 'fieldset':
case 'figcaption':
case 'figure':
case 'footer':
case 'header':
case 'hgroup':
case 'main':
case 'menu':
case 'nav':
case 'ol':
case 'p':
case 'section':
case 'summary':
case 'ul':
case 'pre':
case 'listing':
case 'table':
case 'hr':
case 'xmp':
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return ancestorInfo.pTagInButtonScope;
case 'form':
return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
case 'li':
return ancestorInfo.listItemTagAutoclosing;
case 'dd':
case 'dt':
return ancestorInfo.dlItemTagAutoclosing;
case 'button':
return ancestorInfo.buttonTagInScope;
case 'a':
// Spec says something about storing a list of markers, but it sounds
// equivalent to this check.
return ancestorInfo.aTagInScope;
case 'nobr':
return ancestorInfo.nobrTagInScope;
}
return null;
};
/**
* Given a ReactCompositeComponent instance, return a list of its recursive
* owners, starting at the root and ending with the instance itself.
*/
var findOwnerStack = function (instance) {
if (!instance) {
return [];
}
var stack = [];
do {
stack.push(instance);
} while (instance = instance._currentElement._owner);
stack.reverse();
return stack;
};
var didWarn = {};
validateDOMNesting = function (childTag, childInstance, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.current;
var parentTag = parentInfo && parentInfo.tag;
var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
var problematic = invalidParent || invalidAncestor;
if (problematic) {
var ancestorTag = problematic.tag;
var ancestorInstance = problematic.instance;
var childOwner = childInstance && childInstance._currentElement._owner;
var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner;
var childOwners = findOwnerStack(childOwner);
var ancestorOwners = findOwnerStack(ancestorOwner);
var minStackLen = Math.min(childOwners.length, ancestorOwners.length);
var i;
var deepestCommon = -1;
for (i = 0; i < minStackLen; i++) {
if (childOwners[i] === ancestorOwners[i]) {
deepestCommon = i;
} else {
break;
}
}
var UNKNOWN = '(unknown)';
var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) {
return inst.getName() || UNKNOWN;
});
var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) {
return inst.getName() || UNKNOWN;
});
var ownerInfo = [].concat(
// If the parent and child instances have a common owner ancestor, start
// with that -- otherwise we just start with the parent's owners.
deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag,
// If we're warning about an invalid (non-parent) ancestry, add '...'
invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > ');
var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo;
if (didWarn[warnKey]) {
return;
}
didWarn[warnKey] = true;
var tagDisplayName = childTag;
if (childTag !== '#text') {
tagDisplayName = '<' + childTag + '>';
}
if (invalidParent) {
var info = '';
if (ancestorTag === 'table' && childTag === 'tr') {
info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.';
}
process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>. ' + 'See %s.%s', tagDisplayName, ancestorTag, ownerInfo, info) : void 0;
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>. See %s.', tagDisplayName, ancestorTag, ownerInfo) : void 0;
}
}
};
validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo;
// For testing
validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.current;
var parentTag = parentInfo && parentInfo.tag;
return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo);
};
}
module.exports = validateDOMNesting;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 133 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMEmptyComponent
*/
'use strict';
var _assign = __webpack_require__(4);
var DOMLazyTree = __webpack_require__(82);
var ReactDOMComponentTree = __webpack_require__(36);
var ReactDOMEmptyComponent = function (instantiate) {
// ReactCompositeComponent uses this:
this._currentElement = null;
// ReactDOMComponentTree uses these:
this._hostNode = null;
this._hostParent = null;
this._hostContainerInfo = null;
this._domID = 0;
};
_assign(ReactDOMEmptyComponent.prototype, {
mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
var domID = hostContainerInfo._idCounter++;
this._domID = domID;
this._hostParent = hostParent;
this._hostContainerInfo = hostContainerInfo;
var nodeValue = ' react-empty: ' + this._domID + ' ';
if (transaction.useCreateElement) {
var ownerDocument = hostContainerInfo._ownerDocument;
var node = ownerDocument.createComment(nodeValue);
ReactDOMComponentTree.precacheNode(this, node);
return DOMLazyTree(node);
} else {
if (transaction.renderToStaticMarkup) {
// Normally we'd insert a comment node, but since this is a situation
// where React won't take over (static pages), we can simply return
// nothing.
return '';
}
return '<!--' + nodeValue + '-->';
}
},
receiveComponent: function () {},
getHostNode: function () {
return ReactDOMComponentTree.getNodeFromInstance(this);
},
unmountComponent: function () {
ReactDOMComponentTree.uncacheNode(this);
}
});
module.exports = ReactDOMEmptyComponent;
/***/ },
/* 134 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMTreeTraversal
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var invariant = __webpack_require__(8);
/**
* Return the lowest common ancestor of A and B, or null if they are in
* different trees.
*/
function getLowestCommonAncestor(instA, instB) {
!('_hostNode' in instA) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0;
!('_hostNode' in instB) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0;
var depthA = 0;
for (var tempA = instA; tempA; tempA = tempA._hostParent) {
depthA++;
}
var depthB = 0;
for (var tempB = instB; tempB; tempB = tempB._hostParent) {
depthB++;
}
// If A is deeper, crawl up.
while (depthA - depthB > 0) {
instA = instA._hostParent;
depthA--;
}
// If B is deeper, crawl up.
while (depthB - depthA > 0) {
instB = instB._hostParent;
depthB--;
}
// Walk in lockstep until we find a match.
var depth = depthA;
while (depth--) {
if (instA === instB) {
return instA;
}
instA = instA._hostParent;
instB = instB._hostParent;
}
return null;
}
/**
* Return if A is an ancestor of B.
*/
function isAncestor(instA, instB) {
!('_hostNode' in instA) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0;
!('_hostNode' in instB) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0;
while (instB) {
if (instB === instA) {
return true;
}
instB = instB._hostParent;
}
return false;
}
/**
* Return the parent instance of the passed-in instance.
*/
function getParentInstance(inst) {
!('_hostNode' in inst) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : _prodInvariant('36') : void 0;
return inst._hostParent;
}
/**
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
*/
function traverseTwoPhase(inst, fn, arg) {
var path = [];
while (inst) {
path.push(inst);
inst = inst._hostParent;
}
var i;
for (i = path.length; i-- > 0;) {
fn(path[i], false, arg);
}
for (i = 0; i < path.length; i++) {
fn(path[i], true, arg);
}
}
/**
* Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
* should would receive a `mouseEnter` or `mouseLeave` event.
*
* Does not invoke the callback on the nearest common ancestor because nothing
* "entered" or "left" that element.
*/
function traverseEnterLeave(from, to, fn, argFrom, argTo) {
var common = from && to ? getLowestCommonAncestor(from, to) : null;
var pathFrom = [];
while (from && from !== common) {
pathFrom.push(from);
from = from._hostParent;
}
var pathTo = [];
while (to && to !== common) {
pathTo.push(to);
to = to._hostParent;
}
var i;
for (i = 0; i < pathFrom.length; i++) {
fn(pathFrom[i], true, argFrom);
}
for (i = pathTo.length; i-- > 0;) {
fn(pathTo[i], false, argTo);
}
}
module.exports = {
isAncestor: isAncestor,
getLowestCommonAncestor: getLowestCommonAncestor,
getParentInstance: getParentInstance,
traverseTwoPhase: traverseTwoPhase,
traverseEnterLeave: traverseEnterLeave
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 135 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMTextComponent
*/
'use strict';
var _prodInvariant = __webpack_require__(7),
_assign = __webpack_require__(4);
var DOMChildrenOperations = __webpack_require__(81);
var DOMLazyTree = __webpack_require__(82);
var ReactDOMComponentTree = __webpack_require__(36);
var escapeTextContentForBrowser = __webpack_require__(87);
var invariant = __webpack_require__(8);
var validateDOMNesting = __webpack_require__(132);
/**
* Text nodes violate a couple assumptions that React makes about components:
*
* - When mounting text into the DOM, adjacent text nodes are merged.
* - Text nodes cannot be assigned a React root ID.
*
* This component is used to wrap strings between comment nodes so that they
* can undergo the same reconciliation that is applied to elements.
*
* TODO: Investigate representing React components in the DOM with text nodes.
*
* @class ReactDOMTextComponent
* @extends ReactComponent
* @internal
*/
var ReactDOMTextComponent = function (text) {
// TODO: This is really a ReactText (ReactNode), not a ReactElement
this._currentElement = text;
this._stringText = '' + text;
// ReactDOMComponentTree uses these:
this._hostNode = null;
this._hostParent = null;
// Properties
this._domID = 0;
this._mountIndex = 0;
this._closingComment = null;
this._commentNodes = null;
};
_assign(ReactDOMTextComponent.prototype, {
/**
* Creates the markup for this text node. This node is not intended to have
* any features besides containing text content.
*
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function (transaction, hostParent, hostContainerInfo, context) {
if (process.env.NODE_ENV !== 'production') {
var parentInfo;
if (hostParent != null) {
parentInfo = hostParent._ancestorInfo;
} else if (hostContainerInfo != null) {
parentInfo = hostContainerInfo._ancestorInfo;
}
if (parentInfo) {
// parentInfo should always be present except for the top-level
// component when server rendering
validateDOMNesting('#text', this, parentInfo);
}
}
var domID = hostContainerInfo._idCounter++;
var openingValue = ' react-text: ' + domID + ' ';
var closingValue = ' /react-text ';
this._domID = domID;
this._hostParent = hostParent;
if (transaction.useCreateElement) {
var ownerDocument = hostContainerInfo._ownerDocument;
var openingComment = ownerDocument.createComment(openingValue);
var closingComment = ownerDocument.createComment(closingValue);
var lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment());
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment));
if (this._stringText) {
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText)));
}
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment));
ReactDOMComponentTree.precacheNode(this, openingComment);
this._closingComment = closingComment;
return lazyTree;
} else {
var escapedText = escapeTextContentForBrowser(this._stringText);
if (transaction.renderToStaticMarkup) {
// Normally we'd wrap this between comment nodes for the reasons stated
// above, but since this is a situation where React won't take over
// (static pages), we can simply return the text as it is.
return escapedText;
}
return '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->';
}
},
/**
* Updates this component by updating the text content.
*
* @param {ReactText} nextText The next text content
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function (nextText, transaction) {
if (nextText !== this._currentElement) {
this._currentElement = nextText;
var nextStringText = '' + nextText;
if (nextStringText !== this._stringText) {
// TODO: Save this as pending props and use performUpdateIfNecessary
// and/or updateComponent to do the actual update for consistency with
// other component types?
this._stringText = nextStringText;
var commentNodes = this.getHostNode();
DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText);
}
}
},
getHostNode: function () {
var hostNode = this._commentNodes;
if (hostNode) {
return hostNode;
}
if (!this._closingComment) {
var openingComment = ReactDOMComponentTree.getNodeFromInstance(this);
var node = openingComment.nextSibling;
while (true) {
!(node != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing closing comment for text component %s', this._domID) : _prodInvariant('67', this._domID) : void 0;
if (node.nodeType === 8 && node.nodeValue === ' /react-text ') {
this._closingComment = node;
break;
}
node = node.nextSibling;
}
}
hostNode = [this._hostNode, this._closingComment];
this._commentNodes = hostNode;
return hostNode;
},
unmountComponent: function () {
this._closingComment = null;
this._commentNodes = null;
ReactDOMComponentTree.uncacheNode(this);
}
});
module.exports = ReactDOMTextComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 136 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDefaultBatchingStrategy
*/
'use strict';
var _assign = __webpack_require__(4);
var ReactUpdates = __webpack_require__(56);
var Transaction = __webpack_require__(69);
var emptyFunction = __webpack_require__(12);
var RESET_BATCHED_UPDATES = {
initialize: emptyFunction,
close: function () {
ReactDefaultBatchingStrategy.isBatchingUpdates = false;
}
};
var FLUSH_BATCHED_UPDATES = {
initialize: emptyFunction,
close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates)
};
var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES];
function ReactDefaultBatchingStrategyTransaction() {
this.reinitializeTransaction();
}
_assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, {
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
}
});
var transaction = new ReactDefaultBatchingStrategyTransaction();
var ReactDefaultBatchingStrategy = {
isBatchingUpdates: false,
/**
* Call the provided function in a context within which calls to `setState`
* and friends are batched such that components aren't updated unnecessarily.
*/
batchedUpdates: function (callback, a, b, c, d, e) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
callback(a, b, c, d, e);
} else {
transaction.perform(callback, null, a, b, c, d, e);
}
}
};
module.exports = ReactDefaultBatchingStrategy;
/***/ },
/* 137 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEventListener
*/
'use strict';
var _assign = __webpack_require__(4);
var EventListener = __webpack_require__(138);
var ExecutionEnvironment = __webpack_require__(49);
var PooledClass = __webpack_require__(6);
var ReactDOMComponentTree = __webpack_require__(36);
var ReactUpdates = __webpack_require__(56);
var getEventTarget = __webpack_require__(70);
var getUnboundedScrollPosition = __webpack_require__(139);
/**
* Find the deepest React component completely containing the root of the
* passed-in instance (for use when entire React trees are nested within each
* other). If React trees are not nested, returns null.
*/
function findParent(inst) {
// TODO: It may be a good idea to cache this to prevent unnecessary DOM
// traversal, but caching is difficult to do correctly without using a
// mutation observer to listen for all DOM changes.
while (inst._hostParent) {
inst = inst._hostParent;
}
var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst);
var container = rootNode.parentNode;
return ReactDOMComponentTree.getClosestInstanceFromNode(container);
}
// Used to store ancestor hierarchy in top level callback
function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) {
this.topLevelType = topLevelType;
this.nativeEvent = nativeEvent;
this.ancestors = [];
}
_assign(TopLevelCallbackBookKeeping.prototype, {
destructor: function () {
this.topLevelType = null;
this.nativeEvent = null;
this.ancestors.length = 0;
}
});
PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler);
function handleTopLevelImpl(bookKeeping) {
var nativeEventTarget = getEventTarget(bookKeeping.nativeEvent);
var targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(nativeEventTarget);
// Loop through the hierarchy, in case there's any nested components.
// It's important that we build the array of ancestors before calling any
// event handlers, because event handlers can modify the DOM, leading to
// inconsistencies with ReactMount's node cache. See #1105.
var ancestor = targetInst;
do {
bookKeeping.ancestors.push(ancestor);
ancestor = ancestor && findParent(ancestor);
} while (ancestor);
for (var i = 0; i < bookKeeping.ancestors.length; i++) {
targetInst = bookKeeping.ancestors[i];
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
}
}
function scrollValueMonitor(cb) {
var scrollPosition = getUnboundedScrollPosition(window);
cb(scrollPosition);
}
var ReactEventListener = {
_enabled: true,
_handleTopLevel: null,
WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null,
setHandleTopLevel: function (handleTopLevel) {
ReactEventListener._handleTopLevel = handleTopLevel;
},
setEnabled: function (enabled) {
ReactEventListener._enabled = !!enabled;
},
isEnabled: function () {
return ReactEventListener._enabled;
},
/**
* Traps top-level events by using event bubbling.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {?object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapBubbledEvent: function (topLevelType, handlerBaseName, handle) {
var element = handle;
if (!element) {
return null;
}
return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
},
/**
* Traps a top-level event by using event capturing.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {?object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapCapturedEvent: function (topLevelType, handlerBaseName, handle) {
var element = handle;
if (!element) {
return null;
}
return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
},
monitorScrollValue: function (refresh) {
var callback = scrollValueMonitor.bind(null, refresh);
EventListener.listen(window, 'scroll', callback);
},
dispatchEvent: function (topLevelType, nativeEvent) {
if (!ReactEventListener._enabled) {
return;
}
var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent);
try {
// Event queue being processed in the same cycle allows
// `preventDefault`.
ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping);
} finally {
TopLevelCallbackBookKeeping.release(bookKeeping);
}
}
};
module.exports = ReactEventListener;
/***/ },
/* 138 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
/**
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* @typechecks
*/
var emptyFunction = __webpack_require__(12);
/**
* Upstream version of event listener. Does not take into account specific
* nature of platform.
*/
var EventListener = {
/**
* Listen to DOM events during the bubble phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
listen: function listen(target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function remove() {
target.removeEventListener(eventType, callback, false);
}
};
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, callback);
return {
remove: function remove() {
target.detachEvent('on' + eventType, callback);
}
};
}
},
/**
* Listen to DOM events during the capture phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
capture: function capture(target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, true);
return {
remove: function remove() {
target.removeEventListener(eventType, callback, true);
}
};
} else {
if (process.env.NODE_ENV !== 'production') {
console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.');
}
return {
remove: emptyFunction
};
}
},
registerDefault: function registerDefault() {}
};
module.exports = EventListener;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 139 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
'use strict';
/**
* Gets the scroll position of the supplied element or window.
*
* The return values are unbounded, unlike `getScrollPosition`. This means they
* may be negative or exceed the element boundaries (which is possible using
* inertial scrolling).
*
* @param {DOMWindow|DOMElement} scrollable
* @return {object} Map with `x` and `y` keys.
*/
function getUnboundedScrollPosition(scrollable) {
if (scrollable === window) {
return {
x: window.pageXOffset || document.documentElement.scrollLeft,
y: window.pageYOffset || document.documentElement.scrollTop
};
}
return {
x: scrollable.scrollLeft,
y: scrollable.scrollTop
};
}
module.exports = getUnboundedScrollPosition;
/***/ },
/* 140 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInjection
*/
'use strict';
var DOMProperty = __webpack_require__(37);
var EventPluginHub = __webpack_require__(43);
var EventPluginUtils = __webpack_require__(45);
var ReactComponentEnvironment = __webpack_require__(118);
var ReactClass = __webpack_require__(21);
var ReactEmptyComponent = __webpack_require__(126);
var ReactBrowserEventEmitter = __webpack_require__(107);
var ReactHostComponent = __webpack_require__(127);
var ReactUpdates = __webpack_require__(56);
var ReactInjection = {
Component: ReactComponentEnvironment.injection,
Class: ReactClass.injection,
DOMProperty: DOMProperty.injection,
EmptyComponent: ReactEmptyComponent.injection,
EventPluginHub: EventPluginHub.injection,
EventPluginUtils: EventPluginUtils.injection,
EventEmitter: ReactBrowserEventEmitter.injection,
HostComponent: ReactHostComponent.injection,
Updates: ReactUpdates.injection
};
module.exports = ReactInjection;
/***/ },
/* 141 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactReconcileTransaction
*/
'use strict';
var _assign = __webpack_require__(4);
var CallbackQueue = __webpack_require__(57);
var PooledClass = __webpack_require__(6);
var ReactBrowserEventEmitter = __webpack_require__(107);
var ReactInputSelection = __webpack_require__(142);
var ReactInstrumentation = __webpack_require__(62);
var Transaction = __webpack_require__(69);
var ReactUpdateQueue = __webpack_require__(131);
/**
* Ensures that, when possible, the selection range (currently selected text
* input) is not disturbed by performing the transaction.
*/
var SELECTION_RESTORATION = {
/**
* @return {Selection} Selection information.
*/
initialize: ReactInputSelection.getSelectionInformation,
/**
* @param {Selection} sel Selection information returned from `initialize`.
*/
close: ReactInputSelection.restoreSelection
};
/**
* Suppresses events (blur/focus) that could be inadvertently dispatched due to
* high level DOM manipulations (like temporarily removing a text input from the
* DOM).
*/
var EVENT_SUPPRESSION = {
/**
* @return {boolean} The enabled status of `ReactBrowserEventEmitter` before
* the reconciliation.
*/
initialize: function () {
var currentlyEnabled = ReactBrowserEventEmitter.isEnabled();
ReactBrowserEventEmitter.setEnabled(false);
return currentlyEnabled;
},
/**
* @param {boolean} previouslyEnabled Enabled status of
* `ReactBrowserEventEmitter` before the reconciliation occurred. `close`
* restores the previous value.
*/
close: function (previouslyEnabled) {
ReactBrowserEventEmitter.setEnabled(previouslyEnabled);
}
};
/**
* Provides a queue for collecting `componentDidMount` and
* `componentDidUpdate` callbacks during the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function () {
this.reactMountReady.reset();
},
/**
* After DOM is flushed, invoke all registered `onDOMReady` callbacks.
*/
close: function () {
this.reactMountReady.notifyAll();
}
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING];
if (process.env.NODE_ENV !== 'production') {
TRANSACTION_WRAPPERS.push({
initialize: ReactInstrumentation.debugTool.onBeginFlush,
close: ReactInstrumentation.debugTool.onEndFlush
});
}
/**
* Currently:
* - The order that these are listed in the transaction is critical:
* - Suppresses events.
* - Restores selection range.
*
* Future:
* - Restore document/overflow scroll positions that were unintentionally
* modified via DOM insertions above the top viewport boundary.
* - Implement/integrate with customized constraint based layout system and keep
* track of which dimensions must be remeasured.
*
* @class ReactReconcileTransaction
*/
function ReactReconcileTransaction(useCreateElement) {
this.reinitializeTransaction();
// Only server-side rendering really needs this option (see
// `ReactServerRendering`), but server-side uses
// `ReactServerRenderingTransaction` instead. This option is here so that it's
// accessible and defaults to false when `ReactDOMComponent` and
// `ReactDOMTextComponent` checks it in `mountComponent`.`
this.renderToStaticMarkup = false;
this.reactMountReady = CallbackQueue.getPooled(null);
this.useCreateElement = useCreateElement;
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array<object>} List of operation wrap procedures.
* TODO: convert to array<TransactionWrapper>
*/
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function () {
return this.reactMountReady;
},
/**
* @return {object} The queue to collect React async events.
*/
getUpdateQueue: function () {
return ReactUpdateQueue;
},
/**
* Save current transaction state -- if the return value from this method is
* passed to `rollback`, the transaction will be reset to that state.
*/
checkpoint: function () {
// reactMountReady is the our only stateful wrapper
return this.reactMountReady.checkpoint();
},
rollback: function (checkpoint) {
this.reactMountReady.rollback(checkpoint);
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function () {
CallbackQueue.release(this.reactMountReady);
this.reactMountReady = null;
}
};
_assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin);
PooledClass.addPoolingTo(ReactReconcileTransaction);
module.exports = ReactReconcileTransaction;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 142 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInputSelection
*/
'use strict';
var ReactDOMSelection = __webpack_require__(143);
var containsNode = __webpack_require__(145);
var focusNode = __webpack_require__(96);
var getActiveElement = __webpack_require__(148);
function isInDocument(node) {
return containsNode(document.documentElement, node);
}
/**
* @ReactInputSelection: React input selection module. Based on Selection.js,
* but modified to be suitable for react and has a couple of bug fixes (doesn't
* assume buttons have range selections allowed).
* Input selection module for React.
*/
var ReactInputSelection = {
hasSelectionCapabilities: function (elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true');
},
getSelectionInformation: function () {
var focusedElem = getActiveElement();
return {
focusedElem: focusedElem,
selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null
};
},
/**
* @restoreSelection: If any selection information was potentially lost,
* restore it. This is useful when performing operations that could remove dom
* nodes and place them back in, resulting in focus being lost.
*/
restoreSelection: function (priorSelectionInformation) {
var curFocusedElem = getActiveElement();
var priorFocusedElem = priorSelectionInformation.focusedElem;
var priorSelectionRange = priorSelectionInformation.selectionRange;
if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange);
}
focusNode(priorFocusedElem);
}
},
/**
* @getSelection: Gets the selection bounds of a focused textarea, input or
* contentEditable node.
* -@input: Look up selection bounds of this input
* -@return {start: selectionStart, end: selectionEnd}
*/
getSelection: function (input) {
var selection;
if ('selectionStart' in input) {
// Modern browser with input or textarea.
selection = {
start: input.selectionStart,
end: input.selectionEnd
};
} else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') {
// IE8 input.
var range = document.selection.createRange();
// There can only be one selection per document in IE, so it must
// be in our element.
if (range.parentElement() === input) {
selection = {
start: -range.moveStart('character', -input.value.length),
end: -range.moveEnd('character', -input.value.length)
};
}
} else {
// Content editable or old IE textarea.
selection = ReactDOMSelection.getOffsets(input);
}
return selection || { start: 0, end: 0 };
},
/**
* @setSelection: Sets the selection bounds of a textarea or input and focuses
* the input.
* -@input Set selection bounds of this input or textarea
* -@offsets Object of same form that is returned from get*
*/
setSelection: function (input, offsets) {
var start = offsets.start;
var end = offsets.end;
if (end === undefined) {
end = start;
}
if ('selectionStart' in input) {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
} else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') {
var range = input.createTextRange();
range.collapse(true);
range.moveStart('character', start);
range.moveEnd('character', end - start);
range.select();
} else {
ReactDOMSelection.setOffsets(input, offsets);
}
}
};
module.exports = ReactInputSelection;
/***/ },
/* 143 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMSelection
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(49);
var getNodeForCharacterOffset = __webpack_require__(144);
var getTextContentAccessor = __webpack_require__(51);
/**
* While `isCollapsed` is available on the Selection object and `collapsed`
* is available on the Range object, IE11 sometimes gets them wrong.
* If the anchor/focus nodes and offsets are the same, the range is collapsed.
*/
function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) {
return anchorNode === focusNode && anchorOffset === focusOffset;
}
/**
* Get the appropriate anchor and focus node/offset pairs for IE.
*
* The catch here is that IE's selection API doesn't provide information
* about whether the selection is forward or backward, so we have to
* behave as though it's always forward.
*
* IE text differs from modern selection in that it behaves as though
* block elements end with a new line. This means character offsets will
* differ between the two APIs.
*
* @param {DOMElement} node
* @return {object}
*/
function getIEOffsets(node) {
var selection = document.selection;
var selectedRange = selection.createRange();
var selectedLength = selectedRange.text.length;
// Duplicate selection so we can move range without breaking user selection.
var fromStart = selectedRange.duplicate();
fromStart.moveToElementText(node);
fromStart.setEndPoint('EndToStart', selectedRange);
var startOffset = fromStart.text.length;
var endOffset = startOffset + selectedLength;
return {
start: startOffset,
end: endOffset
};
}
/**
* @param {DOMElement} node
* @return {?object}
*/
function getModernOffsets(node) {
var selection = window.getSelection && window.getSelection();
if (!selection || selection.rangeCount === 0) {
return null;
}
var anchorNode = selection.anchorNode;
var anchorOffset = selection.anchorOffset;
var focusNode = selection.focusNode;
var focusOffset = selection.focusOffset;
var currentRange = selection.getRangeAt(0);
// In Firefox, range.startContainer and range.endContainer can be "anonymous
// divs", e.g. the up/down buttons on an <input type="number">. Anonymous
// divs do not seem to expose properties, triggering a "Permission denied
// error" if any of its properties are accessed. The only seemingly possible
// way to avoid erroring is to access a property that typically works for
// non-anonymous divs and catch any error that may otherwise arise. See
// path_to_url
try {
/* eslint-disable no-unused-expressions */
currentRange.startContainer.nodeType;
currentRange.endContainer.nodeType;
/* eslint-enable no-unused-expressions */
} catch (e) {
return null;
}
// If the node and offset values are the same, the selection is collapsed.
// `Selection.isCollapsed` is available natively, but IE sometimes gets
// this value wrong.
var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length;
var tempRange = currentRange.cloneRange();
tempRange.selectNodeContents(node);
tempRange.setEnd(currentRange.startContainer, currentRange.startOffset);
var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset);
var start = isTempRangeCollapsed ? 0 : tempRange.toString().length;
var end = start + rangeLength;
// Detect whether the selection is backward.
var detectionRange = document.createRange();
detectionRange.setStart(anchorNode, anchorOffset);
detectionRange.setEnd(focusNode, focusOffset);
var isBackward = detectionRange.collapsed;
return {
start: isBackward ? end : start,
end: isBackward ? start : end
};
}
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setIEOffsets(node, offsets) {
var range = document.selection.createRange().duplicate();
var start, end;
if (offsets.end === undefined) {
start = offsets.start;
end = start;
} else if (offsets.start > offsets.end) {
start = offsets.end;
end = offsets.start;
} else {
start = offsets.start;
end = offsets.end;
}
range.moveToElementText(node);
range.moveStart('character', start);
range.setEndPoint('EndToStart', range);
range.moveEnd('character', end - start);
range.select();
}
/**
* In modern non-IE browsers, we can support both forward and backward
* selections.
*
* Note: IE10+ supports the Selection object, but it does not support
* the `extend` method, which means that even in modern IE, it's not possible
* to programmatically create a backward selection. Thus, for all IE
* versions, we use the old IE API to create our selections.
*
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setModernOffsets(node, offsets) {
if (!window.getSelection) {
return;
}
var selection = window.getSelection();
var length = node[getTextContentAccessor()].length;
var start = Math.min(offsets.start, length);
var end = offsets.end === undefined ? start : Math.min(offsets.end, length);
// IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if (!selection.extend && start > end) {
var temp = end;
end = start;
start = temp;
}
var startMarker = getNodeForCharacterOffset(node, start);
var endMarker = getNodeForCharacterOffset(node, end);
if (startMarker && endMarker) {
var range = document.createRange();
range.setStart(startMarker.node, startMarker.offset);
selection.removeAllRanges();
if (start > end) {
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
} else {
range.setEnd(endMarker.node, endMarker.offset);
selection.addRange(range);
}
}
}
var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window);
var ReactDOMSelection = {
/**
* @param {DOMElement} node
*/
getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets,
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets
};
module.exports = ReactDOMSelection;
/***/ },
/* 144 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getNodeForCharacterOffset
*/
'use strict';
/**
* Given any node return the first leaf node without children.
*
* @param {DOMElement|DOMTextNode} node
* @return {DOMElement|DOMTextNode}
*/
function getLeafNode(node) {
while (node && node.firstChild) {
node = node.firstChild;
}
return node;
}
/**
* Get the next sibling within a container. This will walk up the
* DOM if a node's siblings have been exhausted.
*
* @param {DOMElement|DOMTextNode} node
* @return {?DOMElement|DOMTextNode}
*/
function getSiblingNode(node) {
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
}
}
/**
* Get object describing the nodes which contain characters at offset.
*
* @param {DOMElement|DOMTextNode} root
* @param {number} offset
* @return {?object}
*/
function getNodeForCharacterOffset(root, offset) {
var node = getLeafNode(root);
var nodeStart = 0;
var nodeEnd = 0;
while (node) {
if (node.nodeType === 3) {
nodeEnd = nodeStart + node.textContent.length;
if (nodeStart <= offset && nodeEnd >= offset) {
return {
node: node,
offset: offset - nodeStart
};
}
nodeStart = nodeEnd;
}
node = getLeafNode(getSiblingNode(node));
}
}
module.exports = getNodeForCharacterOffset;
/***/ },
/* 145 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var isTextNode = __webpack_require__(146);
/*eslint-disable no-bitwise */
/**
* Checks if a given DOM node contains or is another DOM node.
*/
function containsNode(outerNode, innerNode) {
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
return containsNode(outerNode, innerNode.parentNode);
} else if ('contains' in outerNode) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
module.exports = containsNode;
/***/ },
/* 146 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var isNode = __webpack_require__(147);
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM text node.
*/
function isTextNode(object) {
return isNode(object) && object.nodeType == 3;
}
module.exports = isTextNode;
/***/ },
/* 147 */
/***/ function(module, exports) {
'use strict';
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM node.
*/
function isNode(object) {
return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string'));
}
module.exports = isNode;
/***/ },
/* 148 */
/***/ function(module, exports) {
'use strict';
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
/* eslint-disable fb-www/typeof-undefined */
/**
* Same as document.activeElement but wraps in a try-catch block. In IE it is
* not safe to call document.activeElement if there is nothing focused.
*
* The activeElement will be null only if the document or document body is not
* yet defined.
*/
function getActiveElement() /*?DOMElement*/{
if (typeof document === 'undefined') {
return null;
}
try {
return document.activeElement || document.body;
} catch (e) {
return document.body;
}
}
module.exports = getActiveElement;
/***/ },
/* 149 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SVGDOMPropertyConfig
*/
'use strict';
var NS = {
xlink: 'path_to_url
xml: 'path_to_url
};
// We use attributes for everything SVG so let's avoid some duplication and run
// code instead.
// The following are all specified in the HTML config already so we exclude here.
// - class (as className)
// - color
// - height
// - id
// - lang
// - max
// - media
// - method
// - min
// - name
// - style
// - target
// - type
// - width
var ATTRS = {
accentHeight: 'accent-height',
accumulate: 0,
additive: 0,
alignmentBaseline: 'alignment-baseline',
allowReorder: 'allowReorder',
alphabetic: 0,
amplitude: 0,
arabicForm: 'arabic-form',
ascent: 0,
attributeName: 'attributeName',
attributeType: 'attributeType',
autoReverse: 'autoReverse',
azimuth: 0,
baseFrequency: 'baseFrequency',
baseProfile: 'baseProfile',
baselineShift: 'baseline-shift',
bbox: 0,
begin: 0,
bias: 0,
by: 0,
calcMode: 'calcMode',
capHeight: 'cap-height',
clip: 0,
clipPath: 'clip-path',
clipRule: 'clip-rule',
clipPathUnits: 'clipPathUnits',
colorInterpolation: 'color-interpolation',
colorInterpolationFilters: 'color-interpolation-filters',
colorProfile: 'color-profile',
colorRendering: 'color-rendering',
contentScriptType: 'contentScriptType',
contentStyleType: 'contentStyleType',
cursor: 0,
cx: 0,
cy: 0,
d: 0,
decelerate: 0,
descent: 0,
diffuseConstant: 'diffuseConstant',
direction: 0,
display: 0,
divisor: 0,
dominantBaseline: 'dominant-baseline',
dur: 0,
dx: 0,
dy: 0,
edgeMode: 'edgeMode',
elevation: 0,
enableBackground: 'enable-background',
end: 0,
exponent: 0,
externalResourcesRequired: 'externalResourcesRequired',
fill: 0,
fillOpacity: 'fill-opacity',
fillRule: 'fill-rule',
filter: 0,
filterRes: 'filterRes',
filterUnits: 'filterUnits',
floodColor: 'flood-color',
floodOpacity: 'flood-opacity',
focusable: 0,
fontFamily: 'font-family',
fontSize: 'font-size',
fontSizeAdjust: 'font-size-adjust',
fontStretch: 'font-stretch',
fontStyle: 'font-style',
fontVariant: 'font-variant',
fontWeight: 'font-weight',
format: 0,
from: 0,
fx: 0,
fy: 0,
g1: 0,
g2: 0,
glyphName: 'glyph-name',
glyphOrientationHorizontal: 'glyph-orientation-horizontal',
glyphOrientationVertical: 'glyph-orientation-vertical',
glyphRef: 'glyphRef',
gradientTransform: 'gradientTransform',
gradientUnits: 'gradientUnits',
hanging: 0,
horizAdvX: 'horiz-adv-x',
horizOriginX: 'horiz-origin-x',
ideographic: 0,
imageRendering: 'image-rendering',
'in': 0,
in2: 0,
intercept: 0,
k: 0,
k1: 0,
k2: 0,
k3: 0,
k4: 0,
kernelMatrix: 'kernelMatrix',
kernelUnitLength: 'kernelUnitLength',
kerning: 0,
keyPoints: 'keyPoints',
keySplines: 'keySplines',
keyTimes: 'keyTimes',
lengthAdjust: 'lengthAdjust',
letterSpacing: 'letter-spacing',
lightingColor: 'lighting-color',
limitingConeAngle: 'limitingConeAngle',
local: 0,
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
markerHeight: 'markerHeight',
markerUnits: 'markerUnits',
markerWidth: 'markerWidth',
mask: 0,
maskContentUnits: 'maskContentUnits',
maskUnits: 'maskUnits',
mathematical: 0,
mode: 0,
numOctaves: 'numOctaves',
offset: 0,
opacity: 0,
operator: 0,
order: 0,
orient: 0,
orientation: 0,
origin: 0,
overflow: 0,
overlinePosition: 'overline-position',
overlineThickness: 'overline-thickness',
paintOrder: 'paint-order',
panose1: 'panose-1',
pathLength: 'pathLength',
patternContentUnits: 'patternContentUnits',
patternTransform: 'patternTransform',
patternUnits: 'patternUnits',
pointerEvents: 'pointer-events',
points: 0,
pointsAtX: 'pointsAtX',
pointsAtY: 'pointsAtY',
pointsAtZ: 'pointsAtZ',
preserveAlpha: 'preserveAlpha',
preserveAspectRatio: 'preserveAspectRatio',
primitiveUnits: 'primitiveUnits',
r: 0,
radius: 0,
refX: 'refX',
refY: 'refY',
renderingIntent: 'rendering-intent',
repeatCount: 'repeatCount',
repeatDur: 'repeatDur',
requiredExtensions: 'requiredExtensions',
requiredFeatures: 'requiredFeatures',
restart: 0,
result: 0,
rotate: 0,
rx: 0,
ry: 0,
scale: 0,
seed: 0,
shapeRendering: 'shape-rendering',
slope: 0,
spacing: 0,
specularConstant: 'specularConstant',
specularExponent: 'specularExponent',
speed: 0,
spreadMethod: 'spreadMethod',
startOffset: 'startOffset',
stdDeviation: 'stdDeviation',
stemh: 0,
stemv: 0,
stitchTiles: 'stitchTiles',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strikethroughPosition: 'strikethrough-position',
strikethroughThickness: 'strikethrough-thickness',
string: 0,
stroke: 0,
strokeDasharray: 'stroke-dasharray',
strokeDashoffset: 'stroke-dashoffset',
strokeLinecap: 'stroke-linecap',
strokeLinejoin: 'stroke-linejoin',
strokeMiterlimit: 'stroke-miterlimit',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
surfaceScale: 'surfaceScale',
systemLanguage: 'systemLanguage',
tableValues: 'tableValues',
targetX: 'targetX',
targetY: 'targetY',
textAnchor: 'text-anchor',
textDecoration: 'text-decoration',
textRendering: 'text-rendering',
textLength: 'textLength',
to: 0,
transform: 0,
u1: 0,
u2: 0,
underlinePosition: 'underline-position',
underlineThickness: 'underline-thickness',
unicode: 0,
unicodeBidi: 'unicode-bidi',
unicodeRange: 'unicode-range',
unitsPerEm: 'units-per-em',
vAlphabetic: 'v-alphabetic',
vHanging: 'v-hanging',
vIdeographic: 'v-ideographic',
vMathematical: 'v-mathematical',
values: 0,
vectorEffect: 'vector-effect',
version: 0,
vertAdvY: 'vert-adv-y',
vertOriginX: 'vert-origin-x',
vertOriginY: 'vert-origin-y',
viewBox: 'viewBox',
viewTarget: 'viewTarget',
visibility: 0,
widths: 0,
wordSpacing: 'word-spacing',
writingMode: 'writing-mode',
x: 0,
xHeight: 'x-height',
x1: 0,
x2: 0,
xChannelSelector: 'xChannelSelector',
xlinkActuate: 'xlink:actuate',
xlinkArcrole: 'xlink:arcrole',
xlinkHref: 'xlink:href',
xlinkRole: 'xlink:role',
xlinkShow: 'xlink:show',
xlinkTitle: 'xlink:title',
xlinkType: 'xlink:type',
xmlBase: 'xml:base',
xmlns: 0,
xmlnsXlink: 'xmlns:xlink',
xmlLang: 'xml:lang',
xmlSpace: 'xml:space',
y: 0,
y1: 0,
y2: 0,
yChannelSelector: 'yChannelSelector',
z: 0,
zoomAndPan: 'zoomAndPan'
};
var SVGDOMPropertyConfig = {
Properties: {},
DOMAttributeNamespaces: {
xlinkActuate: NS.xlink,
xlinkArcrole: NS.xlink,
xlinkHref: NS.xlink,
xlinkRole: NS.xlink,
xlinkShow: NS.xlink,
xlinkTitle: NS.xlink,
xlinkType: NS.xlink,
xmlBase: NS.xml,
xmlLang: NS.xml,
xmlSpace: NS.xml
},
DOMAttributeNames: {}
};
Object.keys(ATTRS).forEach(function (key) {
SVGDOMPropertyConfig.Properties[key] = 0;
if (ATTRS[key]) {
SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key];
}
});
module.exports = SVGDOMPropertyConfig;
/***/ },
/* 150 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SelectEventPlugin
*/
'use strict';
var EventConstants = __webpack_require__(41);
var EventPropagators = __webpack_require__(42);
var ExecutionEnvironment = __webpack_require__(49);
var ReactDOMComponentTree = __webpack_require__(36);
var ReactInputSelection = __webpack_require__(142);
var SyntheticEvent = __webpack_require__(53);
var getActiveElement = __webpack_require__(148);
var isTextInputElement = __webpack_require__(72);
var keyOf = __webpack_require__(25);
var shallowEqual = __webpack_require__(124);
var topLevelTypes = EventConstants.topLevelTypes;
var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11;
var eventTypes = {
select: {
phasedRegistrationNames: {
bubbled: keyOf({ onSelect: null }),
captured: keyOf({ onSelectCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange]
}
};
var activeElement = null;
var activeElementInst = null;
var lastSelection = null;
var mouseDown = false;
// Track whether a listener exists for this plugin. If none exist, we do
// not extract events. See #3639.
var hasListener = false;
var ON_SELECT_KEY = keyOf({ onSelect: null });
/**
* Get an object which is a unique representation of the current selection.
*
* The return value will not be consistent across nodes or browsers, but
* two identical selections on the same node will return identical objects.
*
* @param {DOMElement} node
* @return {object}
*/
function getSelection(node) {
if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) {
return {
start: node.selectionStart,
end: node.selectionEnd
};
} else if (window.getSelection) {
var selection = window.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
} else if (document.selection) {
var range = document.selection.createRange();
return {
parentElement: range.parentElement(),
text: range.text,
top: range.boundingTop,
left: range.boundingLeft
};
}
}
/**
* Poll selection to see whether it's changed.
*
* @param {object} nativeEvent
* @return {?SyntheticEvent}
*/
function constructSelectEvent(nativeEvent, nativeEventTarget) {
// Ensure we have the right element, and that the user is not dragging a
// selection (this matches native `select` event behavior). In HTML5, select
// fires only on input and textarea thus if there's no focused element we
// won't dispatch.
if (mouseDown || activeElement == null || activeElement !== getActiveElement()) {
return null;
}
// Only fire when selection has actually changed.
var currentSelection = getSelection(activeElement);
if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
lastSelection = currentSelection;
var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget);
syntheticEvent.type = 'select';
syntheticEvent.target = activeElement;
EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent);
return syntheticEvent;
}
return null;
}
/**
* This plugin creates an `onSelect` event that normalizes select events
* across form elements.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - contentEditable
*
* This differs from native browser implementations in the following ways:
* - Fires on contentEditable fields as well as inputs.
* - Fires for collapsed selection.
* - Fires after user input.
*/
var SelectEventPlugin = {
eventTypes: eventTypes,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
if (!hasListener) {
return null;
}
var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window;
switch (topLevelType) {
// Track the input node that has focus.
case topLevelTypes.topFocus:
if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
activeElement = targetNode;
activeElementInst = targetInst;
lastSelection = null;
}
break;
case topLevelTypes.topBlur:
activeElement = null;
activeElementInst = null;
lastSelection = null;
break;
// Don't fire the event while the user is dragging. This matches the
// semantics of the native select event.
case topLevelTypes.topMouseDown:
mouseDown = true;
break;
case topLevelTypes.topContextMenu:
case topLevelTypes.topMouseUp:
mouseDown = false;
return constructSelectEvent(nativeEvent, nativeEventTarget);
// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't). IE's event fires out of order with respect
// to key and input events on deletion, so we discard it.
//
// Firefox doesn't support selectionchange, so check selection status
// after each key entry. The selection changes after keydown and before
// keyup, but we check on keydown as well in the case of holding down a
// key, when multiple keydown events are fired but only one keyup is.
// This is also our approach for IE handling, for the reason above.
case topLevelTypes.topSelectionChange:
if (skipSelectionChangeEvent) {
break;
}
// falls through
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
return constructSelectEvent(nativeEvent, nativeEventTarget);
}
return null;
},
didPutListener: function (inst, registrationName, listener) {
if (registrationName === ON_SELECT_KEY) {
hasListener = true;
}
}
};
module.exports = SelectEventPlugin;
/***/ },
/* 151 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SimpleEventPlugin
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var EventConstants = __webpack_require__(41);
var EventListener = __webpack_require__(138);
var EventPropagators = __webpack_require__(42);
var ReactDOMComponentTree = __webpack_require__(36);
var SyntheticAnimationEvent = __webpack_require__(152);
var SyntheticClipboardEvent = __webpack_require__(153);
var SyntheticEvent = __webpack_require__(53);
var SyntheticFocusEvent = __webpack_require__(154);
var SyntheticKeyboardEvent = __webpack_require__(155);
var SyntheticMouseEvent = __webpack_require__(75);
var SyntheticDragEvent = __webpack_require__(158);
var SyntheticTouchEvent = __webpack_require__(159);
var SyntheticTransitionEvent = __webpack_require__(160);
var SyntheticUIEvent = __webpack_require__(76);
var SyntheticWheelEvent = __webpack_require__(161);
var emptyFunction = __webpack_require__(12);
var getEventCharCode = __webpack_require__(156);
var invariant = __webpack_require__(8);
var keyOf = __webpack_require__(25);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
abort: {
phasedRegistrationNames: {
bubbled: keyOf({ onAbort: true }),
captured: keyOf({ onAbortCapture: true })
}
},
animationEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onAnimationEnd: true }),
captured: keyOf({ onAnimationEndCapture: true })
}
},
animationIteration: {
phasedRegistrationNames: {
bubbled: keyOf({ onAnimationIteration: true }),
captured: keyOf({ onAnimationIterationCapture: true })
}
},
animationStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onAnimationStart: true }),
captured: keyOf({ onAnimationStartCapture: true })
}
},
blur: {
phasedRegistrationNames: {
bubbled: keyOf({ onBlur: true }),
captured: keyOf({ onBlurCapture: true })
}
},
canPlay: {
phasedRegistrationNames: {
bubbled: keyOf({ onCanPlay: true }),
captured: keyOf({ onCanPlayCapture: true })
}
},
canPlayThrough: {
phasedRegistrationNames: {
bubbled: keyOf({ onCanPlayThrough: true }),
captured: keyOf({ onCanPlayThroughCapture: true })
}
},
click: {
phasedRegistrationNames: {
bubbled: keyOf({ onClick: true }),
captured: keyOf({ onClickCapture: true })
}
},
contextMenu: {
phasedRegistrationNames: {
bubbled: keyOf({ onContextMenu: true }),
captured: keyOf({ onContextMenuCapture: true })
}
},
copy: {
phasedRegistrationNames: {
bubbled: keyOf({ onCopy: true }),
captured: keyOf({ onCopyCapture: true })
}
},
cut: {
phasedRegistrationNames: {
bubbled: keyOf({ onCut: true }),
captured: keyOf({ onCutCapture: true })
}
},
doubleClick: {
phasedRegistrationNames: {
bubbled: keyOf({ onDoubleClick: true }),
captured: keyOf({ onDoubleClickCapture: true })
}
},
drag: {
phasedRegistrationNames: {
bubbled: keyOf({ onDrag: true }),
captured: keyOf({ onDragCapture: true })
}
},
dragEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragEnd: true }),
captured: keyOf({ onDragEndCapture: true })
}
},
dragEnter: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragEnter: true }),
captured: keyOf({ onDragEnterCapture: true })
}
},
dragExit: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragExit: true }),
captured: keyOf({ onDragExitCapture: true })
}
},
dragLeave: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragLeave: true }),
captured: keyOf({ onDragLeaveCapture: true })
}
},
dragOver: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragOver: true }),
captured: keyOf({ onDragOverCapture: true })
}
},
dragStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragStart: true }),
captured: keyOf({ onDragStartCapture: true })
}
},
drop: {
phasedRegistrationNames: {
bubbled: keyOf({ onDrop: true }),
captured: keyOf({ onDropCapture: true })
}
},
durationChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onDurationChange: true }),
captured: keyOf({ onDurationChangeCapture: true })
}
},
emptied: {
phasedRegistrationNames: {
bubbled: keyOf({ onEmptied: true }),
captured: keyOf({ onEmptiedCapture: true })
}
},
encrypted: {
phasedRegistrationNames: {
bubbled: keyOf({ onEncrypted: true }),
captured: keyOf({ onEncryptedCapture: true })
}
},
ended: {
phasedRegistrationNames: {
bubbled: keyOf({ onEnded: true }),
captured: keyOf({ onEndedCapture: true })
}
},
error: {
phasedRegistrationNames: {
bubbled: keyOf({ onError: true }),
captured: keyOf({ onErrorCapture: true })
}
},
focus: {
phasedRegistrationNames: {
bubbled: keyOf({ onFocus: true }),
captured: keyOf({ onFocusCapture: true })
}
},
input: {
phasedRegistrationNames: {
bubbled: keyOf({ onInput: true }),
captured: keyOf({ onInputCapture: true })
}
},
invalid: {
phasedRegistrationNames: {
bubbled: keyOf({ onInvalid: true }),
captured: keyOf({ onInvalidCapture: true })
}
},
keyDown: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyDown: true }),
captured: keyOf({ onKeyDownCapture: true })
}
},
keyPress: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyPress: true }),
captured: keyOf({ onKeyPressCapture: true })
}
},
keyUp: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyUp: true }),
captured: keyOf({ onKeyUpCapture: true })
}
},
load: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoad: true }),
captured: keyOf({ onLoadCapture: true })
}
},
loadedData: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadedData: true }),
captured: keyOf({ onLoadedDataCapture: true })
}
},
loadedMetadata: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadedMetadata: true }),
captured: keyOf({ onLoadedMetadataCapture: true })
}
},
loadStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadStart: true }),
captured: keyOf({ onLoadStartCapture: true })
}
},
// Note: We do not allow listening to mouseOver events. Instead, use the
// onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`.
mouseDown: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseDown: true }),
captured: keyOf({ onMouseDownCapture: true })
}
},
mouseMove: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseMove: true }),
captured: keyOf({ onMouseMoveCapture: true })
}
},
mouseOut: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseOut: true }),
captured: keyOf({ onMouseOutCapture: true })
}
},
mouseOver: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseOver: true }),
captured: keyOf({ onMouseOverCapture: true })
}
},
mouseUp: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseUp: true }),
captured: keyOf({ onMouseUpCapture: true })
}
},
paste: {
phasedRegistrationNames: {
bubbled: keyOf({ onPaste: true }),
captured: keyOf({ onPasteCapture: true })
}
},
pause: {
phasedRegistrationNames: {
bubbled: keyOf({ onPause: true }),
captured: keyOf({ onPauseCapture: true })
}
},
play: {
phasedRegistrationNames: {
bubbled: keyOf({ onPlay: true }),
captured: keyOf({ onPlayCapture: true })
}
},
playing: {
phasedRegistrationNames: {
bubbled: keyOf({ onPlaying: true }),
captured: keyOf({ onPlayingCapture: true })
}
},
progress: {
phasedRegistrationNames: {
bubbled: keyOf({ onProgress: true }),
captured: keyOf({ onProgressCapture: true })
}
},
rateChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onRateChange: true }),
captured: keyOf({ onRateChangeCapture: true })
}
},
reset: {
phasedRegistrationNames: {
bubbled: keyOf({ onReset: true }),
captured: keyOf({ onResetCapture: true })
}
},
scroll: {
phasedRegistrationNames: {
bubbled: keyOf({ onScroll: true }),
captured: keyOf({ onScrollCapture: true })
}
},
seeked: {
phasedRegistrationNames: {
bubbled: keyOf({ onSeeked: true }),
captured: keyOf({ onSeekedCapture: true })
}
},
seeking: {
phasedRegistrationNames: {
bubbled: keyOf({ onSeeking: true }),
captured: keyOf({ onSeekingCapture: true })
}
},
stalled: {
phasedRegistrationNames: {
bubbled: keyOf({ onStalled: true }),
captured: keyOf({ onStalledCapture: true })
}
},
submit: {
phasedRegistrationNames: {
bubbled: keyOf({ onSubmit: true }),
captured: keyOf({ onSubmitCapture: true })
}
},
suspend: {
phasedRegistrationNames: {
bubbled: keyOf({ onSuspend: true }),
captured: keyOf({ onSuspendCapture: true })
}
},
timeUpdate: {
phasedRegistrationNames: {
bubbled: keyOf({ onTimeUpdate: true }),
captured: keyOf({ onTimeUpdateCapture: true })
}
},
touchCancel: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchCancel: true }),
captured: keyOf({ onTouchCancelCapture: true })
}
},
touchEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchEnd: true }),
captured: keyOf({ onTouchEndCapture: true })
}
},
touchMove: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchMove: true }),
captured: keyOf({ onTouchMoveCapture: true })
}
},
touchStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchStart: true }),
captured: keyOf({ onTouchStartCapture: true })
}
},
transitionEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onTransitionEnd: true }),
captured: keyOf({ onTransitionEndCapture: true })
}
},
volumeChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onVolumeChange: true }),
captured: keyOf({ onVolumeChangeCapture: true })
}
},
waiting: {
phasedRegistrationNames: {
bubbled: keyOf({ onWaiting: true }),
captured: keyOf({ onWaitingCapture: true })
}
},
wheel: {
phasedRegistrationNames: {
bubbled: keyOf({ onWheel: true }),
captured: keyOf({ onWheelCapture: true })
}
}
};
var topLevelEventsToDispatchConfig = {
topAbort: eventTypes.abort,
topAnimationEnd: eventTypes.animationEnd,
topAnimationIteration: eventTypes.animationIteration,
topAnimationStart: eventTypes.animationStart,
topBlur: eventTypes.blur,
topCanPlay: eventTypes.canPlay,
topCanPlayThrough: eventTypes.canPlayThrough,
topClick: eventTypes.click,
topContextMenu: eventTypes.contextMenu,
topCopy: eventTypes.copy,
topCut: eventTypes.cut,
topDoubleClick: eventTypes.doubleClick,
topDrag: eventTypes.drag,
topDragEnd: eventTypes.dragEnd,
topDragEnter: eventTypes.dragEnter,
topDragExit: eventTypes.dragExit,
topDragLeave: eventTypes.dragLeave,
topDragOver: eventTypes.dragOver,
topDragStart: eventTypes.dragStart,
topDrop: eventTypes.drop,
topDurationChange: eventTypes.durationChange,
topEmptied: eventTypes.emptied,
topEncrypted: eventTypes.encrypted,
topEnded: eventTypes.ended,
topError: eventTypes.error,
topFocus: eventTypes.focus,
topInput: eventTypes.input,
topInvalid: eventTypes.invalid,
topKeyDown: eventTypes.keyDown,
topKeyPress: eventTypes.keyPress,
topKeyUp: eventTypes.keyUp,
topLoad: eventTypes.load,
topLoadedData: eventTypes.loadedData,
topLoadedMetadata: eventTypes.loadedMetadata,
topLoadStart: eventTypes.loadStart,
topMouseDown: eventTypes.mouseDown,
topMouseMove: eventTypes.mouseMove,
topMouseOut: eventTypes.mouseOut,
topMouseOver: eventTypes.mouseOver,
topMouseUp: eventTypes.mouseUp,
topPaste: eventTypes.paste,
topPause: eventTypes.pause,
topPlay: eventTypes.play,
topPlaying: eventTypes.playing,
topProgress: eventTypes.progress,
topRateChange: eventTypes.rateChange,
topReset: eventTypes.reset,
topScroll: eventTypes.scroll,
topSeeked: eventTypes.seeked,
topSeeking: eventTypes.seeking,
topStalled: eventTypes.stalled,
topSubmit: eventTypes.submit,
topSuspend: eventTypes.suspend,
topTimeUpdate: eventTypes.timeUpdate,
topTouchCancel: eventTypes.touchCancel,
topTouchEnd: eventTypes.touchEnd,
topTouchMove: eventTypes.touchMove,
topTouchStart: eventTypes.touchStart,
topTransitionEnd: eventTypes.transitionEnd,
topVolumeChange: eventTypes.volumeChange,
topWaiting: eventTypes.waiting,
topWheel: eventTypes.wheel
};
for (var type in topLevelEventsToDispatchConfig) {
topLevelEventsToDispatchConfig[type].dependencies = [type];
}
var ON_CLICK_KEY = keyOf({ onClick: null });
var onClickListeners = {};
function getDictionaryKey(inst) {
// Prevents V8 performance issue:
// path_to_url
return '.' + inst._rootNodeID;
}
var SimpleEventPlugin = {
eventTypes: eventTypes,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
if (!dispatchConfig) {
return null;
}
var EventConstructor;
switch (topLevelType) {
case topLevelTypes.topAbort:
case topLevelTypes.topCanPlay:
case topLevelTypes.topCanPlayThrough:
case topLevelTypes.topDurationChange:
case topLevelTypes.topEmptied:
case topLevelTypes.topEncrypted:
case topLevelTypes.topEnded:
case topLevelTypes.topError:
case topLevelTypes.topInput:
case topLevelTypes.topInvalid:
case topLevelTypes.topLoad:
case topLevelTypes.topLoadedData:
case topLevelTypes.topLoadedMetadata:
case topLevelTypes.topLoadStart:
case topLevelTypes.topPause:
case topLevelTypes.topPlay:
case topLevelTypes.topPlaying:
case topLevelTypes.topProgress:
case topLevelTypes.topRateChange:
case topLevelTypes.topReset:
case topLevelTypes.topSeeked:
case topLevelTypes.topSeeking:
case topLevelTypes.topStalled:
case topLevelTypes.topSubmit:
case topLevelTypes.topSuspend:
case topLevelTypes.topTimeUpdate:
case topLevelTypes.topVolumeChange:
case topLevelTypes.topWaiting:
// HTML Events
// @see path_to_url#events-0
EventConstructor = SyntheticEvent;
break;
case topLevelTypes.topKeyPress:
// Firefox creates a keypress event for function keys too. This removes
// the unwanted keypress events. Enter is however both printable and
// non-printable. One would expect Tab to be as well (but it isn't).
if (getEventCharCode(nativeEvent) === 0) {
return null;
}
/* falls through */
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
EventConstructor = SyntheticKeyboardEvent;
break;
case topLevelTypes.topBlur:
case topLevelTypes.topFocus:
EventConstructor = SyntheticFocusEvent;
break;
case topLevelTypes.topClick:
// Firefox creates a click event on right mouse clicks. This removes the
// unwanted click events.
if (nativeEvent.button === 2) {
return null;
}
/* falls through */
case topLevelTypes.topContextMenu:
case topLevelTypes.topDoubleClick:
case topLevelTypes.topMouseDown:
case topLevelTypes.topMouseMove:
case topLevelTypes.topMouseOut:
case topLevelTypes.topMouseOver:
case topLevelTypes.topMouseUp:
EventConstructor = SyntheticMouseEvent;
break;
case topLevelTypes.topDrag:
case topLevelTypes.topDragEnd:
case topLevelTypes.topDragEnter:
case topLevelTypes.topDragExit:
case topLevelTypes.topDragLeave:
case topLevelTypes.topDragOver:
case topLevelTypes.topDragStart:
case topLevelTypes.topDrop:
EventConstructor = SyntheticDragEvent;
break;
case topLevelTypes.topTouchCancel:
case topLevelTypes.topTouchEnd:
case topLevelTypes.topTouchMove:
case topLevelTypes.topTouchStart:
EventConstructor = SyntheticTouchEvent;
break;
case topLevelTypes.topAnimationEnd:
case topLevelTypes.topAnimationIteration:
case topLevelTypes.topAnimationStart:
EventConstructor = SyntheticAnimationEvent;
break;
case topLevelTypes.topTransitionEnd:
EventConstructor = SyntheticTransitionEvent;
break;
case topLevelTypes.topScroll:
EventConstructor = SyntheticUIEvent;
break;
case topLevelTypes.topWheel:
EventConstructor = SyntheticWheelEvent;
break;
case topLevelTypes.topCopy:
case topLevelTypes.topCut:
case topLevelTypes.topPaste:
EventConstructor = SyntheticClipboardEvent;
break;
}
!EventConstructor ? process.env.NODE_ENV !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : _prodInvariant('86', topLevelType) : void 0;
var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
},
didPutListener: function (inst, registrationName, listener) {
// Mobile Safari does not fire properly bubble click events on
// non-interactive elements, which means delegated click listeners do not
// fire. The workaround for this bug involves attaching an empty click
// listener on the target node.
if (registrationName === ON_CLICK_KEY) {
var key = getDictionaryKey(inst);
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
if (!onClickListeners[key]) {
onClickListeners[key] = EventListener.listen(node, 'click', emptyFunction);
}
}
},
willDeleteListener: function (inst, registrationName) {
if (registrationName === ON_CLICK_KEY) {
var key = getDictionaryKey(inst);
onClickListeners[key].remove();
delete onClickListeners[key];
}
}
};
module.exports = SimpleEventPlugin;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 152 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticAnimationEvent
*/
'use strict';
var SyntheticEvent = __webpack_require__(53);
/**
* @interface Event
* @see path_to_url#AnimationEvent-interface
* @see path_to_url
*/
var AnimationEventInterface = {
animationName: null,
elapsedTime: null,
pseudoElement: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface);
module.exports = SyntheticAnimationEvent;
/***/ },
/* 153 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticClipboardEvent
*/
'use strict';
var SyntheticEvent = __webpack_require__(53);
/**
* @interface Event
* @see path_to_url
*/
var ClipboardEventInterface = {
clipboardData: function (event) {
return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
module.exports = SyntheticClipboardEvent;
/***/ },
/* 154 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticFocusEvent
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(76);
/**
* @interface FocusEvent
* @see path_to_url
*/
var FocusEventInterface = {
relatedTarget: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
module.exports = SyntheticFocusEvent;
/***/ },
/* 155 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticKeyboardEvent
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(76);
var getEventCharCode = __webpack_require__(156);
var getEventKey = __webpack_require__(157);
var getEventModifierState = __webpack_require__(78);
/**
* @interface KeyboardEvent
* @see path_to_url
*/
var KeyboardEventInterface = {
key: getEventKey,
location: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
repeat: null,
locale: null,
getModifierState: getEventModifierState,
// Legacy Interface
charCode: function (event) {
// `charCode` is the result of a KeyPress event and represents the value of
// the actual printable character.
// KeyPress is deprecated, but its replacement is not yet final and not
// implemented in any major browser. Only KeyPress has charCode.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
return 0;
},
keyCode: function (event) {
// `keyCode` is the result of a KeyDown/Up event and represents the value of
// physical keyboard key.
// The actual meaning of the value depends on the users' keyboard layout
// which cannot be detected. Assuming that it is a US keyboard layout
// provides a surprisingly accurate mapping for US and European users.
// Due to this, it is left to the user to implement at this time.
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
},
which: function (event) {
// `which` is an alias for either `keyCode` or `charCode` depending on the
// type of the event.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
module.exports = SyntheticKeyboardEvent;
/***/ },
/* 156 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventCharCode
*/
'use strict';
/**
* `charCode` represents the actual "character code" and is safe to use with
* `String.fromCharCode`. As such, only keys that correspond to printable
* characters produce a valid `charCode`, the only exception to this is Enter.
* The Tab-key is considered non-printable and does not have a `charCode`,
* presumably because it does not produce a tab-character in browsers.
*
* @param {object} nativeEvent Native browser event.
* @return {number} Normalized `charCode` property.
*/
function getEventCharCode(nativeEvent) {
var charCode;
var keyCode = nativeEvent.keyCode;
if ('charCode' in nativeEvent) {
charCode = nativeEvent.charCode;
// FF does not set `charCode` for the Enter-key, check against `keyCode`.
if (charCode === 0 && keyCode === 13) {
charCode = 13;
}
} else {
// IE8 does not implement `charCode`, but `keyCode` has the correct value.
charCode = keyCode;
}
// Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
// Must not discard the (non-)printable Enter-key.
if (charCode >= 32 || charCode === 13) {
return charCode;
}
return 0;
}
module.exports = getEventCharCode;
/***/ },
/* 157 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventKey
*/
'use strict';
var getEventCharCode = __webpack_require__(156);
/**
* Normalization of deprecated HTML5 `key` values
* @see path_to_url#Key_names
*/
var normalizeKey = {
'Esc': 'Escape',
'Spacebar': ' ',
'Left': 'ArrowLeft',
'Up': 'ArrowUp',
'Right': 'ArrowRight',
'Down': 'ArrowDown',
'Del': 'Delete',
'Win': 'OS',
'Menu': 'ContextMenu',
'Apps': 'ContextMenu',
'Scroll': 'ScrollLock',
'MozPrintableKey': 'Unidentified'
};
/**
* Translation from legacy `keyCode` to HTML5 `key`
* Only special keys supported, all others depend on keyboard layout or browser
* @see path_to_url#Key_names
*/
var translateToKey = {
8: 'Backspace',
9: 'Tab',
12: 'Clear',
13: 'Enter',
16: 'Shift',
17: 'Control',
18: 'Alt',
19: 'Pause',
20: 'CapsLock',
27: 'Escape',
32: ' ',
33: 'PageUp',
34: 'PageDown',
35: 'End',
36: 'Home',
37: 'ArrowLeft',
38: 'ArrowUp',
39: 'ArrowRight',
40: 'ArrowDown',
45: 'Insert',
46: 'Delete',
112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6',
118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12',
144: 'NumLock',
145: 'ScrollLock',
224: 'Meta'
};
/**
* @param {object} nativeEvent Native browser event.
* @return {string} Normalized `key` property.
*/
function getEventKey(nativeEvent) {
if (nativeEvent.key) {
// Normalize inconsistent values reported by browsers due to
// implementations of a working draft specification.
// FireFox implements `key` but returns `MozPrintableKey` for all
// printable characters (normalized to `Unidentified`), ignore it.
var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
if (key !== 'Unidentified') {
return key;
}
}
// Browser does not implement `key`, polyfill as much of it as we can.
if (nativeEvent.type === 'keypress') {
var charCode = getEventCharCode(nativeEvent);
// The enter-key is technically both printable and non-printable and can
// thus be captured by `keypress`, no other non-printable key should.
return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
}
if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
// While user keyboard layout determines the actual meaning of each
// `keyCode` value, almost all function keys have a universal value.
return translateToKey[nativeEvent.keyCode] || 'Unidentified';
}
return '';
}
module.exports = getEventKey;
/***/ },
/* 158 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticDragEvent
*/
'use strict';
var SyntheticMouseEvent = __webpack_require__(75);
/**
* @interface DragEvent
* @see path_to_url
*/
var DragEventInterface = {
dataTransfer: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
module.exports = SyntheticDragEvent;
/***/ },
/* 159 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticTouchEvent
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(76);
var getEventModifierState = __webpack_require__(78);
/**
* @interface TouchEvent
* @see path_to_url
*/
var TouchEventInterface = {
touches: null,
targetTouches: null,
changedTouches: null,
altKey: null,
metaKey: null,
ctrlKey: null,
shiftKey: null,
getModifierState: getEventModifierState
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
module.exports = SyntheticTouchEvent;
/***/ },
/* 160 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticTransitionEvent
*/
'use strict';
var SyntheticEvent = __webpack_require__(53);
/**
* @interface Event
* @see path_to_url#transition-events-
* @see path_to_url
*/
var TransitionEventInterface = {
propertyName: null,
elapsedTime: null,
pseudoElement: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface);
module.exports = SyntheticTransitionEvent;
/***/ },
/* 161 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticWheelEvent
*/
'use strict';
var SyntheticMouseEvent = __webpack_require__(75);
/**
* @interface WheelEvent
* @see path_to_url
*/
var WheelEventInterface = {
deltaX: function (event) {
return 'deltaX' in event ? event.deltaX :
// Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
},
deltaY: function (event) {
return 'deltaY' in event ? event.deltaY :
// Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
'wheelDeltaY' in event ? -event.wheelDeltaY :
// Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
'wheelDelta' in event ? -event.wheelDelta : 0;
},
deltaZ: null,
// Browsers without "deltaMode" is reporting in raw wheel delta where one
// notch on the scroll is always +/- 120, roughly equivalent to pixels.
// A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
// ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
deltaMode: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticMouseEvent}
*/
function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
module.exports = SyntheticWheelEvent;
/***/ },
/* 162 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMount
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var DOMLazyTree = __webpack_require__(82);
var DOMProperty = __webpack_require__(37);
var ReactBrowserEventEmitter = __webpack_require__(107);
var ReactCurrentOwner = __webpack_require__(10);
var ReactDOMComponentTree = __webpack_require__(36);
var ReactDOMContainerInfo = __webpack_require__(163);
var ReactDOMFeatureFlags = __webpack_require__(164);
var ReactElement = __webpack_require__(9);
var ReactFeatureFlags = __webpack_require__(58);
var ReactInstanceMap = __webpack_require__(119);
var ReactInstrumentation = __webpack_require__(62);
var ReactMarkupChecksum = __webpack_require__(165);
var ReactReconciler = __webpack_require__(59);
var ReactUpdateQueue = __webpack_require__(131);
var ReactUpdates = __webpack_require__(56);
var emptyObject = __webpack_require__(19);
var instantiateReactComponent = __webpack_require__(121);
var invariant = __webpack_require__(8);
var setInnerHTML = __webpack_require__(84);
var shouldUpdateReactComponent = __webpack_require__(125);
var warning = __webpack_require__(11);
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var ROOT_ATTR_NAME = DOMProperty.ROOT_ATTRIBUTE_NAME;
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
var instancesByReactRootID = {};
/**
* Finds the index of the first character
* that's not common between the two given strings.
*
* @return {number} the index of the character where the strings diverge
*/
function firstDifferenceIndex(string1, string2) {
var minLen = Math.min(string1.length, string2.length);
for (var i = 0; i < minLen; i++) {
if (string1.charAt(i) !== string2.charAt(i)) {
return i;
}
}
return string1.length === string2.length ? -1 : minLen;
}
/**
* @param {DOMElement|DOMDocument} container DOM element that may contain
* a React component
* @return {?*} DOM element that may have the reactRoot ID, or null.
*/
function getReactRootElementInContainer(container) {
if (!container) {
return null;
}
if (container.nodeType === DOC_NODE_TYPE) {
return container.documentElement;
} else {
return container.firstChild;
}
}
function internalGetID(node) {
// If node is something like a window, document, or text node, none of
// which support attributes or a .getAttribute method, gracefully return
// the empty string, as if the attribute were missing.
return node.getAttribute && node.getAttribute(ATTR_NAME) || '';
}
/**
* Mounts this component and inserts it into the DOM.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {DOMElement} container DOM element to mount into.
* @param {ReactReconcileTransaction} transaction
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function mountComponentIntoNode(wrapperInstance, container, transaction, shouldReuseMarkup, context) {
var markerName;
if (ReactFeatureFlags.logTopLevelRenders) {
var wrappedElement = wrapperInstance._currentElement.props;
var type = wrappedElement.type;
markerName = 'React mount: ' + (typeof type === 'string' ? type : type.displayName || type.name);
console.time(markerName);
}
var markup = ReactReconciler.mountComponent(wrapperInstance, transaction, null, ReactDOMContainerInfo(wrapperInstance, container), context, 0 /* parentDebugID */
);
if (markerName) {
console.timeEnd(markerName);
}
wrapperInstance._renderedComponent._topLevelWrapper = wrapperInstance;
ReactMount._mountImageIntoNode(markup, container, wrapperInstance, shouldReuseMarkup, transaction);
}
/**
* Batched mount.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {DOMElement} container DOM element to mount into.
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
/* useCreateElement */
!shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement);
transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context);
ReactUpdates.ReactReconcileTransaction.release(transaction);
}
/**
* Unmounts a component and removes it from the DOM.
*
* @param {ReactComponent} instance React component instance.
* @param {DOMElement} container DOM element to unmount from.
* @final
* @internal
* @see {ReactMount.unmountComponentAtNode}
*/
function unmountComponentFromNode(instance, container, safely) {
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onBeginFlush();
}
ReactReconciler.unmountComponent(instance, safely);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onEndFlush();
}
if (container.nodeType === DOC_NODE_TYPE) {
container = container.documentElement;
}
// path_to_url
while (container.lastChild) {
container.removeChild(container.lastChild);
}
}
/**
* True if the supplied DOM node has a direct React-rendered child that is
* not a React root element. Useful for warning in `render`,
* `unmountComponentAtNode`, etc.
*
* @param {?DOMElement} node The candidate DOM node.
* @return {boolean} True if the DOM element contains a direct child that was
* rendered by React but is not a root element.
* @internal
*/
function hasNonRootReactChild(container) {
var rootEl = getReactRootElementInContainer(container);
if (rootEl) {
var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl);
return !!(inst && inst._hostParent);
}
}
/**
* True if the supplied DOM node is a React DOM element and
* it has been rendered by another copy of React.
*
* @param {?DOMElement} node The candidate DOM node.
* @return {boolean} True if the DOM has been rendered by another copy of React
* @internal
*/
function nodeIsRenderedByOtherInstance(container) {
var rootEl = getReactRootElementInContainer(container);
return !!(rootEl && isReactNode(rootEl) && !ReactDOMComponentTree.getInstanceFromNode(rootEl));
}
/**
* True if the supplied DOM node is a valid node element.
*
* @param {?DOMElement} node The candidate DOM node.
* @return {boolean} True if the DOM is a valid DOM node.
* @internal
*/
function isValidContainer(node) {
return !!(node && (node.nodeType === ELEMENT_NODE_TYPE || node.nodeType === DOC_NODE_TYPE || node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE));
}
/**
* True if the supplied DOM node is a valid React node element.
*
* @param {?DOMElement} node The candidate DOM node.
* @return {boolean} True if the DOM is a valid React DOM node.
* @internal
*/
function isReactNode(node) {
return isValidContainer(node) && (node.hasAttribute(ROOT_ATTR_NAME) || node.hasAttribute(ATTR_NAME));
}
function getHostRootInstanceInContainer(container) {
var rootEl = getReactRootElementInContainer(container);
var prevHostInstance = rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl);
return prevHostInstance && !prevHostInstance._hostParent ? prevHostInstance : null;
}
function getTopLevelWrapperInContainer(container) {
var root = getHostRootInstanceInContainer(container);
return root ? root._hostContainerInfo._topLevelWrapper : null;
}
/**
* Temporary (?) hack so that we can store all top-level pending updates on
* composites instead of having to worry about different types of components
* here.
*/
var topLevelRootCounter = 1;
var TopLevelWrapper = function () {
this.rootID = topLevelRootCounter++;
};
TopLevelWrapper.prototype.isReactComponent = {};
if (process.env.NODE_ENV !== 'production') {
TopLevelWrapper.displayName = 'TopLevelWrapper';
}
TopLevelWrapper.prototype.render = function () {
// this.props is actually a ReactElement
return this.props;
};
/**
* Mounting is the process of initializing a React component by creating its
* representative DOM elements and inserting them into a supplied `container`.
* Any prior content inside `container` is destroyed in the process.
*
* ReactMount.render(
* component,
* document.getElementById('container')
* );
*
* <div id="container"> <-- Supplied `container`.
* <div data-reactid=".3"> <-- Rendered reactRoot of React
* // ... component.
* </div>
* </div>
*
* Inside of `container`, the first element rendered is the "reactRoot".
*/
var ReactMount = {
TopLevelWrapper: TopLevelWrapper,
/**
* Used by devtools. The keys are not important.
*/
_instancesByReactRootID: instancesByReactRootID,
/**
* This is a hook provided to support rendering React components while
* ensuring that the apparent scroll position of its `container` does not
* change.
*
* @param {DOMElement} container The `container` being rendered into.
* @param {function} renderCallback This must be called once to do the render.
*/
scrollMonitor: function (container, renderCallback) {
renderCallback();
},
/**
* Take a component that's already mounted into the DOM and replace its props
* @param {ReactComponent} prevComponent component instance already in the DOM
* @param {ReactElement} nextElement component instance to render
* @param {DOMElement} container container to render into
* @param {?function} callback function triggered on completion
*/
_updateRootComponent: function (prevComponent, nextElement, nextContext, container, callback) {
ReactMount.scrollMonitor(container, function () {
ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement, nextContext);
if (callback) {
ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback);
}
});
return prevComponent;
},
/**
* Render a new component into the DOM. Hooked by hooks!
*
* @param {ReactElement} nextElement element to render
* @param {DOMElement} container container to render into
* @param {boolean} shouldReuseMarkup if we should skip the markup insertion
* @return {ReactComponent} nextComponent
*/
_renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case.
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0;
!isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : _prodInvariant('37') : void 0;
ReactBrowserEventEmitter.ensureScrollValueMonitoring();
var componentInstance = instantiateReactComponent(nextElement, false);
// The initial render is synchronous but any updates that happen during
// rendering, in componentWillMount or componentDidMount, will be batched
// according to the current batching strategy.
ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context);
var wrapperID = componentInstance._instance.rootID;
instancesByReactRootID[wrapperID] = componentInstance;
return componentInstance;
},
/**
* Renders a React component into the DOM in the supplied `container`.
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactComponent} parentComponent The conceptual parent of this render tree.
* @param {ReactElement} nextElement Component element to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
!(parentComponent != null && ReactInstanceMap.has(parentComponent)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : _prodInvariant('38') : void 0;
return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback);
},
_renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
ReactUpdateQueue.validateCallback(callback, 'ReactDOM.render');
!ReactElement.isValidElement(nextElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' :
// Check if it quacks like an element
nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : _prodInvariant('39', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : void 0;
process.env.NODE_ENV !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : void 0;
var nextWrappedElement = ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement);
var nextContext;
if (parentComponent) {
var parentInst = ReactInstanceMap.get(parentComponent);
nextContext = parentInst._processChildContext(parentInst._context);
} else {
nextContext = emptyObject;
}
var prevComponent = getTopLevelWrapperInContainer(container);
if (prevComponent) {
var prevWrappedElement = prevComponent._currentElement;
var prevElement = prevWrappedElement.props;
if (shouldUpdateReactComponent(prevElement, nextElement)) {
var publicInst = prevComponent._renderedComponent.getPublicInstance();
var updatedCallback = callback && function () {
callback.call(publicInst);
};
ReactMount._updateRootComponent(prevComponent, nextWrappedElement, nextContext, container, updatedCallback);
return publicInst;
} else {
ReactMount.unmountComponentAtNode(container);
}
}
var reactRootElement = getReactRootElementInContainer(container);
var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement);
var containerHasNonRootReactChild = hasNonRootReactChild(container);
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : void 0;
if (!containerHasReactMarkup || reactRootElement.nextSibling) {
var rootElementSibling = reactRootElement;
while (rootElementSibling) {
if (internalGetID(rootElementSibling)) {
process.env.NODE_ENV !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : void 0;
break;
}
rootElementSibling = rootElementSibling.nextSibling;
}
}
}
var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild;
var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, nextContext)._renderedComponent.getPublicInstance();
if (callback) {
callback.call(component);
}
return component;
},
/**
* Renders a React component into the DOM in the supplied `container`.
* See path_to_url#reactdom.render
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactElement} nextElement Component element to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
render: function (nextElement, container, callback) {
return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback);
},
/**
* Unmounts and destroys the React component rendered in the `container`.
* See path_to_url#reactdom.unmountcomponentatnode
*
* @param {DOMElement} container DOM element containing a React component.
* @return {boolean} True if a component was found in and unmounted from
* `container`
*/
unmountComponentAtNode: function (container) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (Strictly speaking, unmounting won't cause a
// render but we still don't expect to be in a render call here.)
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0;
!isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : _prodInvariant('40') : void 0;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(!nodeIsRenderedByOtherInstance(container), 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by another copy of React.') : void 0;
}
var prevComponent = getTopLevelWrapperInContainer(container);
if (!prevComponent) {
// Check if the node being unmounted was rendered by React, but isn't a
// root node.
var containerHasNonRootReactChild = hasNonRootReactChild(container);
// Check if the container itself is a React root node.
var isContainerReactRoot = container.nodeType === 1 && container.hasAttribute(ROOT_ATTR_NAME);
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : void 0;
}
return false;
}
delete instancesByReactRootID[prevComponent._instance.rootID];
ReactUpdates.batchedUpdates(unmountComponentFromNode, prevComponent, container, false);
return true;
},
_mountImageIntoNode: function (markup, container, instance, shouldReuseMarkup, transaction) {
!isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : _prodInvariant('41') : void 0;
if (shouldReuseMarkup) {
var rootElement = getReactRootElementInContainer(container);
if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) {
ReactDOMComponentTree.precacheNode(instance, rootElement);
return;
} else {
var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
var rootMarkup = rootElement.outerHTML;
rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum);
var normalizedMarkup = markup;
if (process.env.NODE_ENV !== 'production') {
// because rootMarkup is retrieved from the DOM, various normalizations
// will have occurred which will not be present in `markup`. Here,
// insert markup into a <div> or <iframe> depending on the container
// type to perform the same normalizations before comparing.
var normalizer;
if (container.nodeType === ELEMENT_NODE_TYPE) {
normalizer = document.createElement('div');
normalizer.innerHTML = markup;
normalizedMarkup = normalizer.innerHTML;
} else {
normalizer = document.createElement('iframe');
document.body.appendChild(normalizer);
normalizer.contentDocument.write(markup);
normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML;
document.body.removeChild(normalizer);
}
}
var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup);
var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20);
!(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using server rendering but the checksum was invalid. This usually means you rendered a different component type or props on the client from the one on the server, or your render() methods are impure. React cannot handle this case due to cross-browser quirks by rendering at the document root. You should look for environment dependent code in your components and ensure the props are the same client and server side:\n%s', difference) : _prodInvariant('42', difference) : void 0;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : void 0;
}
}
}
!(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but you didn\'t use server rendering. We can\'t do this without using server rendering due to cross-browser quirks. See ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('43') : void 0;
if (transaction.useCreateElement) {
while (container.lastChild) {
container.removeChild(container.lastChild);
}
DOMLazyTree.insertTreeBefore(container, markup, null);
} else {
setInnerHTML(container, markup);
ReactDOMComponentTree.precacheNode(instance, container.firstChild);
}
if (process.env.NODE_ENV !== 'production') {
var hostNode = ReactDOMComponentTree.getInstanceFromNode(container.firstChild);
if (hostNode._debugID !== 0) {
ReactInstrumentation.debugTool.onHostOperation(hostNode._debugID, 'mount', markup.toString());
}
}
}
};
module.exports = ReactMount;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 163 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMContainerInfo
*/
'use strict';
var validateDOMNesting = __webpack_require__(132);
var DOC_NODE_TYPE = 9;
function ReactDOMContainerInfo(topLevelWrapper, node) {
var info = {
_topLevelWrapper: topLevelWrapper,
_idCounter: 1,
_ownerDocument: node ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument : null,
_node: node,
_tag: node ? node.nodeName.toLowerCase() : null,
_namespaceURI: node ? node.namespaceURI : null
};
if (process.env.NODE_ENV !== 'production') {
info._ancestorInfo = node ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null;
}
return info;
}
module.exports = ReactDOMContainerInfo;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 164 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMFeatureFlags
*/
'use strict';
var ReactDOMFeatureFlags = {
useCreateElement: true
};
module.exports = ReactDOMFeatureFlags;
/***/ },
/* 165 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMarkupChecksum
*/
'use strict';
var adler32 = __webpack_require__(166);
var TAG_END = /\/?>/;
var COMMENT_START = /^<\!\-\-/;
var ReactMarkupChecksum = {
CHECKSUM_ATTR_NAME: 'data-react-checksum',
/**
* @param {string} markup Markup string
* @return {string} Markup string with checksum attribute attached
*/
addChecksumToMarkup: function (markup) {
var checksum = adler32(markup);
// Add checksum (handle both parent tags, comments and self-closing tags)
if (COMMENT_START.test(markup)) {
return markup;
} else {
return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&');
}
},
/**
* @param {string} markup to use
* @param {DOMElement} element root React element
* @returns {boolean} whether or not the markup is the same
*/
canReuseMarkup: function (markup, element) {
var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
existingChecksum = existingChecksum && parseInt(existingChecksum, 10);
var markupChecksum = adler32(markup);
return markupChecksum === existingChecksum;
}
};
module.exports = ReactMarkupChecksum;
/***/ },
/* 166 */
/***/ function(module, exports) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule adler32
*
*/
'use strict';
var MOD = 65521;
// adler32 is not cryptographically strong, and is only used to sanity check that
// markup generated on the server matches the markup generated on the client.
// This implementation (a modified version of the SheetJS version) has been optimized
// for our use case, at the expense of conforming to the adler32 specification
// for non-ascii inputs.
function adler32(data) {
var a = 1;
var b = 0;
var i = 0;
var l = data.length;
var m = l & ~0x3;
while (i < m) {
var n = Math.min(i + 4096, m);
for (; i < n; i += 4) {
b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3));
}
a %= MOD;
b %= MOD;
}
for (; i < l; i++) {
b += a += data.charCodeAt(i);
}
a %= MOD;
b %= MOD;
return a | b << 16;
}
module.exports = adler32;
/***/ },
/* 167 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule findDOMNode
*/
'use strict';
var _prodInvariant = __webpack_require__(7);
var ReactCurrentOwner = __webpack_require__(10);
var ReactDOMComponentTree = __webpack_require__(36);
var ReactInstanceMap = __webpack_require__(119);
var getHostComponentFromComposite = __webpack_require__(168);
var invariant = __webpack_require__(8);
var warning = __webpack_require__(11);
/**
* Returns the DOM node rendered by this element.
*
* See path_to_url#reactdom.finddomnode
*
* @param {ReactComponent|DOMElement} componentOrElement
* @return {?DOMElement} The root node of this element.
*/
function findDOMNode(componentOrElement) {
if (process.env.NODE_ENV !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0;
owner._warnedAboutRefsInRender = true;
}
}
if (componentOrElement == null) {
return null;
}
if (componentOrElement.nodeType === 1) {
return componentOrElement;
}
var inst = ReactInstanceMap.get(componentOrElement);
if (inst) {
inst = getHostComponentFromComposite(inst);
return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null;
}
if (typeof componentOrElement.render === 'function') {
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : _prodInvariant('44') : void 0;
} else {
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement)) : void 0;
}
}
module.exports = findDOMNode;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 168 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getHostComponentFromComposite
*/
'use strict';
var ReactNodeTypes = __webpack_require__(123);
function getHostComponentFromComposite(inst) {
var type;
while ((type = inst._renderedNodeType) === ReactNodeTypes.COMPOSITE) {
inst = inst._renderedComponent;
}
if (type === ReactNodeTypes.HOST) {
return inst._renderedComponent;
} else if (type === ReactNodeTypes.EMPTY) {
return null;
}
}
module.exports = getHostComponentFromComposite;
/***/ },
/* 169 */
/***/ function(module, exports, __webpack_require__) {
/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule renderSubtreeIntoContainer
*/
'use strict';
var ReactMount = __webpack_require__(162);
module.exports = ReactMount.renderSubtreeIntoContainer;
/***/ },
/* 170 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMUnknownPropertyHook
*/
'use strict';
var DOMProperty = __webpack_require__(37);
var EventPluginRegistry = __webpack_require__(44);
var ReactComponentTreeHook = __webpack_require__(28);
var warning = __webpack_require__(11);
if (process.env.NODE_ENV !== 'production') {
var reactProps = {
children: true,
dangerouslySetInnerHTML: true,
key: true,
ref: true,
autoFocus: true,
defaultValue: true,
valueLink: true,
defaultChecked: true,
checkedLink: true,
innerHTML: true,
suppressContentEditableWarning: true,
onFocusIn: true,
onFocusOut: true
};
var warnedProperties = {};
var validateProperty = function (tagName, name, debugID) {
if (DOMProperty.properties.hasOwnProperty(name) || DOMProperty.isCustomAttribute(name)) {
return true;
}
if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) {
return true;
}
if (EventPluginRegistry.registrationNameModules.hasOwnProperty(name)) {
return true;
}
warnedProperties[name] = true;
var lowerCasedName = name.toLowerCase();
// data-* attributes should be lowercase; suggest the lowercase version
var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null;
var registrationName = EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? EventPluginRegistry.possibleRegistrationNames[lowerCasedName] : null;
if (standardName != null) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown DOM property %s. Did you mean %s?%s', name, standardName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0;
return true;
} else if (registrationName != null) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown event handler property %s. Did you mean `%s`?%s', name, registrationName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0;
return true;
} else {
// We were unable to guess which prop the user intended.
// It is likely that the user was just blindly spreading/forwarding props
// Components should be careful to only render valid props/attributes.
// Warning will be invoked in warnUnknownProperties to allow grouping.
return false;
}
};
}
var warnUnknownProperties = function (debugID, element) {
var unknownProps = [];
for (var key in element.props) {
var isValid = validateProperty(element.type, key, debugID);
if (!isValid) {
unknownProps.push(key);
}
}
var unknownPropString = unknownProps.map(function (prop) {
return '`' + prop + '`';
}).join(', ');
if (unknownProps.length === 1) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown prop %s on <%s> tag. Remove this prop from the element. ' + 'For details, see path_to_url unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0;
} else if (unknownProps.length > 1) {
process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown props %s on <%s> tag. Remove these props from the element. ' + 'For details, see path_to_url unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0;
}
};
function handleElement(debugID, element) {
if (element == null || typeof element.type !== 'string') {
return;
}
if (element.type.indexOf('-') >= 0 || element.props.is) {
return;
}
warnUnknownProperties(debugID, element);
}
var ReactDOMUnknownPropertyHook = {
onBeforeMountComponent: function (debugID, element) {
handleElement(debugID, element);
},
onBeforeUpdateComponent: function (debugID, element) {
handleElement(debugID, element);
}
};
module.exports = ReactDOMUnknownPropertyHook;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 171 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMNullInputValuePropHook
*/
'use strict';
var ReactComponentTreeHook = __webpack_require__(28);
var warning = __webpack_require__(11);
var didWarnValueNull = false;
function handleElement(debugID, element) {
if (element == null) {
return;
}
if (element.type !== 'input' && element.type !== 'textarea' && element.type !== 'select') {
return;
}
if (element.props != null && element.props.value === null && !didWarnValueNull) {
process.env.NODE_ENV !== 'production' ? warning(false, '`value` prop on `%s` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.%s', element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0;
didWarnValueNull = true;
}
}
var ReactDOMNullInputValuePropHook = {
onBeforeMountComponent: function (debugID, element) {
handleElement(debugID, element);
},
onBeforeUpdateComponent: function (debugID, element) {
handleElement(debugID, element);
}
};
module.exports = ReactDOMNullInputValuePropHook;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 172 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _validator = __webpack_require__(173);
var _DownloadForm = __webpack_require__(237);
var _DownloadForm2 = _interopRequireDefault(_DownloadForm);
var _DownloadList = __webpack_require__(242);
var _DownloadList2 = _interopRequireDefault(_DownloadList);
var _helpers = __webpack_require__(245);
var _localStorage = __webpack_require__(246);
var _localStorage2 = _interopRequireDefault(_localStorage);
__webpack_require__(247);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* global document */
var DownloadPanel = function (_Component) {
_inherits(DownloadPanel, _Component);
function DownloadPanel(props) {
_classCallCheck(this, DownloadPanel);
var _this = _possibleConstructorReturn(this, (DownloadPanel.__proto__ || Object.getPrototypeOf(DownloadPanel)).call(this, props));
console.log(_localStorage2.default.getItem('videos'));
var storedVideos = _localStorage2.default.getItem('videos');
_this.state = { videos: storedVideos || [] };
_this.handleSubmit = _this.handleSubmit.bind(_this);
_this.handleClearClick = _this.handleClearClick.bind(_this);
_this.handleVideoDownloadClick = _this.handleVideoDownloadClick.bind(_this);
return _this;
}
_createClass(DownloadPanel, [{
key: 'handleClearClick',
value: function handleClearClick() {
this.setState({ videos: [] });
_localStorage2.default.removeItem('videos');
}
}, {
key: 'handleVideoDownloadClick',
value: function handleVideoDownloadClick(e) {
var videos = this.state.videos;
var videoUrl = e.target.getAttribute('data-orig');
var updatedVideos = videos.filter(function (video) {
return video.url !== videoUrl;
});
this.setState({ videos: updatedVideos });
// Can't use this.state.videos because this is bound to the function
_localStorage2.default.setItem('videos', updatedVideos);
}
}, {
key: 'handleSubmit',
value: function handleSubmit(e) {
var _this2 = this;
e.preventDefault();
var urlInput = document.querySelector('.downloadForm__input');
var url = urlInput.value;
if (url.length === 0) {
return;
}
urlInput.value = '';
if (!(0, _validator.isURL)(url)) {
urlInput.classList.add('downloadForm__input--error');
urlInput.placeholder = 'Invalid URL';
setTimeout(function () {
urlInput.classList.remove('downloadForm__input--error');
urlInput.placeholder = '';
}, 2000);
return;
}
// Provide instant feedback by adding as much as we know to state
var videos = this.state.videos;
this.setState({ videos: [{
name: url,
url: url,
downloading: true
}].concat(_toConsumableArray(videos)) });
(0, _helpers.post)('/download', 'url=' + url).then(function (newVideo) {
videos = _this2.state.videos;
var updatedVideos = videos.map(function (video) {
return video.url === newVideo.url ? Object.assign({}, video, newVideo) : video;
});
_this2.setState({ videos: updatedVideos });
_localStorage2.default.setItem('videos', _this2.state.videos);
}, function (error) {
console.log('Failed!', error);
});
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
{ className: 'downloadPanel' },
_react2.default.createElement(_DownloadForm2.default, { onSubmit: this.handleSubmit }),
_react2.default.createElement(_DownloadList2.default, {
videos: this.state.videos,
onClearClick: this.handleClearClick,
onVideoDownloadClick: this.handleVideoDownloadClick
})
);
}
}]);
return DownloadPanel;
}(_react.Component);
exports.default = DownloadPanel;
/***/ },
/* 173 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _toDate = __webpack_require__(174);
var _toDate2 = _interopRequireDefault(_toDate);
var _toFloat = __webpack_require__(176);
var _toFloat2 = _interopRequireDefault(_toFloat);
var _toInt = __webpack_require__(177);
var _toInt2 = _interopRequireDefault(_toInt);
var _toBoolean = __webpack_require__(178);
var _toBoolean2 = _interopRequireDefault(_toBoolean);
var _equals = __webpack_require__(179);
var _equals2 = _interopRequireDefault(_equals);
var _contains = __webpack_require__(180);
var _contains2 = _interopRequireDefault(_contains);
var _matches = __webpack_require__(182);
var _matches2 = _interopRequireDefault(_matches);
var _isEmail = __webpack_require__(183);
var _isEmail2 = _interopRequireDefault(_isEmail);
var _isURL = __webpack_require__(187);
var _isURL2 = _interopRequireDefault(_isURL);
var _isMACAddress = __webpack_require__(189);
var _isMACAddress2 = _interopRequireDefault(_isMACAddress);
var _isIP = __webpack_require__(188);
var _isIP2 = _interopRequireDefault(_isIP);
var _isFQDN = __webpack_require__(186);
var _isFQDN2 = _interopRequireDefault(_isFQDN);
var _isBoolean = __webpack_require__(190);
var _isBoolean2 = _interopRequireDefault(_isBoolean);
var _isAlpha = __webpack_require__(191);
var _isAlpha2 = _interopRequireDefault(_isAlpha);
var _isAlphanumeric = __webpack_require__(193);
var _isAlphanumeric2 = _interopRequireDefault(_isAlphanumeric);
var _isNumeric = __webpack_require__(194);
var _isNumeric2 = _interopRequireDefault(_isNumeric);
var _isLowercase = __webpack_require__(195);
var _isLowercase2 = _interopRequireDefault(_isLowercase);
var _isUppercase = __webpack_require__(196);
var _isUppercase2 = _interopRequireDefault(_isUppercase);
var _isAscii = __webpack_require__(197);
var _isAscii2 = _interopRequireDefault(_isAscii);
var _isFullWidth = __webpack_require__(198);
var _isFullWidth2 = _interopRequireDefault(_isFullWidth);
var _isHalfWidth = __webpack_require__(199);
var _isHalfWidth2 = _interopRequireDefault(_isHalfWidth);
var _isVariableWidth = __webpack_require__(200);
var _isVariableWidth2 = _interopRequireDefault(_isVariableWidth);
var _isMultibyte = __webpack_require__(201);
var _isMultibyte2 = _interopRequireDefault(_isMultibyte);
var _isSurrogatePair = __webpack_require__(202);
var _isSurrogatePair2 = _interopRequireDefault(_isSurrogatePair);
var _isInt = __webpack_require__(203);
var _isInt2 = _interopRequireDefault(_isInt);
var _isFloat = __webpack_require__(204);
var _isFloat2 = _interopRequireDefault(_isFloat);
var _isDecimal = __webpack_require__(205);
var _isDecimal2 = _interopRequireDefault(_isDecimal);
var _isHexadecimal = __webpack_require__(206);
var _isHexadecimal2 = _interopRequireDefault(_isHexadecimal);
var _isDivisibleBy = __webpack_require__(207);
var _isDivisibleBy2 = _interopRequireDefault(_isDivisibleBy);
var _isHexColor = __webpack_require__(208);
var _isHexColor2 = _interopRequireDefault(_isHexColor);
var _isMD = __webpack_require__(209);
var _isMD2 = _interopRequireDefault(_isMD);
var _isJSON = __webpack_require__(210);
var _isJSON2 = _interopRequireDefault(_isJSON);
var _isNull = __webpack_require__(211);
var _isNull2 = _interopRequireDefault(_isNull);
var _isLength = __webpack_require__(212);
var _isLength2 = _interopRequireDefault(_isLength);
var _isByteLength = __webpack_require__(185);
var _isByteLength2 = _interopRequireDefault(_isByteLength);
var _isUUID = __webpack_require__(213);
var _isUUID2 = _interopRequireDefault(_isUUID);
var _isMongoId = __webpack_require__(214);
var _isMongoId2 = _interopRequireDefault(_isMongoId);
var _isDate = __webpack_require__(215);
var _isDate2 = _interopRequireDefault(_isDate);
var _isAfter = __webpack_require__(217);
var _isAfter2 = _interopRequireDefault(_isAfter);
var _isBefore = __webpack_require__(218);
var _isBefore2 = _interopRequireDefault(_isBefore);
var _isIn = __webpack_require__(219);
var _isIn2 = _interopRequireDefault(_isIn);
var _isCreditCard = __webpack_require__(220);
var _isCreditCard2 = _interopRequireDefault(_isCreditCard);
var _isISIN = __webpack_require__(221);
var _isISIN2 = _interopRequireDefault(_isISIN);
var _isISBN = __webpack_require__(222);
var _isISBN2 = _interopRequireDefault(_isISBN);
var _isMobilePhone = __webpack_require__(223);
var _isMobilePhone2 = _interopRequireDefault(_isMobilePhone);
var _isCurrency = __webpack_require__(224);
var _isCurrency2 = _interopRequireDefault(_isCurrency);
var _isISO = __webpack_require__(216);
var _isISO2 = _interopRequireDefault(_isISO);
var _isBase = __webpack_require__(225);
var _isBase2 = _interopRequireDefault(_isBase);
var _isDataURI = __webpack_require__(226);
var _isDataURI2 = _interopRequireDefault(_isDataURI);
var _ltrim = __webpack_require__(227);
var _ltrim2 = _interopRequireDefault(_ltrim);
var _rtrim = __webpack_require__(228);
var _rtrim2 = _interopRequireDefault(_rtrim);
var _trim = __webpack_require__(229);
var _trim2 = _interopRequireDefault(_trim);
var _escape = __webpack_require__(230);
var _escape2 = _interopRequireDefault(_escape);
var _unescape = __webpack_require__(231);
var _unescape2 = _interopRequireDefault(_unescape);
var _stripLow = __webpack_require__(232);
var _stripLow2 = _interopRequireDefault(_stripLow);
var _whitelist = __webpack_require__(234);
var _whitelist2 = _interopRequireDefault(_whitelist);
var _blacklist = __webpack_require__(233);
var _blacklist2 = _interopRequireDefault(_blacklist);
var _isWhitelisted = __webpack_require__(235);
var _isWhitelisted2 = _interopRequireDefault(_isWhitelisted);
var _normalizeEmail = __webpack_require__(236);
var _normalizeEmail2 = _interopRequireDefault(_normalizeEmail);
var _toString = __webpack_require__(181);
var _toString2 = _interopRequireDefault(_toString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var version = '5.6.0';
var validator = {
version: version,
toDate: _toDate2.default,
toFloat: _toFloat2.default, toInt: _toInt2.default,
toBoolean: _toBoolean2.default,
equals: _equals2.default, contains: _contains2.default, matches: _matches2.default,
isEmail: _isEmail2.default, isURL: _isURL2.default, isMACAddress: _isMACAddress2.default, isIP: _isIP2.default, isFQDN: _isFQDN2.default,
isBoolean: _isBoolean2.default,
isAlpha: _isAlpha2.default, isAlphanumeric: _isAlphanumeric2.default, isNumeric: _isNumeric2.default, isLowercase: _isLowercase2.default, isUppercase: _isUppercase2.default,
isAscii: _isAscii2.default, isFullWidth: _isFullWidth2.default, isHalfWidth: _isHalfWidth2.default, isVariableWidth: _isVariableWidth2.default,
isMultibyte: _isMultibyte2.default, isSurrogatePair: _isSurrogatePair2.default,
isInt: _isInt2.default, isFloat: _isFloat2.default, isDecimal: _isDecimal2.default, isHexadecimal: _isHexadecimal2.default, isDivisibleBy: _isDivisibleBy2.default,
isHexColor: _isHexColor2.default,
isMD5: _isMD2.default,
isJSON: _isJSON2.default,
isNull: _isNull2.default,
isLength: _isLength2.default, isByteLength: _isByteLength2.default,
isUUID: _isUUID2.default, isMongoId: _isMongoId2.default,
isDate: _isDate2.default, isAfter: _isAfter2.default, isBefore: _isBefore2.default,
isIn: _isIn2.default,
isCreditCard: _isCreditCard2.default,
isISIN: _isISIN2.default, isISBN: _isISBN2.default,
isMobilePhone: _isMobilePhone2.default,
isCurrency: _isCurrency2.default,
isISO8601: _isISO2.default,
isBase64: _isBase2.default, isDataURI: _isDataURI2.default,
ltrim: _ltrim2.default, rtrim: _rtrim2.default, trim: _trim2.default,
escape: _escape2.default, unescape: _unescape2.default, stripLow: _stripLow2.default,
whitelist: _whitelist2.default, blacklist: _blacklist2.default,
isWhitelisted: _isWhitelisted2.default,
normalizeEmail: _normalizeEmail2.default,
toString: _toString2.default
};
exports.default = validator;
module.exports = exports['default'];
/***/ },
/* 174 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = toDate;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function toDate(date) {
(0, _assertString2.default)(date);
date = Date.parse(date);
return !isNaN(date) ? new Date(date) : null;
}
module.exports = exports['default'];
/***/ },
/* 175 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = assertString;
function assertString(input) {
if (typeof input !== 'string') {
throw new TypeError('This library (validator.js) validates strings only');
}
}
module.exports = exports['default'];
/***/ },
/* 176 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = toFloat;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function toFloat(str) {
(0, _assertString2.default)(str);
return parseFloat(str);
}
module.exports = exports['default'];
/***/ },
/* 177 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = toInt;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function toInt(str, radix) {
(0, _assertString2.default)(str);
return parseInt(str, radix || 10);
}
module.exports = exports['default'];
/***/ },
/* 178 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = toBoolean;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function toBoolean(str, strict) {
(0, _assertString2.default)(str);
if (strict) {
return str === '1' || str === 'true';
}
return str !== '0' && str !== 'false' && str !== '';
}
module.exports = exports['default'];
/***/ },
/* 179 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = equals;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function equals(str, comparison) {
(0, _assertString2.default)(str);
return str === comparison;
}
module.exports = exports['default'];
/***/ },
/* 180 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = contains;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
var _toString = __webpack_require__(181);
var _toString2 = _interopRequireDefault(_toString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function contains(str, elem) {
(0, _assertString2.default)(str);
return str.indexOf((0, _toString2.default)(elem)) >= 0;
}
module.exports = exports['default'];
/***/ },
/* 181 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
exports.default = toString;
function toString(input) {
if ((typeof input === 'undefined' ? 'undefined' : _typeof(input)) === 'object' && input !== null) {
if (typeof input.toString === 'function') {
input = input.toString();
} else {
input = '[object Object]';
}
} else if (input === null || typeof input === 'undefined' || isNaN(input) && !input.length) {
input = '';
}
return String(input);
}
module.exports = exports['default'];
/***/ },
/* 182 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = matches;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function matches(str, pattern, modifiers) {
(0, _assertString2.default)(str);
if (Object.prototype.toString.call(pattern) !== '[object RegExp]') {
pattern = new RegExp(pattern, modifiers);
}
return pattern.test(str);
}
module.exports = exports['default'];
/***/ },
/* 183 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isEmail;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
var _merge = __webpack_require__(184);
var _merge2 = _interopRequireDefault(_merge);
var _isByteLength = __webpack_require__(185);
var _isByteLength2 = _interopRequireDefault(_isByteLength);
var _isFQDN = __webpack_require__(186);
var _isFQDN2 = _interopRequireDefault(_isFQDN);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var default_email_options = {
allow_display_name: false,
allow_utf8_local_part: true,
require_tld: true
};
/* eslint-disable max-len */
/* eslint-disable no-control-regex */
var displayName = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\s]*<(.+)>$/i;
var emailUserPart = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$/i;
var quotedEmailUser = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$/i;
var emailUserUtf8Part = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$/i;
var quotedEmailUserUtf8 = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*$/i;
/* eslint-enable max-len */
/* eslint-enable no-control-regex */
function isEmail(str, options) {
(0, _assertString2.default)(str);
options = (0, _merge2.default)(options, default_email_options);
if (options.allow_display_name) {
var display_email = str.match(displayName);
if (display_email) {
str = display_email[1];
}
}
var parts = str.split('@');
var domain = parts.pop();
var user = parts.join('@');
var lower_domain = domain.toLowerCase();
if (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com') {
user = user.replace(/\./g, '').toLowerCase();
}
if (!(0, _isByteLength2.default)(user, { max: 64 }) || !(0, _isByteLength2.default)(domain, { max: 256 })) {
return false;
}
if (!(0, _isFQDN2.default)(domain, { require_tld: options.require_tld })) {
return false;
}
if (user[0] === '"') {
user = user.slice(1, user.length - 1);
return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : quotedEmailUser.test(user);
}
var pattern = options.allow_utf8_local_part ? emailUserUtf8Part : emailUserPart;
var user_parts = user.split('.');
for (var i = 0; i < user_parts.length; i++) {
if (!pattern.test(user_parts[i])) {
return false;
}
}
return true;
}
module.exports = exports['default'];
/***/ },
/* 184 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = merge;
function merge() {
var obj = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var defaults = arguments[1];
for (var key in defaults) {
if (typeof obj[key] === 'undefined') {
obj[key] = defaults[key];
}
}
return obj;
}
module.exports = exports['default'];
/***/ },
/* 185 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
exports.default = isByteLength;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable prefer-rest-params */
function isByteLength(str, options) {
(0, _assertString2.default)(str);
var min = void 0;
var max = void 0;
if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
min = options.min || 0;
max = options.max;
} else {
// backwards compatibility: isByteLength(str, min [, max])
min = arguments[1];
max = arguments[2];
}
var len = encodeURI(str).split(/%..|./).length - 1;
return len >= min && (typeof max === 'undefined' || len <= max);
}
module.exports = exports['default'];
/***/ },
/* 186 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isFDQN;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
var _merge = __webpack_require__(184);
var _merge2 = _interopRequireDefault(_merge);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var default_fqdn_options = {
require_tld: true,
allow_underscores: false,
allow_trailing_dot: false
};
function isFDQN(str, options) {
(0, _assertString2.default)(str);
options = (0, _merge2.default)(options, default_fqdn_options);
/* Remove the optional trailing dot before checking validity */
if (options.allow_trailing_dot && str[str.length - 1] === '.') {
str = str.substring(0, str.length - 1);
}
var parts = str.split('.');
if (options.require_tld) {
var tld = parts.pop();
if (!parts.length || !/^([a-z\u00a1-\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) {
return false;
}
}
for (var part, i = 0; i < parts.length; i++) {
part = parts[i];
if (options.allow_underscores) {
part = part.replace(/_/g, '');
}
if (!/^[a-z\u00a1-\uffff0-9-]+$/i.test(part)) {
return false;
}
if (/[\uff01-\uff5e]/.test(part)) {
// disallow full-width chars
return false;
}
if (part[0] === '-' || part[part.length - 1] === '-') {
return false;
}
}
return true;
}
module.exports = exports['default'];
/***/ },
/* 187 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isURL;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
var _isFQDN = __webpack_require__(186);
var _isFQDN2 = _interopRequireDefault(_isFQDN);
var _isIP = __webpack_require__(188);
var _isIP2 = _interopRequireDefault(_isIP);
var _merge = __webpack_require__(184);
var _merge2 = _interopRequireDefault(_merge);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var default_url_options = {
protocols: ['http', 'https', 'ftp'],
require_tld: true,
require_protocol: false,
require_valid_protocol: true,
allow_underscores: false,
allow_trailing_dot: false,
allow_protocol_relative_urls: false
};
function isURL(url, options) {
(0, _assertString2.default)(url);
if (!url || url.length >= 2083 || /\s/.test(url)) {
return false;
}
if (url.indexOf('mailto:') === 0) {
return false;
}
options = (0, _merge2.default)(options, default_url_options);
var protocol = void 0,
auth = void 0,
host = void 0,
hostname = void 0,
port = void 0,
port_str = void 0,
split = void 0;
split = url.split('#');
url = split.shift();
split = url.split('?');
url = split.shift();
split = url.split('://');
if (split.length > 1) {
protocol = split.shift();
if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) {
return false;
}
} else if (options.require_protocol) {
return false;
} else if (options.allow_protocol_relative_urls && url.substr(0, 2) === '//') {
split[0] = url.substr(2);
}
url = split.join('://');
split = url.split('/');
url = split.shift();
split = url.split('@');
if (split.length > 1) {
auth = split.shift();
if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) {
return false;
}
}
hostname = split.join('@');
split = hostname.split(':');
host = split.shift();
if (split.length) {
port_str = split.join(':');
port = parseInt(port_str, 10);
if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) {
return false;
}
}
if (!(0, _isIP2.default)(host) && !(0, _isFQDN2.default)(host, options) && host !== 'localhost') {
return false;
}
if (options.host_whitelist && options.host_whitelist.indexOf(host) === -1) {
return false;
}
if (options.host_blacklist && options.host_blacklist.indexOf(host) !== -1) {
return false;
}
return true;
}
module.exports = exports['default'];
/***/ },
/* 188 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isIP;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ipv4Maybe = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
var ipv6Block = /^[0-9A-F]{1,4}$/i;
function isIP(str) {
var version = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];
(0, _assertString2.default)(str);
version = String(version);
if (!version) {
return isIP(str, 4) || isIP(str, 6);
} else if (version === '4') {
if (!ipv4Maybe.test(str)) {
return false;
}
var parts = str.split('.').sort(function (a, b) {
return a - b;
});
return parts[3] <= 255;
} else if (version === '6') {
var blocks = str.split(':');
var foundOmissionBlock = false; // marker to indicate ::
// At least some OS accept the last 32 bits of an IPv6 address
// (i.e. 2 of the blocks) in IPv4 notation, and RFC 3493 says
// that '::ffff:a.b.c.d' is valid for IPv4-mapped IPv6 addresses,
// and '::a.b.c.d' is deprecated, but also valid.
var foundIPv4TransitionBlock = isIP(blocks[blocks.length - 1], 4);
var expectedNumberOfBlocks = foundIPv4TransitionBlock ? 7 : 8;
if (blocks.length > expectedNumberOfBlocks) {
return false;
}
// initial or final ::
if (str === '::') {
return true;
} else if (str.substr(0, 2) === '::') {
blocks.shift();
blocks.shift();
foundOmissionBlock = true;
} else if (str.substr(str.length - 2) === '::') {
blocks.pop();
blocks.pop();
foundOmissionBlock = true;
}
for (var i = 0; i < blocks.length; ++i) {
// test for a :: which can not be at the string start/end
// since those cases have been handled above
if (blocks[i] === '' && i > 0 && i < blocks.length - 1) {
if (foundOmissionBlock) {
return false; // multiple :: in address
}
foundOmissionBlock = true;
} else if (foundIPv4TransitionBlock && i === blocks.length - 1) {
// it has been checked before that the last
// block is a valid IPv4 address
} else if (!ipv6Block.test(blocks[i])) {
return false;
}
}
if (foundOmissionBlock) {
return blocks.length >= 1;
}
return blocks.length === expectedNumberOfBlocks;
}
return false;
}
module.exports = exports['default'];
/***/ },
/* 189 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isMACAddress;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var macAddress = /^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$/;
function isMACAddress(str) {
(0, _assertString2.default)(str);
return macAddress.test(str);
}
module.exports = exports['default'];
/***/ },
/* 190 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isBoolean;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isBoolean(str) {
(0, _assertString2.default)(str);
return ['true', 'false', '1', '0'].indexOf(str) >= 0;
}
module.exports = exports['default'];
/***/ },
/* 191 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isAlpha;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
var _alpha = __webpack_require__(192);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isAlpha(str) {
var locale = arguments.length <= 1 || arguments[1] === undefined ? 'en-US' : arguments[1];
(0, _assertString2.default)(str);
if (locale in _alpha.alpha) {
return _alpha.alpha[locale].test(str);
}
throw new Error('Invalid locale \'' + locale + '\'');
}
module.exports = exports['default'];
/***/ },
/* 192 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var alpha = exports.alpha = {
'en-US': /^[A-Z]+$/i,
'cs-CZ': /^[A-Z]+$/i,
'de-DE': /^[A-Z]+$/i,
'es-ES': /^[A-Z]+$/i,
'fr-FR': /^[A-Z]+$/i,
'nl-NL': /^[A-Z]+$/i,
'hu-HU': /^[A-Z]+$/i,
'pl-PL': /^[A-Z]+$/i,
'pt-PT': /^[A-Z]+$/i,
'ru-RU': /^[--]+$/i,
'tr-TR': /^[A-Z]+$/i,
ar: /^[]+$/
};
var alphanumeric = exports.alphanumeric = {
'en-US': /^[0-9A-Z]+$/i,
'cs-CZ': /^[0-9A-Z]+$/i,
'de-DE': /^[0-9A-Z]+$/i,
'es-ES': /^[0-9A-Z]+$/i,
'fr-FR': /^[0-9A-Z]+$/i,
'hu-HU': /^[0-9A-Z]+$/i,
'nl-NL': /^[0-9A-Z]+$/i,
'pl-PL': /^[0-9A-Z]+$/i,
'pt-PT': /^[0-9A-Z]+$/i,
'ru-RU': /^[0-9--]+$/i,
'tr-TR': /^[0-9A-Z]+$/i,
ar: /^[0-9]+$/
};
var englishLocales = exports.englishLocales = ['AU', 'GB', 'HK', 'IN', 'NZ', 'ZA', 'ZM'];
for (var locale, i = 0; i < englishLocales.length; i++) {
locale = 'en-' + englishLocales[i];
alpha[locale] = alpha['en-US'];
alphanumeric[locale] = alphanumeric['en-US'];
}
// Source: path_to_url
var arabicLocales = exports.arabicLocales = ['AE', 'BH', 'DZ', 'EG', 'IQ', 'JO', 'KW', 'LB', 'LY', 'MA', 'QM', 'QA', 'SA', 'SD', 'SY', 'TN', 'YE'];
for (var _locale, _i = 0; _i < arabicLocales.length; _i++) {
_locale = 'ar-' + arabicLocales[_i];
alpha[_locale] = alpha.ar;
alphanumeric[_locale] = alphanumeric.ar;
}
/***/ },
/* 193 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isAlphanumeric;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
var _alpha = __webpack_require__(192);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isAlphanumeric(str) {
var locale = arguments.length <= 1 || arguments[1] === undefined ? 'en-US' : arguments[1];
(0, _assertString2.default)(str);
if (locale in _alpha.alphanumeric) {
return _alpha.alphanumeric[locale].test(str);
}
throw new Error('Invalid locale \'' + locale + '\'');
}
module.exports = exports['default'];
/***/ },
/* 194 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isNumeric;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var numeric = /^[-+]?[0-9]+$/;
function isNumeric(str) {
(0, _assertString2.default)(str);
return numeric.test(str);
}
module.exports = exports['default'];
/***/ },
/* 195 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isLowercase;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isLowercase(str) {
(0, _assertString2.default)(str);
return str === str.toLowerCase();
}
module.exports = exports['default'];
/***/ },
/* 196 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isUppercase;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isUppercase(str) {
(0, _assertString2.default)(str);
return str === str.toUpperCase();
}
module.exports = exports['default'];
/***/ },
/* 197 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isAscii;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable no-control-regex */
var ascii = /^[\x00-\x7F]+$/;
/* eslint-enable no-control-regex */
function isAscii(str) {
(0, _assertString2.default)(str);
return ascii.test(str);
}
module.exports = exports['default'];
/***/ },
/* 198 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fullWidth = undefined;
exports.default = isFullWidth;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var fullWidth = exports.fullWidth = /[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/;
function isFullWidth(str) {
(0, _assertString2.default)(str);
return fullWidth.test(str);
}
/***/ },
/* 199 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.halfWidth = undefined;
exports.default = isHalfWidth;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var halfWidth = exports.halfWidth = /[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/;
function isHalfWidth(str) {
(0, _assertString2.default)(str);
return halfWidth.test(str);
}
/***/ },
/* 200 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isVariableWidth;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
var _isFullWidth = __webpack_require__(198);
var _isHalfWidth = __webpack_require__(199);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isVariableWidth(str) {
(0, _assertString2.default)(str);
return _isFullWidth.fullWidth.test(str) && _isHalfWidth.halfWidth.test(str);
}
module.exports = exports['default'];
/***/ },
/* 201 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isMultibyte;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable no-control-regex */
var multibyte = /[^\x00-\x7F]/;
/* eslint-enable no-control-regex */
function isMultibyte(str) {
(0, _assertString2.default)(str);
return multibyte.test(str);
}
module.exports = exports['default'];
/***/ },
/* 202 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isSurrogatePair;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var surrogatePair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/;
function isSurrogatePair(str) {
(0, _assertString2.default)(str);
return surrogatePair.test(str);
}
module.exports = exports['default'];
/***/ },
/* 203 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isInt;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/;
var intLeadingZeroes = /^[-+]?[0-9]+$/;
function isInt(str, options) {
(0, _assertString2.default)(str);
options = options || {};
// Get the regex to use for testing, based on whether
// leading zeroes are allowed or not.
var regex = options.hasOwnProperty('allow_leading_zeroes') && options.allow_leading_zeroes ? intLeadingZeroes : int;
// Check min/max
var minCheckPassed = !options.hasOwnProperty('min') || str >= options.min;
var maxCheckPassed = !options.hasOwnProperty('max') || str <= options.max;
return regex.test(str) && minCheckPassed && maxCheckPassed;
}
module.exports = exports['default'];
/***/ },
/* 204 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isFloat;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var float = /^(?:[-+]?(?:[0-9]+))?(?:\.[0-9]*)?(?:[eE][\+\-]?(?:[0-9]+))?$/;
function isFloat(str, options) {
(0, _assertString2.default)(str);
options = options || {};
if (str === '' || str === '.') {
return false;
}
return float.test(str) && (!options.hasOwnProperty('min') || str >= options.min) && (!options.hasOwnProperty('max') || str <= options.max);
}
module.exports = exports['default'];
/***/ },
/* 205 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isDecimal;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var decimal = /^[-+]?([0-9]+|\.[0-9]+|[0-9]+\.[0-9]+)$/;
function isDecimal(str) {
(0, _assertString2.default)(str);
return str !== '' && decimal.test(str);
}
module.exports = exports['default'];
/***/ },
/* 206 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isHexadecimal;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var hexadecimal = /^[0-9A-F]+$/i;
function isHexadecimal(str) {
(0, _assertString2.default)(str);
return hexadecimal.test(str);
}
module.exports = exports['default'];
/***/ },
/* 207 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isDivisibleBy;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
var _toFloat = __webpack_require__(176);
var _toFloat2 = _interopRequireDefault(_toFloat);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isDivisibleBy(str, num) {
(0, _assertString2.default)(str);
return (0, _toFloat2.default)(str) % parseInt(num, 10) === 0;
}
module.exports = exports['default'];
/***/ },
/* 208 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isHexColor;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var hexcolor = /^#?([0-9A-F]{3}|[0-9A-F]{6})$/i;
function isHexColor(str) {
(0, _assertString2.default)(str);
return hexcolor.test(str);
}
module.exports = exports['default'];
/***/ },
/* 209 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isMD5;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var md5 = /^[a-f0-9]{32}$/;
function isMD5(str) {
(0, _assertString2.default)(str);
return md5.test(str);
}
module.exports = exports['default'];
/***/ },
/* 210 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
exports.default = isJSON;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isJSON(str) {
(0, _assertString2.default)(str);
try {
var obj = JSON.parse(str);
return !!obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object';
} catch (e) {/* ignore */}
return false;
}
module.exports = exports['default'];
/***/ },
/* 211 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isNull;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isNull(str) {
(0, _assertString2.default)(str);
return str.length === 0;
}
module.exports = exports['default'];
/***/ },
/* 212 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
exports.default = isLength;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable prefer-rest-params */
function isLength(str, options) {
(0, _assertString2.default)(str);
var min = void 0;
var max = void 0;
if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
min = options.min || 0;
max = options.max;
} else {
// backwards compatibility: isLength(str, min [, max])
min = arguments[1];
max = arguments[2];
}
var surrogatePairs = str.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || [];
var len = str.length - surrogatePairs.length;
return len >= min && (typeof max === 'undefined' || len <= max);
}
module.exports = exports['default'];
/***/ },
/* 213 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isUUID;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var uuid = {
3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,
4: /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,
5: /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,
all: /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i
};
function isUUID(str) {
var version = arguments.length <= 1 || arguments[1] === undefined ? 'all' : arguments[1];
(0, _assertString2.default)(str);
var pattern = uuid[version];
return pattern && pattern.test(str);
}
module.exports = exports['default'];
/***/ },
/* 214 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isMongoId;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
var _isHexadecimal = __webpack_require__(206);
var _isHexadecimal2 = _interopRequireDefault(_isHexadecimal);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isMongoId(str) {
(0, _assertString2.default)(str);
return (0, _isHexadecimal2.default)(str) && str.length === 24;
}
module.exports = exports['default'];
/***/ },
/* 215 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isDate;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
var _isISO = __webpack_require__(216);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getTimezoneOffset(str) {
var iso8601Parts = str.match(_isISO.iso8601);
var timezone = void 0,
sign = void 0,
hours = void 0,
minutes = void 0;
if (!iso8601Parts) {
str = str.toLowerCase();
timezone = str.match(/(?:\s|gmt\s*)(-|\+)(\d{1,4})(\s|$)/);
if (!timezone) {
return str.indexOf('gmt') !== -1 ? 0 : null;
}
sign = timezone[1];
var offset = timezone[2];
if (offset.length === 3) {
offset = '0' + offset;
}
if (offset.length <= 2) {
hours = 0;
minutes = parseInt(offset, 10);
} else {
hours = parseInt(offset.slice(0, 2), 10);
minutes = parseInt(offset.slice(2, 4), 10);
}
} else {
timezone = iso8601Parts[21];
if (!timezone) {
// if no hour/minute was provided, the date is GMT
return !iso8601Parts[12] ? 0 : null;
}
if (timezone === 'z' || timezone === 'Z') {
return 0;
}
sign = iso8601Parts[22];
if (timezone.indexOf(':') !== -1) {
hours = parseInt(iso8601Parts[23], 10);
minutes = parseInt(iso8601Parts[24], 10);
} else {
hours = 0;
minutes = parseInt(iso8601Parts[23], 10);
}
}
return (hours * 60 + minutes) * (sign === '-' ? 1 : -1);
}
function isDate(str) {
(0, _assertString2.default)(str);
var normalizedDate = new Date(Date.parse(str));
if (isNaN(normalizedDate)) {
return false;
}
// normalizedDate is in the user's timezone. Apply the input
// timezone offset to the date so that the year and day match
// the input
var timezoneOffset = getTimezoneOffset(str);
if (timezoneOffset !== null) {
var timezoneDifference = normalizedDate.getTimezoneOffset() - timezoneOffset;
normalizedDate = new Date(normalizedDate.getTime() + 60000 * timezoneDifference);
}
var day = String(normalizedDate.getDate());
var dayOrYear = void 0,
dayOrYearMatches = void 0,
year = void 0;
// check for valid double digits that could be late days
// check for all matches since a string like '12/23' is a valid date
// ignore everything with nearby colons
dayOrYearMatches = str.match(/(^|[^:\d])[23]\d([^T:\d]|$)/g);
if (!dayOrYearMatches) {
return true;
}
dayOrYear = dayOrYearMatches.map(function (digitString) {
return digitString.match(/\d+/g)[0];
}).join('/');
year = String(normalizedDate.getFullYear()).slice(-2);
if (dayOrYear === day || dayOrYear === year) {
return true;
} else if (dayOrYear === '' + day / year || dayOrYear === '' + year / day) {
return true;
}
return false;
}
module.exports = exports['default'];
/***/ },
/* 216 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.iso8601 = undefined;
exports.default = function (str) {
(0, _assertString2.default)(str);
return iso8601.test(str);
};
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable max-len */
// from path_to_url
var iso8601 = exports.iso8601 = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
/* eslint-enable max-len */
/***/ },
/* 217 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isAfter;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
var _toDate = __webpack_require__(174);
var _toDate2 = _interopRequireDefault(_toDate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isAfter(str) {
var date = arguments.length <= 1 || arguments[1] === undefined ? String(new Date()) : arguments[1];
(0, _assertString2.default)(str);
var comparison = (0, _toDate2.default)(date);
var original = (0, _toDate2.default)(str);
return !!(original && comparison && original > comparison);
}
module.exports = exports['default'];
/***/ },
/* 218 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isBefore;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
var _toDate = __webpack_require__(174);
var _toDate2 = _interopRequireDefault(_toDate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isBefore(str) {
var date = arguments.length <= 1 || arguments[1] === undefined ? String(new Date()) : arguments[1];
(0, _assertString2.default)(str);
var comparison = (0, _toDate2.default)(date);
var original = (0, _toDate2.default)(str);
return !!(original && comparison && original < comparison);
}
module.exports = exports['default'];
/***/ },
/* 219 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
exports.default = isIn;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
var _toString = __webpack_require__(181);
var _toString2 = _interopRequireDefault(_toString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isIn(str, options) {
(0, _assertString2.default)(str);
var i = void 0;
if (Object.prototype.toString.call(options) === '[object Array]') {
var array = [];
for (i in options) {
if ({}.hasOwnProperty.call(options, i)) {
array[i] = (0, _toString2.default)(options[i]);
}
}
return array.indexOf(str) >= 0;
} else if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
return options.hasOwnProperty(str);
} else if (options && typeof options.indexOf === 'function') {
return options.indexOf(str) >= 0;
}
return false;
}
module.exports = exports['default'];
/***/ },
/* 220 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isCreditCard;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable max-len */
var creditCard = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})|62[0-9]{14}$/;
/* eslint-enable max-len */
function isCreditCard(str) {
(0, _assertString2.default)(str);
var sanitized = str.replace(/[^0-9]+/g, '');
if (!creditCard.test(sanitized)) {
return false;
}
var sum = 0;
var digit = void 0;
var tmpNum = void 0;
var shouldDouble = void 0;
for (var i = sanitized.length - 1; i >= 0; i--) {
digit = sanitized.substring(i, i + 1);
tmpNum = parseInt(digit, 10);
if (shouldDouble) {
tmpNum *= 2;
if (tmpNum >= 10) {
sum += tmpNum % 10 + 1;
} else {
sum += tmpNum;
}
} else {
sum += tmpNum;
}
shouldDouble = !shouldDouble;
}
return !!(sum % 10 === 0 ? sanitized : false);
}
module.exports = exports['default'];
/***/ },
/* 221 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isISIN;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isin = /^[A-Z]{2}[0-9A-Z]{9}[0-9]$/;
function isISIN(str) {
(0, _assertString2.default)(str);
if (!isin.test(str)) {
return false;
}
var checksumStr = str.replace(/[A-Z]/g, function (character) {
return parseInt(character, 36);
});
var sum = 0;
var digit = void 0;
var tmpNum = void 0;
var shouldDouble = true;
for (var i = checksumStr.length - 2; i >= 0; i--) {
digit = checksumStr.substring(i, i + 1);
tmpNum = parseInt(digit, 10);
if (shouldDouble) {
tmpNum *= 2;
if (tmpNum >= 10) {
sum += tmpNum + 1;
} else {
sum += tmpNum;
}
} else {
sum += tmpNum;
}
shouldDouble = !shouldDouble;
}
return parseInt(str.substr(str.length - 1), 10) === (10000 - sum) % 10;
}
module.exports = exports['default'];
/***/ },
/* 222 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isISBN;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isbn10Maybe = /^(?:[0-9]{9}X|[0-9]{10})$/;
var isbn13Maybe = /^(?:[0-9]{13})$/;
var factor = [1, 3];
function isISBN(str) {
var version = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];
(0, _assertString2.default)(str);
version = String(version);
if (!version) {
return isISBN(str, 10) || isISBN(str, 13);
}
var sanitized = str.replace(/[\s-]+/g, '');
var checksum = 0;
var i = void 0;
if (version === '10') {
if (!isbn10Maybe.test(sanitized)) {
return false;
}
for (i = 0; i < 9; i++) {
checksum += (i + 1) * sanitized.charAt(i);
}
if (sanitized.charAt(9) === 'X') {
checksum += 10 * 10;
} else {
checksum += 10 * sanitized.charAt(9);
}
if (checksum % 11 === 0) {
return !!sanitized;
}
} else if (version === '13') {
if (!isbn13Maybe.test(sanitized)) {
return false;
}
for (i = 0; i < 12; i++) {
checksum += factor[i % 2] * sanitized.charAt(i);
}
if (sanitized.charAt(12) - (10 - checksum % 10) % 10 === 0) {
return !!sanitized;
}
}
return false;
}
module.exports = exports['default'];
/***/ },
/* 223 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isMobilePhone;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable max-len */
var phones = {
'ar-DZ': /^(\+?213|0)(5|6|7)\d{8}$/,
'ar-SY': /^(!?(\+?963)|0)?9\d{8}$/,
'ar-SA': /^(!?(\+?966)|0)?5\d{8}$/,
'en-US': /^(\+?1)?[2-9]\d{2}[2-9](?!11)\d{6}$/,
'cs-CZ': /^(\+?420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,
'de-DE': /^(\+?49[ \.\-])?([\(]{1}[0-9]{1,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/,
'da-DK': /^(\+?45)?(\d{8})$/,
'el-GR': /^(\+?30)?(69\d{8})$/,
'en-AU': /^(\+?61|0)4\d{8}$/,
'en-GB': /^(\+?44|0)7\d{9}$/,
'en-HK': /^(\+?852\-?)?[569]\d{3}\-?\d{4}$/,
'en-IN': /^(\+?91|0)?[789]\d{9}$/,
'en-NZ': /^(\+?64|0)2\d{7,9}$/,
'en-ZA': /^(\+?27|0)\d{9}$/,
'en-ZM': /^(\+?26)?09[567]\d{7}$/,
'es-ES': /^(\+?34)?(6\d{1}|7[1234])\d{7}$/,
'fi-FI': /^(\+?358|0)\s?(4(0|1|2|4|5)?|50)\s?(\d\s?){4,8}\d$/,
'fr-FR': /^(\+?33|0)[67]\d{8}$/,
'hu-HU': /^(\+?36)(20|30|70)\d{7}$/,
'it-IT': /^(\+?39)?\s?3\d{2} ?\d{6,7}$/,
'ja-JP': /^(\+?81|0)\d{1,4}[ \-]?\d{1,4}[ \-]?\d{4}$/,
'ms-MY': /^(\+?6?01){1}(([145]{1}(\-|\s)?\d{7,8})|([236789]{1}(\s|\-)?\d{7}))$/,
'nb-NO': /^(\+?47)?[49]\d{7}$/,
'nl-BE': /^(\+?32|0)4?\d{8}$/,
'nn-NO': /^(\+?47)?[49]\d{7}$/,
'pl-PL': /^(\+?48)? ?[5-8]\d ?\d{3} ?\d{2} ?\d{2}$/,
'pt-BR': /^(\+?55|0)\-?[1-9]{2}\-?[2-9]{1}\d{3,4}\-?\d{4}$/,
'pt-PT': /^(\+?351)?9[1236]\d{7}$/,
'ru-RU': /^(\+?7|8)?9\d{9}$/,
'tr-TR': /^(\+?90|0)?5\d{9}$/,
'vi-VN': /^(\+?84|0)?((1(2([0-9])|6([2-9])|88|99))|(9((?!5)[0-9])))([0-9]{7})$/,
'zh-CN': /^(\+?0?86\-?)?1[345789]\d{9}$/,
'zh-TW': /^(\+?886\-?|0)?9\d{8}$/
};
/* eslint-enable max-len */
// aliases
phones['en-CA'] = phones['en-US'];
phones['fr-BE'] = phones['nl-BE'];
function isMobilePhone(str, locale) {
(0, _assertString2.default)(str);
if (locale in phones) {
return phones[locale].test(str);
}
return false;
}
module.exports = exports['default'];
/***/ },
/* 224 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isCurrency;
var _merge = __webpack_require__(184);
var _merge2 = _interopRequireDefault(_merge);
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function currencyRegex(options) {
var symbol = '(\\' + options.symbol.replace(/\./g, '\\.') + ')' + (options.require_symbol ? '' : '?'),
negative = '-?',
whole_dollar_amount_without_sep = '[1-9]\\d*',
whole_dollar_amount_with_sep = '[1-9]\\d{0,2}(\\' + options.thousands_separator + '\\d{3})*',
valid_whole_dollar_amounts = ['0', whole_dollar_amount_without_sep, whole_dollar_amount_with_sep],
whole_dollar_amount = '(' + valid_whole_dollar_amounts.join('|') + ')?',
decimal_amount = '(\\' + options.decimal_separator + '\\d{2})?';
var pattern = whole_dollar_amount + decimal_amount;
// default is negative sign before symbol, but there are two other options (besides parens)
if (options.allow_negatives && !options.parens_for_negatives) {
if (options.negative_sign_after_digits) {
pattern += negative;
} else if (options.negative_sign_before_digits) {
pattern = negative + pattern;
}
}
// South African Rand, for example, uses R 123 (space) and R-123 (no space)
if (options.allow_negative_sign_placeholder) {
pattern = '( (?!\\-))?' + pattern;
} else if (options.allow_space_after_symbol) {
pattern = ' ?' + pattern;
} else if (options.allow_space_after_digits) {
pattern += '( (?!$))?';
}
if (options.symbol_after_digits) {
pattern += symbol;
} else {
pattern = symbol + pattern;
}
if (options.allow_negatives) {
if (options.parens_for_negatives) {
pattern = '(\\(' + pattern + '\\)|' + pattern + ')';
} else if (!(options.negative_sign_before_digits || options.negative_sign_after_digits)) {
pattern = negative + pattern;
}
}
/* eslint-disable prefer-template */
return new RegExp('^' +
// ensure there's a dollar and/or decimal amount, and that
// it doesn't start with a space or a negative sign followed by a space
'(?!-? )(?=.*\\d)' + pattern + '$');
/* eslint-enable prefer-template */
}
var default_currency_options = {
symbol: '$',
require_symbol: false,
allow_space_after_symbol: false,
symbol_after_digits: false,
allow_negatives: true,
parens_for_negatives: false,
negative_sign_before_digits: false,
negative_sign_after_digits: false,
allow_negative_sign_placeholder: false,
thousands_separator: ',',
decimal_separator: '.',
allow_space_after_digits: false
};
function isCurrency(str, options) {
(0, _assertString2.default)(str);
options = (0, _merge2.default)(options, default_currency_options);
return currencyRegex(options).test(str);
}
module.exports = exports['default'];
/***/ },
/* 225 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isBase64;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var notBase64 = /[^A-Z0-9+\/=]/i;
function isBase64(str) {
(0, _assertString2.default)(str);
var len = str.length;
if (!len || len % 4 !== 0 || notBase64.test(str)) {
return false;
}
var firstPaddingChar = str.indexOf('=');
return firstPaddingChar === -1 || firstPaddingChar === len - 1 || firstPaddingChar === len - 2 && str[len - 1] === '=';
}
module.exports = exports['default'];
/***/ },
/* 226 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isDataURI;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var dataURI = /^\s*data:([a-z]+\/[a-z0-9\-\+]+(;[a-z\-]+=[a-z0-9\-]+)?)?(;base64)?,[a-z0-9!\$&',\(\)\*\+,;=\-\._~:@\/\?%\s]*\s*$/i; // eslint-disable-line max-len
function isDataURI(str) {
(0, _assertString2.default)(str);
return dataURI.test(str);
}
module.exports = exports['default'];
/***/ },
/* 227 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = ltrim;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function ltrim(str, chars) {
(0, _assertString2.default)(str);
var pattern = chars ? new RegExp('^[' + chars + ']+', 'g') : /^\s+/g;
return str.replace(pattern, '');
}
module.exports = exports['default'];
/***/ },
/* 228 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = rtrim;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function rtrim(str, chars) {
(0, _assertString2.default)(str);
var pattern = chars ? new RegExp('[' + chars + ']') : /\s/;
var idx = str.length - 1;
while (idx >= 0 && pattern.test(str[idx])) {
idx--;
}
return idx < str.length ? str.substr(0, idx + 1) : str;
}
module.exports = exports['default'];
/***/ },
/* 229 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = trim;
var _rtrim = __webpack_require__(228);
var _rtrim2 = _interopRequireDefault(_rtrim);
var _ltrim = __webpack_require__(227);
var _ltrim2 = _interopRequireDefault(_ltrim);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function trim(str, chars) {
return (0, _rtrim2.default)((0, _ltrim2.default)(str, chars), chars);
}
module.exports = exports['default'];
/***/ },
/* 230 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = escape;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function escape(str) {
(0, _assertString2.default)(str);
return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>').replace(/\//g, '/').replace(/`/g, '`');
}
module.exports = exports['default'];
/***/ },
/* 231 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = unescape;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function unescape(str) {
(0, _assertString2.default)(str);
return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>').replace(///g, '/').replace(/`/g, '`');
}
module.exports = exports['default'];
/***/ },
/* 232 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = stripLow;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
var _blacklist = __webpack_require__(233);
var _blacklist2 = _interopRequireDefault(_blacklist);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function stripLow(str, keep_new_lines) {
(0, _assertString2.default)(str);
var chars = keep_new_lines ? '\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F' : '\\x00-\\x1F\\x7F';
return (0, _blacklist2.default)(str, chars);
}
module.exports = exports['default'];
/***/ },
/* 233 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = blacklist;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function blacklist(str, chars) {
(0, _assertString2.default)(str);
return str.replace(new RegExp('[' + chars + ']+', 'g'), '');
}
module.exports = exports['default'];
/***/ },
/* 234 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = whitelist;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function whitelist(str, chars) {
(0, _assertString2.default)(str);
return str.replace(new RegExp('[^' + chars + ']+', 'g'), '');
}
module.exports = exports['default'];
/***/ },
/* 235 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isWhitelisted;
var _assertString = __webpack_require__(175);
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isWhitelisted(str, chars) {
(0, _assertString2.default)(str);
for (var i = str.length - 1; i >= 0; i--) {
if (chars.indexOf(str[i]) === -1) {
return false;
}
}
return true;
}
module.exports = exports['default'];
/***/ },
/* 236 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = normalizeEmail;
var _isEmail = __webpack_require__(183);
var _isEmail2 = _interopRequireDefault(_isEmail);
var _merge = __webpack_require__(184);
var _merge2 = _interopRequireDefault(_merge);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var default_normalize_email_options = {
lowercase: true,
remove_dots: true,
remove_extension: true
};
function normalizeEmail(email, options) {
options = (0, _merge2.default)(options, default_normalize_email_options);
if (!(0, _isEmail2.default)(email)) {
return false;
}
var parts = email.split('@', 2);
parts[1] = parts[1].toLowerCase();
if (parts[1] === 'gmail.com' || parts[1] === 'googlemail.com') {
if (options.remove_extension) {
parts[0] = parts[0].split('+')[0];
}
if (options.remove_dots) {
parts[0] = parts[0].replace(/\./g, '');
}
if (!parts[0].length) {
return false;
}
parts[0] = parts[0].toLowerCase();
parts[1] = 'gmail.com';
} else if (options.lowercase) {
parts[0] = parts[0].toLowerCase();
}
return parts.join('@');
}
module.exports = exports['default'];
/***/ },
/* 237 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
__webpack_require__(238);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var DownloadForm = function (_Component) {
_inherits(DownloadForm, _Component);
function DownloadForm() {
_classCallCheck(this, DownloadForm);
return _possibleConstructorReturn(this, (DownloadForm.__proto__ || Object.getPrototypeOf(DownloadForm)).apply(this, arguments));
}
_createClass(DownloadForm, [{
key: 'componentDidMount',
value: function componentDidMount() {}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(
'form',
{ className: 'downloadForm', onSubmit: this.props.onSubmit },
_react2.default.createElement('input', { className: 'downloadForm__input', type: 'text' }),
_react2.default.createElement(
'button',
{ className: 'downloadForm__btn' },
'\u25B6'
)
);
}
}]);
return DownloadForm;
}(_react.Component);
DownloadForm.propTypes = {
onSubmit: _react.PropTypes.func
};
exports.default = DownloadForm;
/***/ },
/* 238 */
/***/ function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__(239);
if(typeof content === 'string') content = [[module.id, content, '']];
// add the styles to the DOM
var update = __webpack_require__(241)(content, {});
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
// When the styles change, update the <style> tags
if(!content.locals) {
module.hot.accept("!!./../../node_modules/css-loader/index.js!./../../node_modules/postcss-loader/index.js!./../../node_modules/sass-loader/index.js!./DownloadForm.scss", function() {
var newContent = require("!!./../../node_modules/css-loader/index.js!./../../node_modules/postcss-loader/index.js!./../../node_modules/sass-loader/index.js!./DownloadForm.scss");
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
update(newContent);
});
}
// When the module is disposed, remove the <style> tags
module.hot.dispose(function() { update(); });
}
/***/ },
/* 239 */
/***/ function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(240)();
// imports
exports.push([module.id, "@import url(path_to_url", ""]);
// module
exports.push([module.id, "* {\n margin: 0;\n padding: 0; }\n\nbody {\n background: #202530;\n color: #eeffff;\n font-family: 'Open Sans', sans-serif; }\n\n.spinner {\n margin-left: auto;\n margin-top: -3px;\n text-align: center;\n width: 60px; }\n\n.spinner > div {\n animation: sk-bouncedelay 1.4s infinite ease-in-out both;\n background-color: #d3d0c8;\n border-radius: 100%;\n display: inline-block;\n height: 8px;\n margin-left: 5px;\n width: 8px; }\n\n.spinner .bounce1 {\n animation-delay: -0.32s; }\n\n.spinner .bounce2 {\n animation-delay: -0.16s; }\n\n@keyframes sk-bouncedelay {\n 0%, 80%, 100% {\n transform: scale(0); }\n 40% {\n transform: scale(1); } }\n\n.downloadForm {\n align-items: center;\n display: flex;\n justify-content: center;\n width: 100%; }\n .downloadForm__input {\n border: none;\n border-radius: 2px;\n box-shadow: 0 0 5px #282828;\n outline: none;\n appearance: none;\n flex: 0 1 500px;\n font-size: 16px;\n height: 20px;\n margin-right: 10px;\n padding: 10px; }\n .downloadForm__input--error {\n border: 1px solid #cc181e;\n color: #cc181e; }\n .downloadForm__btn {\n border: none;\n border-radius: 2px;\n box-shadow: 0 0 5px #282828;\n outline: none;\n background-color: #cc181e;\n color: #eeffff;\n flex: 0 0 70px;\n font-family: 'Open Sans', sans-serif;\n font-size: 18px;\n height: 40px;\n padding-bottom: 3px;\n outline: none; }\n .downloadForm__btn:active {\n background-color: #9e1317; }\n", ""]);
// exports
/***/ },
/* 240 */
/***/ function(module, exports) {
/*
Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
module.exports = function() {
var list = [];
// return the list of modules as css string
list.toString = function toString() {
var result = [];
for(var i = 0; i < this.length; i++) {
var item = this[i];
if(item[2]) {
result.push("@media " + item[2] + "{" + item[1] + "}");
} else {
result.push(item[1]);
}
}
return result.join("");
};
// import a list of modules into the list
list.i = function(modules, mediaQuery) {
if(typeof modules === "string")
modules = [[null, modules, ""]];
var alreadyImportedModules = {};
for(var i = 0; i < this.length; i++) {
var id = this[i][0];
if(typeof id === "number")
alreadyImportedModules[id] = true;
}
for(i = 0; i < modules.length; i++) {
var item = modules[i];
// skip already imported module
// this implementation is not 100% perfect for weird media query combinations
// when a module is imported multiple times with different media queries.
// I hope this will never occur (Hey this way we have smaller bundles)
if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) {
if(mediaQuery && !item[2]) {
item[2] = mediaQuery;
} else if(mediaQuery) {
item[2] = "(" + item[2] + ") and (" + mediaQuery + ")";
}
list.push(item);
}
}
};
return list;
};
/***/ },
/* 241 */
/***/ function(module, exports, __webpack_require__) {
/*
Author Tobias Koppers @sokra
*/
var stylesInDom = {},
memoize = function(fn) {
var memo;
return function () {
if (typeof memo === "undefined") memo = fn.apply(this, arguments);
return memo;
};
},
isOldIE = memoize(function() {
return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase());
}),
getHeadElement = memoize(function () {
return document.head || document.getElementsByTagName("head")[0];
}),
singletonElement = null,
singletonCounter = 0,
styleElementsInsertedAtTop = [];
module.exports = function(list, options) {
if(false) {
if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
}
options = options || {};
// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
// tags it will allow on a page
if (typeof options.singleton === "undefined") options.singleton = isOldIE();
// By default, add <style> tags to the bottom of <head>.
if (typeof options.insertAt === "undefined") options.insertAt = "bottom";
var styles = listToStyles(list);
addStylesToDom(styles, options);
return function update(newList) {
var mayRemove = [];
for(var i = 0; i < styles.length; i++) {
var item = styles[i];
var domStyle = stylesInDom[item.id];
domStyle.refs--;
mayRemove.push(domStyle);
}
if(newList) {
var newStyles = listToStyles(newList);
addStylesToDom(newStyles, options);
}
for(var i = 0; i < mayRemove.length; i++) {
var domStyle = mayRemove[i];
if(domStyle.refs === 0) {
for(var j = 0; j < domStyle.parts.length; j++)
domStyle.parts[j]();
delete stylesInDom[domStyle.id];
}
}
};
}
function addStylesToDom(styles, options) {
for(var i = 0; i < styles.length; i++) {
var item = styles[i];
var domStyle = stylesInDom[item.id];
if(domStyle) {
domStyle.refs++;
for(var j = 0; j < domStyle.parts.length; j++) {
domStyle.parts[j](item.parts[j]);
}
for(; j < item.parts.length; j++) {
domStyle.parts.push(addStyle(item.parts[j], options));
}
} else {
var parts = [];
for(var j = 0; j < item.parts.length; j++) {
parts.push(addStyle(item.parts[j], options));
}
stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
}
}
}
function listToStyles(list) {
var styles = [];
var newStyles = {};
for(var i = 0; i < list.length; i++) {
var item = list[i];
var id = item[0];
var css = item[1];
var media = item[2];
var sourceMap = item[3];
var part = {css: css, media: media, sourceMap: sourceMap};
if(!newStyles[id])
styles.push(newStyles[id] = {id: id, parts: [part]});
else
newStyles[id].parts.push(part);
}
return styles;
}
function insertStyleElement(options, styleElement) {
var head = getHeadElement();
var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1];
if (options.insertAt === "top") {
if(!lastStyleElementInsertedAtTop) {
head.insertBefore(styleElement, head.firstChild);
} else if(lastStyleElementInsertedAtTop.nextSibling) {
head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling);
} else {
head.appendChild(styleElement);
}
styleElementsInsertedAtTop.push(styleElement);
} else if (options.insertAt === "bottom") {
head.appendChild(styleElement);
} else {
throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");
}
}
function removeStyleElement(styleElement) {
styleElement.parentNode.removeChild(styleElement);
var idx = styleElementsInsertedAtTop.indexOf(styleElement);
if(idx >= 0) {
styleElementsInsertedAtTop.splice(idx, 1);
}
}
function createStyleElement(options) {
var styleElement = document.createElement("style");
styleElement.type = "text/css";
insertStyleElement(options, styleElement);
return styleElement;
}
function createLinkElement(options) {
var linkElement = document.createElement("link");
linkElement.rel = "stylesheet";
insertStyleElement(options, linkElement);
return linkElement;
}
function addStyle(obj, options) {
var styleElement, update, remove;
if (options.singleton) {
var styleIndex = singletonCounter++;
styleElement = singletonElement || (singletonElement = createStyleElement(options));
update = applyToSingletonTag.bind(null, styleElement, styleIndex, false);
remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true);
} else if(obj.sourceMap &&
typeof URL === "function" &&
typeof URL.createObjectURL === "function" &&
typeof URL.revokeObjectURL === "function" &&
typeof Blob === "function" &&
typeof btoa === "function") {
styleElement = createLinkElement(options);
update = updateLink.bind(null, styleElement);
remove = function() {
removeStyleElement(styleElement);
if(styleElement.href)
URL.revokeObjectURL(styleElement.href);
};
} else {
styleElement = createStyleElement(options);
update = applyToTag.bind(null, styleElement);
remove = function() {
removeStyleElement(styleElement);
};
}
update(obj);
return function updateStyle(newObj) {
if(newObj) {
if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap)
return;
update(obj = newObj);
} else {
remove();
}
};
}
var replaceText = (function () {
var textStore = [];
return function (index, replacement) {
textStore[index] = replacement;
return textStore.filter(Boolean).join('\n');
};
})();
function applyToSingletonTag(styleElement, index, remove, obj) {
var css = remove ? "" : obj.css;
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = replaceText(index, css);
} else {
var cssNode = document.createTextNode(css);
var childNodes = styleElement.childNodes;
if (childNodes[index]) styleElement.removeChild(childNodes[index]);
if (childNodes.length) {
styleElement.insertBefore(cssNode, childNodes[index]);
} else {
styleElement.appendChild(cssNode);
}
}
}
function applyToTag(styleElement, obj) {
var css = obj.css;
var media = obj.media;
if(media) {
styleElement.setAttribute("media", media)
}
if(styleElement.styleSheet) {
styleElement.styleSheet.cssText = css;
} else {
while(styleElement.firstChild) {
styleElement.removeChild(styleElement.firstChild);
}
styleElement.appendChild(document.createTextNode(css));
}
}
function updateLink(linkElement, obj) {
var css = obj.css;
var sourceMap = obj.sourceMap;
if(sourceMap) {
// path_to_url
css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
}
var blob = new Blob([css], { type: "text/css" });
var oldSrc = linkElement.href;
linkElement.href = URL.createObjectURL(blob);
if(oldSrc)
URL.revokeObjectURL(oldSrc);
}
/***/ },
/* 242 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
__webpack_require__(243);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var DownloadList = function (_Component) {
_inherits(DownloadList, _Component);
function DownloadList() {
_classCallCheck(this, DownloadList);
return _possibleConstructorReturn(this, (DownloadList.__proto__ || Object.getPrototypeOf(DownloadList)).apply(this, arguments));
}
_createClass(DownloadList, [{
key: 'componentDidMount',
value: function componentDidMount() {}
}, {
key: 'render',
value: function render() {
var _this2 = this;
return _react2.default.createElement(
'ul',
{ className: 'downloadList' },
this.props.videos.map(function (video, index) {
return _react2.default.createElement(
'li',
{ key: index, className: 'downloadList__item' },
_react2.default.createElement(
'span',
{ className: 'video__name' },
video.name
),
video.downloading ? _react2.default.createElement(
'div',
{ className: 'spinner' },
_react2.default.createElement('div', { className: 'bounce1' }),
_react2.default.createElement('div', { className: 'bounce2' }),
_react2.default.createElement('div', { className: 'bounce3' })
) : _react2.default.createElement(
'span',
{ className: 'video__link' },
_react2.default.createElement(
'a',
{
onClick: _this2.props.onVideoDownloadClick,
'data-orig': video.url,
href: '/request/' + video.name + '.' + video.format,
download: video.name + '.' + video.format
},
'Download'
)
)
);
}),
this.props.videos.length === 0 ? '' : _react2.default.createElement(
'li',
{ className: 'downloadList__clear', onClick: this.props.onClearClick },
'Clear all'
)
);
}
}]);
return DownloadList;
}(_react.Component);
DownloadList.propTypes = {
videos: _react.PropTypes.array,
onClearClick: _react.PropTypes.func,
onVideoDownloadClick: _react.PropTypes.func
};
exports.default = DownloadList;
/***/ },
/* 243 */
/***/ function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__(244);
if(typeof content === 'string') content = [[module.id, content, '']];
// add the styles to the DOM
var update = __webpack_require__(241)(content, {});
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
// When the styles change, update the <style> tags
if(!content.locals) {
module.hot.accept("!!./../../node_modules/css-loader/index.js!./../../node_modules/postcss-loader/index.js!./../../node_modules/sass-loader/index.js!./DownloadList.scss", function() {
var newContent = require("!!./../../node_modules/css-loader/index.js!./../../node_modules/postcss-loader/index.js!./../../node_modules/sass-loader/index.js!./DownloadList.scss");
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
update(newContent);
});
}
// When the module is disposed, remove the <style> tags
module.hot.dispose(function() { update(); });
}
/***/ },
/* 244 */
/***/ function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(240)();
// imports
exports.push([module.id, "@import url(path_to_url", ""]);
// module
exports.push([module.id, "* {\n margin: 0;\n padding: 0; }\n\nbody {\n background: #202530;\n color: #eeffff;\n font-family: 'Open Sans', sans-serif; }\n\n.spinner {\n margin-left: auto;\n margin-top: -3px;\n text-align: center;\n width: 60px; }\n\n.spinner > div {\n animation: sk-bouncedelay 1.4s infinite ease-in-out both;\n background-color: #d3d0c8;\n border-radius: 100%;\n display: inline-block;\n height: 8px;\n margin-left: 5px;\n width: 8px; }\n\n.spinner .bounce1 {\n animation-delay: -0.32s; }\n\n.spinner .bounce2 {\n animation-delay: -0.16s; }\n\n@keyframes sk-bouncedelay {\n 0%, 80%, 100% {\n transform: scale(0); }\n 40% {\n transform: scale(1); } }\n\n.downloadList {\n border: none;\n border-radius: 2px;\n box-shadow: 0 0 5px #282828;\n outline: none;\n background: #2f343f;\n display: flex;\n flex: 0 1 600px;\n flex-wrap: wrap;\n list-style-type: none;\n margin-top: 20px;\n max-height: 80%;\n overflow-y: auto;\n position: relative; }\n .downloadList__item {\n display: flex;\n flex: 1 0 300px;\n padding: 10px;\n width: 100%; }\n .downloadList__clear {\n background: #2f343f;\n border-top: 1px solid #202530;\n color: #d3d0c8;\n padding: 5px;\n text-align: center;\n width: 100%; }\n .downloadList__clear:hover {\n background: #2b2f39;\n cursor: pointer; }\n .downloadList::-webkit-scrollbar {\n width: 8px; }\n .downloadList::-webkit-scrollbar-track {\n background: #2f343f; }\n .downloadList::-webkit-scrollbar-thumb {\n background: #1c202a; }\n\n.video__name {\n color: #d3d0c8;\n word-break: break-all;\n word-wrap: break-word; }\n\n.video__link {\n font-size: 14px;\n margin-left: auto; }\n .video__link a {\n color: #d3d0c8;\n text-decoration: none; }\n .video__link a:hover {\n text-decoration: underline; }\n .video__link a:visited {\n color: #d3d0c8; }\n", ""]);
// exports
/***/ },
/* 245 */
/***/ function(module, exports) {
'use strict';
/* global XMLHttpRequest */
function get(url) {
// Return a new promise.
return new Promise(function (resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.onload = function () {
// This is called even on 404 etc
// so check the status
if (req.status === 200) {
// Resolve the promise with the response text
resolve(JSON.parse(req.response));
} else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function () {
reject(Error('Network Error'));
};
// Make the request
req.send();
});
}
function post(url, params) {
// Return a new promise.
return new Promise(function (resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('POST', url);
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.onload = function () {
// This is called even on 404 etc
// so check the status
if (req.status === 200) {
// Resolve the promise with the response text
resolve(JSON.parse(req.response));
} else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function () {
reject(Error('Network Error'));
};
// Make the request
req.send(params);
});
}
module.exports = {
get: get,
post: post
};
/***/ },
/* 246 */
/***/ function(module, exports) {
"use strict";
/* global localStorage */
function getItem(key) {
return JSON.parse(localStorage.getItem(key));
}
function setItem(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
function removeItem(key) {
localStorage.removeItem(key);
}
module.exports = {
getItem: getItem,
setItem: setItem,
removeItem: removeItem
};
/***/ },
/* 247 */
/***/ function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__(248);
if(typeof content === 'string') content = [[module.id, content, '']];
// add the styles to the DOM
var update = __webpack_require__(241)(content, {});
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
// When the styles change, update the <style> tags
if(!content.locals) {
module.hot.accept("!!./../../node_modules/css-loader/index.js!./../../node_modules/postcss-loader/index.js!./../../node_modules/sass-loader/index.js!./DownloadPanel.scss", function() {
var newContent = require("!!./../../node_modules/css-loader/index.js!./../../node_modules/postcss-loader/index.js!./../../node_modules/sass-loader/index.js!./DownloadPanel.scss");
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
update(newContent);
});
}
// When the module is disposed, remove the <style> tags
module.hot.dispose(function() { update(); });
}
/***/ },
/* 248 */
/***/ function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(240)();
// imports
exports.push([module.id, "@import url(path_to_url", ""]);
// module
exports.push([module.id, "* {\n margin: 0;\n padding: 0; }\n\nbody {\n background: #202530;\n color: #eeffff;\n font-family: 'Open Sans', sans-serif; }\n\n.spinner {\n margin-left: auto;\n margin-top: -3px;\n text-align: center;\n width: 60px; }\n\n.spinner > div {\n animation: sk-bouncedelay 1.4s infinite ease-in-out both;\n background-color: #d3d0c8;\n border-radius: 100%;\n display: inline-block;\n height: 8px;\n margin-left: 5px;\n width: 8px; }\n\n.spinner .bounce1 {\n animation-delay: -0.32s; }\n\n.spinner .bounce2 {\n animation-delay: -0.16s; }\n\n@keyframes sk-bouncedelay {\n 0%, 80%, 100% {\n transform: scale(0); }\n 40% {\n transform: scale(1); } }\n\n.downloadPanel {\n align-content: center;\n align-items: flex-center;\n display: flex;\n flex-wrap: wrap;\n height: 100vh;\n justify-content: center;\n padding: 0 20px; }\n", ""]);
// exports
/***/ },
/* 249 */
/***/ function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__(250);
if(typeof content === 'string') content = [[module.id, content, '']];
// add the styles to the DOM
var update = __webpack_require__(241)(content, {});
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
// When the styles change, update the <style> tags
if(!content.locals) {
module.hot.accept("!!./../../node_modules/css-loader/index.js!./../../node_modules/postcss-loader/index.js!./../../node_modules/sass-loader/index.js!./shared.scss", function() {
var newContent = require("!!./../../node_modules/css-loader/index.js!./../../node_modules/postcss-loader/index.js!./../../node_modules/sass-loader/index.js!./shared.scss");
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
update(newContent);
});
}
// When the module is disposed, remove the <style> tags
module.hot.dispose(function() { update(); });
}
/***/ },
/* 250 */
/***/ function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(240)();
// imports
exports.push([module.id, "@import url(path_to_url", ""]);
// module
exports.push([module.id, "* {\n margin: 0;\n padding: 0; }\n\nbody {\n background: #202530;\n color: #eeffff;\n font-family: 'Open Sans', sans-serif; }\n\n.spinner {\n margin-left: auto;\n margin-top: -3px;\n text-align: center;\n width: 60px; }\n\n.spinner > div {\n animation: sk-bouncedelay 1.4s infinite ease-in-out both;\n background-color: #d3d0c8;\n border-radius: 100%;\n display: inline-block;\n height: 8px;\n margin-left: 5px;\n width: 8px; }\n\n.spinner .bounce1 {\n animation-delay: -0.32s; }\n\n.spinner .bounce2 {\n animation-delay: -0.16s; }\n\n@keyframes sk-bouncedelay {\n 0%, 80%, 100% {\n transform: scale(0); }\n 40% {\n transform: scale(1); } }\n", ""]);
// exports
/***/ }
/******/ ]);
``` | /content/code_sandbox/public/bundle.js | javascript | 2016-05-27T07:59:24 | 2024-08-14T13:07:59 | ytdl-webserver | Algram/ytdl-webserver | 1,436 | 197,723 |
```yaml
line_length:
warning: 120
``` | /content/code_sandbox/.swiftlint.yml | yaml | 2016-01-19T19:49:55 | 2024-08-10T21:10:40 | Reusable | AliSoftware/Reusable | 2,999 | 10 |
```ruby
Pod::Spec.new do |s|
s.cocoapods_version = '~> 1.4'
s.name = "Reusable"
s.version = "4.1.2"
s.summary = "A Swift Mixin to deal with reusable UITableView & UICollectionView cells and XIB-based views"
s.description = <<-DESC
Reusable is a [Swift Mixin](path_to_url
to easily deal with your reusable UITableViewCell and UICollectionViewCell classes.
Simply mark your `UITableViewCell` or `UICollectionViewCell` sublcasses as
conforming to either `Reusable` or `NibReusable` and you'll be able to
manipulate them way easier, and without worrying with String-type reuseIdentifiers
ever again, and instead use them in a type-safe manner!
Reusable also support marking any arbitrary `UIView` subclass as `NibLoadable` so that
you can then call `loadFromNib()` on the custom view class easily without adding any code.
For more info, see [my blog post](path_to_url
about this technique.
DESC
s.homepage = "path_to_url"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Olivier Halligon" => "olivier@halligon.net" }
s.social_media_url = "path_to_url"
s.ios.deployment_target = "9.0"
s.tvos.deployment_target = "9.0"
s.source = { :git => "path_to_url", :tag => s.version.to_s }
s.swift_version = '5.0'
s.subspec 'View' do |ss|
ss.source_files = "Sources/View/*.swift"
end
s.subspec 'Storyboard' do |ss|
ss.source_files = "Sources/Storyboard/*.swift"
end
s.framework = "UIKit"
end
``` | /content/code_sandbox/Reusable.podspec | ruby | 2016-01-19T19:49:55 | 2024-08-10T21:10:40 | Reusable | AliSoftware/Reusable | 2,999 | 422 |
```swift
// swift-tools-version:5.4
import PackageDescription
let package = Package(
name: "Reusable",
platforms: [.iOS(.v9), .tvOS(.v9)],
products: [
.library(name: "Reusable", targets: ["Reusable"])
],
targets: [
.target(
name: "Reusable",
path: "Sources"
)
],
swiftLanguageVersions: [.v4, .v5]
)
``` | /content/code_sandbox/Package.swift | swift | 2016-01-19T19:49:55 | 2024-08-10T21:10:40 | Reusable | AliSoftware/Reusable | 2,999 | 98 |
```yaml
opt_in_rules:
- empty_count
included:
- ../Sources
- ReusableDemo
line_length:
warning: 120
error: 160
``` | /content/code_sandbox/Example/.swiftlint.yml | yaml | 2016-01-19T19:49:55 | 2024-08-10T21:10:40 | Reusable | AliSoftware/Reusable | 2,999 | 38 |
```json
PODS:
- Reusable (4.1.2):
- Reusable/Storyboard (= 4.1.2)
- Reusable/View (= 4.1.2)
- Reusable/Storyboard (4.1.2)
- Reusable/View (4.1.2)
DEPENDENCIES:
- Reusable (from `../`)
EXTERNAL SOURCES:
Reusable:
:path: "../"
SPEC CHECKSUMS:
Reusable: 6bae6a5e8aa793c9c441db0213c863a64bce9136
PODFILE CHECKSUM: ae97c8d84b9148534471b041a33cec1ba3620b65
COCOAPODS: 1.11.0
``` | /content/code_sandbox/Example/Pods/Manifest.lock | json | 2016-01-19T19:49:55 | 2024-08-10T21:10:40 | Reusable | AliSoftware/Reusable | 2,999 | 174 |
```objective-c
#import <Foundation/Foundation.h>
@interface PodsDummy_Reusable_tvOS : NSObject
@end
@implementation PodsDummy_Reusable_tvOS
@end
``` | /content/code_sandbox/Example/Pods/Target Support Files/Reusable-tvOS/Reusable-tvOS-dummy.m | objective-c | 2016-01-19T19:49:55 | 2024-08-10T21:10:40 | Reusable | AliSoftware/Reusable | 2,999 | 27 |
```objective-c
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
FOUNDATION_EXPORT double ReusableVersionNumber;
FOUNDATION_EXPORT const unsigned char ReusableVersionString[];
``` | /content/code_sandbox/Example/Pods/Target Support Files/Reusable-tvOS/Reusable-tvOS-umbrella.h | objective-c | 2016-01-19T19:49:55 | 2024-08-10T21:10:40 | Reusable | AliSoftware/Reusable | 2,999 | 64 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.