|
| 1 | +import {applyRenderPlugin} from '../modules/file-render-plugin.ts'; |
| 2 | +import {registerGlobalInitFunc} from '../modules/observer.ts'; |
| 3 | + |
| 4 | +/** |
| 5 | + * init file view renderer |
| 6 | + * |
| 7 | + * detect renderable files and apply appropriate plugins |
| 8 | + */ |
| 9 | +export function initFileView(): void { |
| 10 | + // register file view renderer init function |
| 11 | + registerGlobalInitFunc('initFileView', async (container: HTMLElement) => { |
| 12 | + // get file info |
| 13 | + const filename = container.getAttribute('data-filename'); |
| 14 | + const fileUrl = container.getAttribute('data-url'); |
| 15 | + |
| 16 | + // mark loading state |
| 17 | + container.classList.add('is-loading'); |
| 18 | + |
| 19 | + try { |
| 20 | + // check if filename and url exist |
| 21 | + if (!filename || !fileUrl) { |
| 22 | + console.error(`missing filename(${filename}) or file url(${fileUrl}) for rendering`); |
| 23 | + throw new Error('missing necessary file info'); |
| 24 | + } |
| 25 | + |
| 26 | + // try to apply render plugin |
| 27 | + const success = await applyRenderPlugin(container); |
| 28 | + |
| 29 | + // if no suitable plugin is found, show default view |
| 30 | + if (!success) { |
| 31 | + // show default view raw file link |
| 32 | + const fallbackText = container.getAttribute('data-fallback-text') || 'View Raw File'; |
| 33 | + |
| 34 | + container.innerHTML = ` |
| 35 | + <div class="view-raw-fallback"> |
| 36 | + <a href="${fileUrl}" class="ui basic button" target="_blank">${fallbackText}</a> |
| 37 | + </div> |
| 38 | + `; |
| 39 | + } |
| 40 | + } catch (error) { |
| 41 | + console.error('file view init error:', error); |
| 42 | + |
| 43 | + // show error message |
| 44 | + const fallbackText = container.getAttribute('data-fallback-text') || 'View Raw File'; |
| 45 | + |
| 46 | + container.innerHTML = ` |
| 47 | + <div class="ui error message"> |
| 48 | + <div class="header">Failed to render file</div> |
| 49 | + <p>Error: ${String(error)}</p> |
| 50 | + <pre>${JSON.stringify({filename, fileUrl}, null, 2)}</pre> |
| 51 | + <a class="ui basic button" href="${fileUrl || '#'}" target="_blank">${fallbackText}</a> |
| 52 | + </div> |
| 53 | + `; |
| 54 | + } finally { |
| 55 | + // remove loading state |
| 56 | + container.classList.remove('is-loading'); |
| 57 | + } |
| 58 | + }); |
| 59 | +} |
0 commit comments