From: Dan Brown Date: Sun, 11 Aug 2019 19:04:43 +0000 (+0100) Subject: Added ability to use templates X-Git-Tag: v0.27~1^2~21^2~1 X-Git-Url: http://source.bookstackapp.com/bookstack/commitdiff_plain/de3e9ab094eb58b400cd5206bd5b4246094363a9 Added ability to use templates - Added replace, append and prepend actions for template content into both the WYSIWYG editor and markdown editor. - Added further testing to cover. --- diff --git a/app/Entities/Repos/PageRepo.php b/app/Entities/Repos/PageRepo.php index adaa7a8d3..ed142eb61 100644 --- a/app/Entities/Repos/PageRepo.php +++ b/app/Entities/Repos/PageRepo.php @@ -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; + } } diff --git a/app/Http/Controllers/PageController.php b/app/Http/Controllers/PageController.php index 89fb83fd9..8819510a6 100644 --- a/app/Http/Controllers/PageController.php +++ b/app/Http/Controllers/PageController.php @@ -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 index 000000000..05943351a --- /dev/null +++ b/app/Http/Controllers/PageTemplateController.php @@ -0,0 +1,63 @@ +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 index 000000000..f08dfafcb --- /dev/null +++ b/resources/assets/icons/chevron-down.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/resources/assets/js/components/index.js b/resources/assets/js/components/index.js index 1c2abd520..8c12da9b4 100644 --- a/resources/assets/js/components/index.js +++ b/resources/assets/js/components/index.js @@ -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 = {}; diff --git a/resources/assets/js/components/markdown-editor.js b/resources/assets/js/components/markdown-editor.js index b0e4d693a..7cb56eef8 100644 --- a/resources/assets/js/components/markdown-editor.js +++ b/resources/assets/js/components/markdown-editor.js @@ -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 index 000000000..b966762d2 --- /dev/null +++ b/resources/assets/js/components/template-manager.js @@ -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 diff --git a/resources/assets/js/components/wysiwyg-editor.js b/resources/assets/js/components/wysiwyg-editor.js index eb9f025a7..a356c6a9e 100644 --- a/resources/assets/js/components/wysiwyg-editor.js +++ b/resources/assets/js/components/wysiwyg-editor.js @@ -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); diff --git a/resources/assets/sass/_blocks.scss b/resources/assets/sass/_blocks.scss index 032b1cbeb..5f11c2355 100644 --- a/resources/assets/sass/_blocks.scss +++ b/resources/assets/sass/_blocks.scss @@ -83,6 +83,10 @@ line-height: 1; } +.card.border-card { + border: 1px solid #DDD; +} + .card.drag-card { border: 1px solid #DDD; border-radius: 4px; diff --git a/resources/assets/sass/_components.scss b/resources/assets/sass/_components.scss index 039ac4dc8..0b683c6e3 100644 --- a/resources/assets/sass/_components.scss +++ b/resources/assets/sass/_components.scss @@ -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 diff --git a/resources/lang/en/entities.php b/resources/lang/en/entities.php index 1a5eca207..3208a6dfc 100644 --- a/resources/lang/en/entities.php +++ b/resources/lang/en/entities.php @@ -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', diff --git a/resources/views/pages/editor-toolbox.blade.php b/resources/views/pages/editor-toolbox.blade.php index bbf6edee7..3ce4cfbf3 100644 --- a/resources/views/pages/editor-toolbox.blade.php +++ b/resources/views/pages/editor-toolbox.blade.php @@ -24,10 +24,9 @@

{{ trans('entities.templates') }}

- @include('pages.templates-manager', ['page' => $page]) + @include('pages.template-manager', ['page' => $page, 'templates' => $templates])
- diff --git a/resources/views/pages/template-manager-list.blade.php b/resources/views/pages/template-manager-list.blade.php new file mode 100644 index 000000000..68899c8a5 --- /dev/null +++ b/resources/views/pages/template-manager-list.blade.php @@ -0,0 +1,20 @@ +{{ $templates->links() }} + +@foreach($templates as $template) +
+
+
{{ $template->name }}
+
{{ trans('entities.meta_updated', ['timeLength' => $template->updated_at->diffForHumans()]) }}
+
+
+ + +
+
+@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 index 000000000..fbdb70a1b --- /dev/null +++ b/resources/views/pages/template-manager.blade.php @@ -0,0 +1,25 @@ +
+ @if(userCan('templates-manage')) +

+ {{ trans('entities.templates_explain_set_as_template') }} +

+ @include('components.toggle-switch', [ + 'name' => 'template', + 'value' => old('template', $page->template ? 'true' : 'false') === 'true', + 'label' => trans('entities.templates_set_as_template') + ]) +
+ @endif + + @if(count($templates) > 0) + + @endif + +
+ @include('pages.template-manager-list', ['templates' => $templates]) +
+
\ 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 index cabb8a43f..000000000 --- a/resources/views/pages/templates-manager.blade.php +++ /dev/null @@ -1,11 +0,0 @@ -@if(userCan('templates-manage')) -

- {{ trans('entities.templates_explain_set_as_template') }} -

- @include('components.toggle-switch', [ - 'name' => 'template', - 'value' => old('template', $page->template ? 'true' : 'false') === 'true', - 'label' => trans('entities.templates_set_as_template') - ]) -
-@endif \ No newline at end of file diff --git a/routes/web.php b/routes/web.php index 94dd576fe..11ca5d1af 100644 --- a/routes/web.php +++ b/routes/web.php @@ -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'); diff --git a/tests/Entity/PageTemplateTest.php b/tests/Entity/PageTemplateTest.php index 17450f494..2655b3bce 100644 --- a/tests/Entity/PageTemplateTest.php +++ b/tests/Entity/PageTemplateTest.php @@ -47,4 +47,44 @@ class PageTemplateTest extends TestCase ]); } + public function test_templates_content_should_be_fetchable_only_if_page_marked_as_template() + { + $content = '
my_custom_template_content
'; + $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