CONNECT-platform / codedoc

Create beautiful modern documentation websites.

Home Page:https://codedoc.cc

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Hooking codedoc's router to run code on page change

danielsitnik opened this issue · comments

Hello!
I'm working on a plugin to be able to render Mermaid diagrams on Codedoc.

So far I got all the necessary javascript to be included in the pages and the logic to convert the below markdown into the necessary HTML markup.

> :Mermaid
> > graph TD
> >    Start --> Stop

Mermaid works by scanning the current page, finding specific div elements and converting their contents into an SVG image. To do this, you need to run the following JS code on every page:

mermaid.initialize({startOnLoad:true});

My problem right now is that I can only run this code once, when the plugin is loaded and I insert mermaid's <script> tag into the HTML.

Is there a way to hook into Codedoc's router (or any other component) so I can execute the mermaid initialize function on every page change?

Thanks!

That tool looks amazing. I might want to make use of this plugin.

I created this Google Analytics plugin. I think it executes on each page change.

yep, as highlighted by @TysonMN 's example, a custom "navigation" event will be fired whenever there is a page change, so you can hook into it like this:

window.addEventListener('navigation', () => {
  mermaid.initialize(...)
})

Note that this event does NOT fire on initial page load. Also it might get tricky to run a script exactly when everything is loaded. To cover both these issues, I personally use this pattern for executing client-side initialization functions:

import { funcTransport, onReady } from '@connectv/sdh/transport'

export function myInitializationScript() {
  onReady(() => {
    doTheThing()
    window.addEventListener('navigation', doTheThing)
  })
}

export const myInitialization$ = /*#__PURE__*/funcTransport(myInitialization)

This is of course different than injecting scripts as strings, you can read more about it here.

This is great guys, thanks for the explanation!!

@danielsitnik Hi, did you have any luck getting a Mermaid plugin working? I'm also trying to figure out how to get this up and running

Hi @mlota.
Yes! I finished developing the plugin. Right now it works inside my codedoc project but somehow it fails when I turn it into an NPM package and try to use it inside a new project.

I have opened a followup issue here: #117

@mlota the plugin has been published to NPM!

@mlota the plugin has been published to NPM!

Amazing, tried it out and worked first time 👏 . Thanks for creating this plugin!