Skip to content
This repository has been archived by the owner on Jul 28, 2023. It is now read-only.

🎨 Add basic router and wp link directive #83

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 42 additions & 1 deletion src/runtime/directives.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { useContext, useMemo } from 'preact/hooks';
import { useContext, useMemo, useEffect } from 'preact/hooks';
import { useSignalEffect } from '@preact/signals';
import { directive } from './hooks';
import { deepSignal } from './deepsignal';
import { prefetch, navigate } from './router';
import { getCallback } from './utils';

const raf = window.requestAnimationFrame;
Expand Down Expand Up @@ -81,4 +82,44 @@ export default () => {
});
}
);

// The `wp-link` directive.
directive(
'link',
({
directives: {
link: { default: link },
},
props: { href },
element,
}) => {
useEffect(() => {
// Prefetch the page if it is in the directive options.
if (link?.prefetch) {
prefetch(href);
}
});

// Don't do anything if it's falsy.
if (link !== false) {
element.props.onclick = async (event) => {
event.preventDefault();

// Fetch the page (or return it from cache).
await navigate(href);

// Update the scroll, depending on the option. True by default.
if (link?.scroll === 'smooth') {
window.scrollTo({
top: 0,
left: 0,
behavior: 'smooth',
});
} else if (link?.scroll !== false) {
window.scrollTo(0, 0);
}
};
}
}
);
};
15 changes: 2 additions & 13 deletions src/runtime/index.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,13 @@
import { hydrate } from 'preact';
import registerDirectives from './directives';
import registerComponents from './components';
import toVdom from './vdom';
import { createRootFragment } from './utils';
import { init } from './router';

/**
* Initialize the initial vDOM.
*/
document.addEventListener('DOMContentLoaded', async () => {
registerDirectives();
registerComponents();

// Create the root fragment to hydrate everything.
const rootFragment = createRootFragment(
document.documentElement,
document.body
);

const vdom = toVdom(document.body);
hydrate(vdom, rootFragment);

await init();
console.log('hydrated!');
});
65 changes: 65 additions & 0 deletions src/runtime/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { hydrate, render } from 'preact';
import toVdom from './vdom';
import { createRootFragment } from './utils';

// The root to render the vdom (document.body).
let rootFragment;

// The cache of visited and prefetched pages.
export const pages = new Map();

// Helper to remove domain and hash from the URL. We are only interesting in
// caching the path and the query.
const cleanUrl = (url) => {
const u = new URL(url, 'http://a.bc');
return u.pathname + u.search;
};

// Fetch a new page and convert it to a static virtual DOM.
const fetchPage = async (url) => {
const html = await window.fetch(url).then((res) => res.text());
const dom = new window.DOMParser().parseFromString(html, 'text/html');
return toVdom(dom.body);
};

// Prefetch a page. We store the promise to avoid triggering a second fetch for
// a page if a fetching has already started.
export const prefetch = (url) => {
url = cleanUrl(url);
if (!pages.has(url)) {
pages.set(url, fetchPage(url));
}
};

// Navigate to a new page.
export const navigate = async (href) => {
const url = cleanUrl(href);
prefetch(url);
const vdom = await pages.get(url);
render(vdom, rootFragment);
window.history.pushState({ wp: { clientNavigation: true } }, '', href);
};

// Listen to the back and forward buttons and restore the page if it's in the
// cache.
window.addEventListener('popstate', async () => {
const url = cleanUrl(window.location); // Remove hash.
if (pages.has(url)) {
const vdom = await pages.get(url);
render(vdom, rootFragment);
} else {
window.location.reload();
}
});

// Initialize the router with the initial DOM.
export const init = async () => {
const url = cleanUrl(window.location); // Remove hash.

// Create the root fragment to hydrate everything.
rootFragment = createRootFragment(document.documentElement, document.body);

const vdom = toVdom(document.body);
pages.set(url, Promise.resolve(vdom));
hydrate(vdom, rootFragment);
};
7 changes: 3 additions & 4 deletions wp-directives.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
<?php

/**
* Plugin Name: wp-directives
* Version: 0.1.0
Expand Down Expand Up @@ -36,7 +35,7 @@ function wp_directives_register_scripts()
wp_enqueue_script('wp-directive-runtime');
}

add_action('init', 'wp_directives_register_scripts');
add_action('wp_enqueue_scripts', 'wp_directives_register_scripts');

function add_wp_link_attribute($block_content)
{
Expand All @@ -48,10 +47,10 @@ function add_wp_link_attribute($block_content)
}

$link = parse_url($w->get_attribute('href'));
if (is_null($link['host']) || ($link['host'] === $site_url['host'])) {
if (!isset($link['host']) || $link['host'] === $site_url['host']) {
$w->set_attribute('wp-link', 'true');
}
};
}
return (string) $w;
}

Expand Down