Browse Source

Add blocks backend

single-block-api
Peter Stuifzand 2 years ago
parent
commit
5cc4e65638
  1. 15
      backref.go
  2. 434
      editor/src/editor.js
  3. 459
      editor/src/index.js
  4. 25
      editor/src/markdown.js
  5. 8
      editor/src/menu.js
  6. 6
      editor/src/search.js
  7. 206
      editor/src/styles.scss
  8. 513
      file.go
  9. 1
      go.mod
  10. 18
      list-editor/index.js
  11. 2
      list-editor/store.js
  12. 68
      main.go
  13. 227
      render.go
  14. 87
      search.go
  15. 7
      templates/edit.html
  16. 10
      templates/editorjs.html
  17. 195
      templates/layout.html
  18. 2
      templates/sidebar.html

15
backref.go

@ -16,13 +16,6 @@ type Reference struct { @@ -16,13 +16,6 @@ type Reference struct {
Name string
}
// ListItem is a simplification of the information that was saved by the editor
type ListItem struct {
ID string
Indented int
Text string
}
type Refs map[string][]Reference
func processBackrefs(dirname string, page Page) error {
@ -131,11 +124,11 @@ func getBackrefs(fp *FilePages, p string) (map[string][]Backref, error) { @@ -131,11 +124,11 @@ func getBackrefs(fp *FilePages, p string) (map[string][]Backref, error) {
}
result[ref.Name] = append(result[ref.Name], Backref{
Name: ref.Name,
Title: title,
LineHTML: template.HTML(pageText),
Name: ref.Name,
Title: title,
LineHTML: template.HTML(pageText),
LineEditHTML: template.HTML(editPageText),
Line: strings.Map(removeBrackets, ref.Link.Line),
Line: strings.Map(removeBrackets, ref.Link.Line),
})
}

434
editor/src/editor.js

@ -0,0 +1,434 @@ @@ -0,0 +1,434 @@
import listEditor from "wiki-list-editor";
import menu from "./menu";
import createPageSearch from "./fuse";
import util from "./util";
import search from "./search";
import axios from 'axios';
import qs from 'querystring'
import $ from 'jquery';
import Mustache from 'mustache';
import getCaretCoordinates from './caret-position'
import moment from 'moment'
import mermaid from 'mermaid'
import {Network, parseDOTNetwork} from "vis-network/peer";
import PrismJS from 'prismjs'
import 'prismjs/plugins/filter-highlight-all/prism-filter-highlight-all'
import 'prismjs/components/prism-php'
import 'prismjs/components/prism-go'
import 'prismjs/components/prism-perl'
import 'prismjs/components/prism-css'
import 'prismjs/components/prism-markup-templating'
import 'prismjs/components/prism-jq'
import MD from './markdown'
import he from 'he'
function isMultiline(input) {
return input.value.startsWith("```", 0)
|| input.value.startsWith("$$", 0)
}
function addSaver(editor, saveUrl, page, beforeSave) {
return {
save() {
return editor.save().then(outputData => {
beforeSave()
let data = {
'json': 1,
'p': page,
'summary': "",
'content': JSON.stringify(outputData),
};
return axios.post(saveUrl, qs.encode(data))
})
}
}
}
function Indicator(element, timeout) {
let timeoutId;
return {
done() {
timeoutId = setTimeout(() => {
element.classList.add('hide')
}, timeout * 1000);
},
setText(text) {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
element.innerText = text;
element.classList.remove('hide')
},
}
}
function addIndicator(editor, indicator) {
return {
save() {
editor.save().then(() => {
indicator.setText('saved!');
indicator.done();
})
}
}
}
function showSearchResults(searchTool, query, input, value, resultType) {
return showSearchResultsExtended('#link-complete', 'link-template', searchTool, query, input, value, resultType, {
showOnlyResults: true,
belowCursor: true
})
}
function showSearchResultsExtended(element, template, searchTool, query, input, value, resultType, options) {
const $lc = $(element)
return searchTool(query).then(results => {
let opt = options || {};
if (opt.showOnlyResults && (query.length === 0 || !results.length)) {
$lc.fadeOut()
return
}
$lc.data('result-type', resultType)
if (opt.belowCursor) {
let pos = getCaretCoordinates(input, value.selectionEnd, {})
let off = $(input).offset()
pos.top += off.top + pos.height
pos.left += off.left
$lc.offset(pos)
}
var templateText = he.decode(document.getElementById(template).innerHTML);
var rendered = Mustache.render(templateText, {
page: value.trim().replace(/\s+/g, '_'),
results: results
}, {}, ['[[', ']]']);
let selected = $lc.find('li.selected');
if (selected) {
let selectedPos = $lc.find('li').index(selected[0])
rendered = $(rendered)
const $lis = $lc.find('li')
if ($lis.length >= 1) {
selectedPos = Math.min(selectedPos, $lis.length - 1)
rendered.find('li')[selectedPos].classList.add('selected')
}
}
$lc.html(rendered).fadeIn()
return results
})
}
function renderGraphs() {
$('code.language-dot').each(function (i, code) {
if (!code.innerText) {
return true
}
let data = parseDOTNetwork(code.innerText)
let network = new Network(code, data, {
layout: {
randomSeed: 1239043
}
});
$(code).on('click', function () {
return false
})
})
}
function Editor(holder, input) {
let scope = {}
const options = {
transform(text, element) {
if (text === undefined) {
return;
}
let converted = text
if (converted.startsWith("```", 0) || converted.startsWith("$$", 0)) {
converted = MD.render(converted)
// } else if (converted.startsWith("=", 0)) {
// try {
// converted = math.evaluate(converted.substring(1), scope).toString()
// } catch (e) {
// converted = converted + ' <span style="background: red; color: white;">' + e.message + '</span>';
// }
} else {
if (text.match(/^(\w+):: (.+)$/)) {
converted = converted.replace(/^(\w+):: (.*)$/, '**[[$1]]**: $2')
} else if (text.match(/#\[\[TODO]]/)) {
converted = converted.replace('#[[TODO]]', '<input class="checkbox" type="checkbox" />')
} else if (text.match(/#\[\[DONE]]/)) {
converted = converted.replace('#[[DONE]]', '<input class="checkbox" type="checkbox" checked />')
}
MD.options.html = true
converted = MD.renderInline(converted)
MD.options.html = false
}
element.html(converted)
}
}
let inputData = input ? input : JSON.parse(holder.dataset.input)
let editor = listEditor(holder, inputData, options);
holder.$listEditor = editor
$(holder).find('.content input[type="checkbox"]').on('click', function (event) {
let that = this
let id = $(this).closest('.list-item').data('id')
editor.update(id, function (item, prev, next) {
if (that.checked) {
item.text = item.text.replace('#[[TODO]]', '#[[DONE]]')
} else {
item.text = item.text.replace('#[[DONE]]', '#[[TODO]]')
}
return item
});
event.stopPropagation()
return false
})
editor.on('change', function () {
let element = holder
let indicator = Indicator(document.getElementById('save-indicator'), 2);
let saveUrl = element.dataset.saveurl;
let page = element.dataset.page;
indicator.setText('has changes...');
addIndicator(
addSaver(editor, saveUrl, page, () => indicator.setText('saving...')),
indicator
).save()
})
editor.on('rendered', function () {
PrismJS.highlightAll()
mermaid.init()
renderGraphs();
})
menu.connectContextMenu(editor)
return createPageSearch().then(function ({titleSearch, commandSearch, commands}) {
editor.on('start-editing', function (input) {
const $lc = $('#link-complete');
$(input).parents('.list-item').addClass('active');
$lc.on('popup:selected', function (event, linkName, resultType, element) {
let value = input.value
let end = input.selectionEnd
if (resultType === 'link') {
let start = value.lastIndexOf("[[", end)
end += 2
let startAndLink = value.substring(0, start) + "[[" + linkName + "]]"
input.value = startAndLink + value.substring(end)
input.selectionStart = startAndLink.length
input.selectionEnd = startAndLink.length
input.focus()
} else if (resultType === 'command') {
let start = value.lastIndexOf("/", end)
let commandResult = ""
let replace = ""
let prefix = false
let adjustment = 0
let now = moment()
if (linkName === "Current Time") {
commandResult = now.format('HH:mm')
} else if (linkName === "Today") {
commandResult = "[[" + now.format('D MMMM YYYY') + "]]"
} else if (linkName === "Tomorrow") {
commandResult = "[[" + now.add(1, 'day').format('D MMMM YYYY') + "]]"
} else if (linkName === "Yesterday") {
commandResult = "[[" + now.add(-1, 'day').format('D MMMM YYYY') + "]]"
} else if (linkName === "TODO") {
commandResult = "#[[TODO]] "
replace = "#[[DONE]] "
prefix = true
} else if (linkName === "DONE") {
commandResult = "#[[DONE]] "
replace = "#[[TODO]] "
prefix = true
} else if (linkName === "Page Reference") {
commandResult = "[[]]"
adjustment = -2
} else if (linkName === "Code Block") {
commandResult = "```\n\n```"
adjustment = -5
}
let startAndLink = prefix
? commandResult + value.substring(0, start).replace(replace, "")
: value.substring(0, start) + commandResult
input.value = startAndLink + value.substring(end)
input.selectionStart = startAndLink.length + adjustment
input.selectionEnd = startAndLink.length + adjustment
input.focus()
}
return true
})
$lc.on('popup:leave', function (event) {
input.focus()
})
$(input).on('keydown', function (event) {
const isVisible = $('#link-complete:visible').length > 0;
if (event.key === 'Escape' && isVisible) {
$lc.fadeOut()
return false
} else if (event.key === 'Enter' && isVisible) {
const element = $lc.find('li.selected')
const linkName = element.text()
$lc.trigger('popup:selected', [linkName, $lc.data('result-type'), element])
$lc.fadeOut()
return false
} else if (event.key === 'ArrowUp' && isVisible) {
const selected = $lc.find('li.selected')
const prev = selected.prev('li')
if (prev.length) {
prev.addClass('selected')
selected.removeClass('selected')
prev[0].scrollIntoView({block: 'center', inline: 'nearest'})
} else {
// move back from dropdown to input
$lc.trigger('popup:leave')
selected.removeClass('selected')
}
return false
} else if (event.key === 'ArrowDown' && isVisible) {
const selected = $lc.find('li.selected')
if (!selected.length) {
$lc.find('li:not(.selected):first-child').addClass('selected')
return false
}
const next = selected.next('li');
if (next.length) {
next.addClass('selected')
selected.removeClass('selected')
next[0].scrollIntoView({block: 'center', inline: 'nearest'})
}
return false
}
let mirror = {
'[': ']',
'(': ')',
'{': '}',
}
if (!isMultiline(input) && mirror.hasOwnProperty(event.key)) {
let input = this
let val = input.value
let prefix = val.substring(0, input.selectionStart)
let selection = val.substring(input.selectionStart, input.selectionEnd)
let suffix = val.substring(input.selectionEnd)
input.value = prefix + event.key + selection + mirror[event.key] + suffix
input.selectionStart = prefix.length + event.key.length
input.selectionEnd = input.selectionStart + selection.length
$(input).trigger('input')
return false;
}
return true
})
let searchEnabled = false
$(input).on('keyup', function (event) {
if (event.key === '/') {
searchEnabled = true
}
if (searchEnabled && event.key === 'Escape') {
searchEnabled = false
return false;
}
const ignoreKeys = {
'ArrowUp': true,
'ArrowDown': true,
'Enter': true,
}
if (event.key in ignoreKeys) {
return false
}
let value = input.value
let end = input.selectionEnd
let [start, insideLink] = util.cursorInsideLink(value, end)
let insideSearch = false
if (searchEnabled && !insideLink) {
start = value.lastIndexOf("/", end)
insideSearch = start >= 0
}
if (insideSearch) {
let query = value.substring(start + 1, end);
showSearchResults(commandSearch, query, input, value, 'command').then(results => {
if (query.length > 0 && result.length === 0) {
searchEnabled = false
}
})
return true
} else if (insideLink) {
let query = value.substring(start + 2, end);
showSearchResults(titleSearch, query, input, value, 'link');
return true
} else {
$('#link-complete').fadeOut();
}
})
})
editor.on('stop-editing', function (input) {
$(input).parents('.list-item').removeClass('active');
$('#link-complete').off()
PrismJS.highlightAll()
mermaid.init()
renderGraphs();
})
return editor
})
}
let timeout = null;
let searchInput = document.getElementById('search-input');
search(searchInput).then(searcher => {
let showSearch = _.debounce(function (searcher) {
let query = $(searchInput).val()
if (query === '') {
let autocomplete = document.getElementById('autocomplete');
$(autocomplete).hide()
return false
}
showSearchResultsExtended('#autocomplete', 'result-template', query => searcher.search(query), query, searchInput, query, 'search-result')
return true;
}, 200)
$(searchInput).on('keyup', function (event) {
showSearch.cancel()
showSearch(searcher)
return true
})
})
export default Editor;

459
editor/src/index.js

@ -1,19 +1,6 @@ @@ -1,19 +1,6 @@
import listEditor from 'wiki-list-editor';
import MarkdownIt from 'markdown-it';
import MarkdownItWikilinks from './wikilinks';
import MarkdownItMark from 'markdown-it-mark';
import MarkdownItKatex from 'markdown-it-katex';
import axios from 'axios';
import qs from 'querystring'
import $ from 'jquery';
import search from './search';
import createPageSearch from './fuse';
import util from './util';
import Mustache from 'mustache';
import getCaretCoordinates from './caret-position'
import moment from 'moment'
import mermaid from 'mermaid'
import {Network, parseDOTNetwork} from "vis-network/peer";
import PrismJS from 'prismjs'
import 'prismjs/plugins/filter-highlight-all/prism-filter-highlight-all'
import 'prismjs/components/prism-php'
@ -22,13 +9,10 @@ import 'prismjs/components/prism-perl' @@ -22,13 +9,10 @@ import 'prismjs/components/prism-perl'
import 'prismjs/components/prism-css'
import 'prismjs/components/prism-markup-templating'
import 'prismjs/components/prism-jq'
import menu from './menu.js'
import './styles.scss'
import wikiGraph from './graph'
import { create, all } from 'mathjs'
const math = create(all)
import Editor from './editor'
import MD from './markdown'
import 'katex/dist/katex.min.css'
moment.locale('nl')
mermaid.initialize({startOnLoad: true})
@ -40,122 +24,6 @@ PrismJS.plugins.filterHighlightAll.reject.addSelector('.language-dot') @@ -40,122 +24,6 @@ PrismJS.plugins.filterHighlightAll.reject.addSelector('.language-dot')
// wikiGraph('.graph-network')
// })
function isMultiline(input) {
return input.value.startsWith("```", 0)
}
function addSaver(editor, saveUrl, page, beforeSave) {
return {
save() {
return editor.save().then(outputData => {
beforeSave()
let data = {
'json': 1,
'p': page,
'summary': "",
'content': JSON.stringify(outputData),
};
return axios.post(saveUrl, qs.encode(data))
})
}
}
}
function Indicator(element, timeout) {
let timeoutId;
return {
done() {
timeoutId = setTimeout(() => {
element.classList.add('hide')
}, timeout * 1000);
},
setText(text) {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
element.innerText = text;
element.classList.remove('hide')
},
}
}
function addIndicator(editor, indicator) {
return {
save() {
editor.save().then(() => {
indicator.setText('saved!');
indicator.done();
})
}
}
}
function showSearchResults(searchTool, query, input, value, resultType) {
return showSearchResultsExtended('#link-complete', 'link-template', searchTool, query, input, value, resultType, {
showOnlyResults: true,
belowCursor: true
})
}
function showSearchResultsExtended(element, template, searchTool, query, input, value, resultType, options) {
const $lc = $(element)
return searchTool(query).then(results => {
let opt = options || {};
if (opt.showOnlyResults && (query.length === 0 || !results.length)) {
$lc.fadeOut()
return
}
$lc.data('result-type', resultType)
if (opt.belowCursor) {
let pos = getCaretCoordinates(input, value.selectionEnd, {})
let off = $(input).offset()
pos.top += off.top + pos.height
pos.left += off.left
$lc.offset(pos)
}
var templateText = document.getElementById(template).innerHTML;
var rendered = Mustache.render(templateText, {
page: value.trim().replace(/\s+/g, '_'),
results: results
}, {}, ['[[', ']]']);
let selected = $lc.find('li.selected');
if (selected) {
let selectedPos = $lc.find('li').index(selected[0])
rendered = $(rendered)
const $lis = $lc.find('li')
if ($lis.length >= 1) {
selectedPos = Math.min(selectedPos, $lis.length - 1)
rendered.find('li')[selectedPos].classList.add('selected')
}
}
$lc.html(rendered).fadeIn()
return results
})
}
function renderGraphs() {
$('code.language-dot').each(function (i, code) {
if (!code.innerText) {
return true
}
let data = parseDOTNetwork(code.innerText)
let network = new Network(code, data, {
layout: {
randomSeed: 1239043
}
});
$(code).on('click', function () {
return false
})
})
}
/*
* EVENTS
*/
@ -196,318 +64,17 @@ $(document).on('popup:selected', '#autocomplete', function (event, linkName, res @@ -196,318 +64,17 @@ $(document).on('popup:selected', '#autocomplete', function (event, linkName, res
}
})
const MD = new MarkdownIt({
linkify: true,
highlight: function (str, lang) {
if (lang === 'mermaid') {
return '<div class="mermaid">' + str + '</div>';
}
return '';
}
})
MD.use(MarkdownItWikilinks({
baseURL: document.querySelector('body').dataset.baseUrl,
uriSuffix: '',
relativeBaseURL: '/edit/',
htmlAttributes: {
class: 'wiki-link'
},
})).use(MarkdownItMark).use(MarkdownItKatex)
let holders = document.getElementsByClassName('wiki-list-editor');
_.forEach(holders, async (item, i) => {
new Editor(item).then(editor => editor.start());
})
function Editor(holder) {
let scope = {}
const options = {
transform(text, element) {
let converted = text
if (converted.startsWith("```", 0) || converted.startsWith("$$", 0)) {
converted = MD.render(converted)
} else if (converted.startsWith("=", 0)) {
try {
converted = math.evaluate(converted.substring(1), scope).toString()
} catch (e) {
converted = converted + ' <span style="background: red; color: white;">' + e.message + '</span>';
}
} else {
if (text.match(/^(\w+):: (.+)$/)) {
converted = converted.replace(/^(\w+):: (.*)$/, '**[[$1]]**: $2')
} else if (text.match(/#\[\[TODO]]/)) {
converted = converted.replace('#[[TODO]]', '<input class="checkbox" type="checkbox" />')
} else if (text.match(/#\[\[DONE]]/)) {
converted = converted.replace('#[[DONE]]', '<input class="checkbox" type="checkbox" checked />')
}
MD.options.html = true
converted = MD.renderInline(converted)
MD.options.html = false
}
element.html(converted)
}
}
let inputData = JSON.parse(holder.dataset.input)
let editor = listEditor(holder, inputData, options);
holder.$listEditor = editor
$(holder).on('click', '.content input[type="checkbox"]', function (event) {
let that = this
let id = $(this).closest('.list-item').data('id')
editor.update(id, function (item, prev, next) {
if (that.checked) {
item.text = item.text.replace('#[[TODO]]', '#[[DONE]]')
} else {
item.text = item.text.replace('#[[DONE]]', '#[[TODO]]')
}
return item
});
event.stopPropagation()
return true
})
editor.on('change', function () {
let element = holder
let indicator = Indicator(document.getElementById('save-indicator'), 2);
let saveUrl = element.dataset.saveurl;
let page = element.dataset.page;
indicator.setText('has changes...');
addIndicator(
addSaver(editor, saveUrl, page, () => indicator.setText('saving...')),
indicator
).save()
})
editor.on('rendered', function () {
PrismJS.highlightAll()
mermaid.init()
renderGraphs();
})
menu.connectContextMenu(editor)
return createPageSearch().then(function ({titleSearch, commandSearch, commands}) {
editor.on('start-editing', function (input) {
const $lc = $('#link-complete');
$(input).parents('.list-item').addClass('active');
$lc.on('popup:selected', function (event, linkName, resultType, element) {
let value = input.value
let end = input.selectionEnd
if (resultType === 'link') {
let start = value.lastIndexOf("[[", end)
end += 2
let startAndLink = value.substring(0, start) + "[[" + linkName + "]]"
input.value = startAndLink + value.substring(end)
input.selectionStart = startAndLink.length
input.selectionEnd = startAndLink.length
input.focus()
} else if (resultType === 'command') {
let start = value.lastIndexOf("/", end)
let commandResult = ""
let replace = ""
let prefix = false
let adjustment = 0
let now = moment()
if (linkName === "Current Time") {
commandResult = now.format('HH:mm')
} else if (linkName === "Today") {
commandResult = "[[" + now.format('D MMMM YYYY') + "]]"
} else if (linkName === "Tomorrow") {
commandResult = "[[" + now.add(1, 'day').format('D MMMM YYYY') + "]]"
} else if (linkName === "Yesterday") {
commandResult = "[[" + now.add(-1, 'day').format('D MMMM YYYY') + "]]"
} else if (linkName === "TODO") {
commandResult = "#[[TODO]] "
replace = "#[[DONE]] "
prefix = true
} else if (linkName === "DONE") {
commandResult = "#[[DONE]] "
replace = "#[[TODO]] "
prefix = true
} else if (linkName === "Page Reference") {
commandResult = "[[]]"
adjustment = -2
} else if (linkName === "Code Block") {
commandResult = "```\n\n```"
adjustment = -5
}
let startAndLink = prefix
? commandResult + value.substring(0, start).replace(replace, "")
: value.substring(0, start) + commandResult
input.value = startAndLink + value.substring(end)
input.selectionStart = startAndLink.length + adjustment
input.selectionEnd = startAndLink.length + adjustment
input.focus()
}
return true
})
$lc.on('popup:leave', function (event) {
input.focus()
})
$(input).on('keydown', function (event) {
const isVisible = $('#link-complete:visible').length > 0;
if (event.key === 'Escape' && isVisible) {
$lc.fadeOut()
return false
} else if (event.key === 'Enter' && isVisible) {
const element = $lc.find('li.selected')
const linkName = element.text()
$lc.trigger('popup:selected', [linkName, $lc.data('result-type'), element])
$lc.fadeOut()
return false
} else if (event.key === 'ArrowUp' && isVisible) {
const selected = $lc.find('li.selected')
const prev = selected.prev('li')
if (prev.length) {
prev.addClass('selected')
selected.removeClass('selected')
prev[0].scrollIntoView({block: 'center', inline: 'nearest'})
} else {
// move back from dropdown to input
$lc.trigger('popup:leave')
selected.removeClass('selected')
}
return false
} else if (event.key === 'ArrowDown' && isVisible) {
const selected = $lc.find('li.selected')
if (!selected.length) {
$lc.find('li:not(.selected):first-child').addClass('selected')
return false
}
const next = selected.next('li');
if (next.length) {
next.addClass('selected')
selected.removeClass('selected')
next[0].scrollIntoView({block: 'center', inline: 'nearest'})
}
return false
}
let mirror = {
'[': ']',
'(': ')',
'{': '}',
}
if (!isMultiline(input) && mirror.hasOwnProperty(event.key)) {
let input = this
let val = input.value
let prefix = val.substring(0, input.selectionStart)
let selection = val.substring(input.selectionStart, input.selectionEnd)
let suffix = val.substring(input.selectionEnd)
input.value = prefix + event.key + selection + mirror[event.key] + suffix
input.selectionStart = prefix.length + event.key.length
input.selectionEnd = input.selectionStart + selection.length
$(input).trigger('input')
return false;
}
return true
})
let searchEnabled = false
$(input).on('keyup', function (event) {
if (event.key === '/') {
searchEnabled = true
}
if (searchEnabled && event.key === 'Escape') {
searchEnabled = false
return false;
}
const ignoreKeys = {
'ArrowUp': true,
'ArrowDown': true,
'Enter': true,
}
if (event.key in ignoreKeys) {
return false
}
let value = input.value
let end = input.selectionEnd
let [start, insideLink] = util.cursorInsideLink(value, end)
let insideSearch = false
if (searchEnabled && !insideLink) {
start = value.lastIndexOf("/", end)
insideSearch = start >= 0
}
if (insideSearch) {
let query = value.substring(start + 1, end);
showSearchResults(commandSearch, query, input, value, 'command').then(results => {
if (query.length > 0 && result.length === 0) {
searchEnabled = false
}
})
return true
} else if (insideLink) {
let query = value.substring(start + 2, end);
showSearchResults(titleSearch, query, input, value, 'link');
return true
document.querySelectorAll(".page-loader")
.forEach((el, key, parent) => {
let format = el.dataset.format
let edit = el.dataset.edit
fetch('/' + el.dataset.page + '?format=' + format)
.then(res => edit ? res.json() : res.text())
.then(text => {
if (edit) {
new Editor(el, text).then(editor => editor.start());
} else {
$('#link-complete').fadeOut();
el.innerHTML = MD.render(text)
}
})
})
editor.on('stop-editing', function (input) {
$(input).parents('.list-item').removeClass('active');
$('#link-complete').off()
PrismJS.highlightAll()
mermaid.init()
renderGraphs();
})
return editor
})
}
let timeout = null;
let searchInput = document.getElementById('search-input');
search(searchInput).then(searcher => {
let showSearch = _.debounce(function (searcher) {
let query = $(searchInput).val()
if (query === '') {
let autocomplete = document.getElementById('autocomplete');
$(autocomplete).hide()
return false
}
showSearchResultsExtended('#autocomplete', 'result-template', query => searcher.search(query), query, searchInput, query, 'search-result')
return true;
}, 200)
$(searchInput).on('keyup', function (event) {
showSearch.cancel()
showSearch(searcher)
return true
})
})
document.querySelectorAll(".page-loader")
.forEach((el, key, parent) => {
fetch('/' + el.dataset.page + '?format=markdown').then(res => res.text()).then(text => {
el.innerHTML = MD.render(text)
})
})

25
editor/src/markdown.js

@ -0,0 +1,25 @@ @@ -0,0 +1,25 @@
import MarkdownIt from "markdown-it";
import MarkdownItWikilinks from "./wikilinks";
import MarkdownItMark from "markdown-it-mark";
import MarkdownItKatex from "markdown-it-katex";
const MD = new MarkdownIt({
linkify: true,
highlight: function (str, lang) {
if (lang === 'mermaid') {
return '<div class="mermaid">' + str + '</div>';
}
return '';
}
})
MD.use(MarkdownItWikilinks({
baseURL: document.querySelector('body').dataset.baseUrl,
uriSuffix: '',
relativeBaseURL: '/edit/',
htmlAttributes: {
class: 'wiki-link'
},
})).use(MarkdownItMark).use(MarkdownItKatex)
export default MD;

8
editor/src/menu.js

@ -44,6 +44,14 @@ function connectContextMenu(editor) { @@ -44,6 +44,14 @@ function connectContextMenu(editor) {
})
},
className: 'action-copy-line'
},
zoom: {
name: 'Zoom in',
callback: function (key, opt) {
editor.zoomin(this).then(id => {
location.href = '/edit/'+id;
})
}
}
}
});

6
editor/src/search.js

@ -13,11 +13,13 @@ function search(element) { @@ -13,11 +13,13 @@ function search(element) {
let actualResult = [];
$.each(data.hits, (key, value) => {
actualResult.push({
ref: value.id,
title: value.id.replace(/_/g, ' '),
ref: value.fields.page,
title: value.fields.title,
text: value.fragments.text[0]
})
})
element.classList.remove('is-loading')
console.log(actualResult)
return actualResult
})
}

206
editor/src/styles.scss

@ -32,7 +32,9 @@ @@ -32,7 +32,9 @@
@import "~bulma/sass/layout/_all";
@import '~jquery-contextmenu/dist/jquery.contextMenu.css';
@import '~vis-network/styles/vis-network.css';
//@import '~vis-network/styles/vis-network.css';
@import url('https://rsms.me/inter/inter.css');
html {
font-family: 'Inter', sans-serif;
@ -237,3 +239,205 @@ mark { @@ -237,3 +239,205 @@ mark {
.wiki-list-editor {
max-width: 700px;
}
.column a + a :before {
content: '>';
}
.content {
flex-grow: 1;
min-height: 24px;
}
#autocomplete {
z-index: 1;
right: 0;
width: 640px;
overflow-x: hidden;
overflow-y: auto;
height: 600px;
position: absolute;
background: white;
border: 1px solid #ccc;
}
#autocomplete li > a {
display: block;
}
#autocomplete li div {
font-size: 0.8em;
display: block;
color: black;
}
#autocomplete li {
padding: 4px 16px;
max-height: 5em;
overflow: hidden;
}
#autocomplete li:hover {
background: #fefefe;
}
#autocomplete li.selected {
background: lightblue;
}
#link-complete {
z-index: 1;
width: 217px;
overflow-x: hidden;
overflow-y: auto;
height: 300px;
position: absolute;
background: white;
border: 1px solid #ccc;
outline: none;
}
#link-complete li {
padding: 4px 16px;
}
#link-complete li.selected {
background: lightblue;
}
.monospace {
font-family: "Fira Code Retina", monospace;
white-space: pre-wrap;
}
.content input[type="checkbox"] {
vertical-align: text-top;
}
.lighter {
color: #ccc;
}
del {
text-decoration: none;
}
ins {
text-decoration: none;
}
.checklist {
margin-bottom: 1em;
}
.checklist--item {
display: flex;
}
.checklist--item-text {
align-self: center;
}
html {
font-family: 'Inter', sans-serif;
}
body {
font-family: 'Inter', sans-serif;
}
input.input-line {
font-family: 'Inter', sans-serif;
}
.root .list-item {
padding: 3px;
padding-left: 12px;
display: flex;
cursor: pointer;
margin-left: 32px;
flex-direction: column;
border: none;
}
.line {
display: flex;
flex-direction: row;
align-items: center;
}
textarea {
border: none;
resize: none;
}
.list-item .content {
white-space: pre-wrap;
}
.hide {
display: none;
}
.selected {
background: lightblue;
}
.selected .marker {
border-color: lightblue;
}
#editor {
width: 750px;
}
.editor.selected .marker {
/*border-color: white;*/
}
.editor.selected {
background: none;
}
.line {
min-height: 24px;
}
input.input-line, input.input-line:active {
border: none;
outline: none;
margin: 0;
padding: 0;
width: 100%;
font-size: 16px;
}
.gu-mirror {
position: fixed !important;
margin: 0 !important;
z-index: 9999 !important;
opacity: 0.8;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=80)";
filter: alpha(opacity=80);
}
.gu-hide {
display: none !important;
}
.gu-unselectable {
-webkit-user-select: none !important;
-moz-user-select: none !important;
-ms-user-select: none !important;
user-select: none !important;
}
.gu-transit {
opacity: 0.2;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=20)";
filter: alpha(opacity=20);
}
.backrefs {
padding: 24px;
background: #deeeee;
border-top: 3px solid #acc;
}
.breadcrumb li {
max-width: 200px;
}
.breadcrumb li > a {
text-overflow: ellipsis;
overflow: hidden;
display: block;
}

513
file.go

@ -9,9 +9,11 @@ import ( @@ -9,9 +9,11 @@ import (
"html/template"
"io/ioutil"
"log"
"math/rand"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
@ -20,8 +22,9 @@ import ( @@ -20,8 +22,9 @@ import (
)
const (
DocumentsFile = "_documents.json"
LinksFile = "_links.json"
DocumentsFile = "_documents.json"
LinksFile = "_links.json"
BlocksDirectory = "_blocks"
)
type saveMessage struct {
@ -31,6 +34,75 @@ type saveMessage struct { @@ -31,6 +34,75 @@ type saveMessage struct {
author string
}
type Block struct {
Text string
Children []string
Parent string
}
type ID struct {
StrID string
WasInt bool
}
func (id *ID) UnmarshalJSON(data []byte) error {
var intID int
err := json.Unmarshal(data, &intID)
if err == nil {
*id = ID{strconv.FormatInt(int64(intID), 10), true}
return nil
}
var strID string
err = json.Unmarshal(data, &strID)
if err == nil {
*id = ID{strID, false}
return nil
}
return fmt.Errorf("could not unmarshal %q as an int or string", data)
}
func (id *ID) NewID() string {
if id.WasInt {
l := time.Now().UnixNano()
r := rand.Uint64()
return fmt.Sprintf("_%d_%d", l, r)
} else {
return id.StrID
}
}
// ListItemV2 is way to convert from old structure to new structure
type ListItemV2 struct {
ID ID
Indented int
Text string
}
func (v2 ListItemV2) ListItem() ListItem {
return ListItem{
v2.ID.StrID,
v2.Indented,
v2.Text,
}
}
// ListItem is a simplification of the information that was saved by the editor
type ListItem struct {
ID string
Indented int
Text string
}
type ActualListItem struct {
ID string `json:"id"`
Indented int `json:"indented"`
Text string `json:"text"`
Fold string `json:"fold"`
Hidden bool `json:"hidden"`
}
type FilePages struct {
dirname string
saveC chan saveMessage
@ -38,7 +110,13 @@ type FilePages struct { @@ -38,7 +110,13 @@ type FilePages struct {
}
func NewFilePages(dirname string, index bleve.Index) PagesRepository {
err := os.MkdirAll(filepath.Join(dirname, "_blocks"), 0777)
if err != nil {
log.Fatalln(err)
}
fp := &FilePages{dirname, make(chan saveMessage), index}
go func() {
for msg := range fp.saveC {
err := fp.save(msg)
@ -50,38 +128,88 @@ func NewFilePages(dirname string, index bleve.Index) PagesRepository { @@ -50,38 +128,88 @@ func NewFilePages(dirname string, index bleve.Index) PagesRepository {
return fp
}
func convertBlocksToListItems(current string, blocks BlockResponse, indent int) []ActualListItem {
var listItems []ActualListItem
for _, child := range blocks.Children[current] {
l := convertBlocksToListItems(child, blocks, indent+1)
listItems = append(listItems,
ActualListItem{
ID: child,
Indented: indent,
Text: blocks.Texts[child],
Fold: "open",
Hidden: false,
})
listItems = append(listItems, l...)
}
return listItems
}
func (fp *FilePages) Get(title string) Page {
name := strings.Replace(title, " ", "_", -1)
title = strings.Replace(title, "_", " ", -1)
// TODO: cleanup loading of pages