Browse Source

Minify included JavaScript (#704)

Provide minified versions of JavaScript files. The project has a minimal
amount of JavaScript, so a simple tool is included to minify them rather
than pulling in a full build tool.

This will help with SEO tools penalizing for unminified scripts, despite
their small size.
Vince Salvino 4 days ago
parent
commit
d4b6ca41e0

+ 1 - 0
coderedcms/static/coderedcms/js/crx-editor.min.js

@@ -0,0 +1 @@
+$(document).ready(function(){$(document).on('click','.crx-collapsible button',function(){var $target=$(this).parent().find('.crx-collapsible-target');if(!$(this).parent().hasClass('collapsed')){$(this).parent().addClass('collapsed');$target.hide('fast');}else{$(this).parent().removeClass('collapsed');$target.show('fast');}});});

+ 2 - 0
coderedcms/static/coderedcms/js/crx-events.min.js

@@ -0,0 +1,2 @@
+document.addEventListener("DOMContentLoaded",function(){var calendars=document.querySelectorAll("[data-block='calendar']");calendars.forEach(function(el){var pageId=el.dataset.pageId;var defaultDate=el.dataset.defaultDate;var defaultView=el.dataset.defaultView;var eventDisplay=el.dataset.eventDisplay;var eventSourceUrl=el.dataset.eventSourceUrl
+var timezone=el.dataset.timezone;var calendar=new FullCalendar.Calendar(el,{headerToolbar:{left:"prev,next today",center:"title",right:"dayGridMonth,dayGridWeek,timeGridDay,listMonth",},themeSystem:"bootstrap5",buttonText:{prev:"← prev",next:"next →",},initialDate:defaultDate,initialView:defaultView,fixedWeekCount:false,timeZone:timezone,eventDisplay:eventDisplay,eventSources:{url:eventSourceUrl,method:"GET",extraParams:{pid:pageId,},},});calendar.render();});});

+ 8 - 0
coderedcms/static/coderedcms/js/crx-front.min.js

@@ -0,0 +1,8 @@
+const libs={masonry:{url:"https://cdn.jsdelivr.net/npm/masonry-layout@4.2.2/dist/masonry.pkgd.min.js",integrity:"sha256-Nn1q/fx0H7SNLZMQ5Hw5JLaTRZp0yILA/FRexe19VdI=",},};function load_script(lib,success){var head=document.getElementsByTagName("head")[0];if(lib.head){var tmpEl=document.createElement("div");tmpEl.innerHTML=lib.head;head.append(tmpEl.firstElementChild);}
+if(lib.url){fetch(lib.url,{integrity:lib.integrity,referrerPolicy:"origin",}).then(function(response){return response.text();}).then(function(txt){eval?.(txt);}).then(function(){if(success){success();}});}}
+document.addEventListener("DOMContentLoaded",function(){document.querySelectorAll(".lightbox-preview").forEach(function(el){el.addEventListener("click",function(event){var el=event.currentTarget;var orig_src=el.querySelector("img").dataset.originalSrc;var orig_alt=el.querySelector("img").alt;var orig_ttl=el.querySelector("img").title;var lightbox=document.querySelector(el.dataset.bsTarget);lightbox.querySelector("img").setAttribute("src",orig_src);lightbox.querySelector("img").setAttribute("alt",orig_alt);lightbox.querySelector("img").setAttribute("title",orig_ttl);});});document.querySelectorAll(".modal[data-cr-wall-showonce='true']").forEach(function(el){el.addEventListener("hide.bs.modal",function(){localStorage["cr_wall_"+el.dataset.crWallId]="dismissed";});});document.querySelectorAll(".modal[data-cr-wall-id]").forEach(function(el){if(localStorage["cr_wall_"+el.dataset.crWallId]===undefined){const modal=new bootstrap.Modal(el);modal.show();}});if(typeof cr_track_clicks!=="undefined"&&cr_track_clicks){document.querySelectorAll("a").forEach(function(el){el.addEventListener("click",function(event){var el=event.currentTarget;gtag_data={event_category:"Link",event_label:el.textContent.trim().substring(0,30),};if(el.dataset.gaEventCategory){gtag_data["event_category"]=el.dataset.gaEventCategory;}
+if(el.dataset.gaEventLabel){gtag_data["event_label"]=el.dataset.gaEventLabel;}
+gtag("event","click",gtag_data);});});}
+if(typeof cr_external_new_tab!=="undefined"&&cr_external_new_tab){document.querySelectorAll("a").forEach(function(el){var href=el.href.trim();if(!href.startsWith(cr_site_url)&&!href.startsWith("/")&&!href.startsWith("#")&&!href.startsWith("?")){el.setAttribute("target","_blank");}});}
+if(document.querySelectorAll("[data-masonry]").length>0){load_script(libs.masonry);}
+let strips=document.querySelectorAll("[data-block='film-strip']");strips.forEach((el)=>{const leftButton=el.querySelector("[data-button='left']");const rightButton=el.querySelector("[data-button='right']");const container=el.querySelector("[data-block='film-container']");leftButton.addEventListener("click",function(){const panels=el.querySelectorAll("[data-block='film-panel']");let currentBlock=parseInt(el.dataset.currentBlock)-1;if(currentBlock<0)currentBlock=panels.length-1;el.dataset.currentBlock=currentBlock;const elem=panels[currentBlock];const left=elem.offsetLeft;container.scroll({top:0,left:left,behavior:"smooth"});});rightButton.addEventListener("click",function(){const panels=el.querySelectorAll("[data-block='film-panel']");let currentBlock=parseInt(el.dataset.currentBlock)+1;if(currentBlock>=panels.length)currentBlock=0;el.dataset.currentBlock=currentBlock;const elem=panels[currentBlock];const left=elem.offsetLeft;container.scroll({top:0,left:left,behavior:"smooth"});});});});

+ 7 - 0
coderedcms/static/coderedcms/js/crx-maps.min.js

@@ -0,0 +1,7 @@
+function initMap(){const crMap=document.querySelector("#cr-map");const map=new google.maps.Map(crMap,{zoom:parseInt(crMap.dataset.zoom),center:{lat:parseFloat(crMap.dataset.latitude),lng:parseFloat(crMap.dataset.longitude),},mapTypeControl:crMap.dataset.mapTypeControl,streetViewControl:crMap.dataset.streetViewControl,});var infowindow=new google.maps.InfoWindow({});if(navigator.geolocation){var currentLocationControlDiv=document.createElement("div");var currentLocation=new CurrentLocationControl(currentLocationControlDiv,map);currentLocationControlDiv.index=1;map.controls[google.maps.ControlPosition.TOP_LEFT].push(currentLocationControlDiv);}
+google.maps.event.addListener(map,"idle",()=>{const sw=map.getBounds().getSouthWest();const ne=map.getBounds().getNorthEast();let locationDataFeatures=[];map.data.loadGeoJson(crMap.dataset.geojsonUrl+`&viewport=${sw.lat()},${sw.lng()}|${ne.lat()},${ne.lng()}`,null,(features)=>{locationDataFeatures.forEach((dataFeature)=>{map.data.remove(dataFeature);});locationDataFeatures=features;if(crMap.dataset.showList=="True"){updateList(locationDataFeatures);}});});map.data.addListener("click",(ev)=>{const f=ev.feature;infowindow.setContent(f.getProperty("pin_description"));infowindow.setPosition(f.getGeometry().get());infowindow.setOptions({pixelOffset:new google.maps.Size(0,-30),});infowindow.open(map);});if(crMap.dataset.showSearch=="True"){var input=document.getElementById("pac-input");var searchBox=new google.maps.places.SearchBox(input);map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);map.addListener("bounds_changed",function(){searchBox.setBounds(map.getBounds());});searchBox.addListener("places_changed",function(){var places=searchBox.getPlaces();if(places.length==0){return;}
+var bounds=new google.maps.LatLngBounds();places.forEach(function(place){if(!place.geometry){return;}
+if(place.geometry.viewport){bounds.union(place.geometry.viewport);}else{bounds.extend(place.geometry.location);}});map.fitBounds(bounds);});}
+function updateList(features){locList=document.querySelector("#LocationList");locListEmpty=document.querySelector("#LocationListEmpty");new_html="";if(features.length==0){locList.style.display="none";locListEmpty.style.display="";}else{locList.style.display="";locListEmpty.style.display="none";for(i=0;i<features.length;i++){feature=features[i];new_html+=feature.getProperty("list_description");}}
+locList.innerHTML=new_html;}}
+function CurrentLocationControl(controlDiv,map){var controlUI=document.createElement("div");controlUI.style.backgroundColor="#fff";controlUI.style.border="2px solid #fff";controlUI.style.borderRadius="3px";controlUI.style.boxShadow="0 2px 2px rgba(0,0,0,.3)";controlUI.style.cursor="pointer";controlUI.style.marginTop="10px";controlUI.style.marginBottom="22px";controlUI.style.marginLeft="10px";controlUI.style.textAlign="center";controlUI.title="Near Me";controlDiv.appendChild(controlUI);var controlText=document.createElement("div");controlText.style.color="rgb(25,25,25)";controlText.style.fontFamily="Roboto,Arial,sans-serif";controlText.style.fontSize="16px";controlText.style.lineHeight="36px";controlText.style.paddingLeft="5px";controlText.style.paddingRight="5px";controlText.innerHTML="Near Me";controlUI.appendChild(controlText);controlUI.addEventListener("click",function(){navigator.geolocation.getCurrentPosition(function(position){currentPosition=new google.maps.LatLng(position.coords.latitude,position.coords.longitude);map.setCenter(currentPosition);});});}

+ 6 - 0
coderedcms/static/coderedcms/js/crx-streamforms.min.js

@@ -0,0 +1,6 @@
+condition_triggered=function($source_field,$target_field){if($source_field.prop("type")=="checkbox"){$source_field.each(function(){var $source_field=$(this);$trigger_checkbox=$source_field.closest("[value='"+$target_field.data("condition-trigger-value")+"']");if($trigger_checkbox.length>0){if($trigger_checkbox.prop("checked")){$target_field.show();}else{$target_field.hide();}}});}else{if($source_field.val().trim()==$target_field.data("condition-trigger-value").trim()){$target_field.show();}else{$target_field.hide();}}};$("[data-condition-trigger-id]").each(function(){var $target_field=$(this);var source_query="#"+$(this).data("condition-trigger-id");var $source_field=$(source_query+
+" input, "+
+source_query+
+" textarea, "+
+source_query+
+" select");var source_field_name=$source_field.prop("name");condition_triggered($source_field,$target_field);var $form=$(this).closest("form");$form.find("[name='"+source_field_name+"']").change(function(){condition_triggered($(this),$target_field);});});

+ 1 - 1
coderedcms/templates/coderedcms/pages/base.html

@@ -176,7 +176,7 @@
   {% endblock %}
 
   {% block coderedcms_scripts %}
-  <script src="{% static 'coderedcms/js/crx-front.js' %}?v={% coderedcms_version %}"></script>
+  <script src="{% static 'coderedcms/js/crx-front.min.js' %}?v={% coderedcms_version %}"></script>
   {% endblock %}
 
   {% block custom_scripts %}{% endblock %}

+ 1 - 1
coderedcms/templates/coderedcms/pages/event_index_page.html

@@ -33,5 +33,5 @@
 {{ block.super }}
 <script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.js" integrity="sha256-ZztCtsADLKbUFK/X6nOYnJr0eelmV2X3dhLDB/JK6fM=" crossorigin="anonymous"></script>
 <script src="https://cdn.jsdelivr.net/npm/@fullcalendar/bootstrap5@6.1.15/index.global.min.js" integrity="sha256-TslkUnYKZuqQj4Ueu1WQesikFvl2DADWslCx3EfBHZM=" crossorigin="anonymous"></script>
-<script src="{% static 'coderedcms/js/crx-events.js' %}?v={% coderedcms_version %}"></script>
+<script src="{% static 'coderedcms/js/crx-events.min.js' %}?v={% coderedcms_version %}"></script>
 {% endblock %}

+ 1 - 1
coderedcms/templates/coderedcms/pages/location_index_page.html

@@ -38,6 +38,6 @@
 {% endblock %}
 {% block coderedcms_scripts %}
 {{ block.super }}
-<script src="{% static 'coderedcms/js/crx-maps.js' %}?v={% coderedcms_version %}"></script>
+<script src="{% static 'coderedcms/js/crx-maps.min.js' %}?v={% coderedcms_version %}"></script>
 <script defer src="https://maps.googleapis.com/maps/api/js?key={{ google_api_key }}&callback=initMap&libraries=places"></script>
 {% endblock %}

+ 1 - 1
coderedcms/templates/coderedcms/pages/stream_form_page.html

@@ -57,5 +57,5 @@
 {% block coderedcms_scripts %}
 {{ block.super }}
 <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
-<script src="{% static 'coderedcms/js/crx-streamforms.js' %}?v={% coderedcms_version %}"></script>
+<script src="{% static 'coderedcms/js/crx-streamforms.min.js' %}?v={% coderedcms_version %}"></script>
 {% endblock %}

+ 7 - 1
docs/contributing/index.rst

@@ -112,7 +112,7 @@ license header comment states copyright, ownership, license, and also provides c
 
     /*!
     Wagtail CRX (https://www.coderedcorp.com/cms/)
-    Copyright 2018-2023 CodeRed LLC
+    Copyright 2018-2025 CodeRed LLC
     License: https://github.com/coderedcorp/coderedcms/blob/main/LICENSE
     @license magnet:?xt=urn:btih:c80d50af7d3db9be66a4d0a86db0286e4fd33292&dn=bsd-3-clause.txt BSD-3-Clause
     */
@@ -121,6 +121,12 @@ license header comment states copyright, ownership, license, and also provides c
 
     /* @license-end */
 
+When editing JavaScript files, be sure to minify them. The minified files must also be committed to version control as they are distributed as part of our package.
+
+.. code-block:: console
+
+   $ python minify.py
+
 
 Upgrading 3rd-Party CSS/JavaScript Libraries
 --------------------------------------------

+ 22 - 0
minify.py

@@ -0,0 +1,22 @@
+"""
+Utility to minify JavaScript.
+Run this after modifiying JavaScript files, before committing.
+"""
+
+from pathlib import Path
+
+from jsmin import jsmin
+
+
+JSDIR = Path("coderedcms") / "static" / "coderedcms" / "js"
+
+# iterate directory
+for entry in JSDIR.iterdir():
+    if entry.is_file() and entry.suffixes == [".js"]:
+        print(f"Minifying {entry}")
+        minified = ""
+        with open(entry, "r", encoding="utf8") as f:
+            minified = jsmin(f.read())
+        newpath = entry.parent / (entry.stem + ".min.js")
+        with open(newpath, "w", encoding="utf8", newline="\n") as f:
+            f.write(minified)

+ 1 - 0
requirements-dev.txt

@@ -3,6 +3,7 @@
 
 # Requirements, in addition to coderedcms, needed for development.
 build
+jsmin
 libsass
 setuptools>=65.5
 twine