Started attempt at formalising component system used in BookStack

Added a document to try to define things.
Updated the loading so components are registed dynamically.
Added some standardised ways to reference other elems & define options
This commit is contained in:
Dan Brown 2020-06-24 20:38:08 +01:00
parent 71e7dd5894
commit 76d02cd472
No known key found for this signature in database
GPG Key ID: 46D9F943C24A2EF9
10 changed files with 213 additions and 116 deletions

56
dev/docs/components.md Normal file
View File

@ -0,0 +1,56 @@
# JavaScript Components
This document details the format for JavaScript components in BookStack.
#### Defining a Component in JS
```js
class Dropdown {
setup() {
}
}
```
#### Using a Component in HTML
A component is used like so:
```html
<div component="dropdown"></div>
<!-- or, for multiple -->
<div components="dropdown image-picker"></div>
```
The names will be parsed and new component instance will be created if a matching name is found in the `components/index.js` componentMapping.
#### Element References
Within a component you'll often need to refer to other element instances. This can be done like so:
```html
<div component="dropdown">
<span refs="dropdown@toggle othercomponent@handle">View more</span>
</div>
```
You can then access the span element as `this.$refs.toggle` in your component.
#### Component Options
```html
<div component="dropdown"
option:dropdown:delay="500"
option:dropdown:show>
</div>
```
Will result with `this.$opts` being:
```json
{
"delay": "500",
"show": ""
}
```

View File

@ -3,14 +3,16 @@ import {onSelect} from "../services/dom";
/** /**
* Dropdown * Dropdown
* Provides some simple logic to create simple dropdown menus. * Provides some simple logic to create simple dropdown menus.
* @extends {Component}
*/ */
class DropDown { class DropDown {
constructor(elem) { setup() {
this.container = elem; this.container = this.$el;
this.menu = elem.querySelector('.dropdown-menu, [dropdown-menu]'); this.menu = this.$refs.menu;
this.moveMenu = elem.hasAttribute('dropdown-move-menu'); this.toggle = this.$refs.toggle;
this.toggle = elem.querySelector('[dropdown-toggle]'); this.moveMenu = this.$opts.moveMenu;
this.direction = (document.dir === 'rtl') ? 'right' : 'left'; this.direction = (document.dir === 'rtl') ? 'right' : 'left';
this.body = document.body; this.body = document.body;
this.showing = false; this.showing = false;

View File

@ -1,109 +1,145 @@
import dropdown from "./dropdown"; const componentMapping = {};
import overlay from "./overlay";
import backToTop from "./back-to-top";
import notification from "./notification";
import chapterToggle from "./chapter-toggle";
import expandToggle from "./expand-toggle";
import entitySelectorPopup from "./entity-selector-popup";
import entitySelector from "./entity-selector";
import sidebar from "./sidebar";
import pagePicker from "./page-picker";
import pageComments from "./page-comments";
import wysiwygEditor from "./wysiwyg-editor";
import markdownEditor from "./markdown-editor";
import editorToolbox from "./editor-toolbox";
import imagePicker from "./image-picker";
import collapsible from "./collapsible";
import toggleSwitch from "./toggle-switch";
import pageDisplay from "./page-display";
import shelfSort from "./shelf-sort";
import homepageControl from "./homepage-control";
import headerMobileToggle from "./header-mobile-toggle";
import listSortControl from "./list-sort-control";
import triLayout from "./tri-layout";
import breadcrumbListing from "./breadcrumb-listing";
import permissionsTable from "./permissions-table";
import customCheckbox from "./custom-checkbox";
import bookSort from "./book-sort";
import settingAppColorPicker from "./setting-app-color-picker";
import settingColorPicker from "./setting-color-picker";
import entityPermissionsEditor from "./entity-permissions-editor";
import templateManager from "./template-manager";
import newUserPassword from "./new-user-password";
import detailsHighlighter from "./details-highlighter";
import codeHighlighter from "./code-highlighter";
const componentMapping = { const definitionFiles = require.context('./', false, /\.js$/);
'dropdown': dropdown, for (const fileName of definitionFiles.keys()) {
'overlay': overlay, const name = fileName.replace('./', '').split('.')[0];
'back-to-top': backToTop, if (name !== 'index') {
'notification': notification, componentMapping[name] = definitionFiles(fileName).default;
'chapter-toggle': chapterToggle, }
'expand-toggle': expandToggle, }
'entity-selector-popup': entitySelectorPopup,
'entity-selector': entitySelector,
'sidebar': sidebar,
'page-picker': pagePicker,
'page-comments': pageComments,
'wysiwyg-editor': wysiwygEditor,
'markdown-editor': markdownEditor,
'editor-toolbox': editorToolbox,
'image-picker': imagePicker,
'collapsible': collapsible,
'toggle-switch': toggleSwitch,
'page-display': pageDisplay,
'shelf-sort': shelfSort,
'homepage-control': homepageControl,
'header-mobile-toggle': headerMobileToggle,
'list-sort-control': listSortControl,
'tri-layout': triLayout,
'breadcrumb-listing': breadcrumbListing,
'permissions-table': permissionsTable,
'custom-checkbox': customCheckbox,
'book-sort': bookSort,
'setting-app-color-picker': settingAppColorPicker,
'setting-color-picker': settingColorPicker,
'entity-permissions-editor': entityPermissionsEditor,
'template-manager': templateManager,
'new-user-password': newUserPassword,
'details-highlighter': detailsHighlighter,
'code-highlighter': codeHighlighter,
};
window.components = {}; window.components = {};
const componentNames = Object.keys(componentMapping);
/** /**
* Initialize components of the given name within the given element. * Initialize components of the given name within the given element.
* @param {String} componentName * @param {String} componentName
* @param {HTMLElement|Document} parentElement * @param {HTMLElement|Document} parentElement
*/ */
function initComponent(componentName, parentElement) { function searchForComponentInParent(componentName, parentElement) {
let elems = parentElement.querySelectorAll(`[${componentName}]`); const elems = parentElement.querySelectorAll(`[${componentName}]`);
if (elems.length === 0) return;
let component = componentMapping[componentName];
if (typeof window.components[componentName] === "undefined") window.components[componentName] = [];
for (let j = 0, jLen = elems.length; j < jLen; j++) { for (let j = 0, jLen = elems.length; j < jLen; j++) {
let instance = new component(elems[j]); initComponent(componentName, elems[j]);
if (typeof elems[j].components === 'undefined') elems[j].components = {};
elems[j].components[componentName] = instance;
window.components[componentName].push(instance);
} }
} }
/**
* Initialize a component instance on the given dom element.
* @param {String} name
* @param {Element} element
*/
function initComponent(name, element) {
const componentModel = componentMapping[name];
if (componentModel === undefined) return;
// Create our component instance
let instance;
try {
instance = new componentModel(element);
instance.$el = element;
instance.$refs = parseRefs(name, element);
instance.$opts = parseOpts(name, element);
if (typeof instance.setup === 'function') {
instance.setup();
}
} catch (e) {
console.error('Failed to create component', e, name, element);
}
// Add to global listing
if (typeof window.components[name] === "undefined") {
window.components[name] = [];
}
window.components[name].push(instance);
// Add to element listing
if (typeof element.components === 'undefined') {
element.components = {};
}
element.components[name] = instance;
}
/**
* Parse out the element references within the given element
* for the given component name.
* @param {String} name
* @param {Element} element
*/
function parseRefs(name, element) {
const refs = {};
const prefix = `${name}@`
const refElems = element.querySelectorAll(`[refs*="${prefix}"]`);
for (const el of refElems) {
const refNames = el.getAttribute('refs')
.split(' ')
.filter(str => str.startsWith(prefix))
.map(str => str.replace(prefix, ''));
for (const ref of refNames) {
refs[ref] = el;
}
}
return refs;
}
/**
* Parse out the element component options.
* @param {String} name
* @param {Element} element
* @return {Object<String, String>}
*/
function parseOpts(name, element) {
const opts = {};
const prefix = `option:${name}:`;
for (const {name, value} of element.attributes) {
if (name.startsWith(prefix)) {
const optName = name.replace(prefix, '');
opts[kebabToCamel(optName)] = value || '';
}
}
return opts;
}
/**
* Convert a kebab-case string to camelCase
* @param {String} kebab
* @returns {string}
*/
function kebabToCamel(kebab) {
const ucFirst = (word) => word.slice(0,1).toUpperCase() + word.slice(1);
const words = kebab.split('-');
return words[0] + words.slice(1).map(ucFirst).join();
}
/** /**
* Initialize all components found within the given element. * Initialize all components found within the given element.
* @param parentElement * @param parentElement
*/ */
function initAll(parentElement) { function initAll(parentElement) {
if (typeof parentElement === 'undefined') parentElement = document; if (typeof parentElement === 'undefined') parentElement = document;
for (let i = 0, len = componentNames.length; i < len; i++) {
initComponent(componentNames[i], parentElement); // Old attribute system
for (const componentName of Object.keys(componentMapping)) {
searchForComponentInParent(componentName, parentElement);
}
// New component system
const componentElems = parentElement.querySelectorAll(`[component],[components]`);
for (const el of componentElems) {
const componentNames = `${el.getAttribute('component') || ''} ${(el.getAttribute('components'))}`.toLowerCase().split(' ').filter(Boolean);
for (const name of componentNames) {
initComponent(name, el);
}
} }
} }
window.components.init = initAll; window.components.init = initAll;
export default initAll; export default initAll;
/**
* @typedef Component
* @property {HTMLElement} $el
* @property {Object<String, HTMLElement>} $refs
* @property {Object<String, String>} $opts
*/

View File

@ -27,9 +27,9 @@
<button type="button" class="text-button" action="reply" aria-label="{{ trans('common.reply') }}" title="{{ trans('common.reply') }}">@icon('reply')</button> <button type="button" class="text-button" action="reply" aria-label="{{ trans('common.reply') }}" title="{{ trans('common.reply') }}">@icon('reply')</button>
@endif @endif
@if(userCan('comment-delete', $comment)) @if(userCan('comment-delete', $comment))
<div dropdown class="dropdown-container"> <div component="dropdown" class="dropdown-container">
<button type="button" dropdown-toggle aria-haspopup="true" aria-expanded="false" class="text-button" title="{{ trans('common.delete') }}">@icon('delete')</button> <button type="button" refs="dropdown@toggle" aria-haspopup="true" aria-expanded="false" class="text-button" title="{{ trans('common.delete') }}">@icon('delete')</button>
<ul class="dropdown-menu" role="menu"> <ul refs="dropdown@menu" class="dropdown-menu" role="menu">
<li class="px-m text-small text-muted pb-s">{{trans('entities.comment_delete_confirm')}}</li> <li class="px-m text-small text-muted pb-s">{{trans('entities.comment_delete_confirm')}}</li>
<li><button action="delete" type="button" class="text-button text-neg" >@icon('delete'){{ trans('common.delete') }}</button></li> <li><button action="delete" type="button" class="text-button text-neg" >@icon('delete'){{ trans('common.delete') }}</button></li>
</ul> </ul>

View File

@ -50,13 +50,13 @@
</div> </div>
@if(signedInUser()) @if(signedInUser())
<?php $currentUser = user(); ?> <?php $currentUser = user(); ?>
<div class="dropdown-container" dropdown> <div class="dropdown-container" component="dropdown">
<span class="user-name py-s hide-under-l" dropdown-toggle <span class="user-name py-s hide-under-l" refs="dropdown@toggle"
aria-haspopup="true" aria-expanded="false" aria-label="{{ trans('common.profile_menu') }}" tabindex="0"> aria-haspopup="true" aria-expanded="false" aria-label="{{ trans('common.profile_menu') }}" tabindex="0">
<img class="avatar" src="{{$currentUser->getAvatar(30)}}" alt="{{ $currentUser->name }}"> <img class="avatar" src="{{$currentUser->getAvatar(30)}}" alt="{{ $currentUser->name }}">
<span class="name">{{ $currentUser->getShortName(9) }}</span> @icon('caret-down') <span class="name">{{ $currentUser->getShortName(9) }}</span> @icon('caret-down')
</span> </span>
<ul class="dropdown-menu" role="menu"> <ul refs="dropdown@menu" class="dropdown-menu" role="menu">
<li> <li>
<a href="{{ url("/user/{$currentUser->id}") }}">@icon('user'){{ trans('common.view_profile') }}</a> <a href="{{ url("/user/{$currentUser->id}") }}">@icon('user'){{ trans('common.view_profile') }}</a>
</li> </li>

View File

@ -27,10 +27,13 @@
</div> </div>
<div class="text-center px-m py-xs"> <div class="text-center px-m py-xs">
<div v-show="draftsEnabled" dropdown dropdown-move-menu class="dropdown-container draft-display text"> <div v-show="draftsEnabled"
<button type="button" dropdown-toggle aria-haspopup="true" aria-expanded="false" title="{{ trans('entities.pages_edit_draft_options') }}" class="text-primary text-button"><span class="faded-text" v-text="draftText"></span>&nbsp; @icon('more')</button> component="dropdown"
option:dropdown:move-menu="true"
class="dropdown-container draft-display text">
<button type="button" refs="dropdown@toggle" aria-haspopup="true" aria-expanded="false" title="{{ trans('entities.pages_edit_draft_options') }}" class="text-primary text-button"><span class="faded-text" v-text="draftText"></span>&nbsp; @icon('more')</button>
@icon('check-circle', ['class' => 'text-pos draft-notification svg-icon', ':class' => '{visible: draftUpdated}']) @icon('check-circle', ['class' => 'text-pos draft-notification svg-icon', ':class' => '{visible: draftUpdated}'])
<ul class="dropdown-menu" role="menu"> <ul refs="dropdown@menu" class="dropdown-menu" role="menu">
<li> <li>
<button type="button" @click="saveDraft()" class="text-pos">@icon('save'){{ trans('entities.pages_edit_save_draft') }}</button> <button type="button" @click="saveDraft()" class="text-pos">@icon('save'){{ trans('entities.pages_edit_save_draft') }}</button>
</li> </li>
@ -45,9 +48,9 @@
</div> </div>
<div class="action-buttons px-m py-xs" v-cloak> <div class="action-buttons px-m py-xs" v-cloak>
<div dropdown dropdown-move-menu class="dropdown-container"> <div component="dropdown" dropdown-move-menu class="dropdown-container">
<button type="button" dropdown-toggle aria-haspopup="true" aria-expanded="false" class="text-primary text-button">@icon('edit') <span v-text="changeSummaryShort"></span></button> <button refs="dropdown@toggle" type="button" aria-haspopup="true" aria-expanded="false" class="text-primary text-button">@icon('edit') <span v-text="changeSummaryShort"></span></button>
<ul class="wide dropdown-menu"> <ul refs="dropdown@menu" class="wide dropdown-menu">
<li class="px-l py-m"> <li class="px-l py-m">
<p class="text-muted pb-s">{{ trans('entities.pages_edit_enter_changelog_desc') }}</p> <p class="text-muted pb-s">{{ trans('entities.pages_edit_enter_changelog_desc') }}</p>
<input name="summary" id="summary-input" type="text" placeholder="{{ trans('entities.pages_edit_enter_changelog') }}" v-model="changeSummary" /> <input name="summary" id="summary-input" type="text" placeholder="{{ trans('entities.pages_edit_enter_changelog') }}" v-model="changeSummary" />

View File

@ -50,9 +50,9 @@
@else @else
<a href="{{ $revision->getUrl() }}" target="_blank">{{ trans('entities.pages_revisions_preview') }}</a> <a href="{{ $revision->getUrl() }}" target="_blank">{{ trans('entities.pages_revisions_preview') }}</a>
<span class="text-muted">&nbsp;|&nbsp;</span> <span class="text-muted">&nbsp;|&nbsp;</span>
<div dropdown class="dropdown-container"> <div component="dropdown" class="dropdown-container">
<a dropdown-toggle href="#" aria-haspopup="true" aria-expanded="false">{{ trans('entities.pages_revisions_restore') }}</a> <a refs="dropdown@toggle" href="#" aria-haspopup="true" aria-expanded="false">{{ trans('entities.pages_revisions_restore') }}</a>
<ul class="dropdown-menu" role="menu"> <ul refs="dropdown@menu" class="dropdown-menu" role="menu">
<li class="px-m py-s"><small class="text-muted">{{trans('entities.revision_restore_confirm')}}</small></li> <li class="px-m py-s"><small class="text-muted">{{trans('entities.revision_restore_confirm')}}</small></li>
<li> <li>
<form action="{{ $revision->getUrl('/restore') }}" method="POST"> <form action="{{ $revision->getUrl('/restore') }}" method="POST">
@ -64,9 +64,9 @@
</ul> </ul>
</div> </div>
<span class="text-muted">&nbsp;|&nbsp;</span> <span class="text-muted">&nbsp;|&nbsp;</span>
<div dropdown class="dropdown-container"> <div component="dropdown" class="dropdown-container">
<a dropdown-toggle href="#" aria-haspopup="true" aria-expanded="false">{{ trans('common.delete') }}</a> <a refs="dropdown@toggle" href="#" aria-haspopup="true" aria-expanded="false">{{ trans('common.delete') }}</a>
<ul class="dropdown-menu" role="menu"> <ul refs="dropdown@menu" role="menu">
<li class="px-m py-s"><small class="text-muted">{{trans('entities.revision_delete_confirm')}}</small></li> <li class="px-m py-s"><small class="text-muted">{{trans('entities.revision_delete_confirm')}}</small></li>
<li> <li>
<form action="{{ $revision->getUrl('/delete/') }}" method="POST"> <form action="{{ $revision->getUrl('/delete/') }}" method="POST">

View File

@ -1,9 +1,9 @@
<div class="breadcrumb-listing" dropdown breadcrumb-listing="{{ $entity->getType() }}:{{ $entity->id }}"> <div class="breadcrumb-listing" component="dropdown" breadcrumb-listing="{{ $entity->getType() }}:{{ $entity->id }}">
<div class="breadcrumb-listing-toggle" dropdown-toggle <div class="breadcrumb-listing-toggle" refs="dropdown@toggle"
aria-haspopup="true" aria-expanded="false" tabindex="0"> aria-haspopup="true" aria-expanded="false" tabindex="0">
<div class="separator">@icon('chevron-right')</div> <div class="separator">@icon('chevron-right')</div>
</div> </div>
<div dropdown-menu class="breadcrumb-listing-dropdown card" role="menu"> <div refs="dropdown@menu" class="breadcrumb-listing-dropdown card" role="menu">
<div class="breadcrumb-listing-search"> <div class="breadcrumb-listing-search">
@icon('search') @icon('search')
<input autocomplete="off" type="text" name="entity-search" placeholder="{{ trans('common.search') }}" aria-label="{{ trans('common.search') }}"> <input autocomplete="off" type="text" name="entity-search" placeholder="{{ trans('common.search') }}" aria-label="{{ trans('common.search') }}">

View File

@ -1,10 +1,10 @@
<div dropdown class="dropdown-container" id="export-menu"> <div component="dropdown" class="dropdown-container" id="export-menu">
<div dropdown-toggle class="icon-list-item" <div refs="dropdown@toggle" class="icon-list-item"
aria-haspopup="true" aria-expanded="false" aria-label="{{ trans('entities.export') }}" tabindex="0"> aria-haspopup="true" aria-expanded="false" aria-label="{{ trans('entities.export') }}" tabindex="0">
<span>@icon('export')</span> <span>@icon('export')</span>
<span>{{ trans('entities.export') }}</span> <span>{{ trans('entities.export') }}</span>
</div> </div>
<ul class="wide dropdown-menu" role="menu"> <ul refs="dropdown@menu" class="wide dropdown-menu" role="menu">
<li><a href="{{ $entity->getUrl('/export/html') }}" target="_blank">{{ trans('entities.export_html') }} <span class="text-muted float right">.html</span></a></li> <li><a href="{{ $entity->getUrl('/export/html') }}" target="_blank">{{ trans('entities.export_html') }} <span class="text-muted float right">.html</span></a></li>
<li><a href="{{ $entity->getUrl('/export/pdf') }}" target="_blank">{{ trans('entities.export_pdf') }} <span class="text-muted float right">.pdf</span></a></li> <li><a href="{{ $entity->getUrl('/export/pdf') }}" target="_blank">{{ trans('entities.export_pdf') }} <span class="text-muted float right">.pdf</span></a></li>
<li><a href="{{ $entity->getUrl('/export/plaintext') }}" target="_blank">{{ trans('entities.export_text') }} <span class="text-muted float right">.txt</span></a></li> <li><a href="{{ $entity->getUrl('/export/plaintext') }}" target="_blank">{{ trans('entities.export_text') }} <span class="text-muted float right">.txt</span></a></li>

View File

@ -12,9 +12,9 @@
<input type="hidden" value="{{ $order }}" name="order"> <input type="hidden" value="{{ $order }}" name="order">
<div class="list-sort"> <div class="list-sort">
<div class="list-sort-type dropdown-container" dropdown> <div component="dropdown" class="list-sort-type dropdown-container">
<div dropdown-toggle aria-haspopup="true" aria-expanded="false" aria-label="{{ trans('common.sort_options') }}" tabindex="0">{{ $options[$selectedSort] }}</div> <div refs="dropdown@toggle" aria-haspopup="true" aria-expanded="false" aria-label="{{ trans('common.sort_options') }}" tabindex="0">{{ $options[$selectedSort] }}</div>
<ul class="dropdown-menu"> <ul refs="dropdown@menu" class="dropdown-menu">
@foreach($options as $key => $label) @foreach($options as $key => $label)
<li @if($key === $selectedSort) class="active" @endif><a href="#" data-sort-value="{{$key}}">{{ $label }}</a></li> <li @if($key === $selectedSort) class="active" @endif><a href="#" data-sort-value="{{$key}}">{{ $label }}</a></li>
@endforeach @endforeach