-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathless_js.php
More file actions
215 lines (176 loc) · 6.93 KB
/
less_js.php
File metadata and controls
215 lines (176 loc) · 6.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
<?php
/**
* Plugin Name: Less.js in Wordpress
* Plugin URI: https://github.com/dryane/Less.js-In-Wordpress
* Description: Allows you to enqueue <code>.less</code> files and have them automatically compiled whenever a change is detected.
* Author: Daniel Joseph Ryan
* Version: 1.4
* Author URI: https://danieljosephryan.com/
* License: MIT
*/
// Busted! No direct file access
! defined( 'ABSPATH' ) AND exit;
if ( ! class_exists( 'less_js' ) ) {
add_action( 'init', array( 'less_js', 'instance' ) );
class less_js {
protected static $instance = null;
/**
* Creates a new instance. Called on 'after_setup_theme'.
* May be used to access class methods from outside.
*
* @see __construct()
* @static
* @return \less_js
*/
public static function instance() {
null === self:: $instance AND self:: $instance = new self;
return self:: $instance;
}
public $alwaysCompile = false;
public $directory = "/less-css/";
public $lessLink = "https://cdnjs.cloudflare.com/ajax/libs/less.js/3.7.1/less.min.js";
public $minify = true;
public $enqueuedBefore = false;
public $vars = array();
/**
* Constructor
*/
public function __construct() {
add_filter( 'style_loader_tag', array( $this,'parse_enqueued_style'), 10, 4 );
add_action( 'wp_ajax_save_less', array( $this,'save_less') );
add_action( 'wp_ajax_nopriv_save_less', array( $this,'save_less') );
add_action( 'customize_save_after', array( $this,'delete_less') );
}
public function parse_enqueued_style( $html, $handle, $href, $media ) {
if ( !strpos($html, '.less') ) { // If not .less
return $html;
}
$serverCSSFile = $this->get_cache_dir(true) . $handle . ".css";
if ( file_exists( $serverCSSFile ) ) {
$exists = true;
} else {
$exists = false;
}
$serverLESSFile = $_SERVER['DOCUMENT_ROOT'] . str_replace( get_site_url() , "", $href);
$modTime = filemtime($serverLESSFile);
if (get_option("less-js-".$handle) == $modTime) {
$unchanged = true;
} else {
$unchanged = false;
}
if ($exists && $unchanged && !$this->alwaysCompile){ // is cached
$html = str_replace($href,$this->get_cache_dir() . $handle . ".css",$html);
return $html;
} else {
$html = str_replace("rel='stylesheet'",'rel="stylesheet/less"',$html);
$this->enqueue_less_scripts();
return $html;
}
}
public function variables() {
/**
* How to Add More vars
* variable names MUST be lowercase letters only
* add_filter( 'less_vars', 'my_less_vars', 10, 2 );
* function my_less_vars( $vars, $handle ) {
* $vars[ 'black' ] = "#000";
* return $vars;
* }
*
**/
$this->vars['themeurl'] = '"' . get_stylesheet_directory_uri() . '"';
$this->vars['themedirectory'] = '"' . get_stylesheet_directory() . '"';
$this->vars['parenturl'] = '"' . get_template_directory_uri() . '"';
$this->vars['parentdirectory'] = '"' . get_template_directory() . '"';
$this->vars = apply_filters( 'less_vars', $this->vars, $handle );
$vars;
$values = $this->vars;
$keys = array_keys($this->vars);
for ($i = 0; $i < count($keys); $i++) {
$vars .= '\'' . $keys[$i] . '\':\'' . $values[$keys[$i]] . '\'';
if ($i + 1 != count($keys)) {
$vars .= ",";
}
}
return $vars;
}
public function enqueue_less_scripts() {
if ($this->enqueuedBefore) {
return;
}
$this->enqueuedBefore = true;
wp_enqueue_script( 'less-js', $this->lessLink, array('jquery') , null, false );
$vars = $this->variables();
$before_script = "var less = {env:'development',errorReporting:'console',globalVars:{ $vars }};";
wp_add_inline_script( 'less-js', $before_script, 'before' );
$after_script = <<<END
function sendLess(e){window.location.pathname.replace(RegExp("%","g"),"-").replace(RegExp("/","g"),"");var t=e.previousSibling.id.replace("-css",""),s=e.previousSibling.href,n=e.innerHTML,a={};a.name=t,a.href=s,a.css=n,jQuery.post(document.location.origin+"/wp-admin/admin-ajax.php",{action:"save_less",data:a})}document.querySelector("html").addEventListener("DOMNodeInserted",function(e){try{e.target.id.startsWith("less:")&&sendLess(e.target)}catch(e){}}),jQuery(document).ready(function(){style=document.querySelectorAll("head style");for(var e=0;e<style.length;e++)style[e].id.startsWith("less:")&&sendLess(style[e])});
END;
if (!$this->alwaysCompile) {
wp_add_inline_script( 'less-js', $after_script, 'after' );
}
}
public function save_less() {
$data = $_POST['data'];
if ($this->minify) {
$css = $this->minifyCss($data['css']);
}
$my_file = $this->get_cache_dir(true) . $data['name'] . ".css";
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
fwrite($handle, stripslashes($css));
fclose($handle);
$serverLESSFile = $_SERVER['DOCUMENT_ROOT'] . str_replace( get_site_url() , "", $data['href']);
$modTime = filemtime($serverLESSFile);
update_option("less-js-".$data['name'], $modTime);
wp_die();
return;
}
public function delete_less() {
$server = $this->get_cache_dir(true);
if ( file_exists( $server ) ) {
$files = glob($server . '*');
foreach($files as $file){
if(is_file($file)){
unlink($file);
}
}
}
}
/** Helper Functions **/
public function get_cache_dir($returnServer = false) {
$server = get_stylesheet_directory() . $this->directory;
$baseurl = get_stylesheet_directory_uri() . $this->directory;
if ( ! file_exists( $server ) ) {
mkdir( $server );
}
if ($returnServer) {
return $server;
}
return $baseurl;
}
public function minifyCss($css) {
$css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
preg_match_all('/(\'[^\']*?\'|"[^"]*?")/ims', $css, $hit, PREG_PATTERN_ORDER);
for ($i=0; $i < count($hit[1]); $i++) {
$css = str_replace($hit[1][$i], '##########' . $i . '##########', $css);
}
$css = preg_replace('/;[\s\r\n\t]*?}[\s\r\n\t]*/ims', "}\r\n", $css);
$css = preg_replace('/;[\s\r\n\t]*?([\r\n]?[^\s\r\n\t])/ims', ';$1', $css);
$css = preg_replace('/[\s\r\n\t]*:[\s\r\n\t]*?([^\s\r\n\t])/ims', ':$1', $css);
$css = preg_replace('/[\s\r\n\t]*,[\s\r\n\t]*?([^\s\r\n\t])/ims', ',$1', $css);
$css = preg_replace('/[\s\r\n\t]*>[\s\r\n\t]*?([^\s\r\n\t])/ims', '>$1', $css);
$css = preg_replace('/[\s\r\n\t]*\+[\s\r\n\t]*?([^\s\r\n\t])/ims', '+$1', $css);
$css = preg_replace('/[\s\r\n\t]*{[\s\r\n\t]*?([^\s\r\n\t])/ims', '{$1', $css);
$css = preg_replace('/([\d\.]+)[\s\r\n\t]+(px|em|pt|%)/ims', '$1$2', $css);
$css = preg_replace('/([^\d\.]0)(px|em|pt|%)/ims', '$1', $css);
$css = preg_replace('/\p{Zs}+/ims',' ', $css);
$css = str_replace(array("\r\n", "\r", "\n"), '', $css);
for ($i=0; $i < count($hit[1]); $i++) {
$css = str_replace('##########' . $i . '##########', $hit[1][$i], $css);
}
return $css;
}
/** End Helper Functions **/
}
}
do_action( 'customize_save_after', $array );