Skip to content

Commit

Permalink
Editor preview support for external renderers
Browse files Browse the repository at this point in the history
There is an existing PREVIEWABLE_FILE_MODES setting for this purpose, but it
didn't work for anything except markdown.
  • Loading branch information
brechtvl committed Mar 6, 2023
1 parent 68d7d77 commit ea90dd0
Show file tree
Hide file tree
Showing 10 changed files with 93 additions and 36 deletions.
12 changes: 12 additions & 0 deletions modules/markup/renderer.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,3 +317,15 @@ func IsMarkupFile(name, markup string) bool {
}
return false
}

func PreviewableExtensions() []string {
extensions := []string{}

for _, fileMode := range setting.Repository.Editor.PreviewableFileModes {
if renderer, ok := renderers[fileMode]; ok {
extensions = append(extensions, renderer.Extensions()...)
}
}

return extensions
}
4 changes: 4 additions & 0 deletions modules/structs/miscellaneous.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ type MarkdownOption struct {
//
// in: body
Wiki bool
// Path for extension detection
//
// in: body
Path string
}

// MarkdownRender is a rendered markdown document
Expand Down
35 changes: 25 additions & 10 deletions routers/api/v1/misc/markdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ func Markdown(ctx *context.APIContext) {
switch form.Mode {
case "comment":
fallthrough
case "preview":
fallthrough
case "gfm":
urlPrefix := form.Context
meta := map[string]string{}
Expand All @@ -64,23 +66,36 @@ func Markdown(ctx *context.APIContext) {
urlPrefix = util.URLJoin(setting.AppURL, form.Context)
}
}

// "gfm" = Github Flavored Markdown - set this to render as a markdown document
// "preview" = file preview - render as document based on file extension
// "comment" = render as markdown
if ctx.Repo != nil && ctx.Repo.Repository != nil {
// "gfm" = Github Flavored Markdown - set this to render as a document
if form.Mode == "gfm" {
meta = ctx.Repo.Repository.ComposeDocumentMetas()
} else {
if form.Mode == "comment" {
meta = ctx.Repo.Repository.ComposeMetas()
} else {
meta = ctx.Repo.Repository.ComposeDocumentMetas()
}
}
if form.Mode == "gfm" {
if form.Mode != "comment" {
meta["mode"] = "document"
}

if err := markdown.Render(&markup.RenderContext{
Ctx: ctx,
URLPrefix: urlPrefix,
Metas: meta,
IsWiki: form.Wiki,
markupType := ""
relativePath := ""
if form.Mode == "preview" {
relativePath = form.Path
} else {
markupType = markdown.MarkupName
}

if err := markup.Render(&markup.RenderContext{
Ctx: ctx,
URLPrefix: urlPrefix,
Metas: meta,
IsWiki: form.Wiki,
Type: markupType,
RelativePath: relativePath,
}, strings.NewReader(form.Text), ctx.Resp); err != nil {
ctx.InternalServerError(err)
return
Expand Down
13 changes: 11 additions & 2 deletions routers/api/v1/misc/markdown_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func wrap(ctx *context.Context) *context.APIContext {
}
}

func TestAPI_RenderGFM(t *testing.T) {
func testRenderDocument(t *testing.T, mode, path string) {
setting.AppURL = AppURL
markup.Init(&markup.ProcessorHelper{
IsUsernameMentionable: func(ctx go_context.Context, username string) bool {
Expand All @@ -58,10 +58,11 @@ func TestAPI_RenderGFM(t *testing.T) {
})

options := api.MarkdownOption{
Mode: "gfm",
Mode: mode,
Text: "",
Context: Repo,
Wiki: true,
Path: path,
}
requrl, _ := url.Parse(util.URLJoin(AppURL, "api", "v1", "markdown"))
req := &http.Request{
Expand Down Expand Up @@ -128,6 +129,14 @@ Here are some links to the most important topics. You can find the full list of
}
}

func TestAPI_RenderGFM(t *testing.T) {
testRenderDocument(t, "gfm", "")
}

func TestAPI_RenderPreview(t *testing.T) {
testRenderDocument(t, "preview", "test/test.md")
}

var simpleCases = []string{
// Guard wiki sidebar: special syntax
`[[Guardfile-DSL / Configuring-Guard|Guardfile-DSL---Configuring-Guard]]`,
Expand Down
35 changes: 25 additions & 10 deletions routers/web/misc/markdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ func Markdown(ctx *context.Context) {
switch form.Mode {
case "comment":
fallthrough
case "preview":
fallthrough
case "gfm":
urlPrefix := form.Context
meta := map[string]string{}
Expand All @@ -65,23 +67,36 @@ func Markdown(ctx *context.Context) {
urlPrefix = util.URLJoin(setting.AppURL, form.Context)
}
}

// "gfm" = Github Flavored Markdown - set this to render as a markdown document
// "preview" = file preview - render as document based on file extension
// "comment" = render as markdown
if ctx.Repo != nil && ctx.Repo.Repository != nil {
// "gfm" = Github Flavored Markdown - set this to render as a document
if form.Mode == "gfm" {
meta = ctx.Repo.Repository.ComposeDocumentMetas()
} else {
if form.Mode == "comment" {
meta = ctx.Repo.Repository.ComposeMetas()
} else {
meta = ctx.Repo.Repository.ComposeDocumentMetas()
}
}
if form.Mode == "gfm" {
if form.Mode != "comment" {
meta["mode"] = "document"
}

if err := markdown.Render(&markup.RenderContext{
Ctx: ctx,
URLPrefix: urlPrefix,
Metas: meta,
IsWiki: form.Wiki,
markupType := ""
relativePath := ""
if form.Mode == "preview" {
relativePath = form.Path
} else {
markupType = markdown.MarkupName
}

if err := markup.Render(&markup.RenderContext{
Ctx: ctx,
URLPrefix: urlPrefix,
Metas: meta,
IsWiki: form.Wiki,
Type: markupType,
RelativePath: relativePath,
}, strings.NewReader(form.Text), ctx.Resp); err != nil {
ctx.Error(http.StatusInternalServerError, err.Error())
return
Expand Down
7 changes: 3 additions & 4 deletions routers/web/repo/editor.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/markup"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/typesniffer"
"code.gitea.io/gitea/modules/upload"
Expand Down Expand Up @@ -155,9 +156,8 @@ func editFile(ctx *context.Context, isNewFile bool) {
}
ctx.Data["new_branch_name"] = GetUniquePatchBranchName(ctx)
ctx.Data["last_commit"] = ctx.Repo.CommitID
ctx.Data["MarkdownFileExts"] = strings.Join(setting.Markdown.FileExtensions, ",")
ctx.Data["PreviewableExtensions"] = strings.Join(markup.PreviewableExtensions(), ",")
ctx.Data["LineWrapExtensions"] = strings.Join(setting.Repository.Editor.LineWrapExtensions, ",")
ctx.Data["PreviewableFileModes"] = strings.Join(setting.Repository.Editor.PreviewableFileModes, ",")
ctx.Data["Editorconfig"] = GetEditorConfig(ctx, treePath)

ctx.HTML(http.StatusOK, tplEditFile)
Expand Down Expand Up @@ -207,9 +207,8 @@ func editFilePost(ctx *context.Context, form forms.EditRepoFileForm, isNewFile b
ctx.Data["commit_choice"] = form.CommitChoice
ctx.Data["new_branch_name"] = form.NewBranchName
ctx.Data["last_commit"] = ctx.Repo.CommitID
ctx.Data["MarkdownFileExts"] = strings.Join(setting.Markdown.FileExtensions, ",")
ctx.Data["PreviewableExtensions"] = strings.Join(markup.PreviewableExtensions(), ",")
ctx.Data["LineWrapExtensions"] = strings.Join(setting.Repository.Editor.LineWrapExtensions, ",")
ctx.Data["PreviewableFileModes"] = strings.Join(setting.Repository.Editor.PreviewableFileModes, ",")
ctx.Data["Editorconfig"] = GetEditorConfig(ctx, form.TreePath)

if ctx.HasError() {
Expand Down
4 changes: 2 additions & 2 deletions templates/repo/editor/edit.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@
<div class="ui top attached tabular menu" data-write="write" data-preview="preview" data-diff="diff">
<a class="active item" data-tab="write">{{svg "octicon-code"}} {{if .IsNewFile}}{{.locale.Tr "repo.editor.new_file"}}{{else}}{{.locale.Tr "repo.editor.edit_file"}}{{end}}</a>
{{if not .IsNewFile}}
<a class="item" data-tab="preview" data-url="{{.Repository.Link}}/markdown" data-context="{{.RepoLink}}/src/{{.BranchNameSubURL}}" data-preview-file-modes="{{.PreviewableFileModes}}" data-markdown-mode="gfm">{{svg "octicon-eye"}} {{.locale.Tr "preview"}}</a>
<a class="item" data-tab="preview" data-url="{{.Repository.Link}}/markdown" data-context="{{.RepoLink}}/src/{{.BranchNameSubURL}}" data-markup-mode="preview">{{svg "octicon-eye"}} {{.locale.Tr "preview"}}</a>
<a class="item" data-tab="diff" data-url="{{.RepoLink}}/_preview/{{.BranchName | PathEscapeSegments}}/{{.TreePath | PathEscapeSegments}}" data-context="{{.BranchLink}}">{{svg "octicon-diff"}} {{.locale.Tr "repo.editor.preview_changes"}}</a>
{{end}}
</div>
<div class="ui bottom attached active tab segment" data-tab="write">
<textarea id="edit_area" name="content" class="gt-hidden" data-id="repo-{{.Repository.Name}}-{{.TreePath}}"
data-url="{{.Repository.Link}}/markdown"
data-context="{{.RepoLink}}"
data-markdown-file-exts="{{.MarkdownFileExts}}"
data-previewable-extensions="{{.PreviewableExtensions}}"
data-line-wrap-extensions="{{.LineWrapExtensions}}">
{{.FileContent}}</textarea>
<div class="editor-loading is-loading"></div>
Expand Down
4 changes: 4 additions & 0 deletions templates/swagger/v1_json.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -17681,6 +17681,10 @@
"description": "Mode to render\n\nin: body",
"type": "string"
},
"Path": {
"description": "Path for extension detection\n\nin: body",
"type": "string"
},
"Text": {
"description": "Text markdown to render\n\nin: body",
"type": "string"
Expand Down
8 changes: 4 additions & 4 deletions web_src/js/features/codeeditor.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,16 +130,16 @@ function getFileBasedOptions(filename, lineWrapExts) {
};
}

export async function createCodeEditor(textarea, filenameInput, previewFileModes) {
export async function createCodeEditor(textarea, filenameInput) {
const filename = basename(filenameInput.value);
const previewLink = document.querySelector('a[data-tab=preview]');
const markdownExts = (textarea.getAttribute('data-markdown-file-exts') || '').split(',');
const previewableExts = (textarea.getAttribute('data-previewable-extensions') || '').split(',');
const lineWrapExts = (textarea.getAttribute('data-line-wrap-extensions') || '').split(',');
const isMarkdown = markdownExts.includes(extname(filename));
const previewable = previewableExts.includes(extname(filename));
const editorConfig = getEditorconfig(filenameInput);

if (previewLink) {
if (isMarkdown && (previewFileModes || []).includes('markdown')) {
if (previewable) {
const newUrl = (previewLink.getAttribute('data-url') || '').replace(/(.*)\/.*/i, `$1/markdown`);
previewLink.setAttribute('data-url', newUrl);
previewLink.style.display = '';
Expand Down
7 changes: 3 additions & 4 deletions web_src/js/features/repo-editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,16 @@ import {createCodeEditor} from './codeeditor.js';
import {hideElem, showElem} from '../utils/dom.js';

const {csrfToken} = window.config;
let previewFileModes;

function initEditPreviewTab($form) {
const $tabMenu = $form.find('.tabular.menu');
$tabMenu.find('.item').tab();
const $previewTab = $tabMenu.find(`.item[data-tab="${$tabMenu.data('preview')}"]`);
if ($previewTab.length) {
previewFileModes = $previewTab.data('preview-file-modes').split(',');
$previewTab.on('click', function () {
const $this = $(this);
let context = `${$this.data('context')}/`;
const mode = $this.data('markdown-mode') || 'comment';
const mode = $this.data('markup-mode') || 'comment';
const treePathEl = $form.find('input#tree_path');
if (treePathEl.length > 0) {
context += treePathEl.val();
Expand All @@ -27,6 +25,7 @@ function initEditPreviewTab($form) {
mode,
context,
text: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val(),
path: treePathEl.val(),
}, (data) => {
const $previewPanel = $form.find(`.tab[data-tab="${$tabMenu.data('preview')}"]`);
$previewPanel.html(data);
Expand Down Expand Up @@ -147,7 +146,7 @@ export function initRepoEditor() {
if (!$editArea.length) return;

(async () => {
const editor = await createCodeEditor($editArea[0], $editFilename[0], previewFileModes);
const editor = await createCodeEditor($editArea[0], $editFilename[0]);

// Using events from https://github.com/codedance/jquery.AreYouSure#advanced-usage
// to enable or disable the commit button
Expand Down

0 comments on commit ea90dd0

Please sign in to comment.