]> BookStack Code Mirror - bookstack/commitdiff
Added ability to use templates
authorDan Brown <redacted>
Sun, 11 Aug 2019 19:04:43 +0000 (20:04 +0100)
committerDan Brown <redacted>
Sun, 11 Aug 2019 19:04:43 +0000 (20:04 +0100)
- Added replace, append and prepend actions for template content into
both the WYSIWYG editor and markdown editor.
- Added further testing to cover.

17 files changed:
app/Entities/Repos/PageRepo.php
app/Http/Controllers/PageController.php
app/Http/Controllers/PageTemplateController.php [new file with mode: 0644]
resources/assets/icons/chevron-down.svg [new file with mode: 0644]
resources/assets/js/components/index.js
resources/assets/js/components/markdown-editor.js
resources/assets/js/components/template-manager.js [new file with mode: 0644]
resources/assets/js/components/wysiwyg-editor.js
resources/assets/sass/_blocks.scss
resources/assets/sass/_components.scss
resources/lang/en/entities.php
resources/views/pages/editor-toolbox.blade.php
resources/views/pages/template-manager-list.blade.php [new file with mode: 0644]
resources/views/pages/template-manager.blade.php [new file with mode: 0644]
resources/views/pages/templates-manager.blade.php [deleted file]
routes/web.php
tests/Entity/PageTemplateTest.php

index adaa7a8d32d4b830c7eaa7738b1eed17f67a4a94..ed142eb611b53f3d715722ded3bf12bdb2e4455f 100644 (file)
@@ -9,6 +9,7 @@ use Carbon\Carbon;
 use DOMDocument;
 use DOMElement;
 use DOMXPath;
+use Illuminate\Support\Collection;
 
 class PageRepo extends EntityRepo
 {
@@ -532,4 +533,29 @@ class PageRepo extends EntityRepo
 
         return $this->publishPageDraft($copyPage, $pageData);
     }
+
+    /**
+     * Get pages that have been marked as templates.
+     * @param int $count
+     * @param int $page
+     * @param string $search
+     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
+     */
+    public function getPageTemplates(int $count = 10, int $page = 1,  string $search = '')
+    {
+        $query = $this->entityQuery('page')
+            ->where('template', '=', true)
+            ->orderBy('name', 'asc')
+            ->skip( ($page - 1) * $count)
+            ->take($count);
+
+        if ($search) {
+            $query->where('name', 'like', '%' . $search . '%');
+        }
+
+        $paginator = $query->paginate($count, ['*'], 'page', $page);
+        $paginator->withPath('/templates');
+
+        return $paginator;
+    }
 }
index 89fb83fd97f116b2005827b30cce0ff459d81e5b..8819510a6d4388bd600e0c89bee5e9038a09fbda 100644 (file)
@@ -110,11 +110,14 @@ class PageController extends Controller
         $this->setPageTitle(trans('entities.pages_edit_draft'));
 
         $draftsEnabled = $this->signedIn;
+        $templates = $this->pageRepo->getPageTemplates(10);
+
         return view('pages.edit', [
             'page' => $draft,
             'book' => $draft->book,
             'isDraft' => true,
-            'draftsEnabled' => $draftsEnabled
+            'draftsEnabled' => $draftsEnabled,
+            'templates' => $templates,
         ]);
     }
 
@@ -239,11 +242,14 @@ class PageController extends Controller
         }
 
         $draftsEnabled = $this->signedIn;
+        $templates = $this->pageRepo->getPageTemplates(10);
+
         return view('pages.edit', [
             'page' => $page,
             'book' => $page->book,
             'current' => $page,
-            'draftsEnabled' => $draftsEnabled
+            'draftsEnabled' => $draftsEnabled,
+            'templates' => $templates,
         ]);
     }
 
diff --git a/app/Http/Controllers/PageTemplateController.php b/app/Http/Controllers/PageTemplateController.php
new file mode 100644 (file)
index 0000000..0594335
--- /dev/null
@@ -0,0 +1,63 @@
+<?php
+
+namespace BookStack\Http\Controllers;
+
+use BookStack\Entities\Repos\PageRepo;
+use BookStack\Exceptions\NotFoundException;
+use Illuminate\Http\Request;
+
+class PageTemplateController extends Controller
+{
+    protected $pageRepo;
+
+    /**
+     * PageTemplateController constructor.
+     * @param $pageRepo
+     */
+    public function __construct(PageRepo $pageRepo)
+    {
+        $this->pageRepo = $pageRepo;
+        parent::__construct();
+    }
+
+    /**
+     * Fetch a list of templates from the system.
+     * @param Request $request
+     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     */
+    public function list(Request $request)
+    {
+        $page = $request->get('page', 1);
+        $search = $request->get('search', '');
+        $templates = $this->pageRepo->getPageTemplates(10, $page, $search);
+
+        if ($search) {
+            $templates->appends(['search' => $search]);
+        }
+
+        return view('pages.template-manager-list', [
+            'templates' => $templates
+        ]);
+    }
+
+    /**
+     * Get the content of a template.
+     * @param $templateId
+     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
+     * @throws NotFoundException
+     */
+    public function get($templateId)
+    {
+        $page = $this->pageRepo->getById('page', $templateId);
+
+        if (!$page->template) {
+            throw new NotFoundException();
+        }
+
+        return response()->json([
+            'html' => $page->html,
+            'markdown' => $page->markdown,
+        ]);
+    }
+
+}
diff --git a/resources/assets/icons/chevron-down.svg b/resources/assets/icons/chevron-down.svg
new file mode 100644 (file)
index 0000000..f08dfaf
--- /dev/null
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M7.41 8L12 12.58 16.59 8 18 9.41l-6 6-6-6z"/><path d="M0 0h24v24H0z" fill="none"/></svg>
\ No newline at end of file
index 1c2abd5202e1b47b964cbb5d0239fddddf12019e..8c12da9b44506fb3beeb8785afe03c11495d362d 100644 (file)
@@ -27,6 +27,7 @@ import customCheckbox from "./custom-checkbox";
 import bookSort from "./book-sort";
 import settingAppColorPicker from "./setting-app-color-picker";
 import entityPermissionsEditor from "./entity-permissions-editor";
+import templateManager from "./template-manager";
 
 const componentMapping = {
     'dropdown': dropdown,
@@ -57,7 +58,8 @@ const componentMapping = {
     'custom-checkbox': customCheckbox,
     'book-sort': bookSort,
     'setting-app-color-picker': settingAppColorPicker,
-    'entity-permissions-editor': entityPermissionsEditor
+    'entity-permissions-editor': entityPermissionsEditor,
+    'template-manager': templateManager,
 };
 
 window.components = {};
index b0e4d693a4e499810ad5bb40e549815095a9b8ec..7cb56eef831ee5fb75636a1f91345a505dd528a8 100644 (file)
@@ -91,6 +91,7 @@ class MarkdownEditor {
         });
 
         this.codeMirrorSetup();
+        this.listenForBookStackEditorEvents();
     }
 
     // Update the input content and render the display.
@@ -461,6 +462,37 @@ class MarkdownEditor {
         })
     }
 
+    listenForBookStackEditorEvents() {
+
+        function getContentToInsert({html, markdown}) {
+            return markdown || html;
+        }
+
+        // Replace editor content
+        window.$events.listen('editor::replace', (eventContent) => {
+            const markdown = getContentToInsert(eventContent);
+            this.cm.setValue(markdown);
+        });
+
+        // Append editor content
+        window.$events.listen('editor::append', (eventContent) => {
+            const cursorPos = this.cm.getCursor('from');
+            const markdown = getContentToInsert(eventContent);
+            const content = this.cm.getValue() + '\n' + markdown;
+            this.cm.setValue(content);
+            this.cm.setCursor(cursorPos.line, cursorPos.ch);
+        });
+
+        // Prepend editor content
+        window.$events.listen('editor::prepend', (eventContent) => {
+            const cursorPos = this.cm.getCursor('from');
+            const markdown = getContentToInsert(eventContent);
+            const content = markdown + '\n' + this.cm.getValue();
+            this.cm.setValue(content);
+            const prependLineCount = markdown.split('\n').length;
+            this.cm.setCursor(cursorPos.line + prependLineCount, cursorPos.ch);
+        });
+    }
 }
 
 export default MarkdownEditor ;
diff --git a/resources/assets/js/components/template-manager.js b/resources/assets/js/components/template-manager.js
new file mode 100644 (file)
index 0000000..b966762
--- /dev/null
@@ -0,0 +1,85 @@
+import * as DOM from "../services/dom";
+
+class TemplateManager {
+
+    constructor(elem) {
+        this.elem = elem;
+        this.list = elem.querySelector('[template-manager-list]');
+        this.searching = false;
+
+        // Template insert action buttons
+        DOM.onChildEvent(this.elem, '[template-action]', 'click', this.handleTemplateActionClick.bind(this));
+
+        // Template list pagination click
+        DOM.onChildEvent(this.elem, '.pagination a', 'click', this.handlePaginationClick.bind(this));
+
+        // Template list item content click
+        DOM.onChildEvent(this.elem, '.template-item-content', 'click', this.handleTemplateItemClick.bind(this));
+
+        this.setupSearchBox();
+    }
+
+    handleTemplateItemClick(event, templateItem) {
+        const templateId = templateItem.closest('[template-id]').getAttribute('template-id');
+        this.insertTemplate(templateId, 'replace');
+    }
+
+    handleTemplateActionClick(event, actionButton) {
+        event.stopPropagation();
+
+        const action = actionButton.getAttribute('template-action');
+        const templateId = actionButton.closest('[template-id]').getAttribute('template-id');
+        this.insertTemplate(templateId, action);
+    }
+
+    async insertTemplate(templateId, action = 'replace') {
+        const resp = await window.$http.get(`/templates/${templateId}`);
+        const eventName = 'editor::' + action;
+        window.$events.emit(eventName, resp.data);
+    }
+
+    async handlePaginationClick(event, paginationLink) {
+        event.preventDefault();
+        const paginationUrl = paginationLink.getAttribute('href');
+        const resp = await window.$http.get(paginationUrl);
+        this.list.innerHTML = resp.data;
+    }
+
+    setupSearchBox() {
+        const searchBox = this.elem.querySelector('.search-box');
+        const input = searchBox.querySelector('input');
+        const submitButton = searchBox.querySelector('button');
+        const cancelButton = searchBox.querySelector('button.search-box-cancel');
+
+        async function performSearch() {
+            const searchTerm = input.value;
+            const resp = await window.$http.get(`/templates`, {
+                search: searchTerm
+            });
+            cancelButton.style.display = searchTerm ? 'block' : 'none';
+            this.list.innerHTML = resp.data;
+        }
+        performSearch = performSearch.bind(this);
+
+        // Searchbox enter press
+        searchBox.addEventListener('keypress', event => {
+            if (event.key === 'Enter') {
+                event.preventDefault();
+                performSearch();
+            }
+        });
+
+        // Submit button press
+        submitButton.addEventListener('click', event => {
+            performSearch();
+        });
+
+        // Cancel button press
+        cancelButton.addEventListener('click', event => {
+            input.value = '';
+            performSearch();
+        });
+    }
+}
+
+export default TemplateManager;
\ No newline at end of file
index eb9f025a749d91edf62fbad3d8be131892523120..a356c6a9e2a0a4fcfa75028caa78a21ddf94c560 100644 (file)
@@ -378,6 +378,27 @@ function customHrPlugin() {
 }
 
 
+function listenForBookStackEditorEvents(editor) {
+
+    // Replace editor content
+    window.$events.listen('editor::replace', ({html}) => {
+        editor.setContent(html);
+    });
+
+    // Append editor content
+    window.$events.listen('editor::append', ({html}) => {
+        const content = editor.getContent() + html;
+        editor.setContent(content);
+    });
+
+    // Prepend editor content
+    window.$events.listen('editor::prepend', ({html}) => {
+        const content = html + editor.getContent();
+        editor.setContent(content);
+    });
+
+}
+
 class WysiwygEditor {
 
     constructor(elem) {
@@ -536,6 +557,7 @@ class WysiwygEditor {
                 });
 
                 function editorChange() {
+                    console.log('CHANGE');
                     let content = editor.getContent();
                     window.$events.emit('editor-html-change', content);
                 }
@@ -553,6 +575,10 @@ class WysiwygEditor {
                     editor.focus();
                 }
 
+                listenForBookStackEditorEvents(editor);
+
+                // TODO - Update to standardise across both editors
+                // Use events within listenForBookStackEditorEvents instead (Different event signature)
                 window.$events.listen('editor-html-update', html => {
                     editor.setContent(html);
                     editor.selection.select(editor.getBody(), true);
index 032b1cbeb1c467983eaf8da8b1e02c5b0c38d0f2..5f11c235532865e3c3325264e69e4ccf104ead61 100644 (file)
   line-height: 1;
 }
 
+.card.border-card {
+  border: 1px solid #DDD;
+}
+
 .card.drag-card {
   border: 1px solid #DDD;
   border-radius: 4px;
index 039ac4dc8d8c3580c7f0374025ac6aa43a0692e3..0b683c6e315f3f9f6bdd70e0b8313621a353fc24 100644 (file)
@@ -655,4 +655,32 @@ body.flexbox-support #entity-selector-wrap .popup-body .form-group {
 }
 .permissions-table tr:hover [permissions-table-toggle-all-in-row] {
   display: inline;
+}
+
+.template-item {
+  cursor: pointer;
+  position: relative;
+  &:hover, .template-item-actions button:hover {
+    background-color: #F2F2F2;
+  }
+  .template-item-actions {
+    position: absolute;
+    top: 0;
+    right: 0;
+    width: 50px;
+    height: 100%;
+    display: flex;
+    flex-direction: column;
+    border-left: 1px solid #DDD;
+  }
+  .template-item-actions button {
+    cursor: pointer;
+    flex: 1;
+    background: #FFF;
+    border: 0;
+    border-top: 1px solid #DDD;
+  }
+  .template-item-actions button:first-child {
+    border-top: 0;
+  }
 }
\ No newline at end of file
index 1a5eca207817620bd85e9ab029c20c173472ad01..3208a6dfcc212f339b47e9a573933cd3c7233137 100644 (file)
@@ -273,6 +273,9 @@ return [
     'templates' => 'Templates',
     'templates_set_as_template' => 'Page is a template',
     'templates_explain_set_as_template' => 'You can set this page as a template so its contents be utilized when creating other pages. Other users will be able to use this template if they have view permissions for this page.',
+    'templates_replace_content' => 'Replace page content',
+    'templates_append_content' => 'Append to page content',
+    'templates_prepend_content' => 'Prepend to page content',
 
     // Profile View
     'profile_user_for_x' => 'User for :time',
index bbf6edee728d390317d4ada9a31a4e595b5cf548..3ce4cfbf3f02632ff736d7983df2125c74386f2c 100644 (file)
         <h4>{{ trans('entities.templates') }}</h4>
 
         <div class="px-l">
-            @include('pages.templates-manager', ['page' => $page])
+            @include('pages.template-manager', ['page' => $page, 'templates' => $templates])
         </div>
 
-
     </div>
 
 </div>
diff --git a/resources/views/pages/template-manager-list.blade.php b/resources/views/pages/template-manager-list.blade.php
new file mode 100644 (file)
index 0000000..68899c8
--- /dev/null
@@ -0,0 +1,20 @@
+{{ $templates->links() }}
+
+@foreach($templates as $template)
+    <div class="card template-item border-card p-m mb-m" draggable="true" template-id="{{ $template->id }}">
+        <div class="template-item-content" title="{{ trans('entities.templates_replace_content') }}">
+            <div>{{ $template->name }}</div>
+            <div class="text-muted">{{ trans('entities.meta_updated', ['timeLength' => $template->updated_at->diffForHumans()]) }}</div>
+        </div>
+        <div class="template-item-actions">
+            <button type="button"
+                    title="{{ trans('entities.templates_prepend_content') }}"
+                    template-action="prepend">@icon('chevron-up')</button>
+            <button type="button"
+                    title="{{ trans('entities.templates_append_content') }}"
+                    template-action="append">@icon('chevron-down')</button>
+        </div>
+    </div>
+@endforeach
+
+{{ $templates->links() }}
\ No newline at end of file
diff --git a/resources/views/pages/template-manager.blade.php b/resources/views/pages/template-manager.blade.php
new file mode 100644 (file)
index 0000000..fbdb70a
--- /dev/null
@@ -0,0 +1,25 @@
+<div template-manager>
+    @if(userCan('templates-manage'))
+        <p class="text-muted small mb-none">
+            {{ trans('entities.templates_explain_set_as_template') }}
+        </p>
+        @include('components.toggle-switch', [
+               'name' => 'template',
+               'value' => old('template', $page->template ? 'true' : 'false') === 'true',
+               'label' => trans('entities.templates_set_as_template')
+        ])
+        <hr>
+    @endif
+
+    @if(count($templates) > 0)
+        <div class="search-box flexible mb-m">
+            <input type="text" name="template-search" placeholder="{{ trans('common.search') }}">
+            <button type="button">@icon('search')</button>
+            <button class="search-box-cancel text-neg hidden" type="button">@icon('close')</button>
+        </div>
+    @endif
+
+    <div template-manager-list>
+        @include('pages.template-manager-list', ['templates' => $templates])
+    </div>
+</div>
\ No newline at end of file
diff --git a/resources/views/pages/templates-manager.blade.php b/resources/views/pages/templates-manager.blade.php
deleted file mode 100644 (file)
index cabb8a4..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-@if(userCan('templates-manage'))
-    <p class="text-muted small mb-none">
-        {{ trans('entities.templates_explain_set_as_template') }}
-    </p>
-    @include('components.toggle-switch', [
-           'name' => 'template',
-           'value' => old('template', $page->template ? 'true' : 'false') === 'true',
-           'label' => trans('entities.templates_set_as_template')
-    ])
-    <hr>
-@endif
\ No newline at end of file
index 94dd576fe2e928a0229123013e14b824d9b14bdb..11ca5d1af9066285d529e59ce42c9529752d9654 100644 (file)
@@ -158,6 +158,9 @@ Route::group(['middleware' => 'auth'], function () {
     Route::get('/search/chapter/{bookId}', 'SearchController@searchChapter');
     Route::get('/search/entity/siblings', 'SearchController@searchSiblings');
 
+    Route::get('/templates', 'PageTemplateController@list');
+    Route::get('/templates/{templateId}', 'PageTemplateController@get');
+
     // Other Pages
     Route::get('/', 'HomeController@index');
     Route::get('/home', 'HomeController@index');
index 17450f49478e882ee05ce7b24c7feb7c978deaab..2655b3bce8a6c673924cda3c218d0f5513062fcc 100644 (file)
@@ -47,4 +47,44 @@ class PageTemplateTest extends TestCase
         ]);
     }
 
+    public function test_templates_content_should_be_fetchable_only_if_page_marked_as_template()
+    {
+        $content = '<div>my_custom_template_content</div>';
+        $page = Page::first();
+        $editor = $this->getEditor();
+        $this->actingAs($editor);
+
+        $templateFetch = $this->get('/templates/' . $page->id);
+        $templateFetch->assertStatus(404);
+
+        $page->html = $content;
+        $page->template = true;
+        $page->save();
+
+        $templateFetch = $this->get('/templates/' . $page->id);
+        $templateFetch->assertStatus(200);
+        $templateFetch->assertJson([
+            'html' => $content,
+            'markdown' => '',
+        ]);
+    }
+
+    public function test_template_endpoint_returns_paginated_list_of_templates()
+    {
+        $editor = $this->getEditor();
+        $this->actingAs($editor);
+
+        $toBeTemplates = Page::query()->take(12)->get();
+        $page = $toBeTemplates->first();
+
+        $emptyTemplatesFetch = $this->get('/templates');
+        $emptyTemplatesFetch->assertDontSee($page->name);
+
+        Page::query()->whereIn('id', $toBeTemplates->pluck('id')->toArray())->update(['template' => true]);
+
+        $templatesFetch = $this->get('/templates');
+        $templatesFetch->assertSee($page->name);
+        $templatesFetch->assertSee('pagination');
+    }
+
 }
\ No newline at end of file
Morty Proxy This is a proxified and sanitized view of the page, visit original site.