-
Notifications
You must be signed in to change notification settings - Fork 2
/
demo.js
352 lines (292 loc) · 9.46 KB
/
demo.js
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
var htmlText;
var cellIndex;
function indentCSS(source) {
source = source.replace(/\*\//gi, '*/\n');
source = source.replace(/}/gi, '}\n');
source = source.replace(/{/gi, "{\n ");
source = source.replace(/;(?!})/gi, ";\n ");
source = source.replace(/;(?=})/gi, ";\n");
return source;
}
/**
* Try to fetch the config from the URL query string.
*/
function fetchConfig() {
var searchStr = window.location.search;
var query = searchStr.split("=")[1];
try {
return JSON.parse(window.atob(query));
} catch (error) {
console.warn('Could not fetch the config based on the URL. Proceeding with default config.');
return null;
}
}
function updateUrl(config) {
app.updateState({q:window.btoa(JSON.stringify(config || {}))});
}
var closeModal = function (el) {
$(el).closest(".pg-modal").attr('isopen','false');
}
var showEditJSONModal = function () {
// create the editor
var options = {
mode: 'code',
modes: ['code', 'tree']
};
var container = $("#configJSONContainer .json-editor");
if (typeof editor == 'undefined' && container.length) {
editor = new JSONEditor(container[0], options);
}
editor.set(config);
}
var saveEditedJSON = function (el) {
if (editor) {
try {
config = editor.get();
updateUrl(config);
closeModal(el);
//buildGrid();
//$("#jsonContainer").fadeOut();
} catch (error) {
createAlert("Error parsing provided JSON. Please fix the error(s) marked in red below. Please see console for more details.", $('#editor-error-container'), error.name);
}
}
}
function createAlert(html, $container, type){
var type = type || "Warning";
if(!$container){
$container = $(".alerts-container");
}
if(!html){
html = "Some features might behave differently in older browsers. Consider re-configuring your grid."
}
var $alert = $('<div>');
$alert.addClass('alert');
if (type == "Warning") {
$alert.addClass('alert-warning');
} else if (type == "Error") {
$alert.addClass('alert-danger');
}
// TODO: Remove setTimeout once https://github.com/WebReflection/wicked-elements/issues/9 is fixed.
setTimeout(function() {
$alert.attr('type', type);
$alert.attr('message', html);
}, 0);
$container.append($alert);
}
function stateChangeCallback(){
showWarnings();
var targetCellIndex = app.state.cell;
if(app.state.dialogOpen=='true' && app.state.cell !== undefined){
var targetCell = document.getElementById('grid').children[targetCellIndex];
if(targetCell){
targetCell.classList.add('selected-grid');
}
}
}
function showWarnings(){
if (!this.statusWarnings) {
return;
}
$(".alerts-container").html("");
// Auto placement warning
for(var i=0;i<config.cells.length;i++){
if((config.cells[i])&&(config.cells[i].colSpan>config.cols.length)){
createAlert(statusWarnings["auto-placement"]);
break;
}
}
// Grid template 'auto' warning
if(config.cols.join("").indexOf("auto")>=0 || config.rows.join("").indexOf("auto")>=0){
createAlert(statusWarnings["auto-grid-template"]);
}
// fit-content() warning
if(config.cols.join("").indexOf("fit-content")>=0){
createAlert(statusWarnings["fit-content"]);
}
// align-items warning
if(JSON.stringify(config).indexOf("align-items")>=0 || JSON.stringify(config).indexOf("justify-items")>=0){
createAlert(statusWarnings["grid-alignment"]);
}
// grid-gap warning
if(JSON.stringify(config).indexOf("-gap")>=0){
createAlert(statusWarnings["grid-gap"]);
}
//TODO:Additional warning scenarios can be added here.
// At last, update warnings count to be reflected in badge.
var alertsCount = $('.alerts-container .alert').length;
if (alertsCount) {
$('.help-tab').attr('count', alertsCount);
} else {
$('.help-tab').removeAttr('count');
}
}
var htmlExample = "";
var gridContainerClasses;
function getHTML() {
gridContainerClasses = $('#grid').attr('class');
$('#showCSS').html(powergrid.toCss(config));
htmlExample = '<!---<div class="' + gridContainerClasses+ '">\r\n ' + $("#grid").html().replace(/<\/[a-z]+>/g, "$&\r\n ").split(' ').reverse().join(" ").replace(" ","").split(" ").reverse().join(" ") + '</div>//-->';
$('#htmlEg').html(htmlExample);
}
var fullSource = "";
function getFullSource() {
var decoratorStyle = document.querySelector('style#decoratorStylesheet').innerHTML;
var gridStyle = powergrid.toCss(config);
fullSource = '<!---<!doctype html> \r\n<html>\r\n<head>\r\n<style id="decoratorStylesheet">\r\n' + decoratorStyle + '\n</style>\r\n<style id="grid-css">\r\n' + gridStyle + '</style>\r\n</head>\r\n<body>\r\n<div id="grid" class="' + gridContainerClasses + '">\r\n ' + $("#grid").html().replace(/<\/[a-z]+>/g, "$&\r\n ").split(' ').reverse().join(" ").replace(" ","").split(" ").reverse().join(" ") + '</div> \r\n</body>//-->'
$('#full-source').html(fullSource);
}
function copyContent(source) {
var textarea = document.createElement('textarea');
if (source == "html") {
textarea.value = $('#htmlEg').html().replace("<!---", "").replace("//-->", "");
var tooltip = document.querySelector("#myTooltipHtml");
tooltip.innerHTML = "Copied HTML";
}
else if (source == "css") {
textarea.value = indentCSS(powergrid.toCss(config));
var tooltip = document.querySelector("#myTooltipCss");
tooltip.innerHTML = "Copied CSS";
}
else if (source == "full-source") {
textarea.value = replaceAll(fullSource, ['<!---', '//-->', '//-->'], ['', '', '']);
var tooltip = document.querySelector("#myTooltipFullSource");
tooltip.innerHTML = "Copied Source";
}
$('body').append(textarea);
textarea.style.height = 0;
textarea.style.width = 0;
textarea.style.opacity = 0;
textarea.select();
document.execCommand("copy");
textarea.remove();
}
function highlight() {
if (!hljs) { console.warn('Highlight JS library is missing'); return; }
$('code[for]').each(function () {
// Get source code
var sourceId = $(this).attr('for');
var $source = $('#' + sourceId);
if (!$source.length) { return; }
var html = $source.html();
// Fix links
html = replaceAll(html, ['<!---', '//-->', '//-->'], ['', '', '']);
this.innerHTML = '<pre class="hljs"></pre>';
var preTag =this.querySelector('pre');
preTag.textContent = html;
hljs.highlightBlock(this);
$(this).removeClass("hljs");
})
}
function replaceAll(string, search, replacement) {
var newString = string;
if (!$.isArray(search)) {
search = [search];
}
if (!$.isArray(replacement)) {
replacement = [replacement];
}
for (var i = 0; i < search.length; i++) {
newString = newString.replace(search[i], replacement[i]);
}
return newString;
}
/*function openSourceContent(evt, sourceName) {
var i, tabcontent, tablinks;
var tabContainer = $(evt.currentTarget).closest(".power-grid-tab");
tabcontent = tabContainer.siblings(".power-grid-tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = tabContainer[0].getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(sourceName).style.display = "block";
evt.currentTarget.className += " active";
}*/
function tooltipOutFunc(src) {
if (src == "html") {
var tooltip = document.querySelector("#myTooltipHtml");
tooltip.innerHTML = "Copy HTML to clipboard";
}
else if (src == "css") {
var tooltip = document.querySelector("#myTooltipCss");
tooltip.innerHTML = "Copy CSS to clipboard";
}
else if (src == "full-source") {
var tooltip = document.querySelector("#myTooltipFullSource");
tooltip.innerHTML = "Copy Source to clipboard";
}
}
function fetchStatusWarnings() {
var deferred = $.Deferred();
$.ajax({
url:'./status-warnings.json',
dataType: 'json',
success: function(response){
deferred.resolve(response);
},
error: function(err){
deferred.resolve({});
}
});
return deferred.promise();
}
function setDecoratorStyles(){
var styleSheet1 = $("style#decoratorStylesheet").attr("href");
$.when($.ajax(styleSheet1)).then(function(data) {
$("style#decoratorStylesheet").html(data);
prepareViewSource();
},function(){
console.error("failed to load decorator stylesheet");
});
}
function prepareViewSource(){
getHTML();
getFullSource();
highlight();
// $("#sourceContainer").fadeIn();
$(this).find("[tab-id].active").click();
}
$(function () {
config = fetchConfig() || config;
fetchStatusWarnings().then(function(data){
statusWarnings = data.warnings || {};
showWarnings();
});
//Fetch and set common decorator styles
setDecoratorStyles();
//buildGrid();
$('.show-source-code').on('click', prepareViewSource);
// $('.open-ui-configuration').on('click', function () {
// getGridData();
// });
$('.show-json-editor').on('click', function () {
showEditJSONModal();
});
//getGridData();
showEditJSONModal();
//Open all settings modal when user clicks anywhere on document
// $("#grid").on("click",function(e){
// if(e.target == this){
// $("#menuContainer").attr('isOpen','true');
// }
// });
$("#pg-version").html(config.version);
// Open click anywhere overlay for first load
if (!(app && app.state && app.state.dialogOpen=="true")) {
$("#clickAnywhereOverlay").fadeIn(500);
// Auto fadeout overlay after 10 seconds if no response from user
setTimeout(function () {
$("#clickAnywhereOverlay").fadeOut(500);
$("#clickAnywhereOverlay .got-it-button").off("click");
}, 10000);
$("#clickAnywhereOverlay .got-it-button").one("click", function () {
$("#clickAnywhereOverlay").fadeOut(500);
});
}
window.onpopstate = function (event) {
window.location.reload();
};
});