Skip to content

Commit

Permalink
Feature textify (#47)
Browse files Browse the repository at this point in the history
* Added some fancy text creation for google 😄
  • Loading branch information
tbreuss authored Nov 11, 2021
1 parent b631866 commit fca9c85
Show file tree
Hide file tree
Showing 82 changed files with 336 additions and 166 deletions.
251 changes: 246 additions & 5 deletions .eleventy.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,42 @@ const util = require('util')

module.exports = function(eleventyConfig) {

function getCharCodes(s){
let charCodeArr = [];
for(let i = 0; i < s.length; i++){
let code = s.charCodeAt(i);
charCodeArr.push(code);
}
return charCodeArr;
}

function parseItems(items, conjunction)
{
if (!Array.isArray(items)) {
return '';
}
let mappedItems = items.map((item) => {
return '`' + item + '`';
});
let lastItem = mappedItems.pop();
if (mappedItems.length > 0) {
return mappedItems.join(', ') + ' ' + conjunction + ' ' + lastItem;
}
return lastItem;
}

function sumDigits(n) {
return (n - 1) % 9 + 1;
}

function calcSumDigitsOfString(s) {
let ascii = getCharCodes(s);
let sum = ascii.reduce(function (a, b) {
return a + b;
}, 0);
return sumDigits(sum);
}

eleventyConfig.addFilter('dumper', obj => {
return util.inspect(obj)
});
Expand Down Expand Up @@ -38,7 +74,150 @@ module.exports = function(eleventyConfig) {
return JSON.stringify(csvString);
});

eleventyConfig.addFilter('add_link_to_flems', (content, title, flemsSelected, flemsFiles, flemsLinks, version) => {
eleventyConfig.addShortcode('textifyTop', (title, description, date, tags, level, version, author, authorUrl, link, authorMap) => {
// some nice procedural programming ;-)

let textVariantNumber = calcSumDigitsOfString(title) % 3;

let authorExampleCount = 1;
authorMap.forEach((data) => {
if (author === data[0]) {
authorExampleCount = data[1].count;
return;
}
});

let apiMethods = (tags || []).filter(function (tag) {
return tag.includes('m.');
});

let lifecycleMethods = (tags || []).filter(function (tag) {
const methods = ['onbeforeupdate', 'onremove', 'onbeforeremove', 'onupdate', 'oncreate', 'oninit'];
return methods.indexOf(tag) >= 0;
});

let text = [];

if (description && (description.length > 0)) {
text.push(description);
text.push('');
}

if (author.length > 0) {
text.push('The example was contributed by ' + author + ' and last modified on ' + date + '.');
if (authorExampleCount > 2) {
text.push('<a href="' + authorUrl + '">Click here</a> to see more examples contributed by the author.');
} else if(authorExampleCount === 2) {
text.push('<a href="' + authorUrl + '">Click here</a> to see another example contributed by the author.');
}
}

if (version.length > 0) {
text.push ("\n");
if (version === '2.0.4') {
text.push('The snippet is using the most current version ' + version + ' of Mithril JS framework.');
} else {
text.push('The snippet is using version ' + version + ' of Mithril JS framework.');
}
}

if (level.length > 0) {
switch(level) {
case 'beginner':
text.push('It is aimed at beginners and shows some basic recipes.');
break;
case 'advanced':
text.push('It is aimed at more advanced users and shows some things, that are not easy to achieve.');
break;
case 'intermediate':
text.push('It is aimed at intermediate users who are familiar with most of the aspects of the framework.');
break;
case 'expert':
text.push('It is aimed at expert users who are familiar with all of the aspects of the framework and JavaScript itself.');
break;
}
}

if (apiMethods.length > 1) {
text.push('Besides Mithril\'s hyperscript function m() we can see different Mithril API methods like ' + parseItems(apiMethods, 'or') + '.');
} else if (apiMethods.length === 1) {
text.push('In addition to the Mithril hyperscript function m(), here we can see an example of Mithril\'s ' + parseItems(apiMethods, 'or') + ' API method.');
}

if (lifecycleMethods.length > 1) {
text.push('It also demonstrates, how Mithril\'s lifecycle methods (aka hooks) like ' + parseItems(lifecycleMethods, 'and') + ' can be used.');
} else if (lifecycleMethods.length === 1) {
text.push('It also shows, how Mithril\'s lifecycle methods can be used. This can be seen here by using the ' + parseItems(lifecycleMethods, 'and') + ' hook.');
}

if (tags.indexOf('vnode') > 0) {
text.push([
'In this example we can also see the usecase of Vnodes (virtual DOM nodes) which is a JavaScript data structure that describes a DOM tree.',
'We can also see the usecase of virtual DOM nodes (Vnodes) that is a JavaScript data structure describing a DOM tree.',
'Also covered in this example is the use of Vnodes or virtual DOM nodes, a JavaScript data structure that describes a DOM tree.'
][textVariantNumber]);
}

if (link && (link.length > 0)) {
text.push('');
text.push([
'You can find [more information](' + link + ') here.',
'More information about this example [can be found here](' + link + ').',
'[Click here](' + link + '), if you need more information on that.',
][textVariantNumber]);
}

text.push('');
text.push([
'Enough said, here it is!',
'Ready? Here we go!',
'So, here are the code snippets.',
][textVariantNumber]);

if (text.length > 0) {
return markdownLibrary.render(text.join("\n"));
}
return '';
});

eleventyConfig.addShortcode('textifyBottom', (title, date, tags, level, version, author, authorUrl) => {

let textVariantNumber = calcSumDigitsOfString(title) % 3;

let text = [];

if (version.length > 0) {
text.push ("\n");
if (version === '2.0.4') {
text.push([
'If anyone has some improvements, that should be addressed, let me know by [opening an issue](https://github.com/tbreuss/mithril-by-examples/issues).',
'Do you see some improvements, that could be addressed here? Then let me know by [opening an issue](https://github.com/tbreuss/mithril-by-examples/issues).',
'Did you note a typo or something else? So let me know by [opening an issue](https://github.com/tbreuss/mithril-by-examples/issues).',
][textVariantNumber]);
} else {
text.push('🤫 Shh! If anyone want\'s to bring this code snippet up to the current version, or has other improvements, that should be addressed, let me know by [opening an issue](https://github.com/tbreuss/mithril-by-examples/issues).');
}

text.push([
'Or simply fork the repository on GitHub, push your commits and send a pull request.',
'As an alternative, you can fork the repository on GitHub, push your commits and send a pull request.',
'Or much better: just fork the repository on GitHub, push your commits and send a pull request.'
][textVariantNumber]);

text.push([
'For starting your work, you can click the edit link below. Thanks for contributing.',
'To start your work, click on the edit link below. Thank you for contributing to this repo.',
'Ready to start your work? Then click on the edit link below. Thanks in advance!'
][textVariantNumber]);
}

if (text.length > 0) {
return markdownLibrary.render(text.join("\n"));
}
return '';
});

eleventyConfig.addShortcode('flems', (content, title, flemsSelected, flemsFiles, flemsLinks, version) => {

if (!flemsSelected || flemsSelected === '') {
flemsSelected = '.js';
Expand Down Expand Up @@ -110,7 +289,7 @@ module.exports = function(eleventyConfig) {
const matches = content.match(/<code class="language-(.+?)">(.*?)<\/code>/sg);

if (!Array.isArray(matches)) {
return content;
return '';
}

let flemsFilesArray = [];
Expand Down Expand Up @@ -177,13 +356,53 @@ module.exports = function(eleventyConfig) {
}

if (flemsFilesArray.length === 0) {
return content;
return '';
}

const jsonFlemsFiles = JSON.stringify(flemsFilesArray);
const jsonFlemsLinks = JSON.stringify(flemsLinksArray);

let html = `
const htmlDepsRows = flemsLinksArray.map((v) => {
return `<tr><td>${v.type}</td><td>${v.name}</td><td>${v.url}</td></tr>`;
}).join();

let html = '';

if (htmlDepsRows.length > 0) {
html += `
<div class="dependencies">
<h2 id="dependencies" tabindex="-1">Dependencies</h2>
<table>
<thead>
<tr>
<th>Type</th>
<th>Name</th>
<th>URL</th>
</tr>
</thead>
<tbody>
${htmlDepsRows}
</tbody>
</table>
</div>
<style>
.dependencies {
color: white;
}
.dependencies table {
margin-top: -1rem;
}
.dependencies h2, .dependencies th, .dependencies td {
color: var(--darkgray);
}
.dependencies th {
text-align: left;
}
</style>
`;
}

html += `
<div class="modal-container">
<label for="modal" class="example-label">Show Live Example in Flems</label>
<label for="modal" class="modal-background"></label>
Expand All @@ -207,7 +426,7 @@ module.exports = function(eleventyConfig) {
</script>
`;

return content + html;
return html;
});

eleventyConfig.addFilter('readableDate', dateObj => {
Expand Down Expand Up @@ -252,6 +471,28 @@ module.exports = function(eleventyConfig) {
return collection.filter(item => item.data.tags.indexOf(tag) !== -1)
});

eleventyConfig.addCollection('levelMap', function(collection) {
let map = new Map();
collection.getFilteredByGlob('./examples/*.*').forEach(item => {
let key = item.data.level
if (!key || key.length <= 0) {
return
}
key = key.toLowerCase()
let level = {
name: item.data.level,
count: 1
}
if (map.has(key)) {
let count = map.get(key).count
level.count = count + 1
}
map.set(key, level)
}
);
return [...map.entries()];
});

eleventyConfig.addCollection('authorMap', function(collection) {
let map = new Map();
collection.getFilteredByGlob('./examples/*.*').forEach(item => {
Expand Down
11 changes: 9 additions & 2 deletions _includes/layouts/example.html
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,16 @@ <h1>{{ title }}</h1>
{%- endfor %}
</p>

{{ content | add_link_to_flems(title, flems.selected, flems.files, flems.links, version) | safe }}
{%- set authorSlug %}/contributors/{{ author | slug }}/{% endset -%}
{% textifyTop title, desc, date | readableDate, tags, level, version, author, authorSlug | url, link, collections.authorMap %}

<p>
{{ content | safe }}

{% flems content, title, flems.selected, flems.files, flems.links, version %}

{% textifyBottom title, date | readableDate, tags, level, version, author, authorSlug | url %}

<p style="margin-top:2rem;">
<a href="{{ '/examples/' | url }}">See more code examples</a>
&nbsp;|&nbsp; <a target="_blank" href="https://github.com/tbreuss/mithril-by-examples/blob/main/{{ page.inputPath }}">Edit this example on GitHub</a>
</p>
2 changes: 1 addition & 1 deletion css/modal.css
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ input[type="checkbox"]:checked ~ .modal {
.example-label {
box-sizing: border-box;
display: inline-block;
margin: 1.5rem 0;
margin: 1.5rem 0 !important;
padding: 0.75rem 4rem;
background-color: #375d91;
color: #f9f9f9;
Expand Down
3 changes: 1 addition & 2 deletions examples/async-and-await-around-mrequest.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
title: Async and Await Around m.request
desc: Demonstrate async and await around Mitrhils `m.request`.
date: 2021-10-26
tags: [m.request, async-await, m.mount, api, oninit]
level: beginner
Expand All @@ -8,8 +9,6 @@ author: viniciusCamargo
layout: layouts/example.html
---

Demonstrate async and await around Mitrhils `m.request`.

## JavaScript

~~~js
Expand Down
3 changes: 1 addition & 2 deletions examples/authentication-wrapper-around-mrequest.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
title: Authentication Wrapper Around m.request
desc: Example showing an authentication wrapper around Mithrils `m.request`.
date: 2021-10-26
tags: [jwt, local storage, wrapper, m.request, m.route, m.mount, vnode, login, api]
level: beginner
Expand All @@ -8,8 +9,6 @@ author: cmnstmntmn
layout: layouts/example.html
---

Example showing an authentication wrapper around Mithrils `m.request`.

## JavaScript

~~~js
Expand Down
4 changes: 1 addition & 3 deletions examples/autocomplete-component.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
title: Autocomplete Component
desc: "Autocomplete component with local options, conversion from a react example from <https://blog.bitsrc.io/building-a-react-autocomplete-component-from-scratch-3f4d5618aa14>."
date: 2021-10-26
tags: [autocomplete, form, input, m.mount]
level: beginner
Expand All @@ -13,9 +14,6 @@ flems:
- app.js
---

Autocomplete component with local options, conversion from a react example from <https://blog.bitsrc.io/building-a-react-autocomplete-component-from-scratch-3f4d5618aa14>.


## CSS

~~~css
Expand Down
3 changes: 1 addition & 2 deletions examples/blurry-dogs.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
title: Blurry Dogs
desc: "This Mithril code example was taken from [Mithril Gitter](https://gitter.im/mithriljs/mithril.js?at=617e0eaf98c13e75500896f2) and slightly edited. It shows random dog images requested by an API and displayed with an adjustable blur effect."
date: 2021-10-31
tags: [animation, m.stream, m.mount, dom, api, oncreate]
level: beginner
Expand All @@ -11,8 +12,6 @@ flems:
- [email protected]/stream.js
---

This Mithril code example was taken from [Mithril Gitter](https://gitter.im/mithriljs/mithril.js?at=617e0eaf98c13e75500896f2) and slightly edited. It shows random dog images requested by an API and displayed with an adjustable blur effect.

~~~js
function BlurryDog({attrs: {src, blur}}) {

Expand Down
Loading

0 comments on commit fca9c85

Please sign in to comment.