Skip to content

Add support for 3D/CAD file formats preview #34794

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"minimatch": "10.0.2",
"monaco-editor": "0.52.2",
"monaco-editor-webpack-plugin": "7.1.0",
"online-3d-viewer": "0.16.0",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIRC it bloats the binary about 1MB

Can we introduce an config option?

For example:

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From a user's perspective, I personally feel that direct integration is better than dynamic loading.
Because building and installation are one-time processes.
However, if we switch to dynamic loading, each time it might require dynamically loading 1MB of JavaScript.
Especially in the current Chinese network environment, sometimes even some external CDNs cannot be accessed, which would directly make the preview unavailable.

So I personally vote for integration.
Of course, the final decision is up to you.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

However, if we switch to dynamic loading, each time it might require dynamically loading 1MB of JavaScript.

Not "each", only once, there is browser cahce.

Especially in the current Chinese network environment, sometimes even some external CDNs cannot be accessed, which would directly make the preview unavailable.

That's why a config option to let users choose, or deploy one locally.


If we build the renders into Gitea's binary, then it bloats the binary soon when we introduce more in the future.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I fully understand your original intention, but I think this still stems from the perspective of operators. From a user's point of view, such an option shouldn't exist (or there's simply no need for it at all) – the default provided to users should inherently be the optimal solution.

Of course, I recognize that Gitea, as an open-source platform, does have many "operator" users. Your original intention might be to allow them to choose freely, but personally, I wonder if such customization is getting too caught up in minor details?

Alright, I've shared my thoughts. It's up to you all. If adjustments are needed, I'll cooperate with the changes.

Copy link
Contributor

@wxiaoguang wxiaoguang Jun 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Share some of my thoughts:

There are different requirements for various kinds of files to render.

  • Some are widely-used, for example: CSV, PDF, etc
  • Some are only used by some of the users: asciidoc, asciicast, console, 3d models, etc. The percentage varies.

So the question is how to make Gitea have a stable and flexible design to satisfy more renders in the future. Then we have some choices:

  1. Only make widely-used renders builtin, keep the release binary as small as possible.
  2. Make all renders builtin, then we should have some estimation about the side effects, and how large the binary would be in the future.

I haven't got a clear picture of this feature at the moment. What do other maintainers think about?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

on the topic of size I compared 4fc626d with 2e80917 via gsa and this adds 336kB - I don't have a point to make with this, it's just a datapoint for the topic.


my 2 cents on the topic are that we might as well bundle this in if it brings benefit to end users. As an user and and operator I'd rather keep dependencies local to my network so in the event my network goes offline (as in I have no connection to external sites) I can use gitea with all it's features without issue.
If we decide to outsource this into a "source the package from there" setting we remove this feature in a way as the only way to have a fully offline instance with all features would be to setup a webserver to host the packages, load them and remember to update them with the instance.

Though I don't mind less common renderers being outsourced to programs which will do a better job at it and it's "easy" to setup. Take pandoc for example - you can take the gitea container, add pandoc to it and you still have a fully featured offline capable gitea (only outside network connection that is required is during pandoc installation).

Copy link
Member

@lunny lunny Jun 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we have a render plugin concept, and it can be installed dynamically. It can resolve the bloating binary problem. A render plugin could be a NPM package.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Combining the above discussions, I think we need to first reach a unified consensus on the final approach and establish a shared goal before proceeding with the next steps of the work.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My opinions are:

  1. It's fine to make this render builtin
  2. Before introducing too many renders and bloating the binary size too much, we need to take at least one action:
    1. Split some sub-commands into a separate binary (especially the git hook related)
    2. Make the renders plug-able

"pdfobject": "2.3.1",
"perfect-debounce": "1.0.0",
"postcss": "8.5.5",
Expand Down
2 changes: 1 addition & 1 deletion templates/repo/view_file.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@
{{else if .IsPDFFile}}
<div class="pdf-content is-loading" data-global-init="initPdfViewer" data-src="{{$.RawFileLink}}" data-fallback-button-text="{{ctx.Locale.Tr "repo.diff.view_file"}}"></div>
{{else}}
<a href="{{$.RawFileLink}}" rel="nofollow" class="tw-p-4">{{ctx.Locale.Tr "repo.file_view_raw"}}</a>
<div class="file-view-container" data-global-init="initFileView" data-filename="{{.TreePath}}" data-url="{{$.RawFileLink}}" data-fallback-text="{{ctx.Locale.Tr "repo.file_view_raw"}}"></div>
{{end}}
</div>
{{else if .FileSize}}
Expand Down
11 changes: 8 additions & 3 deletions tests/integration/lfs_view_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,14 @@ func TestLFSRender(t *testing.T) {
fileInfo := doc.Find("div.file-info-entry").First().Text()
assert.Contains(t, fileInfo, "LFS")

rawLink, exists := doc.Find("div.file-view > div.view-raw > a").Attr("href")
assert.True(t, exists, "Download link should render instead of content because this is a binary file")
assert.Equal(t, "/user2/lfs/media/branch/master/crypt.bin", rawLink, "The download link should use the proper /media link because it's in LFS")
// find new file view container
fileViewContainer := doc.Find("div.file-view-container")
assert.Positive(t, fileViewContainer.Length(), "File view container should exist")

// check data attribute instead of link href
dataURL, exists := fileViewContainer.Attr("data-url")
assert.True(t, exists, "File view container should have data-url attribute")
assert.Equal(t, "/user2/lfs/media/branch/master/crypt.bin", dataURL, "The data-url should use the proper /media link because it's in LFS")
})

// check that a directory with a README file shows its text
Expand Down
71 changes: 71 additions & 0 deletions web_src/css/file-view.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* File View & Render Plugin Styles
*/

/* file view container */
.file-view-container {
position: relative;
width: 100%;
min-height: 200px;
display: flex;
align-items: center;
justify-content: center;
}

.file-view-container.is-loading {
position: relative;
}

.file-view-container.is-loading::after {
content: "";
position: absolute;
left: 50%;
top: 50%;
width: 40px;
height: 40px;
margin-left: -20px;
margin-top: -20px;
border: 5px solid var(--color-secondary);
border-top-color: transparent;
border-radius: 50%;
animation: spin 1s linear infinite;
}

.view-raw-fallback {
padding: 16px;
text-align: center;
}

/* 3D model viewer */
.model3d-content {
width: 100% !important;
min-height: 400px !important;
border: none !important;
display: flex;
align-items: center;
justify-content: center;
}

@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}

/* error message */
.file-view-container .ui.error.message {
margin: 1em 0;
width: 100%;
}

.file-view-container .ui.error.message pre {
margin-top: 0.5em;
font-size: 12px;
max-height: 150px;
overflow: auto;
background-color: rgba(255, 255, 255, 0.1);
padding: 0.5em;
}
2 changes: 2 additions & 0 deletions web_src/css/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,6 @@

@import "./helpers.css";

@import "./file-view.css";

@tailwind utilities;
59 changes: 59 additions & 0 deletions web_src/js/features/file-view.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import {applyRenderPlugin} from '../modules/file-render-plugin.ts';
import {registerGlobalInitFunc} from '../modules/observer.ts';

/**
* init file view renderer
*
* detect renderable files and apply appropriate plugins
*/
export function initFileView(): void {
// register file view renderer init function
registerGlobalInitFunc('initFileView', async (container: HTMLElement) => {
// get file info
const filename = container.getAttribute('data-filename');
const fileUrl = container.getAttribute('data-url');

// mark loading state
container.classList.add('is-loading');

try {
// check if filename and url exist
if (!filename || !fileUrl) {
console.error(`missing filename(${filename}) or file url(${fileUrl}) for rendering`);
throw new Error('missing necessary file info');
}

// try to apply render plugin
const success = await applyRenderPlugin(container);

// if no suitable plugin is found, show default view
if (!success) {
// show default view raw file link
const fallbackText = container.getAttribute('data-fallback-text') || 'View Raw File';

container.innerHTML = `
<div class="view-raw-fallback">
<a href="${fileUrl}" class="ui basic button" target="_blank">${fallbackText}</a>
</div>
`;
}
} catch (error) {
console.error('file view init error:', error);

// show error message
const fallbackText = container.getAttribute('data-fallback-text') || 'View Raw File';

container.innerHTML = `
<div class="ui error message">
<div class="header">Failed to render file</div>
<p>Error: ${String(error)}</p>
<pre>${JSON.stringify({filename, fileUrl}, null, 2)}</pre>
<a class="ui basic button" href="${fileUrl || '#'}" target="_blank">${fallbackText}</a>
</div>
`;
} finally {
// remove loading state
container.classList.remove('is-loading');
}
});
}
5 changes: 5 additions & 0 deletions web_src/js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import {initStopwatch} from './features/stopwatch.ts';
import {initFindFileInRepo} from './features/repo-findfile.ts';
import {initMarkupContent} from './markup/content.ts';
import {initPdfViewer} from './render/pdf.ts';
import {initFileView} from './features/file-view.ts';
import {register3DViewerPlugin} from './render/plugins/3d-viewer.ts';
import {initUserAuthOauth2, initUserCheckAppUrl} from './features/user-auth.ts';
import {initRepoPullRequestAllowMaintainerEdit, initRepoPullRequestReview, initRepoIssueSidebarDependency, initRepoIssueFilterItemLabel} from './features/repo-issue.ts';
import {initRepoEllipsisButton, initCommitStatuses} from './features/repo-commit.ts';
Expand Down Expand Up @@ -163,6 +165,9 @@ onDomReady(() => {
initColorPickers,

initOAuth2SettingsDisableCheckbox,

initFileView,
register3DViewerPlugin,
]);

// it must be the last one, then the "querySelectorAll" only needs to be executed once for global init functions.
Expand Down
69 changes: 69 additions & 0 deletions web_src/js/modules/file-render-plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/**
* File Render Plugin System
*
* This module provides a plugin architecture for rendering different file types
* in the browser without requiring backend support for identifying file types.
*/

/**
* Interface for file render plugins
*/
export type FileRenderPlugin = {
// unique plugin name
name: string;

// test if plugin can handle specified file
canHandle: (filename: string, mimeType: string) => boolean;

// render file content
render: (container: HTMLElement, fileUrl: string, options?: any) => Promise<void>;
}

// store registered render plugins
const plugins: FileRenderPlugin[] = [];

/**
* register a file render plugin
*/
export function registerFileRenderPlugin(plugin: FileRenderPlugin): void {
plugins.push(plugin);
}

/**
* find suitable render plugin by filename and mime type
*/
function findPlugin(filename: string, mimeType: string): FileRenderPlugin | null {
return plugins.find((plugin) => plugin.canHandle(filename, mimeType)) || null;
}

/**
* apply render plugin to specified container
*/
export async function applyRenderPlugin(container: HTMLElement): Promise<boolean> {
try {
// get file info from container element
const filename = container.getAttribute('data-filename') || '';
const fileUrl = container.getAttribute('data-url') || '';

if (!filename || !fileUrl) {
console.warn('Missing filename or file URL for renderer');
return false;
}

// get mime type (optional)
const mimeType = container.getAttribute('data-mime-type') || '';

// find plugin that can handle this file
const plugin = findPlugin(filename, mimeType);
if (!plugin) {
return false;
}

// apply plugin to render file
await plugin.render(container, fileUrl);
return true;
} catch (error) {
console.error('Error applying render plugin:', error);
return false;
}
}
Loading