Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add widget support #797

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ Welcome to libkiwix's documentation!

usage
api/ref_api
widget
82 changes: 82 additions & 0 deletions docs/widget.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
Kiwix serve widget
====================

Introduction
------------

The kiwix-serve widget provides an easy to embed way to show the `kiwix-serve` homepage.

Usage
-----

To use the widget, simply add an iframe with its `src` attribute set to the `widget` endpoint.
Example HTML Page ::

<!DOCTYPE html>
<html lang="en">
<head>
<title>Widget Test</title>
</head>
<body>
<iframe src="http://192.168.18.8:8080/widget?disabledesc&disablefilter&disabledownload" width=1000 height=1000></iframe>
</body>
</html>

This creates an iframe with the kiwix-serve homepage contents.

Arguments are explained below.

Possible Arguments
-------------------

Currently, the following arguments are supported.

disabledesc (value = N/A)
Disables the description part of a tile.

disablefilter (value = N/A)
Disables the search filters: language, category, tag and search function.

disableclick (value = N/A)
Disables clicking the book to open it for reading.
Comment on lines +40 to +41
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For me (Firefox 103.0) a blank tab is opened


disabledownload (value = N/A)
Disables the download button (if avaialable at all) on the tile.


Custom CSS and JS
-----------------

You can add your custom CSS rules and Javascript code to the widget.

To do that, use the following code as template::

<iframe id="receiver" src="http://192.168.18.8:8080/widget?disabledesc=&disablefilter=&disabledownload=" width="1000" height="1000">
<p>Your browser does not support iframes.</p>
</iframe>

<script>
window.onload = function() {
var receiver = document.getElementById('receiver').contentWindow;
function sendMessage() {
let msg = {
css: `
.book__header {
color:red;
}`,
js: `
function widgetTest() {
console.log("Testing widget");
}
widgetTest();
`
}
receiver.postMessage(msg, 'http://192.168.18.8:8080/widget');
}
sendMessage();
}
</script>


The CSS/JS fields are optional, you may send both or only one.

8 changes: 8 additions & 0 deletions src/server/internalServer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,9 @@ std::unique_ptr<Response> InternalServer::handle_request(const RequestContext& r
if (isEndpointUrl(url, "catch"))
return handle_catch(request);

if (isEndpointUrl(url, "widget"))
return handle_widget(request);

std::string contentUrl = m_root + "/content" + url;
const std::string query = request.get_query();
if ( ! query.empty() )
Expand Down Expand Up @@ -866,6 +869,11 @@ std::unique_ptr<Response> InternalServer::handle_random(const RequestContext& re
}
}

std::unique_ptr<Response> InternalServer::handle_widget(const RequestContext& request)
{
return ContentResponse::build(*this, RESOURCE::templates::widget_html, get_default_data(), "text/html; charset=utf-8", true);
}

std::unique_ptr<Response> InternalServer::handle_captured_external(const RequestContext& request)
{
std::string source = "";
Expand Down
1 change: 1 addition & 0 deletions src/server/internalServer.h
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ class InternalServer {
std::unique_ptr<Response> handle_content(const RequestContext& request);
std::unique_ptr<Response> handle_raw(const RequestContext& request);
std::unique_ptr<Response> handle_locally_customized_resource(const RequestContext& request);
std::unique_ptr<Response> handle_widget(const RequestContext& request);

std::vector<std::string> search_catalog(const RequestContext& request,
kiwix::OPDSDumper& opdsDumper);
Expand Down
2 changes: 2 additions & 0 deletions static/resources_list.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ skin/iso6391To3.js
skin/isotope.pkgd.min.js
skin/index.js
skin/autoComplete.min.js
skin/widget.js
skin/taskbar.css
skin/index.css
skin/fonts/Poppins.ttf
Expand All @@ -20,6 +21,7 @@ templates/search_result.xml
templates/error.html
templates/error.xml
templates/index.html
templates/widget.html
templates/suggestion.json
templates/head_taskbar.html
templates/taskbar_part.html
Expand Down
64 changes: 43 additions & 21 deletions static/skin/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
(function() {
const kiwixServe = (function() {
const root = document.querySelector(`link[type='root']`).getAttribute('href');
const incrementalLoadingParams = {
start: 0,
Expand All @@ -17,6 +17,7 @@
let params = new URLSearchParams(window.location.search || filters || '');
let timer;
let languages = {};
let allowBookClick = true;

function queryUrlBuilder() {
let url = `${root}/catalog/search?`;
Expand Down Expand Up @@ -85,7 +86,7 @@
}

function generateBookHtml(book, sort = false) {
const link = book.querySelector('link[type="text/html"]').getAttribute('href');
let link = book.querySelector('link[type="text/html"]').getAttribute('href');
let iconUrl;
book.querySelectorAll('link[rel="http://opds-spec.org/image/thumbnail"]').forEach(link => {
if (link.getAttribute('type').split(';')[1] == 'width=48' && !iconUrl) {
Expand Down Expand Up @@ -120,6 +121,9 @@
}
const faviconAttr = iconUrl != undefined ? `style="background-image: url('${iconUrl}')"` : '';
const languageAttr = langCode != '' ? `title="${language}" aria-label="${language}"` : 'style="background-color: transparent"';
if (!allowBookClick) {
link = "javascript:void(0)";
}
divTag.innerHTML = `
<div class="book__wrapper">
<a class="book__link" href="${link}" data-hover="Preview">
Expand Down Expand Up @@ -247,14 +251,16 @@
toggleFooter();
}
const kiwixResultText = document.querySelector('.kiwixHomeBody__results')
if (results) {
let resultText = `${results} books`;
if (results === 1) {
resultText = `${results} book`;
if (kiwixResultText) {
if (results) {
let resultText = `${results} books`;
if (results === 1) {
resultText = `${results} book`;
}
kiwixResultText.innerHTML = resultText;
} else {
kiwixResultText.innerHTML = ``;
}
kiwixResultText.innerHTML = resultText;
} else {
kiwixResultText.innerHTML = ``;
}
loader.style.display = 'none';
return books;
Expand All @@ -265,16 +271,20 @@
await fetch(query).then(async (resp) => {
const data = new window.DOMParser().parseFromString(await resp.text(), 'application/xml');
let optionStr = '';
data.querySelectorAll('entry').forEach(entry => {
const title = getInnerHtml(entry, 'title');
const value = getInnerHtml(entry, valueEntryNode);
const hfTitle = humanFriendlyTitle(title);
if (valueEntryNode == 'language') {
languages[value] = hfTitle;
}
optionStr += (hfTitle != '') ? `<option value="${value}">${hfTitle}</option>` : '';
});
document.querySelector(nodeQuery).innerHTML += optionStr;
const entryList = data.querySelectorAll('entry');
const nodeQueryElem = document.querySelector(nodeQuery);
if (entryList && nodeQueryElem) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When nodeQueryElem == null doesn't the loadAndDisplayOptions() function become a no-op? If so why run fetch(query) at all?

entryList.forEach(entry => {
const title = getInnerHtml(entry, 'title');
const value = getInnerHtml(entry, valueEntryNode);
const hfTitle = humanFriendlyTitle(title);
if (valueEntryNode == 'language') {
languages[value] = hfTitle;
}
optionStr += (hfTitle != '') ? `<option value="${value}">${hfTitle}</option>` : '';
});
nodeQueryElem.innerHTML += optionStr;
}
});
}

Expand Down Expand Up @@ -388,6 +398,10 @@
}
});
}

function disableBookClick() {
allowBookClick = false;
}

function addTagElement(tagValue, resetFilter) {
const tagElement = document.getElementsByClassName('tagFilterLabel')[0];
Expand Down Expand Up @@ -429,13 +443,15 @@
}
}

window.addEventListener('resize', (event) => {
function updateBookCount(event) {
if (timer) {clearTimeout(timer)}
timer = setTimeout(() => {
incrementalLoadingParams.count = incrementalLoadingParams.count && viewPortToCount();
loadSubset();
}, 100, event);
});
}

window.addEventListener('resize', (event) => updateBookCount(event));

window.addEventListener('scroll', loadSubset);

Expand Down Expand Up @@ -479,6 +495,7 @@
}
}
updateVisibleParams();
updateBookCount();
document.getElementById('kiwixSearchForm').onsubmit = (event) => {event.preventDefault()};
if (!window.location.search) {
const browserLang = navigator.language.split('-')[0];
Expand All @@ -491,5 +508,10 @@
}
setCookie(filterCookieName, params.toString());
}

return {
updateBookCount,
disableBookClick
};
})();

107 changes: 107 additions & 0 deletions static/skin/widget.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
function disableSearchFilters(widgetStyles) {
const hideNavRule = `
.kiwixNav {
display: none;
}`;
const hideResultsLabelRule = `
.kiwixHomeBody__results {
display: none;
}`;
const hideTagFilterRule = `
.book__tags {
pointer-events: none;
}`;
insertNewCssRules(widgetStyles, [hideNavRule, hideResultsLabelRule, hideTagFilterRule]);
}
Comment on lines +1 to +15
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that if you introduce custom CSS handling first, then disableSearchFilters(), disableDownload(), disableDescription() and hideFooter() can be rewritten via addCustomCss() in a simpler way.


function disableBookClick() {
kiwixServe.disableBookClick();
}

function disableDownload(widgetStyles) {
const hideBookDownloadRule = `
.book__download {
display: none;
}`;
insertNewCssRules(widgetStyles, [hideBookDownloadRule]);
}

function disableDescription(widgetStyles) {
const decreaseHeightRule = `
.book__wrapper {
height:128px;
grid-template-rows: 70px 0 1fr 1fr;
}`;
const hideDescRule = `
.book__description {
display: none;
}`;
insertNewCssRules(widgetStyles, [decreaseHeightRule, hideDescRule]);
}

function hideFooter(widgetStyles) {
const hideFooterRule = `
.kiwixfooter {
display: none !important;
}`;
insertNewCssRules(widgetStyles, [hideFooterRule]);
}

function insertNewCssRules(stylesheet, ruleList) {
if (stylesheet) {
for (rule of ruleList) {
stylesheet.insertRule(rule, 0);
}
}
}

function addCustomCss(cssCode) {
let customCSS = document.createElement('style');
customCSS.innerHTML = cssCode;
document.head.appendChild(customCSS);
}

function addCustomJs(jsCode) {
new Function(`"use strict";${jsCode}`)();
}

function handleMessages(event) {
if ('css' in event.data) {
addCustomCss(event.data.css);
}
if ('js' in event.data) {
addCustomJs(event.data.js);
}
}

function handleWidget() {
const params = new URLSearchParams(window.location.search || filters || '');
const widgetStyleElem = document.createElement('style');
document.head.appendChild(widgetStyleElem);

const widgetStyles = widgetStyleElem.sheet;

const disableFilters = params.has('disablefilter');
const disableClick = params.has('disableclick');
const disableDwld = params.has('disabledownload');
const disableDesc = params.has('disabledesc');

const blankBase = document.createElement('base');
blankBase.target = '_blank';
document.head.appendChild(blankBase); // open all links in new tab

if (disableFilters)
disableSearchFilters(widgetStyles);
if (disableClick)
disableBookClick();
if (disableDwld)
disableDownload(widgetStyles);
if (disableDesc)
disableDescription(widgetStyles);

hideFooter(widgetStyles);
kiwixServe.updateBookCount();
}

window.addEventListener('message', handleMessages);
handleWidget();
Loading