mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-04 22:35:08 +00:00
* fix(web): keep Cache and Logs helpers out of each other's way Both partials declared top-level showError and escapeHtml. Their scripts run at global scope after every HTMX swap, so whichever tab was opened last owned window.showError, and a Cache failure after visiting Logs rendered into the Logs panel (and the other way round). Each script is now an IIFE; Cache still exports deleteCacheFile for its row buttons. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): make the HTMX-failure fallbacks for tab panels actually run - The "HTMX never loaded" fallback read appElement.__x.$data, which is Alpine 2. The page ships Alpine 3, so the check was always false and the Overview never loaded without HTMX. It now reads Alpine.$data(). - The Overview and WiFi panels used hx-on::htmx:response-error, which htmx expands to "htmx:htmx:response-error", an event that never fires. - loadTabContent sent requests with <body> as the source, so htmx fired its events on <body> and no panel's hx-on handler ran at all. The panel is now the source. htmx also resolves its promise on a 4xx/5xx, and the panel was stamped data-loaded anyway, leaving a skeleton that never retried; it is now stamped only when no responseError fired. loadPluginsDirect, loadOverviewDirect and loadWifiDirect are merged into one window.loadPartialDirect(id, url), which also runs the partial's inline scripts before Alpine sees the markup (as htmx-config.js does on htmx:afterSwap). The ~10 s "htmx never arrived" path in loadTabContent uses it for every tab instead of four hard-coded ones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): store and registry failures no longer wipe the Plugin Manager showError replaced the whole #plugins-content with an error message, so one failed store search, custom-registry install or saved-repository call took the installed list, the store and every control with it, with no way back short of reloading the tab. Those failures are now error notifications. The full-panel message is kept only for a first load of the installed list that failed (nothing to show yet); a failed refresh of an already-rendered list is a notification too. showSuccess's fallback branch, which wrote the message into innerHTML unescaped, is gone: showNotification always exists. The "Please try refreshing your browser" hint tested for the text "Failed to Fetch", which no browser produces (Chrome says "Failed to fetch", Firefox "NetworkError..."), so it never appeared. It now keys on the failure itself: a TypeError from fetch(), or PluginAPI's NETWORK_ERROR wrapper around one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): escape plugin action and install output on every path executePluginAction escaped data.message and data.output when an action failed but put data.message straight into innerHTML when it succeeded, and set the OAuth step-2 button's innerHTML from the manifest's step2_button_text. Plugin actions run plugin code, so that is plugin- or server-controlled markup in the page. Both paths now escape, and the button label is set with textContent. The same pattern sat in the install-from-GitHub-URL status lines (plugin_id, the server's message, and error.message, which can echo a repository URL) and the custom-registry load error; those are escaped too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): file-upload widget owns the image list and schedule editor plugins_manager.js loads after the widget bundle, so its older copies of deleteUploadedFile, updateImageList, hideUploadProgress, formatDate, openImageSchedule, toggleImageScheduleEnabled, updateImageSchedule{Mode, Time,Day} and updateCheckboxGroupData replaced the widget's. They are deleted; the widget files are the only definitions. Before switching over, the two sets were diffed and fixed so nothing regresses: - The old copy labelled the schedule/delete buttons for screen readers and lazy-loaded thumbnails; the widget now does both. - The schedule button did nothing on a card rendered by plugin_config.html whenever the image id is a UUID (every upload): the template turns "-" into "_" in the editor's id, and neither JS copy did. Both now use the template's rule. - The widget's "keep the open editor open" copied the editor's innerHTML into the new list. That dropped its event listeners and showed the old values, so after the first change the editor looked live but ignored input. A schedule edit now saves to the hidden input and updates the card's summary in place without re-rendering the list; a list re-render (upload, delete) rebuilds an open editor from the data. Editor controls are routed by one delegated change listener, so there are no per-element listeners to lose. - The old deleteUploadedFile had a JSON branch that removed a #file_<id> element and skipped the re-render. No template or script renders such an element, and JSON uploads are listed through updateImageList like images, so re-rendering (the widget's behaviour) is the consistent one; the branch was not carried over. - The template always renders the summary line (".image-schedule-summary", "Always shown" when unscheduled) so an edit has a line to update. The inline-handler test evaluated plugins_manager.js's updateImageList; test_file_upload_widget.js now covers the widget's list and editor. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): delete the unused handleCredentialsUpload Its last caller went when plugin_config.html switched credential uploads to the file-upload widget's handleSingleFileSelect. Nothing in the web UI, the tests or the plugin monorepo references it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): delete dead and shadowed front-end code Nothing calls any of these (checked across web_interface/, test/ and the ledmatrix-plugins monorepo, including hx-*/x-*/onclick attributes): - app-shell.js: the Alpine methods refreshPlugins (it called a nonexistent this.searchPluginStore), loadPluginConfig, savePluginConfig, getSchemaPropertyType, escapeCssSelector, formatCommitInfo and formatDateInfo, and the top-level copies of savePluginConfig, getSchemaPropertyType, escapeCssSelector, formatCommitInfo, formatDateInfo and togglePluginFromTab. Plugin config forms save through hx-post in plugin_config.html. - window.reconnectSSE (app-shell.js); window.updateArrayTableAddButtonState (array-table.js). - toggleNestedSection, defined twice (app-shell.js and plugins_manager.js) and called from nowhere. - plugins_manager.js: the window.initializePlugins wrapper around an IIFE-local origInit that was always undefined, and __pluginDomReady, which was written but never read. - display.html's fixInvalidNumberInputs fallback: app-shell.js defines it before any partial loads. - base.html's window.loadCodeMirror and the two CodeMirror stylesheet preloads, and the .CodeMirror rules in plugins.html. The raw JSON editor is a plain textarea. Also deleted: app-shell.js definitions that a later script always replaced, so they never ran: executePluginAction (plugins_manager.js assigns its own), uninstallPlugin and its pollUninstallOperation (plugins_manager.js), and updateAllPlugins (install_manager.js). vendor/codemirror stays: test/test_web_smoke.py still requests codemirror.min.js as a sample static asset. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): call showNotification without checking it exists app-shell.js defines window.showNotification (a stand-in that queues until the notification widget loads) and base.html runs it, deferred, before every other script that notifies: app.js, the utilities, the widget bundle, plugins_manager.js, and all partials, which HTMX loads after the page. The 81 `typeof showNotification === 'function'` / `!== 'undefined'` checks, the `window.showNotification || console.log` and `|| alert` fallbacks, and their else branches (alert(), console output, and schedule.html's own hand-built toast) could never take the fallback path. They are removed, as is fonts.html's second copy of the queueing stand-in. The stand-in in app-shell.js keeps its guard (it must not replace the widget's implementation if load order ever changes), and BaseWidget's public notify()/getNotificationFunction() keep their shape for widgets that plugins ship. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): one HTML escaper, window.LEDEscape About 30 files each carried their own escapeHtml / escapeAttr / escHtml / _esc / escapeJs. They disagreed: several (notification.js, display.html's escapeHtml, operation_history.html, the app() stub) did not escape quotes, google-calendar-picker.js and tools.html's escHtml left ' alone, and some turned 0 into ''. Most were fine only because the quote-safe widget copies were preferred at runtime. window.LEDEscape now lives at the top of app-early.js, a blocking script in <head>, so it exists before any other script runs: html(v) & < > " ' as entities, null/undefined as '' attr(v) the same, for call sites that want to say "attribute" jsStringAttr(v) a JS string literal safe inside an inline handler Every former copy is now a one-line name for it (kept so call sites do not change), widgets included, with no fallback. plugins_manager.js loses its four escapeJs wrappers (callers use jsStringAttr), the duplicate escapeAttr and escapeHtml inside renderInstalledCards and renderCustomRegistryPlugins, and the window.escapeHtml / window.escapeAttribute exports, which nothing read. addArrayObjectItem's fallback markup (with a sixth hand-written escape chain) is gone too: window.renderArrayObjectItem is defined earlier in the same file, so the fallback could not run. The unused escapeHtml methods on the Alpine app (app-early.js stub and app-shell.js) are deleted. test_html_escaping.js now runs LEDEscape and every remaining name for it, and fails if a hand-rolled escaper reappears anywhere in web_interface/. Suites that evaluate slices of plugins_manager.js or widget files load LEDEscape from app-early.js through test/js/led_escape.js. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): stop htmx re-running partial scripts after every tab load htmx-config.js runs each swapped-in <script> itself on htmx:afterSwap and meant to turn htmx's own script handling off with htmx.config.allowScriptTags = false. It did that once, while setting up, but base.html loads htmx with a dynamic <script>, so htmx was not defined yet and the setting never applied. On every tab load htmx then tried to run each script again in its settle phase, found it already replaced (no parent node) and threw "Cannot read properties of null (reading 'insertBefore')" into the console, which also skipped the rest of that swap's settle tasks. The setting is now applied in the afterSwap handler, which always runs after htmx exists and before htmx settles the same swap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): show "--" for a system stat the server could not read The stats stream and /system/status now send null for a metric they cannot read (cpu_temp off a Pi, for one) instead of 0. updateSystemStats built the header and Overview text as value + unit, so a null showed as "null°C". CPU, memory and temperature, in the header and on the Overview, now render "--" plus the unit for null or a missing field -- the same placeholder the page starts with, and what tools.html already shows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): one Alpine accessor and one plugin-list signal window.getApp() (app-early.js) returns the root <body x-data="app()"> component through Alpine's public Alpine.$data, or null before Alpine has initialised it. It replaces the private el._x_dataStack[0] reads in app.js, app-early.js, app-shell.js, settings-search.js, overview.html and plugins_manager.js, the three local getAppComponent/appData/getAppData copies, and the Alpine 2 el.__x.$data fallbacks, which Alpine 3 never provides. Publishing the installed-plugin list: one load set window.installedPlugins and dispatched pluginsUpdated twice (loadInstalledPlugins, then renderInstalledPlugins), then wrote into the Alpine component through _x_dataStack[0] and called its updatePluginTabs() directly, and app-early.js's global listener set window.installedPlugins a third time and called updatePluginTabs() again. Now renderInstalledPlugins is the one publisher: it sets window.installedPlugins and dispatches pluginsUpdated once, and the full app()'s listener (app-shell.js) is the receiver. The app-early.js listener only builds the tab row while the app is not the full implementation yet. The "grid not loaded yet" case is a normal state (Plugin Manager tab not opened), so it logs through pluginLog instead of console.warn. updatePluginTabs had a "Debounce" comment and clearTimeout over a timer nothing ever set, and two identical branches; it now just calls _doUpdatePluginTabs (app-early.js detects the full implementation by that name in its source, which the new comment says). app()'s unused baseComponent lookup is removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): reload the plugin list after installs and failed toggles Several callers refreshed the installed list with if (typeof loadInstalledPlugins === 'function') loadInstalledPlugins(); else if (typeof window.loadInstalledPlugins === 'function') ... but loadInstalledPlugins is local to the plugin-manager IIFE and window.loadInstalledPlugins is never defined, so from outside that IIFE both tests were false and nothing reloaded: - A failed plugin toggle left the switch drawn in the new state while the data said the old one. It now re-renders from the reverted data. The optimistic in-place edit also has to forget the grid's last-rendered markup, or setGridHtmlIfChanged sees identical HTML and skips the revert. A successful toggle still keeps the switch (and focus) as drawn. - Installing from a GitHub URL (the early handleGitHubPluginInstall), installing or uploading a Starlark app, and toggling a Starlark app on its config tab never refreshed the list, so the new app had no tab or Installed badge until the page was reloaded. They now force a reload through window.pluginManager.loadInstalledPlugins(true), and the Starlark grid redraws when that finishes instead of after a fixed 500 ms. - The Starlark uninstall inside the IIFE reloaded from the 3 s cache, which could still hold the app; it now forces a reload. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): route debug output through debugLog base.html defines window.debugLog, gated on localStorage.pluginDebug. plugins_manager.js read the same key twice more into its own flags (_PLUGIN_DEBUG_EARLY, and PLUGIN_DEBUG behind a pluginLog() wrapper), and api_client.js's RequestThrottler had a separate `debug` property with a setDebug() that nothing called. All of it now goes through debugLog. The "functions defined" dumps with their ✓ lines, and two per-plugin "enabled=" loops that ran on every render, are dropped; "[PLUGINS STUB]" labels on code that has not been a stub for a long time read "[PLUGINS]". Ungated console.log calls that announced normal events on every page load or action (settings search and tooltips registering, every toast repeated to the console, the schedule pickers initialising, widget registry unregister/clear) go through debugLog too. What remains on console.log is the widget registry's on-demand LEDMatrixWidgets.debug() dump and BaseWidget.notify's no-notifier fallback. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): drop waits and guards that could never fire - handlePluginAction polled up to 10 x 50 ms for window.togglePlugin, configurePlugin, updatePlugin and uninstallPlugin before calling them. All four are defined when the scripts load, before any card can be clicked, so the poll always succeeded at once; it now calls them. The long thinking-aloud comment over the toggle state is replaced by two lines on why the stored state, not the checkbox, decides. - initializePlugins checked typeof on setupGitHubInstallHandlers and applyStoreFiltersAndSort, function declarations in the same IIFE, and wrapped window.checkGitHubAuthStatus(), which returns a promise with its own .catch, in try/catch. - searchPluginStore wrapped each "#store-count" update (a getElementById and an innerHTML assignment) in try/catch four times; one setStoreCount() helper does it. The store's post-render re-attach of the GitHub token handler dropped its try/catch and existence checks for the same reason. - The load-time fallback outside the IIFE tested typeof initializePluginPageWhenReady, which is IIFE-local and so always undefined there; it calls window.initPluginsPage directly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): delete two unused plugin-manager helpers stopOnDemand (IIFE-local; the page's stop button calls window.stopOnDemand from app-shell.js) and debounce had no callers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): document the plugin-config handlers templates call validatePluginConfigForm, handleConfigSave, handleToggleResponse, handlePluginUpdate and refreshPluginConfig each get a JSDoc naming the attribute in partials/plugin_config.html that calls it and what the return value means (only validatePluginConfigForm's matters: false cancels the submit). - The `if (!window.__pluginConfigHandlersInitialized)` wrapper is gone: app-shell.js runs once per page, so it was never false. The block is dedented one level; `git diff -w` shows the real change. - The three handlers read xhr.responseJSON first. XMLHttpRequest has no such property (it is jQuery's), so that branch never ran; one xhrJson(xhr) helper parses responseText for all of them, with the same fallbacks as before. - runPluginOnDemand and stopOnDemand checked that plugins_manager.js's openOnDemandModal/requestOnDemandStop exist; plugins_manager.js is on every page, so they call them. - fixInvalidNumberInputs had a stray "Notification helper function" comment on top of its own; a leftover "section toggle ... duplicate definition removed" note is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): one toast per save, and a failed durations save says so app.js's global htmx:afterRequest listener showed the server's message for every htmx request, and every form and button that posts through htmx (plugin config save/toggle/update, Display, Durations, General, Schedule, Dim schedule, the Overview actions) also reports its own result from hx-on after-request. Each save showed two toasts. The global listener now stays quiet for a request whose element, or its form, has its own after-request handler. That exposed the Rotation & Durations form's handler, which read xhr.responseJSON: XMLHttpRequest has no such property, so it always said "Durations saved" in green, even when the save failed (the global toast had been the only place the error showed). display.html already had a correct version (2xx only counts as saved; the server's message wins; its status may refine success but never overturn failure). That is now window.showSaveResult(xhr, savedText, failedText) in app.js, used by the Display, Durations and General forms; General's inline copy of the same logic is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(web): file headers and comments that say what the code does now - plugins_manager.js, app-shell.js, app.js and app-early.js open with a header: what the file owns, how base.html loads it and in what order relative to the others, and the globals it defines. app-early.js's app() stub also says why it exists and that, with app-shell.js now loaded before Alpine, it does not run in practice. - base.html's note on plugins_manager.js said it must load last to win over same-named functions in app.js/app-shell.js; there are none left, so it now gives the real reason (it uses everything loaded before it). - Change-narration and "already defined at the top, no need to redefine" notes are gone or rewritten as present-tense reasons; comments that were wrong are fixed ("Toggle password visibility" over the function that opens the token panel, "Insert before the closing </nav>" over an appendChild, "(from v2)", the export note that still listed escapeHtml). About forty comments that restated the line below them are removed, and a second window.currentPluginConfig = null outside the IIFE is dropped (the IIFE sets it). - The file-upload, checkbox-group and custom-feeds widgets' render() stubs say plainly that the widget is rendered server-side, instead of "for now" / "placeholder for future client-side rendering". test_plugin_action_delegation.js sliced the source up to one of the removed notes; it now ends the slice at the next section header. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): keep the escapeHtml/escapeAttribute globals for plugin pages 6da77363 removed window.escapeHtml and window.escapeAttribute because nothing in core or the plugin monorepo read them. Plugin web UIs served through serve_plugin_web_ui and third-party plugin pages may still call them, so they come back as aliases of window.LEDEscape.html and .attr, defined in app-early.js before any other script runs. test_html_escaping.js checks the aliases exist. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(changelog): web-frontend Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): encode the image thumbnail path; match script tags case-insensitively CodeQL flagged the upload widget building an <img> src from a stored path, and the escaper test extracting inline scripts with a case-sensitive regex. Each path segment is now URL-encoded (still a same-origin path, and correct for names with spaces or * fix(web): clear Codacy findings in the escaper, app shell and upload widget - LEDEscape looks entities up in a Map instead of indexing an object. - showNotification is declared as a global for app-shell.js. - openImageSchedule checks the index is a non-negative integer and reads the image with Array.prototype.at. - The schedule editor calls escapeHtml directly and documents why its innerHTML template is safe: every value is escaped or constrained. The remaining rule hits are suppressed on that line with the reason. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): build the image schedule editor with DOM calls Codacy does not honour inline suppressions, and the editor's innerHTML template kept tripping its XSS rules even though every value was escaped. The editor is now built with a small element helper (createElement and setAttribute), so no value is ever parsed as HTML, and the file's own escapeHtml goes away. Also for Codacy: - LEDEscape.attr is its own function rather than a second name for html. - The tab loader records a failed load on the panel (data-load-failed) from a named handler, instead of a closure over a local flag. The fake DOM in test_file_upload_widget.js gains append/replaceChildren, its hostile-id check now asserts the id arrives as attribute data with no innerHTML anywhere in the editor, and test_html_escaping.js drops the file-upload.js escaper it no longer has. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): schedule editor helpers as plain functions Codacy's lint flags arrow functions held in local constants and a forEach callback that returns a value. The editor's pieces are now named function declarations (displayStyle, scheduleModeOption, scheduleRangeTime, scheduleDayTime, scheduleDayRow) taking what they need as arguments, and the element helper loops with for...of. htmx is declared as a global in app-shell.js. Output is unchanged; test_file_upload_widget.js passes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
873 lines
33 KiB
HTML
873 lines
33 KiB
HTML
<div class="bg-white rounded-lg shadow p-6">
|
|
<div class="border-b border-gray-200 pb-4 mb-6">
|
|
<h2 class="text-lg font-semibold text-gray-900">Font Management</h2>
|
|
<p class="mt-1 text-sm text-gray-600">Upload, preview and manage the fonts available to every plugin.</p>
|
|
</div>
|
|
|
|
<!-- Font System Overview -->
|
|
<div class="mb-8">
|
|
<!-- Available Fonts -->
|
|
<div class="bg-gray-50 rounded-lg p-4">
|
|
<h3 class="text-md font-medium text-gray-900 mb-3">Available Font Families</h3>
|
|
<div id="available-fonts" class="bg-gray-800 text-gray-100 font-mono text-sm p-3 rounded h-64 overflow-y-auto">
|
|
<div class="text-gray-400">Loading...</div>
|
|
</div>
|
|
<p class="text-sm text-gray-600 mt-2">All available font families in the system.
|
|
<span id="font-usage-note"></span></p>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Font Upload -->
|
|
<div class="bg-gray-50 rounded-lg p-4 mb-8">
|
|
<h3 class="text-md font-medium text-gray-900 mb-4">Upload Custom Fonts</h3>
|
|
<p class="text-sm text-gray-600 mb-4">Upload your own TTF, OTF, or BDF font files to use in your LED matrix display.</p>
|
|
|
|
<div class="font-upload-area" id="font-upload-area">
|
|
<div class="upload-dropzone" id="upload-dropzone">
|
|
<i class="fas fa-cloud-upload-alt text-3xl text-gray-400 mb-3"></i>
|
|
<p class="text-gray-600">Drag and drop font files here, or click to select</p>
|
|
<p class="text-sm text-gray-500">Supports .ttf, .otf, and .bdf files</p>
|
|
<input type="file" id="font-file-input" accept=".ttf,.otf,.bdf" multiple style="display: none;">
|
|
</div>
|
|
</div>
|
|
|
|
<div class="upload-form" id="upload-form" style="display: none;">
|
|
<div class="mt-4 p-4 bg-white rounded border">
|
|
<h4 class="text-sm font-medium text-gray-900 mb-3">Selected Files</h4>
|
|
<div id="selected-files" class="space-y-2 mb-4">
|
|
<!-- Files will be listed here -->
|
|
</div>
|
|
|
|
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
<div>
|
|
<label for="upload-font-family" class="block text-sm font-medium text-gray-700 mb-1">Font Family Name</label>
|
|
<input type="text" id="upload-font-family" class="form-control" placeholder="e.g., my-custom-font">
|
|
<p class="text-sm text-gray-600 mt-1">Custom name for this font (letters, numbers, underscores, hyphens)</p>
|
|
</div>
|
|
<div class="flex items-end">
|
|
<button type="button" id="upload-fonts-btn" class="btn bg-blue-600 hover:bg-blue-700 text-white px-4 py-2">
|
|
<i class="fas fa-upload mr-2"></i>Upload Fonts
|
|
</button>
|
|
<button type="button" id="cancel-upload-btn" class="btn bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 ml-2">
|
|
<i class="fas fa-times mr-2"></i>Cancel
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Upload Progress -->
|
|
<div id="upload-progress" class="mt-4 hidden">
|
|
<div class="bg-white rounded p-4 border">
|
|
<div class="flex items-center justify-between mb-2">
|
|
<span class="text-sm font-medium">Uploading...</span>
|
|
<span id="upload-percent" class="text-sm">0%</span>
|
|
</div>
|
|
<div class="w-full bg-gray-200 rounded-full h-2">
|
|
<div id="upload-progress-bar" class="bg-blue-600 h-2 rounded-full" style="width: 0%"></div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Font Preview -->
|
|
<div class="bg-gray-50 rounded-lg p-4">
|
|
<h3 class="text-md font-medium text-gray-900 mb-4">Font Preview</h3>
|
|
<div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-2 2xl:grid-cols-2 gap-6">
|
|
<div>
|
|
<div id="font-preview-container" class="border border-gray-300 bg-black rounded p-4 min-h-[100px] flex items-center justify-center">
|
|
<img id="font-preview-image" alt="Font preview" class="max-w-full" style="display: none;">
|
|
<span id="font-preview-loading" class="text-gray-400">Select a font to preview</span>
|
|
</div>
|
|
</div>
|
|
<div class="space-y-3">
|
|
<div>
|
|
<label for="preview-text" class="block text-sm font-medium text-gray-700 mb-1">Preview Text</label>
|
|
<input type="text" id="preview-text" value="Sample Text 123" class="form-control text-sm">
|
|
</div>
|
|
<div class="grid grid-cols-2 gap-3">
|
|
<div>
|
|
<label for="preview-family" class="block text-sm font-medium text-gray-700 mb-1">Font Family</label>
|
|
<select id="preview-family" class="form-control text-sm">
|
|
<!-- Dynamically populated from font catalog -->
|
|
</select>
|
|
</div>
|
|
<div>
|
|
<label for="preview-size" class="block text-sm font-medium text-gray-700 mb-1">Font Size</label>
|
|
<select id="preview-size" class="form-control text-sm">
|
|
<option value="xs">XS (6px)</option>
|
|
<option value="sm">SM (8px)</option>
|
|
<option value="md">MD (10px)</option>
|
|
<option value="lg">LG (12px)</option>
|
|
<option value="xl">XL (14px)</option>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
<button id="update-preview-btn" class="btn bg-gray-600 hover:bg-gray-700 text-white px-4 py-2">
|
|
<i class="fas fa-eye mr-2"></i>Update Preview
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
// Prevent script from running multiple times when HTMX reloads content
|
|
(function() {
|
|
// If script has already loaded, just re-initialize the tab without redeclaring variables/functions
|
|
if (typeof window._fontsScriptLoaded !== 'undefined') {
|
|
// Script already loaded, just trigger initialization
|
|
setTimeout(function() {
|
|
if (typeof window.initializeFontsTab === 'function') {
|
|
window.initializeFontsTab();
|
|
}
|
|
}, 50);
|
|
return;
|
|
}
|
|
|
|
// Mark script as loaded
|
|
window._fontsScriptLoaded = true;
|
|
|
|
// Initialize global variables on window object
|
|
window.fontCatalog = window.fontCatalog || {};
|
|
window.fontTokens = window.fontTokens || {};
|
|
window.selectedFontFiles = window.selectedFontFiles || [];
|
|
|
|
// Create references that can be reassigned
|
|
var fontCatalog = window.fontCatalog;
|
|
var fontTokens = window.fontTokens;
|
|
var selectedFontFiles = window.selectedFontFiles;
|
|
|
|
// Retry counter for initialization
|
|
var initRetryCount = 0;
|
|
var MAX_INIT_RETRIES = 50; // 5 seconds max (50 * 100ms)
|
|
|
|
function initializeFontsTab() {
|
|
// Allow re-initialization on each HTMX content swap
|
|
// The window._fontsScriptLoaded guard prevents function redeclaration
|
|
const availableEl = document.getElementById('available-fonts');
|
|
|
|
if (!availableEl) {
|
|
initRetryCount++;
|
|
if (initRetryCount >= MAX_INIT_RETRIES) {
|
|
console.error('Fonts tab elements not found after max retries, giving up');
|
|
return;
|
|
}
|
|
debugLog('Fonts tab elements not found, retrying...', {
|
|
availableFonts: !!availableEl,
|
|
attempt: initRetryCount
|
|
});
|
|
setTimeout(initializeFontsTab, 100);
|
|
return;
|
|
}
|
|
|
|
// Reset retry counter on successful init
|
|
initRetryCount = 0;
|
|
|
|
debugLog('Initializing font management...');
|
|
initializeFontManagement();
|
|
|
|
// Event listeners (use event delegation or ensure elements exist)
|
|
const uploadDropzone = document.getElementById('upload-dropzone');
|
|
const fontFileInput = document.getElementById('font-file-input');
|
|
const uploadFontsBtn = document.getElementById('upload-fonts-btn');
|
|
const cancelUploadBtn = document.getElementById('cancel-upload-btn');
|
|
const updatePreviewBtn = document.getElementById('update-preview-btn');
|
|
|
|
if (uploadDropzone && fontFileInput) {
|
|
uploadDropzone.addEventListener('click', () => {
|
|
fontFileInput.click();
|
|
});
|
|
}
|
|
|
|
if (fontFileInput) {
|
|
fontFileInput.addEventListener('change', handleFileSelection);
|
|
}
|
|
|
|
if (uploadFontsBtn) {
|
|
uploadFontsBtn.addEventListener('click', uploadSelectedFonts);
|
|
}
|
|
|
|
if (cancelUploadBtn) {
|
|
cancelUploadBtn.addEventListener('click', cancelFontUpload);
|
|
}
|
|
|
|
|
|
if (updatePreviewBtn) {
|
|
updatePreviewBtn.addEventListener('click', updateFontPreview);
|
|
}
|
|
|
|
// Drag and drop for upload area
|
|
if (uploadDropzone) {
|
|
uploadDropzone.addEventListener('dragover', (e) => {
|
|
e.preventDefault();
|
|
uploadDropzone.classList.add('drag-over');
|
|
});
|
|
|
|
uploadDropzone.addEventListener('dragleave', () => {
|
|
uploadDropzone.classList.remove('drag-over');
|
|
});
|
|
|
|
uploadDropzone.addEventListener('drop', (e) => {
|
|
e.preventDefault();
|
|
uploadDropzone.classList.remove('drag-over');
|
|
handleFileSelection({ target: { files: e.dataTransfer.files } });
|
|
});
|
|
}
|
|
|
|
debugLog('Fonts tab initialized successfully');
|
|
}
|
|
|
|
// Expose initializeFontsTab to window for re-initialization after HTMX reload
|
|
window.initializeFontsTab = initializeFontsTab;
|
|
|
|
// Initialize after HTMX content swap for dynamic loading
|
|
// Note: We don't use DOMContentLoaded here because this partial is loaded via HTMX
|
|
// after the main page's DOMContentLoaded has already fired
|
|
(function() {
|
|
// Function to initialize when fonts content is loaded
|
|
function tryInitializeFontsTab() {
|
|
const fontsContent = document.getElementById('fonts-content');
|
|
|
|
if (fontsContent) {
|
|
debugLog('Fonts content detected, initializing...');
|
|
setTimeout(() => {
|
|
initializeFontsTab();
|
|
}, 50);
|
|
}
|
|
}
|
|
|
|
// Set up HTMX event listener for when content is swapped
|
|
if (typeof document.body !== 'undefined') {
|
|
document.body.addEventListener('htmx:afterSettle', function(event) {
|
|
// Check if the event target is the fonts-content container or contains it
|
|
const target = event.target;
|
|
if (target && (target.id === 'fonts-content' || target.querySelector && target.querySelector('#fonts-content'))) {
|
|
debugLog('HTMX loaded fonts content, initializing...', target.id);
|
|
tryInitializeFontsTab();
|
|
}
|
|
});
|
|
}
|
|
|
|
// Also check if content is already loaded (e.g., if script runs after HTMX swap)
|
|
// This handles the case where the script executes after HTMX has already swapped
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', tryInitializeFontsTab);
|
|
} else {
|
|
// DOM already loaded, check immediately
|
|
tryInitializeFontsTab();
|
|
}
|
|
})();
|
|
|
|
async function initializeFontManagement() {
|
|
try {
|
|
await loadFontData();
|
|
populateFontSelects();
|
|
updateFontPreview();
|
|
initializeFontUpload();
|
|
} catch (error) {
|
|
console.error('Error initializing font management:', error);
|
|
showNotification('Error loading font configuration', 'error');
|
|
}
|
|
}
|
|
|
|
async function loadFontData() {
|
|
const availableContainer = document.getElementById('available-fonts');
|
|
|
|
// Ensure containers exist before proceeding
|
|
if (!availableContainer) {
|
|
console.error('Font containers not found, cannot load font data');
|
|
return;
|
|
}
|
|
|
|
// Show loading states
|
|
availableContainer.innerHTML = '<div class="text-blue-400">Loading font data...</div>';
|
|
|
|
try {
|
|
// Use absolute URLs to ensure they work when loaded via HTMX
|
|
// no-store: /api/v3 GETs are browser-cacheable for 5 s, and this
|
|
// reload follows an upload or delete (or the usage check before one),
|
|
// so a cached copy would show the list as it was before the change.
|
|
const [catalogRes, tokensRes] = await Promise.all([
|
|
fetch(`/api/v3/fonts/catalog`, { cache: 'no-store' }),
|
|
fetch(`/api/v3/fonts/tokens`)
|
|
]);
|
|
|
|
// Check if all responses are successful
|
|
if (!catalogRes.ok || !tokensRes.ok) {
|
|
const statusText = `HTTP ${catalogRes.status}/${tokensRes.status}`;
|
|
console.error('Font API error:', statusText);
|
|
throw new Error(`Failed to load font data: ${statusText}`);
|
|
}
|
|
|
|
const catalogData = await catalogRes.json();
|
|
const tokensData = await tokensRes.json();
|
|
|
|
// Validate response structure
|
|
if (!catalogData || !catalogData.data || !tokensData || !tokensData.data) {
|
|
console.error('Invalid font API response structure:', {
|
|
catalog: !!catalogData?.data,
|
|
tokens: !!tokensData?.data
|
|
});
|
|
throw new Error('Invalid response format from font API');
|
|
}
|
|
|
|
// Update both window properties and local references
|
|
window.fontCatalog = catalogData.data.catalog || {};
|
|
window.fontUsage = catalogData.data.font_usage || { available: false, generated_at: null };
|
|
window.fontTokens = tokensData.data.tokens || {};
|
|
|
|
// Update local variable references
|
|
fontCatalog = window.fontCatalog;
|
|
fontTokens = window.fontTokens;
|
|
|
|
// Update displays
|
|
updateAvailableFontsDisplay();
|
|
|
|
debugLog('Font data loaded successfully', {
|
|
catalogSize: Object.keys(fontCatalog).length,
|
|
tokensSize: Object.keys(fontTokens).length
|
|
});
|
|
} catch (error) {
|
|
console.error('Error loading font data:', error);
|
|
|
|
// Show error states
|
|
availableContainer.innerHTML = '<div class="text-red-400">Error loading font data. Please refresh the page.</div>';
|
|
|
|
showNotification('Error loading font configuration', 'error');
|
|
}
|
|
}
|
|
|
|
// The plugin ids that use a font, as the catalog reports them: an array
|
|
// (possibly empty) when the display service has reported, null when not.
|
|
function fontUsedBy(fontInfo) {
|
|
if (!fontInfo || typeof fontInfo !== 'object') return null;
|
|
return Array.isArray(fontInfo.used_by)
|
|
? fontInfo.used_by.filter(id => typeof id === 'string')
|
|
: null;
|
|
}
|
|
|
|
function updateAvailableFontsDisplay() {
|
|
const container = document.getElementById('available-fonts');
|
|
if (!container) return;
|
|
|
|
const usage = window.fontUsage || {};
|
|
const note = document.getElementById('font-usage-note');
|
|
if (note) {
|
|
const reported = usage.generated_at
|
|
? ` (reported ${String(usage.generated_at).replace('T', ' ')})` : '';
|
|
note.textContent = usage.available
|
|
? `"Used by" lists the running plugins that registered the font with the display service${reported}. A plugin that opens a font file directly is not listed.`
|
|
: '"Used by" is unknown: the display service has not reported which fonts its plugins use. Start it, or reload this tab a few seconds after it starts.';
|
|
}
|
|
|
|
if (Object.keys(fontCatalog).length === 0) {
|
|
container.innerHTML = '<div class="text-gray-400">No fonts available</div>';
|
|
return;
|
|
}
|
|
|
|
const fontEntries = Object.entries(fontCatalog).map(([name, fontInfo]) => {
|
|
const fontPath = typeof fontInfo === 'string' ? fontInfo : (fontInfo?.path || '');
|
|
const filename = typeof fontInfo === 'object' ? (fontInfo.filename || name) : name;
|
|
const displayName = typeof fontInfo === 'object' ? (fontInfo.display_name || name) : name;
|
|
const fontType = typeof fontInfo === 'object' ? (fontInfo.type || '').toUpperCase() : '';
|
|
// Use is_system flag from API (single source of truth)
|
|
const isSystem = typeof fontInfo === 'object' ? (fontInfo.is_system === true) : false;
|
|
const usedBy = fontUsedBy(fontInfo);
|
|
return { name, filename, displayName, fontType, fontPath, isSystem, usedBy };
|
|
}).sort((a, b) => a.displayName.localeCompare(b.displayName));
|
|
|
|
// Build list using DOM APIs to prevent XSS (plugin ids are untrusted too)
|
|
container.innerHTML = '';
|
|
|
|
const header = document.createElement('div');
|
|
header.className = 'flex items-center gap-2 pb-1 mb-1 border-b border-gray-600 text-xs uppercase text-gray-400';
|
|
const fontHead = document.createElement('span');
|
|
fontHead.className = 'flex-1 min-w-0';
|
|
fontHead.textContent = 'Font';
|
|
const usedHead = document.createElement('span');
|
|
usedHead.className = 'flex-1 min-w-0';
|
|
usedHead.textContent = 'Used by';
|
|
const actionHead = document.createElement('span');
|
|
actionHead.className = 'w-24 flex-shrink-0';
|
|
header.append(fontHead, usedHead, actionHead);
|
|
container.appendChild(header);
|
|
|
|
fontEntries.forEach(font => {
|
|
const row = document.createElement('div');
|
|
row.className = 'flex items-start gap-2 py-1 border-b border-gray-700 last:border-0';
|
|
|
|
const nameSpan = document.createElement('span');
|
|
nameSpan.className = 'truncate flex-1 min-w-0';
|
|
nameSpan.textContent = font.displayName;
|
|
nameSpan.title = font.filename;
|
|
|
|
if (font.fontType) {
|
|
const typeSpan = document.createElement('span');
|
|
typeSpan.className = 'text-gray-500 ml-1';
|
|
typeSpan.textContent = `(${font.fontType})`;
|
|
nameSpan.appendChild(typeSpan);
|
|
}
|
|
|
|
row.appendChild(nameSpan);
|
|
|
|
// Wraps rather than truncates: the list is what a delete is weighed
|
|
// against, and a title tooltip is out of reach on a phone.
|
|
const usedSpan = document.createElement('span');
|
|
usedSpan.className = 'flex-1 min-w-0 break-words';
|
|
if (font.usedBy === null) {
|
|
usedSpan.classList.add('text-gray-500', 'italic');
|
|
usedSpan.textContent = 'unknown';
|
|
usedSpan.title = 'The display service has not reported which fonts its plugins use';
|
|
} else if (font.usedBy.length === 0) {
|
|
usedSpan.classList.add('text-gray-500');
|
|
usedSpan.textContent = '—';
|
|
usedSpan.title = 'No running plugin registered this font';
|
|
} else {
|
|
usedSpan.classList.add('text-gray-300');
|
|
usedSpan.textContent = font.usedBy.join(', ');
|
|
}
|
|
row.appendChild(usedSpan);
|
|
|
|
const actionCell = document.createElement('span');
|
|
actionCell.className = 'w-24 flex-shrink-0 text-right';
|
|
if (font.isSystem) {
|
|
const systemBadge = document.createElement('span');
|
|
systemBadge.className = 'text-gray-600 text-xs';
|
|
systemBadge.textContent = '[system]';
|
|
actionCell.appendChild(systemBadge);
|
|
} else {
|
|
const deleteBtn = document.createElement('button');
|
|
deleteBtn.className = 'text-red-400 hover:text-red-300 text-xs';
|
|
deleteBtn.title = 'Delete font';
|
|
deleteBtn.textContent = '[delete]';
|
|
deleteBtn.dataset.fontName = font.name;
|
|
deleteBtn.addEventListener('click', function() {
|
|
deleteFont(this.dataset.fontName);
|
|
});
|
|
actionCell.appendChild(deleteBtn);
|
|
}
|
|
row.appendChild(actionCell);
|
|
|
|
container.appendChild(row);
|
|
});
|
|
}
|
|
|
|
// Which plugins use a font now. Re-reads the catalog so the warning reflects
|
|
// the display service's latest report rather than the one the tab opened
|
|
// with; falls back to that one if the request fails.
|
|
async function currentFontUsedBy(fontName) {
|
|
const own = (obj) => obj && typeof obj === 'object'
|
|
&& Object.prototype.hasOwnProperty.call(obj, fontName);
|
|
try {
|
|
const response = await fetch('/api/v3/fonts/catalog', { cache: 'no-store' });
|
|
if (response.ok) {
|
|
const catalog = (await response.json())?.data?.catalog;
|
|
if (own(catalog)) return fontUsedBy(catalog[fontName]);
|
|
}
|
|
} catch (error) {
|
|
console.warn('Could not refresh font usage before delete:', error);
|
|
}
|
|
return own(fontCatalog) ? fontUsedBy(fontCatalog[fontName]) : null;
|
|
}
|
|
|
|
// The confirm() text for deleting a font. Plain text: confirm() renders no
|
|
// HTML, so a plugin id cannot inject markup here.
|
|
function deleteFontConfirmMessage(fontFamily, usedBy) {
|
|
if (Array.isArray(usedBy) && usedBy.length > 0) {
|
|
return `Font "${fontFamily}" is in use.\n\nUsed by: ${usedBy.join(', ')}.\n\n`
|
|
+ 'Delete anyway? This action cannot be undone.';
|
|
}
|
|
const base = `Are you sure you want to delete the font "${fontFamily}"? This action cannot be undone.`;
|
|
if (usedBy === null) {
|
|
return `${base}\n\nWhich plugins use it is unknown: the display service has not reported.`;
|
|
}
|
|
return base;
|
|
}
|
|
|
|
async function deleteFont(fontFamily) {
|
|
const usedBy = await currentFontUsedBy(fontFamily);
|
|
if (!confirm(deleteFontConfirmMessage(fontFamily, usedBy))) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(`/api/v3/fonts/${encodeURIComponent(fontFamily)}`, {
|
|
method: 'DELETE'
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const text = await response.text();
|
|
let message;
|
|
try {
|
|
const errorData = JSON.parse(text);
|
|
message = errorData.message || `Server error: ${response.status}`;
|
|
} catch {
|
|
message = `Server error: ${response.status}`;
|
|
}
|
|
showNotification(message, 'error');
|
|
return;
|
|
}
|
|
|
|
const data = await response.json();
|
|
|
|
if (data.status === 'success') {
|
|
showNotification(data.message || `Font "${fontFamily}" deleted successfully`, 'success');
|
|
// Refresh font data and UI
|
|
await loadFontData();
|
|
populateFontSelects();
|
|
// Clear font-selector widget cache if available
|
|
if (typeof window.clearFontSelectorCache === 'function') {
|
|
window.clearFontSelectorCache();
|
|
}
|
|
} else {
|
|
showNotification(data.message || `Failed to delete font "${fontFamily}"`, 'error');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error deleting font:', error);
|
|
showNotification(`Error deleting font: ${error.message}`, 'error');
|
|
}
|
|
}
|
|
|
|
function populateFontSelects() {
|
|
// Populate font family dropdowns from catalog
|
|
const previewSelect = document.getElementById('preview-family');
|
|
|
|
if (!previewSelect) return;
|
|
|
|
// Get font entries sorted by display name
|
|
const fontEntries = Object.entries(fontCatalog).map(([key, info]) => {
|
|
const filename = typeof info === 'object' ? (info.filename || key) : key;
|
|
const displayName = typeof info === 'object' ? (info.display_name || key) : key;
|
|
const fontType = typeof info === 'object' ? (info.type || 'unknown').toUpperCase() : '';
|
|
return { key, filename, displayName, fontType };
|
|
}).sort((a, b) => a.displayName.localeCompare(b.displayName));
|
|
|
|
// Build options using DOM APIs to prevent XSS
|
|
// Clear preview select
|
|
previewSelect.innerHTML = '';
|
|
|
|
// Add font options to both selects
|
|
fontEntries.forEach(font => {
|
|
const typeLabel = font.fontType ? ` (${font.fontType})` : '';
|
|
|
|
const previewOpt = document.createElement('option');
|
|
previewOpt.value = font.filename;
|
|
previewOpt.textContent = font.displayName + typeLabel;
|
|
previewSelect.appendChild(previewOpt);
|
|
});
|
|
|
|
// Select first font in preview if available
|
|
if (fontEntries.length > 0) {
|
|
previewSelect.value = fontEntries[0].filename;
|
|
}
|
|
|
|
debugLog(`Populated font selects with ${fontEntries.length} fonts`);
|
|
}
|
|
|
|
async function updateFontPreview() {
|
|
const previewImage = document.getElementById('font-preview-image');
|
|
const loadingText = document.getElementById('font-preview-loading');
|
|
const textInput = document.getElementById('preview-text');
|
|
const familySelect = document.getElementById('preview-family');
|
|
const sizeSelect = document.getElementById('preview-size');
|
|
|
|
if (!previewImage || !loadingText) return;
|
|
|
|
const text = textInput?.value || 'Sample Text 123';
|
|
const family = familySelect?.value || '';
|
|
const sizeToken = sizeSelect?.value || 'md';
|
|
const sizePx = fontTokens[sizeToken] || 10;
|
|
|
|
if (!family) {
|
|
previewImage.style.display = 'none';
|
|
loadingText.style.display = 'block';
|
|
loadingText.textContent = 'Select a font to preview';
|
|
return;
|
|
}
|
|
|
|
// BDF bitmap fonts cannot be rendered server-side — skip the API call
|
|
if (family.toLowerCase().endsWith('.bdf')) {
|
|
previewImage.style.display = 'none';
|
|
loadingText.style.display = 'block';
|
|
loadingText.textContent = 'Preview not available for BDF bitmap fonts';
|
|
return;
|
|
}
|
|
|
|
// Show loading state
|
|
loadingText.textContent = 'Loading preview...';
|
|
loadingText.style.display = 'block';
|
|
previewImage.style.display = 'none';
|
|
|
|
try {
|
|
const params = new URLSearchParams({
|
|
font: family,
|
|
text: text,
|
|
size: sizePx,
|
|
bg: '000000',
|
|
fg: 'ffffff'
|
|
});
|
|
|
|
const response = await fetch(`/api/v3/fonts/preview?${params}`);
|
|
|
|
if (!response.ok) {
|
|
const text = await response.text();
|
|
let message;
|
|
try {
|
|
const errorData = JSON.parse(text);
|
|
message = errorData.message || `Server error: ${response.status}`;
|
|
} catch {
|
|
message = `Server error: ${response.status}`;
|
|
}
|
|
loadingText.textContent = message;
|
|
loadingText.style.display = 'block';
|
|
previewImage.style.display = 'none';
|
|
return;
|
|
}
|
|
|
|
const data = await response.json();
|
|
|
|
if (data.status === 'success' && data.data?.image) {
|
|
previewImage.src = data.data.image;
|
|
previewImage.style.display = 'block';
|
|
loadingText.style.display = 'none';
|
|
} else {
|
|
loadingText.textContent = data.message || 'Failed to load preview';
|
|
loadingText.style.display = 'block';
|
|
previewImage.style.display = 'none';
|
|
}
|
|
} catch (error) {
|
|
console.error('Error loading font preview:', error);
|
|
loadingText.textContent = 'Error loading preview';
|
|
loadingText.style.display = 'block';
|
|
previewImage.style.display = 'none';
|
|
}
|
|
}
|
|
|
|
function initializeFontUpload() {
|
|
// Setup already done in event listeners
|
|
}
|
|
|
|
function handleFileSelection(event) {
|
|
const files = Array.from(event.target.files);
|
|
const validExtensions = ['ttf', 'otf', 'bdf'];
|
|
const validFiles = files.filter(file => {
|
|
const extension = file.name.toLowerCase().split('.').pop();
|
|
return validExtensions.includes(extension);
|
|
});
|
|
|
|
if (validFiles.length === 0) {
|
|
showNotification('Please select valid .ttf, .otf, or .bdf font files', 'warning');
|
|
return;
|
|
}
|
|
|
|
if (validFiles.length !== files.length) {
|
|
showNotification(`${files.length - validFiles.length} invalid files were ignored`, 'warning');
|
|
}
|
|
|
|
selectedFontFiles = validFiles;
|
|
showUploadForm();
|
|
}
|
|
|
|
function showUploadForm() {
|
|
if (selectedFontFiles.length === 0) return;
|
|
|
|
const uploadForm = document.getElementById('upload-form');
|
|
const selectedFilesContainer = document.getElementById('selected-files');
|
|
const fontFamilyInput = document.getElementById('upload-font-family');
|
|
|
|
// Show selected files using DOM APIs to prevent XSS
|
|
selectedFilesContainer.innerHTML = '';
|
|
selectedFontFiles.forEach(file => {
|
|
const row = document.createElement('div');
|
|
row.className = 'flex items-center justify-between p-2 bg-gray-100 rounded';
|
|
|
|
const span = document.createElement('span');
|
|
span.className = 'text-sm';
|
|
span.textContent = `${file.name} (${(file.size / 1024).toFixed(1)} KB)`;
|
|
|
|
row.appendChild(span);
|
|
selectedFilesContainer.appendChild(row);
|
|
});
|
|
|
|
// Auto-generate font family name from first file
|
|
if (selectedFontFiles.length === 1) {
|
|
const filename = selectedFontFiles[0].name;
|
|
const nameWithoutExt = filename.substring(0, filename.lastIndexOf('.'));
|
|
// Preserve hyphens, convert other special chars to underscores
|
|
fontFamilyInput.value = nameWithoutExt.toLowerCase().replace(/[^a-z0-9-]/g, '_');
|
|
}
|
|
|
|
uploadForm.style.display = 'block';
|
|
uploadForm.scrollIntoView({ behavior: 'smooth' });
|
|
}
|
|
|
|
function cancelFontUpload() {
|
|
selectedFontFiles = [];
|
|
document.getElementById('upload-form').style.display = 'none';
|
|
document.getElementById('font-file-input').value = '';
|
|
}
|
|
|
|
async function uploadSelectedFonts() {
|
|
if (selectedFontFiles.length === 0) {
|
|
showNotification('No files selected', 'warning');
|
|
return;
|
|
}
|
|
|
|
const fontFamilyInput = document.getElementById('upload-font-family');
|
|
const fontFamily = fontFamilyInput.value.trim();
|
|
|
|
if (!fontFamily) {
|
|
showNotification('Please enter a font family name', 'warning');
|
|
return;
|
|
}
|
|
|
|
// Validate font family name (must match backend validation)
|
|
if (!/^[a-z0-9_-]+$/i.test(fontFamily)) {
|
|
showNotification('Font family name can only contain letters, numbers, underscores, and hyphens', 'warning');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
showNotification('Uploading fonts...', 'info');
|
|
showUploadProgress();
|
|
|
|
for (let i = 0; i < selectedFontFiles.length; i++) {
|
|
const file = selectedFontFiles[i];
|
|
const formData = new FormData();
|
|
formData.append('font_file', file);
|
|
formData.append('font_family', i === 0 ? fontFamily : `${fontFamily}_${i + 1}`);
|
|
|
|
const response = await fetch(`/api/v3/fonts/upload`, {
|
|
method: 'POST',
|
|
body: formData
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const text = await response.text();
|
|
let message;
|
|
try {
|
|
const errorData = JSON.parse(text);
|
|
message = errorData.message || `Server error: ${response.status}`;
|
|
} catch {
|
|
message = `Server error: ${response.status}`;
|
|
}
|
|
showNotification(`Error uploading "${file.name}": ${message}`, 'error');
|
|
continue;
|
|
}
|
|
|
|
const data = await response.json();
|
|
|
|
if (data.status === 'success') {
|
|
showNotification(`Font "${data.font_family}" uploaded successfully`, 'success');
|
|
} else {
|
|
showNotification(`Error uploading "${file.name}": ${data.message}`, 'error');
|
|
}
|
|
|
|
// Update progress
|
|
const percent = ((i + 1) / selectedFontFiles.length) * 100;
|
|
updateUploadProgress(percent);
|
|
}
|
|
|
|
// Refresh font data and UI
|
|
await loadFontData();
|
|
populateFontSelects();
|
|
cancelFontUpload();
|
|
hideUploadProgress();
|
|
// Clear font-selector widget cache so new fonts appear in plugin configs
|
|
if (typeof window.clearFontSelectorCache === 'function') {
|
|
window.clearFontSelectorCache();
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('Error uploading fonts:', error);
|
|
showNotification('Error uploading fonts: ' + error, 'error');
|
|
hideUploadProgress();
|
|
}
|
|
}
|
|
|
|
function showUploadProgress() {
|
|
document.getElementById('upload-progress').classList.remove('hidden');
|
|
}
|
|
|
|
function hideUploadProgress() {
|
|
document.getElementById('upload-progress').classList.add('hidden');
|
|
}
|
|
|
|
function updateUploadProgress(percent) {
|
|
document.getElementById('upload-percent').textContent = Math.round(percent) + '%';
|
|
document.getElementById('upload-progress-bar').style.width = percent + '%';
|
|
}
|
|
|
|
})(); // End of script load guard - prevents redeclaration on HTMX reload
|
|
</script>
|
|
|
|
<style>
|
|
.drag-over {
|
|
border-color: var(--color-primary, #3b82f6) !important;
|
|
background-color: var(--color-info-bg, #eff6ff) !important;
|
|
}
|
|
|
|
.font-upload-area {
|
|
margin: 15px 0;
|
|
}
|
|
|
|
.upload-dropzone {
|
|
border: 2px dashed var(--color-field-border, #d1d5db);
|
|
border-radius: 0.75rem;
|
|
padding: 2rem 1.5rem;
|
|
text-align: center;
|
|
background: var(--color-background, #f9fafb);
|
|
transition: border-color 0.15s ease, background-color 0.15s ease;
|
|
cursor: pointer;
|
|
}
|
|
|
|
@media (min-width: 640px) {
|
|
.upload-dropzone {
|
|
padding: 2.5rem;
|
|
}
|
|
}
|
|
|
|
.upload-dropzone:hover {
|
|
border-color: var(--color-primary, #3b82f6);
|
|
background: var(--color-info-bg, #eff6ff);
|
|
}
|
|
|
|
.upload-dropzone i {
|
|
font-size: 3rem;
|
|
color: var(--color-primary, #3b82f6);
|
|
margin-bottom: 0.75rem;
|
|
display: block;
|
|
}
|
|
|
|
.upload-dropzone p {
|
|
margin: 0.25rem 0;
|
|
font-size: 1rem;
|
|
color: var(--color-text-secondary, #374151);
|
|
}
|
|
|
|
.upload-hint {
|
|
font-size: 0.875rem !important;
|
|
color: var(--color-text-tertiary, #4b5563) !important;
|
|
font-style: italic;
|
|
}
|
|
|
|
.upload-form {
|
|
margin-top: 1.25rem;
|
|
padding: 1.25rem;
|
|
background: var(--color-background, #f9fafb);
|
|
border-radius: 0.5rem;
|
|
border: 1px solid var(--color-border, #d1d5db);
|
|
}
|
|
|
|
#font-preview-container {
|
|
max-width: 100%;
|
|
min-height: 100px;
|
|
}
|
|
|
|
#font-preview-image {
|
|
max-width: 100%;
|
|
height: auto;
|
|
}
|
|
</style>
|