Adding mermaid.js support to Vuepress

  • Reading time: 2 min
  • Published 3 months ago

I recently set up Vuepress for the first time to create a documentation for a new library I am working on (more on that in a future post). Since that library will do a few things that might appear sort of magical it seems like a good idea to add a few explanatory graphs to the documentation.

Now, what tool combines markdown-friendliness with creating graphs? Yep, you guessed it: Mermaid.js.

There are numerous ways of making Vuepress do things it can't by default:

  • You can overwrite the whole theme
  • You can add Markdown-It plugins for additional markdown processing
  • You can add global components

The long story here would be to elaborate on why overwriting the theme is not an option and the plugin route didn't pan out. But let's not bore ourselves with that story. So yeah, I created a new global component in .vuepress/components/Mermaid.vue and worked away. However, it's unfortunately not exactly that simple. Since Vuepress is a SPA or rather even an PWA, rendering works a little bit different. Which in short means that it's very easy to get something to show up on first load of a component but there's a little work involved in having things work after navigation. The technical background to this can be referenced in the vue-router Documentation.

What I ended up with is rendering the mermaid graphs to SVG and then rendering the SVG in the component's render() Function:

import mermaid from 'mermaid/src/mermaidAPI'

let graphIdCounter = 0

export default {
  name: 'Mermaid',
  data() {
    return {
      svg: undefined,
      graph: this.$slots.default[0].text
    }
  },
  render(h) {
    return h('div', { domProps: { innerHTML: this.svg }})
  },
  mounted() {
    mermaid.initialize({ startOnLoad: true })

    let renderDiv = document.createElement('div')
    document.body.appendChild(renderDiv)

    mermaid.render(
      'mermaid' + ++graphIdCounter,
      this.graph,
      (svg) => {
        this.svg = svg
        document.body.removeChild(renderDiv)
      },
      renderDiv
    )
  }
}

Alas, this was not quite the end of it. I would have hoped that I'd be off to the races with yarn add mermaid. That's not even close. Here's the full list of dependencies you'll have to add:

  • mermaid
  • sass-loader
  • node-sass

After this, adding mermaid graphs anywhere in the documentation markdown is as easy as

<mermaid>
graph TD
mermaid-->isAwesome
isAwesome-->mermaid
</mermaid>

Which then renders to:

Get the number of days in a month with moment.js

  • Reading time: 1 min
  • Published 3 years ago
var date = moment();
var currentMonth = date.month();

var daysInMonth = 31;         // Every month has 31 days
if (currentMonth % 2 == 1) {  // except every other month
    if (currentMonth == 1) {  // and then there is februrary
        if (date.isLeapYear()) { 
            daysInMonth = 29; // which has 29 if it's a leap year
        } else {
            daysInMonth = 28; // and 28 if it isn't.
        }
    } else {
        daysInMonth = 30;
    }
}

Using Git Hooks for code style fixes

  • Reading time: 1 min
  • Published 3 years ago

Pretty much every modern language has an established Coding Style Guide. For PHP, this is PSR-2. As with other style guides of this sort, there is a tool for automatically applying the appropriate fixes to one's code

I only recently finally switched to using PSR-2 and to make sure I wouldn't accidentally miss running the style fixer, I added this little snipped to my .git/hooks/pre-commit-Hook:

modified_php=$(git ls-files --modified | grep "\.php$")

for f in $modified
do
    php-cs-fixer fix --level psr2 $f
done

Redirecting in Laravel Form Requests

  • Reading time: 1 min
  • Published 4 years ago

While Form Request Validation in Laravel 5 usually does exactly what it's supposed to do, I recently had to append a location hash to the redirect URL. Turns out that's as simple as overwriting the FormRequest's getRedirectUrl()-method:

protected function getRedirectUrl()
{
  $url = $this->redirector->getUrlGenerator();
  return $url->previous().'#hash';
}

Dependency Injection with inherited Controllers in Laravel 5

  • Reading time: 3 min
  • Published 4 years ago

Usually, when setting up my controllers in a Laravel 5 application, I end up creating one or several base controllers for different entry points (e.g. APIController, FrontendController, ...) While I deem this a good practice, it can lead to problems with Laravel's otherwise fantastic Dependency Injection. To illustrate, take a look at the following:

// FrontendController.php

class FrontendController extends Controller
{
  public function __construct(\Illuminate\Contracts\Events\Dispatcher $dispatcher)
  {
    $dispatcher->listen('composing: frontend.base', function ()
      {
        // handle root view compose
      }
    );
  }
}

// BlogController.php

class BlogController extends FrontendController
{
  protected $repo = null;

  public function __construct(TextRepository $repo)
  {
    $this->repo = $repo;
  }
}

As some IDEs and testing tools would say: There are multiple problems!

  1. The BlogController's constructor does not call the parent.
  2. The constructors do neither match nor can all required parameters be handed down.
  3. Actually there is no number three but lists with two points always seem awkward.

Look at the mess I made!

Not calling the parent constructor which probably does important things? Bad idea. Could be fixed with changing the constructor of BlogController to:

public function __construct(TextRepository $repo)
{
  $this->repo = $repo;
  parent::__construct();
}

But then again that's not quite right too, is it? It should be more along the lines of this:

public function __construct(\Illuminate\Contracts\Events\Dispatcher $dispatcher, TextRepository $repo)
{
  $this->repo = $repo;
  parent::__construct($dispatcher);
}

Which is ugly as hell. Let alone remembering that for all of the other descendants of the FrontendController.

Let's make that pretty

Right around the time I realized that I didn't want to write that second version even once, I thought "hey, Eloquent models have this boot() method. That could be a way to go."

Said and done. I refactored my code to this:

// FrontendController.php

...
  public function __construct(\Illuminate\Contracts\Events\Dispatcher $dispatcher)
  {
    // the dispatcher stuff

    if (method_exists($this, 'boot')) $this->boot();
  }

// BlogController.php

public class BlogController extends FrontendController
{
  public function boot(TextRepository $repo)
  {
    $this->repo = $repo;
  }
}

Which, of course, did not work. And - as too often is the case - the error was all too obvious to me once I had committed the crime. So, after a while, I figured that if Laravel can resolve class names to inject from type hints, why shouldn't I. Thus followed some research on method reflection and I ended up with this:

// FrontendController.php

...
  public function __construct(\Illuminate\Contracts\Events\Dispatcher $dispatcher)
  {
    // the dispatcher stuff

    if (method_exists($this, 'boot'))
    {
      // resolve the boot dependencies
      $reflect = new \ReflectionMethod($this, 'boot');
      $reflectedParameters = $reflect->getParameters();

      $bootArguments = [];

      foreach ($reflectedParameters as $reflectedParameter)
      {
        preg_match("/.*<required> (.+) \${$reflectedParameter->getName()}/", $reflectedParameter, $typeHint);

        if (count($typeHint) == 2)
        {
          $className = $typeHint[1];
          $resolved = app()->make($className);

          array_push($bootArguments, $resolved);
        } 
      }

      call_user_func_array([&$this, 'boot'], $bootArguments);
    }
  }

And this, finally, works just as expected. One thing to note though: Bad things will happen if you have anything but type-hinted to-be-resolved classes as attributes to the boot() method.

Deep Linking in Eloquent Models

  • Reading time: 1 min
  • Published 4 years ago

Sometimes, when designing data models, it turns out that access to a property of a related model might be handy from the current model. For the case of one-to-many relations, Laravel’s Eloquent already comes with the hasManyThrough()-method. But what if it’s a one-to-one relation? And what if the attribute one wants to have access to is up a few levels in the model hierarchy? Well, turns out that can be pretty easily done, too.

Assuming, three models A, B, C all related, e.g. B has a_id, C has b_id and C would benefit from direct access to A, that can be achieved through Eloquent with the following code:

class C extends Model
{
    ...

    public function b()
    {
        return $this->belongsTo('B');
    }

    public function a()
    {
        return $this->belongsTo('A');
    }

    public function getAIDAttribute()
    {
        return $this->b->a_id;
    }

    ...
}

Of course, one might also use this to fetch a specific attribute instead of creating a complete relation. Keep in mind though, that this may cause serious performance issues since the ORM has to fetch all referenced entities before it can return anything.

Lightweight links for Prism.js

  • Reading time: 1 min
  • Published 4 years ago

Although Prism.js provides a very good autolinker plugin, it did not quite fit my needs for a recent project. Here's what I came up with as a stupidly simple replacement that's not as sophisticated (i.e. does not do links in Markdown and such stuff) but works perfectly well with to-be-highlighted JSON.

Prism.hooks.add('wrap', function(env) {
    if (env.type == 'string', env.content.match(/http/))
    {
        env.content = "<a href=\\"" 
                    + env.content.replace('"', '') 
                    + "\\">" 
                    + env.content 
                    + "</a>";
    }
});

Just add this to your site's scripts and everything will be better.

On showing tables

  • Reading time: 1 min
  • Published 4 years ago

Showing the existing tables in a database can be really handy. Unfortunately, MySQL's SHOW TABLES; is not a standard sql command. Although it quite honestly should be. Thus, for quick reference, here goes:

  • MySQL: SHOW TABLES;
  • Postgres: SELECT name FROM pg_catalog.pg_tables;
  • SQLite: SELECT name FROM sqlite_master WHERE type = 'table';

There probably is a SELECT-Syntax for MySQL too, but who really cares? The one above is so much shorter in any case.

Speeding up test cycles

  • Reading time: 1 min
  • Published 4 years ago

Codeception supports several layers of selecting which tests to actually run when you invoke codecept run. This can - among other times - be extremely useful when you're trying to fix a bug and you really only need that one single test method to run or when you're just doing API development and don't need to check all of your UI integration tests for the time being.

# run all tests in all test suites
$ ./codecept run 

# run all tests in a single test suite
$ ./codecept run <suite> 

# run a single test case in the given suite
$ ./codecept run <suite> <test>          

# run only the given method in the test case
$ ./codecept run <suite> <test>:<method>