16 Commits

17 changed files with 872 additions and 668 deletions

View File

@@ -1,4 +1,14 @@
# DS2 Core # DS2-core
DS2-core is a lightweight PugJS-based framework for building design systems.
The design system compiles to mostly pure HTML, SCSS and JavaScript. There are a few enhanced parts that use PHP in order to handle non-critical tasks Zip files on the fly to collect component JavaScript and SCSS. PugJS is used because it can handle some of the automation such as creating includes making components extremely modular.
## Requirements
The requirements for ds2-core are pretty light. You'll want to be able to process [PugJS](https://pugjs.org/api/getting-started.html) (formerly Jade) and [SCSS](https://sass-lang.com/documentation/) -- and that's about it.
For our own design system, we use ds2-core with [Prepros](https://prepros.io) (which you can use the Free Unlimited Trial for, but why not splurge and spend the $30USD to support the developer and skip the nags). On MacOS, you could also use [CodeKit](https://codekitapp.com/).
Alternatively, if you have pre-processor pipelines for Pug and SCSS, which you can install using npm, or any other language you decide to pull in, you can use those to compile if that ends up being easier for you. The framework isn't too picky, so long as things go into the right place.
## "Installation" ## "Installation"
@@ -11,20 +21,23 @@ src/pg/core/download.php.pug | public
All other pug files should compile to from src/pg/ to a relative path of public/* All other pug files should compile to from src/pg/ to a relative path of public/*
## Running the core ## Running the core
functions ### Callback functions
Callback functions can be used in
beforeArticleLoad - called before any patterns are started to load - beforeArticleLoad - called before any patterns have started to load
success - called when loading a pattern is successful if the result is an HTTP 200 - success - called when loading a pattern is successful if the result is an HTTP 200
afterArticleLoad - called after any patterns are started to load - afterArticleLoad - called after any patterns have started to load
done - called when the ajax for any pattern is done, whether successful or not. This is a useful place to load any javascript initializations that pattern. - done - called when the ajax for any pattern is done, whether successful or not. This is a useful place to load any javascript initializations that pattern.
## About the content variable ## Creating an item
The content variable in \_config.pug defines your array of patterns. It is made up of the following attributes:
## The content object
The content variable in \/src\/pg\/_config.pug defines your array of patterns. It is made up of the following attributes:
- name - the hypenated name of the pattern - name - the hypenated name of the pattern
- status - this should be one of the statuses from your status array - status - this should be one of the statuses from your status array
- display - (optional) if present this will be displayed, as is, instead of the name - display - (optional) if present this will be displayed, as is, instead of the name
@@ -49,6 +62,42 @@ In your design system implementation,
This will ensure that the .pug file will get processed and the .pp file will be handled as text will get compiled, but they should display correctly and remain in sync while maintaining the minimum number of files. This will ensure that the .pug file will get processed and the .pp file will be handled as text will get compiled, but they should display correctly and remain in sync while maintaining the minimum number of files.
## Using core code with your own pattern documentation.
Using
---
Creating a new pattern
Begin by creating a folder within your strucutre to hold the pattern. Add the folder to your config file.
Generating css
You've likely created your component's css as an include file beginning with an underscore. create a second file named the same that includes any dependencies (such as breakpoints) that are required to generate your valid css.
You can now include the css in your pattern's index file.
Generating pug
Create a custom tool in prepros, give it a name such as "PP to Pug" set the input extension to .pp and the output extension to .pug and check Process Automatically . The command should be
Mac / Linux
cp {{input}} {{output}}
Windows
copy {{input}} {{output}}
Once you've added the tool, set the output to "relative path" and set the output extension to pug. For each .pp file you may have to check process automatically as it doesn't always identify the new extension.
You will now be able to include the .pp file in your pattern's index file while including the .pug file which will give a compiled version of your component's html.
---
## Troubleshooting
## Credits ## Credits
This framework includes [PrismJS](https://prismjs.com/) for code syntax highlighting. PrismJS is released under the [MIT license](https://opensource.org/licenses/MIT)> This framework includes [PrismJS](https://prismjs.com/) for code syntax highlighting. PrismJS is released under the [MIT license](https://opensource.org/licenses/MIT)>

View File

@@ -281,13 +281,14 @@
"expanded_folders": "expanded_folders":
[ [
"/Users/am/Desktop/ds2-core", "/Users/am/Desktop/ds2-core",
"/Users/am/Desktop/ds2-core/src", "/Users/am/Desktop/ds2-core/src/pg/patterns"
"/Users/am/Desktop/ds2-core/src/pg",
"/Users/am/Desktop/ds2-core/src/pg/patterns",
"/Users/am/Desktop/ds2-core/src/pg/patterns/core"
], ],
"file_history": "file_history":
[ [
"/Users/am/Desktop/ds2-core/src/js/scaffolding.js",
"/Users/am/Desktop/ds2-core/src/js/core/_core.js",
"/Users/am/Desktop/ds2-core/Readme.md",
"/Users/am/Desktop/ds2-core/src/pg/core/_colour-samples.pug",
"/Users/am/Desktop/ds2-core/src/pg/patterns/core/components/switch/index.pug", "/Users/am/Desktop/ds2-core/src/pg/patterns/core/components/switch/index.pug",
"/Users/am/Desktop/ds2-core/src/pg/patterns/core/components/sticky-note/index.pug", "/Users/am/Desktop/ds2-core/src/pg/patterns/core/components/sticky-note/index.pug",
"/Users/am/Desktop/ds2-core/src/pg/patterns/core/layouts/breakpoints/index.pug", "/Users/am/Desktop/ds2-core/src/pg/patterns/core/layouts/breakpoints/index.pug",
@@ -411,11 +412,7 @@
"/Users/am/Desktop/my DS2/src/pg/patterns/components/tooltip/index.pug", "/Users/am/Desktop/my DS2/src/pg/patterns/components/tooltip/index.pug",
"/Users/am/Desktop/my DS2/src/pg/patterns/components/link/index.pug", "/Users/am/Desktop/my DS2/src/pg/patterns/components/link/index.pug",
"/Users/am/Desktop/my DS2/src/pg/patterns/components/progress-bar/index.pug", "/Users/am/Desktop/my DS2/src/pg/patterns/components/progress-bar/index.pug",
"/Users/am/Desktop/my DS2/src/pg/patterns/layouts/main-navigation/index.pug", "/Users/am/Desktop/my DS2/src/pg/patterns/layouts/main-navigation/index.pug"
"/Users/am/Desktop/my DS2/src/pg/patterns/layouts/breakpoints/index.pug",
"/Users/am/Desktop/my DS2/src/pg/patterns/visual-design/notifications/index.pug",
"/Users/am/Desktop/my DS2/src/pg/patterns/visual-design/spacing/spacing.css",
"/Users/am/Desktop/my DS2/src/pg/patterns/visual-design/colours/index.pug"
], ],
"find": "find":
{ {
@@ -434,6 +431,7 @@
"case_sensitive": false, "case_sensitive": false,
"find_history": "find_history":
[ [
"oneClickSelect",
"../core/_master-pattern.pug", "../core/_master-pattern.pug",
"../core", "../core",
"hide-deprecated", "hide-deprecated",

View File

@@ -1207,6 +1207,9 @@
"concat-js": { "concat-js": {
"enable": false "enable": false
}, },
"babel": {
"enable": true
},
"bundle-js": { "bundle-js": {
"enable": true, "enable": true,
"options": { "options": {

View File

@@ -4,31 +4,34 @@
/* 1 */ /* 1 */
/***/ (function(module) { /***/ (function(module) {
const getDate = function(){ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
var getDate = function getDate() {
var d = new Date(); var d = new Date();
return d.toLocaleDateString(lang, {day: "numeric", month: "long", year: "numeric"}); return d.toLocaleDateString(lang, {
} day: "numeric",
month: "long",
year: "numeric"
});
};
String.prototype.toTitleCase = function () { String.prototype.toTitleCase = function () {
return this.replace(/\w\S*/g, function (txt) { return this.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}); });
} };
String.prototype.toSentenceCase = function () { String.prototype.toSentenceCase = function () {
return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase(); return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase();
} };
String.prototype.toContent = function () { String.prototype.toContent = function () {
return this.replace(/-/g, " "); return this.replace(/-/g, " ");
} };
String.prototype.toPath = function () { String.prototype.toPath = function () {
return this.trim().replace(/ /g, "_").replace(/-/g, "_").replace(/[\/\W]/g, "").replace(/_/g, "-"); return this.trim().replace(/ /g, "_").replace(/-/g, "_").replace(/[\/\W]/g, "").replace(/_/g, "-");
} };
var font = {
const font = {
size: 0 size: 0
} };
var copyFallback = function copyFallback(copyInfo, attr) {
const copyColourFallback = (copyInfo, attr) => { console.log("fallback");
console.log("fallback")
var textArea = document.createElement('textarea'); var textArea = document.createElement('textarea');
textArea.value = copyInfo; textArea.value = copyInfo;
@@ -36,67 +39,46 @@ const copyColourFallback = (copyInfo, attr) => {
textArea.style.top = '0'; textArea.style.top = '0';
textArea.style.left = '0'; textArea.style.left = '0';
textArea.style.position = 'fixed'; textArea.style.position = 'fixed';
document.body.appendChild(textArea); document.body.appendChild(textArea);
textArea.focus(); textArea.focus();
textArea.select(); textArea.select();
try { try {
var successful = document.execCommand('copy'); var successful = document.execCommand('copy');
setTimeout(function () { setTimeout(function () {
if (successful) { if (successful) {
//copyInfo.success(); //copyInfo.success();
showMessage(`Copied ${attr}.`) showMessage("Copied ".concat(attr, "."));
} else { } else {
//copyInfo.error(); //copyInfo.error();
showMessage(`Copy failed (${attr}).`, false) showMessage("Copy failed (".concat(attr, ")."), false);
} }
}, 1); }, 1);
} catch (err) { } catch (err) {
setTimeout(function () { setTimeout(function () {
showMessage(`Copy failed (${attr}). ${err.Message}`, false); showMessage("Copy failed (".concat(attr, "). ").concat(err.Message), false);
//copyInfo.error(err); //copyInfo.error(err);
}, 1); }, 1);
} }
document.body.removeChild(textArea); document.body.removeChild(textArea);
} };
var showMessage = function showMessage(m, s) {
const showMessage = (m, s) => {
s = s == undefined ? true : s; s = s == undefined ? true : s;
console.log("Copy success (navigator.clipboard)"); console.log("Copy success (navigator.clipboard)");
let status = document.createElement("div"); var status = document.createElement("div");
status.setAttribute("id", "copystatus"); status.setAttribute("id", "copystatus");
// status.style.display = "none"; // status.style.display = "none";
status.innerHTML = "<div class='" + (s ? "succeeded" : "failed") + "'>" + m + "</div>"; status.innerHTML = "<div class='" + (s ? "succeeded" : "failed") + "'>" + m + "</div>";
document.querySelector("body").prepend(status) document.querySelector("body").prepend(status);
status.querySelector("div").style.top = window.scrollY + 100 + "px";
status.querySelector("div").style.top = (window.scrollY + 100)+ "px"; setTimeout(function () {
setTimeout( () => {
status.remove(); status.remove();
}, 1000); }, 1000);
} };
var getURLVars = function getURLVars() {
const oneClickSelect = (e, t = e.currentTarget) => {
// In here, "this" is the element
var range, selection;
if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(t);
selection.removeAllRanges();
selection.addRange(range);
} else if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(t);
range.select();
}
}
const getURLVars = () => {
var oResult = {}; var oResult = {};
if (location.search.length > 0) { if (location.search.length > 0) {
var aQueryString = (location.search.substr(1)).split("&"); var aQueryString = location.search.substr(1).split("&");
for (var i = 0; i < aQueryString.length; i++) { for (var i = 0; i < aQueryString.length; i++) {
var aTemp = aQueryString[i].split("="); var aTemp = aQueryString[i].split("=");
if (aTemp[1].length > 0) { if (aTemp[1].length > 0) {
@@ -105,13 +87,12 @@ const getURLVars = () => {
} }
} }
return oResult; return oResult;
} };
module.exports = { module.exports = {
url: (() => { url: function () {
var v = {}; var v = {};
if (location.search.length > 0) { if (location.search.length > 0) {
var qs = (location.search.substr(1)).split("&"); var qs = location.search.substr(1).split("&");
for (var i = 0; i < qs.length; i++) { for (var i = 0; i < qs.length; i++) {
var t = qs[i].split("="); var t = qs[i].split("=");
if (t[1].length > 0) { if (t[1].length > 0) {
@@ -120,24 +101,20 @@ module.exports = {
} }
} }
return v; return v;
})(), }(),
cookie: { cookie: {
set: (name, value, expires, path, domain, secure) => { set: function set(name, value, expires, path, domain, secure) {
switch(typeof expires) { switch (_typeof(expires)) {
case "number": case "number":
var d = new Date() var d = new Date();
expires = d.setTime(d + (expires*24*60*60*1000)); expires = d.setTime(d + expires * 24 * 60 * 60 * 1000);
break; break;
case "object": case "object":
expires = expires.toGMTString(); expires = expires.toGMTString();
} }
document.cookie= name + "=" + escape(value) + document.cookie = name + "=" + escape(value) + (expires ? "; expires=" + expires : "") + "; path=/" + (domain ? "; domain=" + domain : "") + (secure ? "; secure" : "");
((expires) ? "; expires=" + expires : "") +
("; path=/") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}, },
get: (cname) => { get: function get(cname) {
var name = cname + "="; var name = cname + "=";
var ca = document.cookie.split(";"); var ca = document.cookie.split(";");
for (var i = 0; i < ca.length; i++) { for (var i = 0; i < ca.length; i++) {
@@ -151,165 +128,181 @@ module.exports = {
} }
return ""; return "";
}, },
remove: (cnane) => { remove: function remove(cname) {
setCookie(cname, "", -1); module.exports.cookie.set(cname, null, new Date(null));
},
},
colour: {
copy: (w, t) => {
let c = t.parentNode.getAttribute("data-" + (w=="var" ? "token" : w));
c = w == "var" ? `var(${c})` : c;
if (navigator.clipboard) {
navigator.clipboard.writeText(c).then(function() {
showMessage(`Copied ${w}.`);
}, function(e) {
copyColourFallback(c,w);
});
} else {
copyColourFallback(c, w);
} }
}, },
oneClickSelect: function oneClickSelect(e) {
positionTooltip: () => { var t = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : e.currentTarget;
document.querySelectorAll("color-pill > span").forEach((ps) => { // In here, "this" is the element
ps.querySelectorAll("div.tooltip-tc").forEach((tip) => { var range, selection;
if ( (font.size * 10) > ps.offsetLeft ) { if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(t);
selection.removeAllRanges();
selection.addRange(range);
} else if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(t);
range.select();
}
},
colour: {
copy: function copy(w, t) {
var c = t.parentNode.getAttribute("data-" + (w == "var" ? "token" : w));
c = w == "var" ? "var(".concat(c, ")") : c;
if (navigator.clipboard) {
navigator.clipboard.writeText(c).then(function () {
showMessage("Copied ".concat(w, "."));
}, function (e) {
copyFallback(c, w);
});
} else {
copyFallback(c, w);
}
},
positionTooltip: function positionTooltip() {
document.querySelectorAll("color-pill > span").forEach(function (ps) {
ps.querySelectorAll("div.tooltip-tc").forEach(function (tip) {
if (font.size * 10 > ps.offsetLeft) {
tip.setAttribute("tip-position", "right"); tip.setAttribute("tip-position", "right");
} else { } else {
tip.setAttribute("tip-position", "bottom"); tip.setAttribute("tip-position", "bottom");
} }
}); });
}) });
} }
}, },
// getCSS: (el, prop, b = false) { getCSS: function getCSS(el, prop) {
// return window.getComputedStyle(el, null).getPropertyValue(prop); var b = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
// }, return window.getComputedStyle(el, null).getPropertyValue(prop);
init: (args = {}) => { },
const url = getURLVars(); getTabPath: function getTabPath(t) {
var url = window.location.toString();
url = url.indexOf("?") > 0 ? url.substring(0, url.indexOf("?")) : url;
url = "".concat(url, "?p=").concat(t.closest("article").getAttribute("data-path"), "#").concat(t.getAttribute("id"));
var type = "URL";
if (navigator.clipboard) {
navigator.clipboard.writeText(url).then(function () {
showMessage("Copied ".concat(type, "."));
}, function (e) {
copyFallback(url, type);
});
} else {
copyFallback(url, type);
}
},
init: function init() {
var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var url = getURLVars();
font.size = parseFloat(getComputedStyle(document.documentElement).fontSize.replace("px", "")); font.size = parseFloat(getComputedStyle(document.documentElement).fontSize.replace("px", ""));
if (url.p !== undefined) { if (url.p !== undefined) {
document.querySelectorAll("main article:not([data-path^='" + url.p + "'])").forEach((a) => { document.querySelectorAll("main article:not([data-path^='" + url.p + "'])").forEach(function (a) {
a.remove(); a.remove();
}); });
if (url.p == -1) { if (url.p == -1) {
document.querySelector("title").innerHTML = `${url.p.toContent().toTitleCase()} | ${ document.querySelector("title").getAttribute("data-site") }`; document.querySelector("title").innerHTML = "".concat(url.p.toContent().toTitleCase(), " | ").concat(document.querySelector("title").getAttribute("data-site"));
} else { } else {
document.querySelector("title").innerHTML = `${url.p.substring(url.p.lastIndexOf("/")+1).toContent().toTitleCase()} | ${ document.querySelector("title").getAttribute("data-site") }` var theTitle = document.querySelectorAll("article");
if (theTitle.length > 0) {
theTitle = theTitle[0].getAttribute("data-name").toContent().toTitleCase();
if (document.querySelector("article").getAttribute("data-display") !== null) {
theTitle = document.querySelector("article").getAttribute("data-display");
}
document.querySelector("title").innerHTML = "".concat(theTitle, " | ").concat(document.querySelector("title").getAttribute("data-site"));
}
} }
} }
if (typeof args.beforeArticleLoad == "function") args.beforeArticleLoad(); if (typeof args.beforeArticleLoad == "function") args.beforeArticleLoad();
document.querySelectorAll("article").forEach(function (a) {
document.querySelectorAll("article").forEach((a) => {
if (a.getAttribute("data-template") != "none") { if (a.getAttribute("data-template") != "none") {
const observer = new IntersectionObserver(articles => { var observer = new IntersectionObserver(function (articles) {
articles.forEach(article => { articles.forEach(function (article) {
let a = article.target; var a = article.target;
// console.log("observing: ", { id: a.getAttribute("id"), intersecting: a.isIntersecting } )
// if (article.intersectionRatio > 0) {
// console.log("Is interesecting: ", { id: article.target.getAttribute("id"), intersecting: article.isIntersecting, ratio: article.intersectionRatio } )
if (article.isIntersecting == true) { if (article.isIntersecting == true) {
let path = a.getAttribute("data-path"); var path = a.getAttribute("data-path");
path = "patterns/" + path = "patterns/" + (a.getAttribute("data-core") == "true" ? "core/" + path.substring(path.lastIndexOf("/") + 1) : a.getAttribute("data-path")) + "/index.html";
(a.getAttribute("data-core") == "true" ? var ASYNC = true;
"core/" + path.substring(path.lastIndexOf("/") + 1) : var ajx = new XMLHttpRequest();
a.getAttribute("data-path")) ajx.onreadystatechange = function () {
+ "/index.html";
const ASYNC = true;
let ajx = new XMLHttpRequest();
ajx.onreadystatechange = () => {
if (ajx.readyState == 4) { if (ajx.readyState == 4) {
observer.unobserve(article.target); observer.unobserve(article.target);
switch (ajx.status) { switch (ajx.status) {
case 200: case 200:
a.innerHTML = a.innerHTML + ajx.responseText; a.innerHTML = a.innerHTML + ajx.responseText;
a.style.height = "auto" a.style.height = "auto";
switch (a.getAttribute("data-template")) { switch (a.getAttribute("data-template")) {
case "pug": case "pug":
a.querySelectorAll("pre").forEach((aa) => { a.querySelectorAll("pre").forEach(function (aa) {
aa.innerHTML = `<code class="${aa.getAttribute("class")}">${aa.innerHTML}</code>`; aa.innerHTML = "<code class=\"".concat(aa.getAttribute("class"), "\">").concat(aa.innerHTML, "</code>");
}) });
break; break;
case "md": case "md":
a.querySelectorAll("code").forEach((aa) => { a.querySelectorAll("code").forEach(function (aa) {
aa.classList.add("language-html"); aa.classList.add("language-html");
}) });
break; break;
} }
a.querySelectorAll("code").forEach(function (c) {
a.querySelectorAll("code").forEach((c)=> {
c.classList.add("line-numbers"); c.classList.add("line-numbers");
c.innerHTML = c.innerHTML.replace(/</g, "&lt;"); c.innerHTML = c.innerHTML.replace(/</g, "&lt;");
c.classList.add("copy-to-clipboard-button"); c.classList.add("copy-to-clipboard-button");
}) });
if (typeof args.success == "function") args.success(a); if (typeof args.success == "function") args.success(a);
Prism.highlightAll(); Prism.highlightAll();
a.querySelectorAll("code").forEach(function (c) {
a.querySelectorAll("code").forEach((c)=> { c.onclick = function (e) {
c.onclick = (e) => { module.exports.oneClickSelect(e);
oneClickSelect(e); };
} });
})
module.exports.colour.positionTooltip(); module.exports.colour.positionTooltip();
window.onresize = () => { window.onresize = function () {
module.exports.colour.positionTooltip(); module.exports.colour.positionTooltip();
} };
a.querySelectorAll("name > span, color-pill > span").forEach(function (pill) {
a.querySelectorAll("name > span, color-pill > span").forEach((pill) => { pill.onclick = function (e) {
pill.onclick = (e) => {
e.preventDefault(); e.preventDefault();
let w = ""; var w = "";
if (e.metaKey || e.ctrlKey || e.keyCode == 91 || e.keyCode == 224) { if (e.metaKey || e.ctrlKey || e.keyCode == 91 || e.keyCode == 224) {
w = "var"; w = "var";
} else if (e.altKey) { } else if (e.altKey) {
w = "token" w = "token";
} else if (e.shiftKey) { } else if (e.shiftKey) {
w = "rgb"; w = "rgb";
} else { } else {
w = "hex"; w = "hex";
} }
module.exports.colour.copy(w, pill); module.exports.colour.copy(w, pill);
} };
}) });
break; break;
case 404: case 404:
if (typeof args.notFound == "function") args.notFound(a, path); if (typeof args.notFound == "function") args.notFound(a, path);
break; break;
default: default:
console.log("uncaught http error", { status: ajx.status, path: a.getAttribute("data-path") }); console.log("uncaught http error", {
status: ajx.status,
path: a.getAttribute("data-path")
});
} }
a.style.height = "auto"; a.style.height = "auto";
if (typeof args.done == "function") args.done(a); if (typeof args.done == "function") args.done(a);
} }
}; };
ajx.open("GET", path, ASYNC); ajx.open("GET", path, ASYNC);
ajx.send(); ajx.send();
} }
}) });
}, { threshold: 0, rootMargin: "100%" }) }, {
threshold: 0,
rootMargin: "100%"
});
observer.observe(a); observer.observe(a);
} else { } else {
a.style.height = "auto"; a.style.height = "auto";
} }
}) });
if (typeof args.afterArticleLoad == "function") args.afterArticleLoad(); if (typeof args.afterArticleLoad == "function") args.afterArticleLoad();
} }
}; };
@@ -3028,45 +3021,47 @@ __webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ init: function() { return /* binding */ init; } /* harmony export */ init: function() { return /* binding */ init; }
/* harmony export */ }); /* harmony export */ });
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
//- DS2 core (c) 2024 Alexander McIlwraith //- DS2 core (c) 2024 Alexander McIlwraith
//- Licensed under CC BY-SA 4.0 //- Licensed under CC BY-SA 4.0
const font = { var font = {
size: 0 size: 0
} };
var pos = {
const pos = {
x: 0, x: 0,
y: 0 y: 0
} };
function drag(sticky) { function drag(sticky) {
sticky.onmousedown = event => { sticky.onmousedown = function (event) {
// get the position within the sticky // get the position within the sticky
pos.x = (event.clientX - sticky.offsetLeft); pos.x = event.clientX - sticky.offsetLeft;
pos.y = (event.clientY - sticky.offsetTop); pos.y = event.clientY - sticky.offsetTop;
// on mouse move, move the sticky to the position, minus the offset, of the mouse // on mouse move, move the sticky to the position, minus the offset, of the mouse
document.onmousemove = documentEvent => { document.onmousemove = function (documentEvent) {
sticky.style.top = (documentEvent.clientY - pos.y) + 'px'; sticky.style.top = documentEvent.clientY - pos.y + 'px';
sticky.style.left = (documentEvent.clientX - pos.x) + 'px'; sticky.style.left = documentEvent.clientX - pos.x + 'px';
sticky.setAttribute("moved", "true"); sticky.setAttribute("moved", "true");
} };
// when done, remove mouse move and mouse up handlers. // when done, remove mouse move and mouse up handlers.
document.onmouseup = () => { document.onmouseup = function () {
document.onmouseup = null; document.onmouseup = null;
document.onmousemove = null; document.onmousemove = null;
};
};
} }
}
}
function waitForElement(selector) { function waitForElement(selector) {
return new Promise(resolve => { return new Promise(function (resolve) {
if (document.querySelector(selector)) { if (document.querySelector(selector)) {
return resolve(document.querySelector(selector)); return resolve(document.querySelector(selector));
} }
var observer = new MutationObserver(function (mutations) {
const observer = new MutationObserver(mutations => {
if (document.querySelector(selector)) { if (document.querySelector(selector)) {
observer.disconnect(); observer.disconnect();
resolve(document.querySelector(selector)); resolve(document.querySelector(selector));
@@ -3080,84 +3075,81 @@ function waitForElement(selector) {
}); });
}); });
} }
var checkBottom = function checkBottom(attach) {
const checkBottom = (attach) => {
// check if top or bottom // check if top or bottom
if (attach.y < 0) { if (attach.y < 0) {
attach.ys = "bottom"; attach.ys = "bottom";
attach.y = attach.y * -1; attach.y = attach.y * -1;
} }
} };
var setStickyPostions = function setStickyPostions(s, attach) {
const setStickyPostions = (s, attach) => {
// set // set
s.style[attach.ys] = `${attach.y}px`; s.style[attach.ys] = "".concat(attach.y, "px");
s.style[attach.xs] = `${attach.x}px`; s.style[attach.xs] = "".concat(attach.x, "px");
s.style.display = "grid"; s.style.display = "grid";
} };
var css = function css(el, attr) {
const css = (el, attr) => { var st = "";
let st = "" Object.entries(attr).forEach(function (val) {
Object.entries(attr).forEach(val => { var _val = _slicedToArray(val, 2),
const [key, value] = val; key = _val[0],
st += `${key}: ${value}; `; value = _val[1];
}) st += "".concat(key, ": ").concat(value, "; ");
});
el.setAttribute("style", st.trim()); el.setAttribute("style", st.trim());
} };
var calculateStickyPosition = function calculateStickyPosition(s) {
var float = s.getAttribute("float");
const calculateStickyPosition = (s) => { var p = s.parentNode.getBoundingClientRect();
let float = s.getAttribute("float");
let p = s.parentNode.getBoundingClientRect()
switch (float) { switch (float) {
case "left": case "left":
css(s, {left: (p.left * -1) + "px"}) css(s, {
left: p.left * -1 + "px"
});
break; break;
case "right": case "right":
css(s, { left: (Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) - p.left - s.offsetWidth - (font.size * 2)) + "px" }); css(s, {
left: Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) - p.left - s.offsetWidth - font.size * 2 + "px"
});
break; break;
} }
var offset = s.getAttribute("offset");
let offset = s.getAttribute("offset");
if (offset !== null) { if (offset !== null) {
offset = offset.trim().split(" "); offset = offset.trim().split(" ");
css(s, {top: offset[0], left: offset[1] }) css(s, {
top: offset[0],
left: offset[1]
});
} }
} };
function init() {
function init(p = document){ var p = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document;
font.size = parseFloat(getComputedStyle(document.documentElement).fontSize.replace("px", "")); font.size = parseFloat(getComputedStyle(document.documentElement).fontSize.replace("px", ""));
p.querySelectorAll("sticky-note").forEach(function (s) {
p.querySelectorAll("sticky-note").forEach((s) => {
if (s.querySelectorAll("svg").length == 0) { if (s.querySelectorAll("svg").length == 0) {
var wrapper = document.createElement("sticky-note-wrapper");
let wrapper = document.createElement("sticky-note-wrapper");
s.parentNode.insertBefore(wrapper, s); s.parentNode.insertBefore(wrapper, s);
wrapper.appendChild(s); wrapper.appendChild(s);
s.setAttribute("content", s.innerHTML.replace(/"/g, "\"")); s.setAttribute("content", s.innerHTML.replace(/"/g, "\""));
s.innerHTML = `<div><svg width='0' height='0'><defs><clipPath id='stickyClip' clipPathUnits='objectBoundingBox'><path d='M 0 0 Q 0 0.69, 0.03 0.96 0.03 0.96, 1 0.96 Q 0.96 0.69, 0.96 0 0.96 0, 0 0' stroke-linejoin='round' stroke-linecap='square' /></clipPath></defs></svg></div><div><div>${s.innerHTML}</div></div>`; s.innerHTML = "<div><svg width='0' height='0'><defs><clipPath id='stickyClip' clipPathUnits='objectBoundingBox'><path d='M 0 0 Q 0 0.69, 0.03 0.96 0.03 0.96, 1 0.96 Q 0.96 0.69, 0.96 0 0.96 0, 0 0' stroke-linejoin='round' stroke-linecap='square' /></clipPath></defs></svg></div><div><div>".concat(s.innerHTML, "</div></div>");
} }
calculateStickyPosition(s); calculateStickyPosition(s);
drag(s); drag(s);
s.ondblclick = (e) => { s.ondblclick = function (e) {
if (e.ctrlKey) { if (e.ctrlKey) {
calculateStickyPosition(s); calculateStickyPosition(s);
} else { } else {
// add one click select // add one click select
} }
} };
}) });
window.onresize = function () {
window.onresize = () => {
font.size = parseFloat(getComputedStyle(document.documentElement).fontSize.replace("px", "")); font.size = parseFloat(getComputedStyle(document.documentElement).fontSize.replace("px", ""));
let stickies = p.querySelectorAll("sticky-note"); var stickies = p.querySelectorAll("sticky-note");
stickies.forEach((s) => { stickies.forEach(function (s) {
calculateStickyPosition(s); calculateStickyPosition(s);
}); });
} };
} }
/***/ }), /***/ }),
@@ -3168,7 +3160,7 @@ function init(p = document){
//- Licensed under CC BY-SA 4.0 //- Licensed under CC BY-SA 4.0
function flip(e) { function flip(e) {
let sw = e.currentTarget; var sw = e.currentTarget;
switch (sw.getAttribute("aria-checked")) { switch (sw.getAttribute("aria-checked")) {
case "true": case "true":
sw.setAttribute("aria-checked", "false"); sw.setAttribute("aria-checked", "false");
@@ -3177,20 +3169,24 @@ function flip(e) {
sw.setAttribute("aria-checked", "true"); sw.setAttribute("aria-checked", "true");
break; break;
} }
}; }
;
module.exports = { module.exports = {
init: (p = document) => { init: function init() {
p.querySelectorAll("[role='switch']").forEach((sw) => { var p = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document;
try {
p.querySelectorAll("[role='switch']").forEach(function (sw) {
sw.innerHTML = "<span></span>"; sw.innerHTML = "<span></span>";
sw.setAttribute("aria-checked", "false"); sw.setAttribute("aria-checked", "false");
sw.setAttribute("tabindex", "0"); sw.setAttribute("tabindex", "0");
sw.addEventListener("click", flip, false); sw.addEventListener("click", flip, false);
sw.addEventListener("keypress", flip, false); sw.addEventListener("keypress", flip, false);
}) });
} catch (e) {
console.warn("Cannot initialise switches.", e);
} }
} }
};
/***/ }), /***/ }),
/* 10 */ /* 10 */
@@ -3206,69 +3202,100 @@ __webpack_require__.r(__webpack_exports__);
*/ */
// create a pure JS mouse click event // create a pure JS mouse click event
const click = new MouseEvent('click', { var click = new MouseEvent('click', {
view: window, view: window,
bubbles: false, bubbles: false,
cancelable: true cancelable: true
}); });
var waitForElement = function waitForElement(selector) {
return new Promise(function (resolve) {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector));
}
var observer = new MutationObserver(function (mutations) {
if (document.querySelector(selector)) {
observer.disconnect();
resolve(document.querySelector(selector));
}
});
function init(p = document, s = true) { // If you get "parameter 1 is not of type 'Node'" error, see https://stackoverflow.com/a/77855838/492336
p.querySelectorAll(".tab-group, tabset").forEach(tabGroup => { observer.observe(document.body, {
childList: true,
subtree: true
});
});
};
function init() {
var container = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document;
var spacer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
container.querySelectorAll(".tab-group, tabset").forEach(function (tabGroup) {
if (tabGroup.querySelector("[role=tablist]") === null) { if (tabGroup.querySelector("[role=tablist]") === null) {
const tabgroup = tabGroup.getAttribute("id"); var tabgroup = tabGroup.getAttribute("id");
let tablist = ""; var tablist = "";
Array.from(tabGroup.children).forEach(function (child) {
Array.from(tabGroup.children).forEach(child => { var tab = child.getAttribute("tab") || child.getAttribute("data-tab");
const tab = child.getAttribute("tab") || child.getAttribute("data-tab");
if (tab !== null) { if (tab !== null) {
const tabID = tab.replace(/\W+/g, "-").toLowerCase(); var tabID = tab.replace(/\W+/g, "-").toLowerCase();
const tabPanel = document.createElement('div'); var tabPanel = document.createElement('div');
tabPanel.id = `tab-panel-${tabgroup}-${tabID}`; tabPanel.id = "tab-panel-".concat(tabgroup, "-").concat(tabID);
tabPanel.className = tablist === "" ? "open" : ""; tabPanel.className = tablist === "" ? "open" : "";
tabPanel.setAttribute("role", "tabpanel"); tabPanel.setAttribute("role", "tabpanel");
tabPanel.setAttribute("tabindex", "0"); tabPanel.setAttribute("tabindex", "0");
tabPanel.setAttribute("aria-labelledby", `tab-${tabgroup}-${tabID}`); tabPanel.setAttribute("aria-labelledby", "tab-".concat(tabgroup, "-").concat(tabID));
tabPanel.appendChild(child.cloneNode(true)); tabPanel.appendChild(child.cloneNode(true));
child.parentNode.replaceChild(tabPanel, child); child.parentNode.replaceChild(tabPanel, child);
tablist += `<li tabindex="0" role="tab" ${tablist === "" ? "class='selected'" : ""} id="tab-${tabgroup}-${tabID}"><span>${tab}</span></li>`; tablist += "<li tabindex=\"0\" role=\"tab\" ".concat(tablist === "" ? "class='selected'" : "", " id=\"tab-").concat(tabgroup, "-").concat(tabID, "\"><span>").concat(tab, "</span></li>");
} else { } else {
child.classList.add("tab-hidden"); child.classList.add("tab-hidden");
} }
}); });
var ul = document.createElement('ul');
const ul = document.createElement('ul');
ul.setAttribute("role", "tablist"); ul.setAttribute("role", "tablist");
ul.innerHTML = s != true ? `${tablist}` : `${tablist}<li role="separator" class="separator"></li>`; ul.innerHTML = spacer != true ? "".concat(tablist) : "".concat(tablist, "<li role=\"separator\" class=\"separator\"></li>");
tabGroup.insertBefore(ul, tabGroup.firstChild); tabGroup.insertBefore(ul, tabGroup.firstChild);
tabGroup.querySelectorAll('[role="tab"]').forEach(function (tab) {
tabGroup.querySelectorAll('[role="tab"]').forEach(tab => { tab.addEventListener("click", function (e) {
tab.addEventListener("click", () => { if (e.altKey && typeof args.altModifier == "function") {
const siblings = Array.from(tab.parentNode.children); args.altModifier(tab);
siblings.forEach(sibling => sibling.classList.remove("selected")); } else if (e.shiftKey && typeof args.shiftModifier == "function") {
tab.classList.add("selected"); args.shiftModifier(tab);
} else if (e.metaKey && typeof args.metaModifier == "function") {
const tabPanels = Array.from(tab.parentNode.parentNode.children) args.metaModifier(tab);
.filter(child => child.getAttribute("role") === "tabpanel"); } else {
tabPanels.forEach(panel => panel.classList.remove("open")); var siblings = Array.from(tab.parentNode.children);
siblings.forEach(function (sibling) {
const tabPanelId = tab.getAttribute("id").replace("tab", "tab-panel"); return sibling.classList.remove("selected");
document.getElementById(tabPanelId).classList.add("open");
}); });
tab.classList.add("selected");
var tabPanels = Array.from(tab.parentNode.parentNode.children).filter(function (child) {
tab.addEventListener("keypress", (e) => { return child.getAttribute("role") === "tabpanel";
});
tabPanels.forEach(function (panel) {
return panel.classList.remove("open");
});
var tabPanelId = tab.getAttribute("id").replace("tab", "tab-panel");
document.getElementById(tabPanelId).classList.add("open");
}
});
tab.addEventListener("keypress", function (e) {
e.preventDefault(); e.preventDefault();
if (e.which == 32 || e.which == 13) { if (e.which == 32 || e.which == 13) {
e.currentTarget.dispatchEvent(click); e.currentTarget.dispatchEvent(click);
} }
}) });
});
}
if (document.location.hash != "" && document.location.hash.substring(0, 5) == "#tab-") {
waitForElement(document.location.hash).then(function (el) {
el.scrollIntoView();
el.dispatchEvent(click);
}); });
} }
}); });
} }
/***/ }) /***/ })
/******/ ]); /******/ ]);
/************************************************************************/ /************************************************************************/
@@ -3387,53 +3414,49 @@ __webpack_require__.r(__webpack_exports__);
// init core // init c
_core_core_js__WEBPACK_IMPORTED_MODULE_0__.init({ _core_core_js__WEBPACK_IMPORTED_MODULE_0__.init({
success: (a) => { success: function success(a) {
_pg_patterns_core_tabs_tabs_js__WEBPACK_IMPORTED_MODULE_9__.init(a); _pg_patterns_core_tabs_tabs_js__WEBPACK_IMPORTED_MODULE_9__.init(a, true, {
shiftModifier: _core_core_js__WEBPACK_IMPORTED_MODULE_0__.getTabPath
});
_pg_patterns_core_switch_switch_js__WEBPACK_IMPORTED_MODULE_8__.init(a); _pg_patterns_core_switch_switch_js__WEBPACK_IMPORTED_MODULE_8__.init(a);
_pg_patterns_core_sticky_note_sticky_note_js__WEBPACK_IMPORTED_MODULE_7__.init(a); _pg_patterns_core_sticky_note_sticky_note_js__WEBPACK_IMPORTED_MODULE_7__.init(a);
}, },
notFound: (a, path) => { notFound: function notFound(a, path) {
a.innerHTML = `${a.innerHTML}<div class='notification-box error'><p>This pattern appears to be missing.<br><small>(${path} returned http status 404)</small></p></div>`; a.innerHTML = "".concat(a.innerHTML, "<div class='notification-box error'><p>This pattern appears to be missing.<br><small>(").concat(path, " returned http status 404)</small></p></div>");
} }
}); });
// deprecated switch handler // deprecated switch handler
const flipInfoSwitch = (e, s = e.currentTarget) => { var flipInfoSwitch = function flipInfoSwitch(e) {
var s = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : e.currentTarget;
switch (s.getAttribute("id")) { switch (s.getAttribute("id")) {
case "deprecated": case "deprecated":
_core_core_js__WEBPACK_IMPORTED_MODULE_0__.cookie.set("show-deprecated", s.getAttribute("aria-checked"), 30, "/"); _core_core_js__WEBPACK_IMPORTED_MODULE_0__.cookie.set("show-deprecated", s.getAttribute("aria-checked"), 30, "/");
document.querySelector("main").querySelectorAll("article[data-status=deprecated]").forEach((a) => { document.querySelector("main").querySelectorAll("article[data-status=deprecated]").forEach(function (a) {
a.classList[( s.getAttribute("aria-checked") == "true" ? "add" : "remove" )]("show-deprecated"); a.classList[s.getAttribute("aria-checked") == "true" ? "add" : "remove"]("show-deprecated");
}); });
break; break;
case "breakpoints": case "breakpoints":
console.log("here")
_core_core_js__WEBPACK_IMPORTED_MODULE_0__.cookie.set("show-breakpoints", s.getAttribute("aria-checked"), 30, "/"); _core_core_js__WEBPACK_IMPORTED_MODULE_0__.cookie.set("show-breakpoints", s.getAttribute("aria-checked"), 30, "/");
document.querySelector("html").classList[( s.getAttribute("aria-checked") == "true" ? "add" : "remove" )]("show-breakpoints"); document.querySelector("html").classList[s.getAttribute("aria-checked") == "true" ? "add" : "remove"]("show-breakpoints");
break; break;
} }
};
}
// create a pure JS mouse click event // create a pure JS mouse click event
const click = new MouseEvent('click', { var click = new MouseEvent('click', {
view: window, view: window,
bubbles: false, bubbles: false,
cancelable: true cancelable: true
}); });
// get the switch, initialize it and add the handler // get the switch, initialize it and add the handler
let switches = document.querySelector(".info-switches"); var switches = document.querySelector(".info-switches");
_pg_patterns_core_switch_switch_js__WEBPACK_IMPORTED_MODULE_8__.init(switches); _pg_patterns_core_switch_switch_js__WEBPACK_IMPORTED_MODULE_8__.init(switches);
var deprecated = document.querySelector("#deprecated");
let deprecated = document.querySelector("#deprecated"); var breakpoints = document.querySelector("#breakpoints");
let breakpoints = document.querySelector("#breakpoints");
deprecated.onclick = flipInfoSwitch; deprecated.onclick = flipInfoSwitch;
deprecated.keypress = flipInfoSwitch; deprecated.keypress = flipInfoSwitch;
breakpoints.onclick = flipInfoSwitch; breakpoints.onclick = flipInfoSwitch;
@@ -3449,7 +3472,6 @@ if (_core_core_js__WEBPACK_IMPORTED_MODULE_0__.cookie.get("show-breakpoints") ==
// just for fun... We'll show deprecated if they match the path // just for fun... We'll show deprecated if they match the path
// document.querySelector(`#${core.url.p.replace(/\//g, "-")}`).classList.add("show-deprecated"); // document.querySelector(`#${core.url.p.replace(/\//g, "-")}`).classList.add("show-deprecated");
}(); }();
/******/ })() /******/ })()
; ;

File diff suppressed because one or more lines are too long

View File

@@ -287,23 +287,23 @@
<div class="tab-group" id="colors"> <div class="tab-group" id="colors">
<div data-tab="css"> <div data-tab="css">
<pre class="language-css">:root { <pre class="language-css">:root {
--colour-blue: #2e51a1, --colour-blue: #2e51a1;
--colour-blue-l: #5c7abf, --colour-blue-l: #5c7abf;
--colour-blue-xl: #b2c3ec, --colour-blue-xl: #b2c3ec;
--colour-blue-d: #133176, --colour-blue-d: #133176;
--colour-blue-xd: #031235, --colour-blue-xd: #031235;
--colour-grey: #7f7f7f, --colour-grey: #7f7f7f;
--colour-grey-l: #b2b2b2, --colour-grey-l: #b2b2b2;
--colour-grey-xl: #d8d8d8, --colour-grey-xl: #d8d8d8;
--colour-grey-xxl: #f0f0f0, --colour-grey-xxl: #f0f0f0;
--colour-white: #fff, --colour-white: #fff;
--colour-page: #fff, --colour-page: #fff;
--colour-light: #fff, --colour-light: #fff;
--colour-grey-d: #4c4c4c, --colour-grey-d: #4c4c4c;
--colour-grey-xd: #4c4c4c, --colour-grey-xd: #4c4c4c;
--colour-black: #000, --colour-black: #000;
--colour-dark: #000, --colour-dark: #000;
}</pre> }</pre>
</div> </div>
<div data-tab="scss"> <div data-tab="scss">

View File

@@ -82,6 +82,7 @@ function flip(e) {
module.exports = { module.exports = {
init: (p = document) => { init: (p = document) => {
try {
p.querySelectorAll("[role='switch']").forEach((sw) => { p.querySelectorAll("[role='switch']").forEach((sw) => {
sw.innerHTML = "<span></span>"; sw.innerHTML = "<span></span>";
sw.setAttribute("aria-checked", "false"); sw.setAttribute("aria-checked", "false");
@@ -89,6 +90,9 @@ module.exports = {
sw.addEventListener("click", flip, false); sw.addEventListener("click", flip, false);
sw.addEventListener("keypress", flip, false); sw.addEventListener("keypress", flip, false);
}) })
} catch (e) {
console.warn("Cannot initialise switches.", e);
}
} }
} }
</pre> </pre>

View File

@@ -2,6 +2,13 @@
<html> <html>
<head> <head>
<title>Pattern</title> <title>Pattern</title>
<script>
let u = document.location.href.substring(0, document.location.href.search(/patterns/i));
let p = document.location.pathname.substring(document.location.pathname.search(/patterns/i));
p = p.replace(/\/$|\/index\.html/i, "").substring(9);
window.location = u + "?p=" + p;
</script>
</head> </head>
<body data-prismjs-copy-timeout="1500"> <body data-prismjs-copy-timeout="1500">
<h2>What is it</h2> <h2>What is it</h2>
@@ -17,6 +24,14 @@
<p>Users should not need to see content of multiple tabs simultaneously and the user should be able to easily recognise where they are within the content. </p> <p>Users should not need to see content of multiple tabs simultaneously and the user should be able to easily recognise where they are within the content. </p>
<h2>How to use it</h2> <h2>How to use it</h2>
<p>The structure of the tab set is defined in html. There are two forms supported. Adding a class of <code class="inline">.tab-group</code> to the container element will work in place of the <code class="inline">tabset</code> tag, and the tab panels can be defined using either <code class="inline">tab=""</code> or <code class="inline">data-tab=""</code>. Passing an optional element to the init function will initialise tabs within that element. </p> <p>The structure of the tab set is defined in html. There are two forms supported. Adding a class of <code class="inline">.tab-group</code> to the container element will work in place of the <code class="inline">tabset</code> tag, and the tab panels can be defined using either <code class="inline">tab=""</code> or <code class="inline">data-tab=""</code>. Passing an optional element to the init function will initialise tabs within that element. </p>
<p>The tab initalize function now takes a new function parameter in the form of an third argument is an object that can take the following callbacks: </p>
<ul>
<li>altModifer (When the altKey is used)</li>
<li>shiftModifier (When the shift key is used)</li>
<li>metaModifier (When the Windows key or Apple key is used)</li>
</ul>
<p>You can use these callbacks to create a custom event to get the tab information. </p>
<p>Note: There is a new core function (core.getTabPath) that will generate the query string and url hash for use in DS2 Core. You may wish to update your scaffolding.js file to make use of this functionality. </p>
<tabset id="tabs"> <tabset id="tabs">
<pre class="language-html" tab="html"> <pre class="language-html" tab="html">
<tabset id="uniqueID"> <tabset id="uniqueID">
@@ -169,8 +184,31 @@ const click = new MouseEvent('click', {
cancelable: true cancelable: true
}); });
export function init(p = document, s = true) { const waitForElement = (selector) => {
p.querySelectorAll(".tab-group, tabset").forEach(tabGroup => { return new Promise(resolve => {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector));
}
const observer = new MutationObserver(mutations => {
if (document.querySelector(selector)) {
observer.disconnect();
resolve(document.querySelector(selector));
}
});
// If you get "parameter 1 is not of type 'Node'" error, see https://stackoverflow.com/a/77855838/492336
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
export function init(container = document, spacer = true, args = {}) {
container.querySelectorAll(".tab-group, tabset").forEach(tabGroup => {
if (tabGroup.querySelector("[role=tablist]") === null) { if (tabGroup.querySelector("[role=tablist]") === null) {
const tabgroup = tabGroup.getAttribute("id"); const tabgroup = tabGroup.getAttribute("id");
@@ -196,11 +234,18 @@ export function init(p = document, s = true) {
const ul = document.createElement('ul'); const ul = document.createElement('ul');
ul.setAttribute("role", "tablist"); ul.setAttribute("role", "tablist");
ul.innerHTML = s != true ? `${tablist}` : `${tablist}<li role="separator" class="separator"></li>`; ul.innerHTML = spacer != true ? `${tablist}` : `${tablist}<li role="separator" class="separator"></li>`;
tabGroup.insertBefore(ul, tabGroup.firstChild); tabGroup.insertBefore(ul, tabGroup.firstChild);
tabGroup.querySelectorAll('[role="tab"]').forEach(tab => { tabGroup.querySelectorAll('[role="tab"]').forEach(tab => {
tab.addEventListener("click", () => { tab.addEventListener("click", (e) => {
if (e.altKey && typeof args.altModifier == "function") {
args.altModifier(tab);
} else if (e.shiftKey && typeof args.shiftModifier == "function") {
args.shiftModifier(tab);
} else if (e.metaKey && typeof args.metaModifier == "function") {
args.metaModifier(tab);
} else {
const siblings = Array.from(tab.parentNode.children); const siblings = Array.from(tab.parentNode.children);
siblings.forEach(sibling => sibling.classList.remove("selected")); siblings.forEach(sibling => sibling.classList.remove("selected"));
tab.classList.add("selected"); tab.classList.add("selected");
@@ -211,6 +256,7 @@ export function init(p = document, s = true) {
const tabPanelId = tab.getAttribute("id").replace("tab", "tab-panel"); const tabPanelId = tab.getAttribute("id").replace("tab", "tab-panel");
document.getElementById(tabPanelId).classList.add("open"); document.getElementById(tabPanelId).classList.add("open");
}
}); });
@@ -222,6 +268,14 @@ export function init(p = document, s = true) {
}) })
}); });
} }
if (document.location.hash != "" && document.location.hash.substring(0,5) == "#tab-") {
waitForElement(document.location.hash).then((el) => {
el.scrollIntoView();
el.dispatchEvent(click);
});
}
}); });
} }
</pre> </pre>

View File

@@ -21,7 +21,7 @@ const font = {
size: 0 size: 0
} }
const copyColourFallback = (copyInfo, attr) => { const copyFallback = (copyInfo, attr) => {
console.log("fallback") console.log("fallback")
var textArea = document.createElement('textarea'); var textArea = document.createElement('textarea');
textArea.value = copyInfo; textArea.value = copyInfo;
@@ -71,22 +71,6 @@ const showMessage = (m, s) => {
}, 1000); }, 1000);
} }
const oneClickSelect = (e, t = e.currentTarget) => {
// In here, "this" is the element
var range, selection;
if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(t);
selection.removeAllRanges();
selection.addRange(range);
} else if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(t);
range.select();
}
}
const getURLVars = () => { const getURLVars = () => {
var oResult = {}; var oResult = {};
if (location.search.length > 0) { if (location.search.length > 0) {
@@ -145,12 +129,26 @@ module.exports = {
} }
return ""; return "";
}, },
remove: (cnane) => { remove: (cname) => {
setCookie(cname, "", -1); module.exports.cookie.set(cname, null, new Date(null));
}, },
}, },
oneClickSelect: (e, t = e.currentTarget) => {
// In here, "this" is the element
var range, selection;
if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(t);
selection.removeAllRanges();
selection.addRange(range);
} else if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(t);
range.select();
}
},
colour: { colour: {
copy: (w, t) => { copy: (w, t) => {
let c = t.parentNode.getAttribute("data-" + (w=="var" ? "token" : w)); let c = t.parentNode.getAttribute("data-" + (w=="var" ? "token" : w));
c = w == "var" ? `var(${c})` : c; c = w == "var" ? `var(${c})` : c;
@@ -159,10 +157,10 @@ module.exports = {
navigator.clipboard.writeText(c).then(function() { navigator.clipboard.writeText(c).then(function() {
showMessage(`Copied ${w}.`); showMessage(`Copied ${w}.`);
}, function(e) { }, function(e) {
copyColourFallback(c,w); copyFallback(c,w);
}); });
} else { } else {
copyColourFallback(c, w); copyFallback(c, w);
} }
}, },
@@ -178,9 +176,26 @@ module.exports = {
}) })
} }
}, },
// getCSS: (el, prop, b = false) { getCSS: (el, prop, b = false) => {
// return window.getComputedStyle(el, null).getPropertyValue(prop); return window.getComputedStyle(el, null).getPropertyValue(prop);
// }, },
getTabPath: (t) => {
let url = window.location.toString();
url = url.indexOf("?") > 0 ? url.substring(0,url.indexOf("?")) : url;
url = `${url}?p=${t.closest("article").getAttribute("data-path")}#${t.getAttribute("id")}`
let type = "URL";
if (navigator.clipboard) {
navigator.clipboard.writeText(url).then(function() {
showMessage(`Copied ${type}.`);
}, function(e) {
copyFallback(url,type);
});
} else {
copyFallback(url, type);
}
},
init: (args = {}) => { init: (args = {}) => {
const url = getURLVars(); const url = getURLVars();
font.size = parseFloat(getComputedStyle(document.documentElement).fontSize.replace("px","")); font.size = parseFloat(getComputedStyle(document.documentElement).fontSize.replace("px",""));
@@ -192,13 +207,16 @@ module.exports = {
if (url.p == -1) { if (url.p == -1) {
document.querySelector("title").innerHTML = `${url.p.toContent().toTitleCase()} | ${ document.querySelector("title").getAttribute("data-site") }`; document.querySelector("title").innerHTML = `${url.p.toContent().toTitleCase()} | ${ document.querySelector("title").getAttribute("data-site") }`;
} else { } else {
let theTitle = docuemnt.querySelector("article").getAttribute("data-name").toContent().toTitleCase(); let theTitle = document.querySelectorAll("article");
if (docuemnt.querySelector("article").getAttribute("data-display") !== null) { if (theTitle.length > 0) {
theTitle = docuemnt.querySelector("article").getAttribute("data-display") theTitle = theTitle[0].getAttribute("data-name").toContent().toTitleCase();
if (document.querySelector("article").getAttribute("data-display") !== null) {
theTitle = document.querySelector("article").getAttribute("data-display")
} }
document.querySelector("title").innerHTML = `${theTitle} | ${ document.querySelector("title").getAttribute("data-site") }` document.querySelector("title").innerHTML = `${theTitle} | ${ document.querySelector("title").getAttribute("data-site") }`
} }
} }
}
if (typeof args.beforeArticleLoad == "function") args.beforeArticleLoad(); if (typeof args.beforeArticleLoad == "function") args.beforeArticleLoad();
@@ -208,10 +226,6 @@ module.exports = {
articles.forEach(article => { articles.forEach(article => {
let a = article.target; let a = article.target;
// console.log("observing: ", { id: a.getAttribute("id"), intersecting: a.isIntersecting } )
// if (article.intersectionRatio > 0) {
// console.log("Is interesecting: ", { id: article.target.getAttribute("id"), intersecting: article.isIntersecting, ratio: article.intersectionRatio } )
if (article.isIntersecting == true) { if (article.isIntersecting == true) {
let path = a.getAttribute("data-path"); let path = a.getAttribute("data-path");
path = "patterns/" + path = "patterns/" +
@@ -252,7 +266,7 @@ module.exports = {
a.querySelectorAll("code").forEach((c)=> { a.querySelectorAll("code").forEach((c)=> {
c.onclick = (e) => { c.onclick = (e) => {
oneClickSelect(e); module.exports.oneClickSelect(e);
} }
}) })

View File

@@ -12,10 +12,12 @@ import * as stickynote from "../pg/patterns/core/sticky-note/_sticky-note.js";
import * as swtch from "../pg/patterns/core/switch/_switch.js"; import * as swtch from "../pg/patterns/core/switch/_switch.js";
import * as tabs from "../pg/patterns/core/tabs/_tabs.js"; import * as tabs from "../pg/patterns/core/tabs/_tabs.js";
// init core // init c
core.init({ core.init({
success: (a) => { success: (a) => {
tabs.init(a); tabs.init(a, true, {
shiftModifier: core.getTabPath,
});
swtch.init(a); swtch.init(a);
stickynote.init(a); stickynote.init(a);
}, },
@@ -24,6 +26,7 @@ core.init({
} }
}); });
// deprecated switch handler // deprecated switch handler
const flipInfoSwitch = (e, s = e.currentTarget) => { const flipInfoSwitch = (e, s = e.currentTarget) => {
@@ -37,12 +40,10 @@ const flipInfoSwitch = (e, s = e.currentTarget) => {
break; break;
case "breakpoints" : case "breakpoints" :
console.log("here")
core.cookie.set("show-breakpoints", s.getAttribute("aria-checked"), 30, "/"); core.cookie.set("show-breakpoints", s.getAttribute("aria-checked"), 30, "/");
document.querySelector("html").classList[( s.getAttribute("aria-checked") == "true" ? "add" : "remove" )]("show-breakpoints"); document.querySelector("html").classList[( s.getAttribute("aria-checked") == "true" ? "add" : "remove" )]("show-breakpoints");
break; break;
} }
} }
// create a pure JS mouse click event // create a pure JS mouse click event

View File

@@ -128,12 +128,12 @@
- function generateCSS(c, p) { - function generateCSS(c, p) {
- let o = ""; - let o = "";
- for (let i = 0; i < c.length; i++) { - for (let i = 0; i < c.length; i++) {
- o += `\n\t--${p}-${c[i].name.toLowerCase()}: ${ color(c[i].color, "hex").toLowerCase() },\n`; - o += `\n\t--${p}-${c[i].name.toLowerCase()}: ${ color(c[i].color, "hex").toLowerCase() };\n`;
- for (let ii = 0; ii < c[i].grad.l.length; ii++) { - for (let ii = 0; ii < c[i].grad.l.length; ii++) {
- o += `\t--${p}-${c[i].grad.l[ii].n.toLowerCase()}: ${ color(c[i].grad.l[ii].c, "hex").toLowerCase() },\n`; - o += `\t--${p}-${c[i].grad.l[ii].n.toLowerCase()}: ${ color(c[i].grad.l[ii].c, "hex").toLowerCase() };\n`;
- } - }
- for (let ii = 0; ii < c[i].grad.d.length; ii++) { - for (let ii = 0; ii < c[i].grad.d.length; ii++) {
- o += `\t--${p}-${c[i].grad.d[ii].n.toLowerCase()}: ${ color(c[i].grad.d[ii].c, "hex").toLowerCase() },\n`; - o += `\t--${p}-${c[i].grad.d[ii].n.toLowerCase()}: ${ color(c[i].grad.d[ii].c, "hex").toLowerCase() };\n`;
- } - }
- } - }
- return o; - return o;

View File

@@ -37,6 +37,11 @@ html
head head
title Pattern title Pattern
script.
let u = document.location.href.substring(0, document.location.href.search(/patterns/i));
let p = document.location.pathname.substring(document.location.pathname.search(/patterns/i));
p = p.replace(/\/$|\/index\.html/i, "").substring(9);
window.location = u + "?p=" + p;
body(data-assetpath= assetpath data-prismjs-copy-timeout="1500") body(data-assetpath= assetpath data-prismjs-copy-timeout="1500")

View File

@@ -75,7 +75,7 @@ include _colour-samples
"lighter lighter lighter darker darker darker" "lighter lighter lighter darker darker darker"
"notes notes notes notes notes notes"; "notes notes notes notes notes notes";
grid-template-columns: repeat(6, 1fr); grid-template-columns: repeat(6, 1fr);
grid-template-rows: repeat(2, 1.5rem) 10rem repeat(3, max-content); // 3rem repeat(2, 2rem) 1.5rem repeat(3, max-content); grid-template-rows: repeat(2, 1.5rem) repeat(4, max-content); // 3rem repeat(2, 2rem) 1.5rem repeat(3, max-content);
padding: 1rem; padding: 1rem;
width: 20rem; width: 20rem;
max-width: 318px; max-width: 318px;
@@ -115,7 +115,7 @@ include _colour-samples
display: grid; display: grid;
gap: .5rem; gap: .5rem;
grid-template-columns: repeat(3, 1fr); grid-template-columns: repeat(3, 1fr);
grid-template-rows: 2.5rem repeat(2, max-content); grid-template-rows: repeat(3, max-content);
.result { .result {
align-items: center; align-items: center;
border-radius: .5rem; border-radius: .5rem;
@@ -188,7 +188,7 @@ include _colour-samples
padding: .5rem; padding: .5rem;
width: 20rem; width: 20rem;
max-width: 318px; max-width: 318px;
height: 10.5rem; height: max-contents;
display: grid; display: grid;
gap: .5rem; gap: .5rem;
@@ -231,6 +231,7 @@ include _colour-samples
display: block; display: block;
width: 100%; width: 100%;
place-self: stretch; place-self: stretch;
text-align: center;
span { span {
border: none; border: none;
font-size: .9rem; font-size: .9rem;

View File

@@ -15,6 +15,7 @@ function flip(e) {
module.exports = { module.exports = {
init: (p = document) => { init: (p = document) => {
try {
p.querySelectorAll("[role='switch']").forEach((sw) => { p.querySelectorAll("[role='switch']").forEach((sw) => {
sw.innerHTML = "<span></span>"; sw.innerHTML = "<span></span>";
sw.setAttribute("aria-checked", "false"); sw.setAttribute("aria-checked", "false");
@@ -22,5 +23,8 @@ module.exports = {
sw.addEventListener("click", flip, false); sw.addEventListener("click", flip, false);
sw.addEventListener("keypress", flip, false); sw.addEventListener("keypress", flip, false);
}) })
} catch (e) {
console.warn("Cannot initialise switches.", e);
}
} }
} }

View File

@@ -9,8 +9,31 @@ const click = new MouseEvent('click', {
cancelable: true cancelable: true
}); });
export function init(p = document, s = true) { const waitForElement = (selector) => {
p.querySelectorAll(".tab-group, tabset").forEach(tabGroup => { return new Promise(resolve => {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector));
}
const observer = new MutationObserver(mutations => {
if (document.querySelector(selector)) {
observer.disconnect();
resolve(document.querySelector(selector));
}
});
// If you get "parameter 1 is not of type 'Node'" error, see https://stackoverflow.com/a/77855838/492336
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
export function init(container = document, spacer = true, args = {}) {
container.querySelectorAll(".tab-group, tabset").forEach(tabGroup => {
if (tabGroup.querySelector("[role=tablist]") === null) { if (tabGroup.querySelector("[role=tablist]") === null) {
const tabgroup = tabGroup.getAttribute("id"); const tabgroup = tabGroup.getAttribute("id");
@@ -36,11 +59,18 @@ export function init(p = document, s = true) {
const ul = document.createElement('ul'); const ul = document.createElement('ul');
ul.setAttribute("role", "tablist"); ul.setAttribute("role", "tablist");
ul.innerHTML = s != true ? `${tablist}` : `${tablist}<li role="separator" class="separator"></li>`; ul.innerHTML = spacer != true ? `${tablist}` : `${tablist}<li role="separator" class="separator"></li>`;
tabGroup.insertBefore(ul, tabGroup.firstChild); tabGroup.insertBefore(ul, tabGroup.firstChild);
tabGroup.querySelectorAll('[role="tab"]').forEach(tab => { tabGroup.querySelectorAll('[role="tab"]').forEach(tab => {
tab.addEventListener("click", () => { tab.addEventListener("click", (e) => {
if (e.altKey && typeof args.altModifier == "function") {
args.altModifier(tab);
} else if (e.shiftKey && typeof args.shiftModifier == "function") {
args.shiftModifier(tab);
} else if (e.metaKey && typeof args.metaModifier == "function") {
args.metaModifier(tab);
} else {
const siblings = Array.from(tab.parentNode.children); const siblings = Array.from(tab.parentNode.children);
siblings.forEach(sibling => sibling.classList.remove("selected")); siblings.forEach(sibling => sibling.classList.remove("selected"));
tab.classList.add("selected"); tab.classList.add("selected");
@@ -51,6 +81,7 @@ export function init(p = document, s = true) {
const tabPanelId = tab.getAttribute("id").replace("tab", "tab-panel"); const tabPanelId = tab.getAttribute("id").replace("tab", "tab-panel");
document.getElementById(tabPanelId).classList.add("open"); document.getElementById(tabPanelId).classList.add("open");
}
}); });
@@ -62,5 +93,13 @@ export function init(p = document, s = true) {
}) })
}); });
} }
if (document.location.hash != "" && document.location.hash.substring(0,5) == "#tab-") {
waitForElement(document.location.hash).then((el) => {
el.scrollIntoView();
el.dispatchEvent(click);
});
}
}); });
} }

View File

@@ -22,6 +22,15 @@ block content
+h(2) +h(2)
p The structure of the tab set is defined in html. There are two forms supported. Adding a class of #[code.inline .tab-group] to the container element will work in place of the #[code.inline tabset] tag, and the tab panels can be defined using either #[code.inline tab=""] or #[code.inline data-tab=""]. Passing an optional element to the init function will initialise tabs within that element. p The structure of the tab set is defined in html. There are two forms supported. Adding a class of #[code.inline .tab-group] to the container element will work in place of the #[code.inline tabset] tag, and the tab panels can be defined using either #[code.inline tab=""] or #[code.inline data-tab=""]. Passing an optional element to the init function will initialise tabs within that element.
p The tab initalize function now takes a new function parameter in the form of an third argument is an object that can take the following callbacks:
ul
li altModifer (When the altKey is used)
li shiftModifier (When the shift key is used)
li metaModifier (When the Windows key or Apple key is used)
p You can use these callbacks to create a custom event to get the tab information.
p Note: There is a new core function (core.getTabPath) that will generate the query string and url hash for use in DS2 Core. You may wish to update your scaffolding.js file to make use of this functionality.
tabset#tabs tabset#tabs
pre.language-html(tab="html") pre.language-html(tab="html")

View File

@@ -74,7 +74,7 @@
"lighter lighter lighter darker darker darker" "lighter lighter lighter darker darker darker"
"notes notes notes notes notes notes"; "notes notes notes notes notes notes";
grid-template-columns: repeat(6, 1fr); grid-template-columns: repeat(6, 1fr);
grid-template-rows: repeat(2, 1.5rem) 10rem repeat(3, max-content); // 3rem repeat(2, 2rem) 1.5rem repeat(3, max-content); grid-template-rows: repeat(2, 1.5rem) repeat(4, max-content); // 3rem repeat(2, 2rem) 1.5rem repeat(3, max-content);
padding: 1rem; padding: 1rem;
width: 20rem; width: 20rem;
max-width: 318px; max-width: 318px;
@@ -114,7 +114,7 @@
display: grid; display: grid;
gap: .5rem; gap: .5rem;
grid-template-columns: repeat(3, 1fr); grid-template-columns: repeat(3, 1fr);
grid-template-rows: 2.5rem repeat(2, max-content); grid-template-rows: repeat(3, max-content);
.result { .result {
align-items: center; align-items: center;
border-radius: .5rem; border-radius: .5rem;
@@ -187,7 +187,7 @@
padding: .5rem; padding: .5rem;
width: 20rem; width: 20rem;
max-width: 318px; max-width: 318px;
height: 10.5rem; height: max-contents;
display: grid; display: grid;
gap: .5rem; gap: .5rem;
@@ -230,6 +230,7 @@
display: block; display: block;
width: 100%; width: 100%;
place-self: stretch; place-self: stretch;
text-align: center;
span { span {
border: none; border: none;
font-size: .9rem; font-size: .9rem;