Moved page editing to angular controller and started work on update drafts

This commit is contained in:
Dan Brown 2016-03-09 22:32:07 +00:00
parent 1d6137f7e2
commit 59ce228c2e
14 changed files with 202 additions and 32 deletions

View File

@ -142,6 +142,23 @@ class PageController extends Controller
return redirect($page->getUrl()); return redirect($page->getUrl());
} }
/**
* Save a draft update as a revision.
* @param Request $request
* @param $pageId
* @return \Illuminate\Http\JsonResponse
*/
public function saveUpdateDraft(Request $request, $pageId)
{
$this->validate($request, [
'name' => 'required|string|max:255'
]);
$page = $this->pageRepo->getById($pageId);
$this->checkOwnablePermission('page-update', $page);
$this->pageRepo->saveUpdateDraft($page, $request->only(['name', 'html']));
return response()->json(['status' => 'success', 'message' => 'Draft successfully saved']);
}
/** /**
* Redirect from a special link url which * Redirect from a special link url which
* uses the page id rather than the name. * uses the page id rather than the name.

View File

@ -75,6 +75,9 @@ Route::group(['middleware' => 'auth'], function () {
Route::delete('/{imageId}', 'ImageController@destroy'); Route::delete('/{imageId}', 'ImageController@destroy');
}); });
// Ajax routes
Route::put('/ajax/page/{id}/save-draft', 'PageController@saveUpdateDraft');
// Links // Links
Route::get('/link/{id}', 'PageController@redirectFromLink'); Route::get('/link/{id}', 'PageController@redirectFromLink');

View File

@ -34,7 +34,7 @@ class Page extends Entity
public function revisions() public function revisions()
{ {
return $this->hasMany('BookStack\PageRevision')->orderBy('created_at', 'desc'); return $this->hasMany('BookStack\PageRevision')->where('type', '=', 'version')->orderBy('created_at', 'desc');
} }
public function getUrl() public function getUrl()

View File

@ -1,6 +1,4 @@
<?php <?php namespace BookStack;
namespace BookStack;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@ -8,16 +6,28 @@ class PageRevision extends Model
{ {
protected $fillable = ['name', 'html', 'text']; protected $fillable = ['name', 'html', 'text'];
/**
* Get the user that created the page revision
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function createdBy() public function createdBy()
{ {
return $this->belongsTo('BookStack\User', 'created_by'); return $this->belongsTo('BookStack\User', 'created_by');
} }
/**
* Get the page this revision originates from.
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function page() public function page()
{ {
return $this->belongsTo('BookStack\Page'); return $this->belongsTo('BookStack\Page');
} }
/**
* Get the url for this revision.
* @return string
*/
public function getUrl() public function getUrl()
{ {
return $this->page->getUrl() . '/revisions/' . $this->id; return $this->page->getUrl() . '/revisions/' . $this->id;

View File

@ -4,6 +4,7 @@
use Activity; use Activity;
use BookStack\Book; use BookStack\Book;
use BookStack\Exceptions\NotFoundException; use BookStack\Exceptions\NotFoundException;
use DOMDocument;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use BookStack\Page; use BookStack\Page;
use BookStack\PageRevision; use BookStack\PageRevision;
@ -66,9 +67,10 @@ class PageRepo extends EntityRepo
public function findPageUsingOldSlug($pageSlug, $bookSlug) public function findPageUsingOldSlug($pageSlug, $bookSlug)
{ {
$revision = $this->pageRevision->where('slug', '=', $pageSlug) $revision = $this->pageRevision->where('slug', '=', $pageSlug)
->whereHas('page', function($query) { ->whereHas('page', function ($query) {
$this->restrictionService->enforcePageRestrictions($query); $this->restrictionService->enforcePageRestrictions($query);
}) })
->where('type', '=', 'version')
->where('book_slug', '=', $bookSlug)->orderBy('created_at', 'desc') ->where('book_slug', '=', $bookSlug)->orderBy('created_at', 'desc')
->with('page')->first(); ->with('page')->first();
return $revision !== null ? $revision->page : null; return $revision !== null ? $revision->page : null;
@ -100,8 +102,8 @@ class PageRepo extends EntityRepo
* Save a new page into the system. * Save a new page into the system.
* Input validation must be done beforehand. * Input validation must be done beforehand.
* @param array $input * @param array $input
* @param Book $book * @param Book $book
* @param int $chapterId * @param int $chapterId
* @return Page * @return Page
*/ */
public function saveNew(array $input, Book $book, $chapterId = null) public function saveNew(array $input, Book $book, $chapterId = null)
@ -128,9 +130,9 @@ class PageRepo extends EntityRepo
*/ */
protected function formatHtml($htmlText) protected function formatHtml($htmlText)
{ {
if($htmlText == '') return $htmlText; if ($htmlText == '') return $htmlText;
libxml_use_internal_errors(true); libxml_use_internal_errors(true);
$doc = new \DOMDocument(); $doc = new DOMDocument();
$doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8')); $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
$container = $doc->documentElement; $container = $doc->documentElement;
@ -239,8 +241,8 @@ class PageRepo extends EntityRepo
/** /**
* Updates a page with any fillable data and saves it into the database. * Updates a page with any fillable data and saves it into the database.
* @param Page $page * @param Page $page
* @param int $book_id * @param int $book_id
* @param string $input * @param string $input
* @return Page * @return Page
*/ */
@ -297,6 +299,7 @@ class PageRepo extends EntityRepo
$revision->book_slug = $page->book->slug; $revision->book_slug = $page->book->slug;
$revision->created_by = auth()->user()->id; $revision->created_by = auth()->user()->id;
$revision->created_at = $page->updated_at; $revision->created_at = $page->updated_at;
$revision->type = 'version';
$revision->save(); $revision->save();
// Clear old revisions // Clear old revisions
if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) { if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
@ -306,6 +309,36 @@ class PageRepo extends EntityRepo
return $revision; return $revision;
} }
/**
* Save a page update draft.
* @param Page $page
* @param array $data
* @return PageRevision
*/
public function saveUpdateDraft(Page $page, $data = [])
{
$userId = auth()->user()->id;
$drafts = $this->pageRevision->where('created_by', '=', $userId)
->where('type', 'update_draft')
->where('page_id', '=', $page->id)
->orderBy('created_at', 'desc')->get();
if ($drafts->count() > 0) {
$draft = $drafts->first();
} else {
$draft = $this->pageRevision->newInstance();
$draft->page_id = $page->id;
$draft->slug = $page->slug;
$draft->book_slug = $page->book->slug;
$draft->created_by = $userId;
$draft->type = 'update_draft';
}
$draft->fill($data);
$draft->save();
return $draft;
}
/** /**
* Gets a single revision via it's id. * Gets a single revision via it's id.
* @param $id * @param $id
@ -333,7 +366,7 @@ class PageRepo extends EntityRepo
/** /**
* Changes the related book for the specified page. * Changes the related book for the specified page.
* Changes the book id of any relations to the page that store the book id. * Changes the book id of any relations to the page that store the book id.
* @param int $bookId * @param int $bookId
* @param Page $page * @param Page $page
* @return Page * @return Page
*/ */

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddPageRevisionTypes extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('page_revisions', function (Blueprint $table) {
$table->string('type')->default('version');
$table->index('type');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('page_revisions', function (Blueprint $table) {
$table->dropColumn('type');
});
}
}

View File

@ -213,4 +213,49 @@ module.exports = function (ngApp, events) {
}]); }]);
ngApp.controller('PageEditController', ['$scope', '$http', '$attrs', '$interval', function ($scope, $http, $attrs, $interval) {
$scope.editorOptions = require('./pages/page-form');
$scope.editorHtml = '';
$scope.draftText = '';
var pageId = Number($attrs.pageId);
var isEdit = pageId !== 0;
if (isEdit) {
startAutoSave();
}
$scope.editorChange = function() {
$scope.draftText = '';
}
function startAutoSave() {
var currentTitle = $('#name').val();
var currentHtml = $scope.editorHtml;
console.log('Starting auto save');
$interval(() => {
var newTitle = $('#name').val();
var newHtml = $scope.editorHtml;
if (newTitle !== currentTitle || newHtml !== currentHtml) {
currentHtml = newHtml;
currentTitle = newTitle;
saveDraftUpdate(newTitle, newHtml);
}
}, 1000*5);
}
function saveDraftUpdate(title, html) {
$http.put('/ajax/page/' + pageId + '/save-draft', {
name: title,
html: html
}).then((responseData) => {
$scope.draftText = 'Draft saved'
})
}
}]);
}; };

View File

@ -162,5 +162,31 @@ module.exports = function (ngApp, events) {
}; };
}]); }]);
ngApp.directive('tinymce', [function() {
return {
restrict: 'A',
scope: {
tinymce: '=',
ngModel: '=',
ngChange: '='
},
link: function (scope, element, attrs) {
function tinyMceSetup(editor) {
editor.on('keyup', (e) => {
var content = editor.getContent();
scope.$apply(() => {
scope.ngModel = content;
});
scope.ngChange(content);
});
}
scope.tinymce.extraSetups.push(tinyMceSetup);
tinymce.init(scope.tinymce);
}
}
}])
}; };

View File

@ -119,11 +119,5 @@ function elemExists(selector) {
return document.querySelector(selector) !== null; return document.querySelector(selector) !== null;
} }
// TinyMCE editor
if (elemExists('#html-editor')) {
var tinyMceOptions = require('./pages/page-form');
tinymce.init(tinyMceOptions);
}
// Page specific items // Page specific items
require('./pages/page-show'); require('./pages/page-show');

View File

@ -1,4 +1,4 @@
module.exports = { var mceOptions = module.exports = {
selector: '#html-editor', selector: '#html-editor',
content_css: [ content_css: [
'/css/styles.css' '/css/styles.css'
@ -51,8 +51,15 @@ module.exports = {
args.content = ''; args.content = '';
} }
}, },
extraSetups: [],
setup: function (editor) { setup: function (editor) {
console.log(mceOptions.extraSetups);
for (var i = 0; i < mceOptions.extraSetups.length; i++) {
mceOptions.extraSetups[i](editor);
}
(function () { (function () {
var wrap; var wrap;

View File

@ -8,7 +8,7 @@
@section('content') @section('content')
<div class="flex-fill flex" ng-non-bindable> <div class="flex-fill flex">
<form action="{{$book->getUrl() . '/page'}}" method="POST" class="flex flex-fill"> <form action="{{$book->getUrl() . '/page'}}" method="POST" class="flex flex-fill">
@include('pages/form') @include('pages/form')
@if($chapter) @if($chapter)

View File

@ -8,8 +8,8 @@
@section('content') @section('content')
<div class="flex-fill flex" ng-non-bindable> <div class="flex-fill flex">
<form action="{{$page->getUrl()}}" method="POST" class="flex flex-fill"> <form action="{{$page->getUrl()}}" data-page-id="{{ $page->id }}" method="POST" class="flex flex-fill">
<input type="hidden" name="_method" value="PUT"> <input type="hidden" name="_method" value="PUT">
@include('pages/form', ['model' => $page]) @include('pages/form', ['model' => $page])
</form> </form>

View File

@ -1,7 +1,7 @@
<div class="page-editor flex-fill flex" ng-non-bindable> <div class="page-editor flex-fill flex" ng-controller="PageEditController" page-id="{{ $model->id or 0 }}">
{{ csrf_field() }} {{ csrf_field() }}
<div class="faded-small toolbar"> <div class="faded-small toolbar">
@ -12,7 +12,10 @@
<a onclick="$('body>header').slideToggle();" class="text-button text-primary"><i class="zmdi zmdi-swap-vertical"></i>Toggle Header</a> <a onclick="$('body>header').slideToggle();" class="text-button text-primary"><i class="zmdi zmdi-swap-vertical"></i>Toggle Header</a>
</div> </div>
</div> </div>
<div class="col-sm-8 faded"> <div class="col-sm-4 faded text-center">
<span ng-bind="draftText"></span>
</div>
<div class="col-sm-4 faded">
<div class="action-buttons"> <div class="action-buttons">
<a href="{{ back()->getTargetUrl() }}" class="text-button text-primary"><i class="zmdi zmdi-close"></i>Cancel</a> <a href="{{ back()->getTargetUrl() }}" class="text-button text-primary"><i class="zmdi zmdi-close"></i>Cancel</a>
<button type="submit" id="save-button" class="text-button text-pos"><i class="zmdi zmdi-floppy"></i>Save Page</button> <button type="submit" id="save-button" class="text-button text-pos"><i class="zmdi zmdi-floppy"></i>Save Page</button>
@ -22,13 +25,13 @@
</div> </div>
</div> </div>
<div class="title-input page-title clearfix"> <div class="title-input page-title clearfix" ng-non-bindable>
<div class="input"> <div class="input">
@include('form/text', ['name' => 'name', 'placeholder' => 'Page Title']) @include('form/text', ['name' => 'name', 'placeholder' => 'Page Title'])
</div> </div>
</div> </div>
<div class="edit-area flex-fill flex"> <div class="edit-area flex-fill flex">
<textarea id="html-editor" name="html" rows="5" <textarea id="html-editor" tinymce="editorOptions" ng-change="editorChange" ng-model="editorHtml" name="html" rows="5"
@if($errors->has('html')) class="neg" @endif>@if(isset($model) || old('html')){{htmlspecialchars( old('html') ? old('html') : $model->html)}}@endif</textarea> @if($errors->has('html')) class="neg" @endif>@if(isset($model) || old('html')){{htmlspecialchars( old('html') ? old('html') : $model->html)}}@endif</textarea>
@if($errors->has('html')) @if($errors->has('html'))
<div class="text-neg text-small">{{ $errors->first('html') }}</div> <div class="text-neg text-small">{{ $errors->first('html') }}</div>

View File

@ -24,10 +24,10 @@
<table class="table"> <table class="table">
<tr> <tr>
<th>Name</th> <th width="40%">Name</th>
<th colspan="2">Created By</th> <th colspan="2" width="20%">Created By</th>
<th>Revision Date</th> <th width="20%">Revision Date</th>
<th>Actions</th> <th width="20%">Actions</th>
</tr> </tr>
@foreach($page->revisions as $revision) @foreach($page->revisions as $revision)
<tr> <tr>
@ -38,7 +38,7 @@
@endif @endif
</td> </td>
<td> @if($revision->createdBy) {{$revision->createdBy->name}} @else Deleted User @endif</td> <td> @if($revision->createdBy) {{$revision->createdBy->name}} @else Deleted User @endif</td>
<td><small>{{$revision->created_at->format('jS F, Y H:i:s')}} ({{$revision->created_at->diffForHumans()}})</small></td> <td><small>{{$revision->created_at->format('jS F, Y H:i:s')}} <br> ({{$revision->created_at->diffForHumans()}})</small></td>
<td> <td>
<a href="{{$revision->getUrl()}}" target="_blank">Preview</a> <a href="{{$revision->getUrl()}}" target="_blank">Preview</a>
<span class="text-muted">&nbsp;|&nbsp;</span> <span class="text-muted">&nbsp;|&nbsp;</span>