mirror of
https://github.com/YuzuZensai/Termix.git
synced 2026-11-12 18:16:40 +00:00
release-2.9.0 (#1532)
* fix(macos): skip single-instance lock in Mac App Store builds (#1454) fix(macos): skip single-instance lock in Mac App Store builds * Fix/backend optional sharp (#1455) Fix/backend optional sharp * feat: issue #1218 (#1218) https://github.com/Termix-SSH/Support/issues/1218 * feat: Add option to use saved global custom theme under Connection Defaults (#1209) https://github.com/Termix-SSH/Support/issues/1209 * feat: Add Fleet Sharing functionality to the UI (#1228) https://github.com/Termix-SSH/Support/issues/1228 * feat: Add a list view to the Docker management page (#1237) https://github.com/Termix-SSH/Support/issues/1237 * feat: issue #1264 (#1264) https://github.com/Termix-SSH/Support/issues/1264 * feat: 2FA With FortiToken (#1288) https://github.com/Termix-SSH/Support/issues/1288 * feat: Allow to disable showing paths to folders (#1274) https://github.com/Termix-SSH/Support/issues/1274 * feat: Sync Network Graph between Desktop and Remote Server (#1245) https://github.com/Termix-SSH/Support/issues/1245 * feat: Version Number on offline servers (#1291) https://github.com/Termix-SSH/Support/issues/1291 * feat: Support OrbStack Docker socket path on macOS / Fix "Docker is not installed" on mac... (#1302) https://github.com/Termix-SSH/Support/issues/1302 * feat: Sidebar host click should focus existing tab instead of opening a new connection (#1289) https://github.com/Termix-SSH/Support/issues/1289 * fix: Search in side bar shows overlapping hosts when grouped by tags (#1303) https://github.com/Termix-SSH/Support/issues/1303 * fix: I can't send a file on its own. (#1304) https://github.com/Termix-SSH/Support/issues/1304 * fix: sudo password not autofilling (#1248) https://github.com/Termix-SSH/Support/issues/1248 * fix: node-MainThread (#1300) https://github.com/Termix-SSH/Support/issues/1300 * fix: Tunnel authentication with shared credentials (#1295) https://github.com/Termix-SSH/Support/issues/1295 * fix: host key updates not syncing, metrics 404 race on first connect Host key writes never bumped updatedAt so sync never picked them up. Also retry the first metrics fetch briefly instead of failing right away. * chore: increment ver * feat: add category and icon fields to plugin manifest schema * ci(deps): bump the github-actions group with 2 updates (#1458) Bumps the github-actions group with 2 updates: [crowdin/github-action](https://github.com/crowdin/github-action) and [actions/github-script](https://github.com/actions/github-script). Updates `crowdin/github-action` from 2 to 3 - [Release notes](https://github.com/crowdin/github-action/releases) - [Commits](https://github.com/crowdin/github-action/compare/v2...v3) Updates `actions/github-script` from 7 to 9 - [Release notes](https://github.com/actions/github-script/releases) - [Commits](https://github.com/actions/github-script/compare/v7...v9) --- updated-dependencies: - dependency-name: crowdin/github-action dependency-version: '3' dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions - dependency-name: actions/github-script dependency-version: '9' dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-patch-updates group with 13 updates (#1459) Bumps the dev-patch-updates group with 13 updates: | Package | From | To | | --- | --- | --- | | [@codemirror/commands](https://github.com/codemirror/commands) | `6.11.0` | `6.11.1` | | [@codemirror/search](https://github.com/codemirror/search) | `6.7.1` | `6.7.2` | | [@codemirror/view](https://github.com/codemirror/view) | `6.43.9` | `6.43.12` | | [@testing-library/dom](https://github.com/testing-library/dom-testing-library) | `10.4.1` | `10.4.2` | | [@testing-library/react](https://github.com/testing-library/react-testing-library) | `16.3.2` | `16.3.3` | | [@testing-library/user-event](https://github.com/testing-library/user-event) | `14.6.5` | `14.6.7` | | [@types/ssh2](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/ssh2) | `1.15.5` | `1.15.6` | | [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.1.0` | `6.1.1` | | [cytoscape](https://github.com/cytoscape/cytoscape.js) | `3.34.1` | `3.34.3` | | [eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) | `0.5.4` | `0.5.7` | | [i18next](https://github.com/i18next/i18next) | `26.4.0` | `26.4.2` | | [prettier](https://github.com/prettier/prettier) | `3.9.6` | `3.9.8` | | [react-i18next](https://github.com/i18next/react-i18next) | `17.0.12` | `17.0.14` | Updates `@codemirror/commands` from 6.11.0 to 6.11.1 - [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/commands/commits) Updates `@codemirror/search` from 6.7.1 to 6.7.2 - [Changelog](https://github.com/codemirror/search/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/search/commits) Updates `@codemirror/view` from 6.43.9 to 6.43.12 - [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/view/commits) Updates `@testing-library/dom` from 10.4.1 to 10.4.2 - [Release notes](https://github.com/testing-library/dom-testing-library/releases) - [Changelog](https://github.com/testing-library/dom-testing-library/blob/main/CHANGELOG.md) - [Commits](https://github.com/testing-library/dom-testing-library/compare/v10.4.1...v10.4.2) Updates `@testing-library/react` from 16.3.2 to 16.3.3 - [Release notes](https://github.com/testing-library/react-testing-library/releases) - [Changelog](https://github.com/testing-library/react-testing-library/blob/main/CHANGELOG.md) - [Commits](https://github.com/testing-library/react-testing-library/compare/v16.3.2...v16.3.3) Updates `@testing-library/user-event` from 14.6.5 to 14.6.7 - [Release notes](https://github.com/testing-library/user-event/releases) - [Changelog](https://github.com/testing-library/user-event/blob/main/CHANGELOG.md) - [Commits](https://github.com/testing-library/user-event/compare/v14.6.5...v14.6.7) Updates `@types/ssh2` from 1.15.5 to 1.15.6 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/ssh2) Updates `@vitejs/plugin-react` from 6.1.0 to 6.1.1 - [Release notes](https://github.com/vitejs/vite-plugin-react/releases) - [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.1/packages/plugin-react) Updates `cytoscape` from 3.34.1 to 3.34.3 - [Release notes](https://github.com/cytoscape/cytoscape.js/releases) - [Commits](https://github.com/cytoscape/cytoscape.js/compare/v3.34.1...v3.34.3) Updates `eslint-plugin-react-refresh` from 0.5.4 to 0.5.7 - [Release notes](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/releases) - [Changelog](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/blob/main/CHANGELOG.md) - [Commits](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/compare/v0.5.4...v0.5.7) Updates `i18next` from 26.4.0 to 26.4.2 - [Release notes](https://github.com/i18next/i18next/releases) - [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/i18next/compare/v26.4.0...v26.4.2) Updates `prettier` from 3.9.6 to 3.9.8 - [Release notes](https://github.com/prettier/prettier/releases) - [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md) - [Commits](https://github.com/prettier/prettier/compare/3.9.6...3.9.8) Updates `react-i18next` from 17.0.12 to 17.0.14 - [Changelog](https://github.com/i18next/react-i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/react-i18next/compare/v17.0.12...v17.0.14) --- updated-dependencies: - dependency-name: "@codemirror/commands" dependency-version: 6.11.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@codemirror/search" dependency-version: 6.7.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@codemirror/view" dependency-version: 6.43.12 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@testing-library/dom" dependency-version: 10.4.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@testing-library/react" dependency-version: 16.3.3 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@testing-library/user-event" dependency-version: 14.6.7 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@types/ssh2" dependency-version: 1.15.6 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@vitejs/plugin-react" dependency-version: 6.1.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: cytoscape dependency-version: 3.34.3 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: eslint-plugin-react-refresh dependency-version: 0.5.7 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: i18next dependency-version: 26.4.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: prettier dependency-version: 3.9.8 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: react-i18next dependency-version: 17.0.14 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump the prod-patch-updates group with 6 updates (#1461) Bumps the prod-patch-updates group with 6 updates: | Package | From | To | | --- | --- | --- | | [@tanstack/react-virtual](https://github.com/TanStack/virtual/tree/HEAD/packages/react-virtual) | `3.14.10` | `3.14.13` | | [compression](https://github.com/expressjs/compression) | `1.8.1` | `1.8.2` | | [jose](https://github.com/panva/jose) | `6.2.9` | `6.2.12` | | [jszip](https://github.com/Stuk/jszip) | `3.10.1` | `3.10.2` | | [socks](https://github.com/JoshGlazebrook/socks) | `2.8.9` | `2.8.10` | | [undici](https://github.com/nodejs/undici) | `8.10.0` | `8.10.2` | Updates `@tanstack/react-virtual` from 3.14.10 to 3.14.13 - [Release notes](https://github.com/TanStack/virtual/releases) - [Changelog](https://github.com/TanStack/virtual/blob/main/packages/react-virtual/CHANGELOG.md) - [Commits](https://github.com/TanStack/virtual/commits/@tanstack/react-virtual@3.14.13/packages/react-virtual) Updates `compression` from 1.8.1 to 1.8.2 - [Release notes](https://github.com/expressjs/compression/releases) - [Changelog](https://github.com/expressjs/compression/blob/master/HISTORY.md) - [Commits](https://github.com/expressjs/compression/compare/v1.8.1...v1.8.2) Updates `jose` from 6.2.9 to 6.2.12 - [Release notes](https://github.com/panva/jose/releases) - [Changelog](https://github.com/panva/jose/blob/main/CHANGELOG.md) - [Commits](https://github.com/panva/jose/compare/v6.2.9...v6.2.12) Updates `jszip` from 3.10.1 to 3.10.2 - [Changelog](https://github.com/Stuk/jszip/blob/main/CHANGES.md) - [Commits](https://github.com/Stuk/jszip/compare/v3.10.1...v3.10.2) Updates `socks` from 2.8.9 to 2.8.10 - [Release notes](https://github.com/JoshGlazebrook/socks/releases) - [Commits](https://github.com/JoshGlazebrook/socks/compare/2.8.9...2.8.10) Updates `undici` from 8.10.0 to 8.10.2 - [Release notes](https://github.com/nodejs/undici/releases) - [Commits](https://github.com/nodejs/undici/compare/v8.10.0...v8.10.2) --- updated-dependencies: - dependency-name: "@tanstack/react-virtual" dependency-version: 3.14.13 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: compression dependency-version: 1.8.2 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: jose dependency-version: 6.2.12 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: jszip dependency-version: 3.10.2 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: socks dependency-version: 2.8.10 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: undici dependency-version: 8.10.2 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * feat: add plugin worker protocol, bootstrap and plugin_storage table Worker-side ctx proxy plus the message envelope it talks over, and the per-plugin key/value table behind ctx.storage with migrations for all three dialects. Rows cascade with the plugin so uninstalling leaves nothing behind. * feat: add allowlisted host view for plugins An allowlist rather than a list of fields to strip. A blocklist rots: the moment a new secret-bearing column lands on SSHHost it starts leaking silently. With an allowlist a new field stays invisible to plugins until someone adds it here on purpose. * feat: add plugin loader with manifest validation and crash restart Validates an unpacked plugin, spawns a worker_threads worker and manages activate/deactivate/crash-restart with backoff, disabling after three tries. The crash counter clears only after a plugin stays up past a stability window, not on activation. Clearing it on activation let a plugin that activates cleanly and then dies restart forever, because every attempt looked like the first. loader.ts documents what the worker boundary does and does not buy you. Node's permission model is process-wide, not per-worker, so it cannot be enabled for plugin workers alone and is not claimed here. * feat: route internal events through a shared plugin event bus Formalises three ad-hoc publish paths that already existed: automation-events.ts, metrics/automation-bridge.ts and the hostSessionStatus singleton, now the host.session.status topic. Both invariants the old code relied on are preserved. Publishing stays fire-and-forget, so a failing subscriber cannot disturb a metrics poll or a host delete. The automations engine subscribes to the bus at scheduler start instead of being imported ad hoc, which keeps the edge one-directional: automations may import repositories, hosts modules must not import automations. * feat: add plugin ctx broker with permission gate and audit Every ctx call a plugin makes is checked against its granted capabilities, performed by the main thread, then audited. A capability must be both declared in the manifest and granted in the database, so widening a plugin's reach always needs a new manifest the user can see, never just a database row. Audit attribution is set by the broker, not the plugin. The plugin supplies only the details, so it cannot forge the actor. fix: stop plugin workers seeing plaintext credentials in error messages A failing ctx.ssh.connect handed the worker the raw error from deep in the SSH stack, which embeds the connect config. The worker received, in full: Authentication failed for root using password <SECRET> where <SECRET> was the host's real plaintext password. Any plugin with ssh.exec could read it by catching the error, defeating the whole point of the handle-based ssh API. Errors crossing the boundary are now sanitised. Only PluginFacingError and PluginPermissionError, both authored here, reach a plugin verbatim; anything else becomes a generic message and the real one goes to the log. This uses a marker class rather than matching on message text, because matching would start leaking again the moment an upstream error happened to contain a familiar phrase. Covered by credential-isolation.test.ts, which plants a sentinel in every secret-bearing field and asserts it appears in no message the worker ever receives. * feat: dispatch plugin HTTP routes and wire the runtime into startup ctx.http.route now registers a real router on the /plugin-api/:pluginId dispatcher, replacing its stub 404. A plugin never touches the Express req/res: it gets a plain summary and returns a plain object, so sockets and session cookies stay on this side of the boundary. Authorization and cookie headers are not forwarded. Plugins load last in the start-up sequence, after the server is fully wired, and are terminated before the database on shutdown so none can outlive it. A plugin that fails to load cannot stop the backend. fix: correct the nginx plugin-api location regex The pattern was ^/plugin-api/(/.*)?$, which needs a double slash and so never matched /plugin-api/<id>/<route>. Every other block in the file uses ^/prefix(/.*)?$. Left alone, plugin routes would work in dev and 404 only behind Docker. * fix: update stale SFTP transfer test for single file destination paths The test still asserted transferToHost was called with the destination directory "/srv". Commit 7727fa09 (#1304) deliberately changed a single file transfer to send the full destination path including the filename, so the correct expectation is "/srv/remote-1.txt". The code was right and the test was left behind. * feat: ship the ssh terminal as a first-party in-process plugin Adds a hardcoded process:transport-owner tier so the terminal can own its WebSocket server and ssh2 clients, which cannot cross the worker boundary. * feat: ship docker as a first-party in-process plugin Moves docker backend and frontend into plugins/docker/, alongside ssh-terminal. Adds a host editor tab seam, a dashboard card registry, and a build step to compile plugin backends into dist. * feat: ship host metrics as a first-party in-process plugin * fix: harden plugin auth and add per-request identity for ctx calls Require auth on /plugin-api, gate plugin enable/grant/revoke routes behind admin.plugins.manage, and thread the calling user through worker ctx.hosts/ctx.ssh calls instead of always using the install owner. Also adds the plugin permissions grant/revoke UI. * feat: ship the AI assistant as a first-party in-process plugin Moves src/backend/ai and its routes into plugins/ai, mounted through a small /ai dispatcher instead of its own port. Moves the ai-enabled and ai-private-endpoints settings routes out of user-settings-routes.ts into the plugin too, so it has no leftover core dependents. * fix: remove compiled plugin JS left behind in plugins/ after build copy-bundled-plugins.cjs compiled and rewrote plugin backend TS in place, copied it to dist/plugins, but never deleted the .js it had just emitted next to the .ts sources. Those files shadowed the real source for vitest/tsx and had import paths rewritten for the dist layout, so tests failed with "Cannot find module" once a local build had run. Affects docker, host-metrics and ai, not just this one. * feat: add a permission-gated backend service registry for plugins * feat: add a permission-gated UI action registry and action slots for plugins Moves the terminal toolbar's hardwired AI button into a slot the ssh-terminal plugin offers and the ai plugin fills, gated on ai.services.use. * feat: add cross-plugin secret references gated by the provider's RBAC permission * feat: move proxmox discovery/import/sync into a first-party plugin * feat: move remote desktop (RDP/VNC/Telnet) into a first-party plugin Relocates guacamole backend/frontend source and tests into plugins/remote-desktop, following the ssh-terminal/docker pattern. * feat: wire remote-desktop plugin into core and rename i18n keys Repoints core consumers (dispatcher, collab, session-sharing, tab utils) at the plugin, adds isTabTypeAvailable gating for rdp/vnc/ telnet, widens hostCapability to accept an array, and renames the guacamole i18n namespace to remoteDesktop. * feat: move fleets into a first-party plugin * feat: move automations into a first-party plugin * feat: remove legacy alert rules, superseded by automations Alert rules already auto-migrate into automations on boot and the old engine stands down after. Deletes the rule/firing tables, routes, UI, and AI tools; keeps notification channels since automations still use them. Also fixes automations' notify step, which still called the deleted repository. * feat: move network topology into a first-party plugin * feat: move tailscale device discovery and settings into a plugin Adds plugins/tailscale/ with a devices sidebar tab, admin settings section, and re-auth dialog. Host Metrics tailscale manager card and SSH re-auth banner parsing stay in core. * feat: move workspaces into a first-party plugin * feat: move web endpoint into a first-party plugin * feat: collapse plugin runtime to one tier behind a plugin SDK * feat: make each plugin an npm workspace built by a termix-plugin CLI * feat: give plugins their own tables, migrations and sync entities * feat: serve plugin http and websockets from one mount instead of ports * feat: namespace plugin permissions and keep them valid when a plugin is off * feat: give plugins their own settings and one settings screen * feat: load plugin frontends at runtime and remove plugin ids from the shell * fix: mock the ai status fetch in its activate test * feat: add auth extension points and one ssh connect pipeline * feat: rebuild workspaces as the reference plugin * fix: gate second factors after SSO/LDAP behind an admin setting * feat: convert network-topology to a full plugin (B1) * feat: move snippets backend and tables into a plugin (B2) * feat: point core frontend snippets pickers at the plugin (B2) * feat: add the snippets plugin (B2) * feat: wire ai, automations, fleets and ssh-terminal to snippets (B2) * feat: finish the tailscale plugin, including SSH auth (B3) * feat: finish the fleets plugin, add ctx.hosts and host-commands SDK (B4) * chore: update proxmox and host-metrics locale files for B5 * chore: regenerate drizzle migration journals for B5 * feat: add ctx.hosts create/update to the SDK, host-metrics drops proxmox * feat: move proxmox node stats and collectors into the proxmox plugin * feat: drop proxmox host columns, use plugin settings instead * feat: finish the fleets plugin, add ctx.hosts and host-commands SDK (B4) * feat: convert file manager into a plugin * feat: convert ssh tunnels into a plugin * feat: finish the web-endpoint plugin, add ctx.desktop (B8) * feat: move the terminal fully into the ssh-terminal plugin (B9) * feat: convert tmux monitoring into a plugin (B10) * feat: convert serial console into the serial plugin * feat: move session sharing and collab rooms into a plugin (B12) * feat: turn session recording into a plugin (B13) * feat: finish the remote-desktop plugin (B14) * feat: finish the host-metrics plugin, move host status into core (B16) * feat: finish the docker plugin (B15) * feat: finish the automations plugin (B17) * feat: finish the ai plugin (B18) * feat: finish the homepage plugin, move service links and canvas out of core (B19) * feat: convert wake-on-lan into a plugin (B20) * feat: convert secret-sources into a plugin (B20) * feat: move totp and passkeys into plugins (C1) * feat: move sso and ldap logins into plugins (C2) * feat: move opkssh and warpgate into plugins (C3) * feat: move step-ca into a plugin (C4) * feat: move vault ssh signing into a plugin (C5) * feat: move termix identity into a plugin (C6) * feat: move acme certificate automation into a plugin (C7) * fix: finish 2.9.0 plugin moves and get every check green * chore: lock the plugin boundary and remove 2.9.0 leftovers * fix: harden the plugin runtime after the 2.9.0 security review * feat: add plugin packing, signing, pinned trust and tmxplug bundling * test: prove 2.8 to 2.9.0 upgrade is lossless and fix what it caught * fix: give bundled plugin backends a real require for CJS deps * feat: improve UI loading time and jitter * feat: show credential sharing inline in the sidebar like host sharing * feat: tailscale add host and copy ip, fix outbound fetch hang and plugin ESM warning * feat: unify alerts into one plugin, channels, rules and inbox * feat: rebuild desktop sync as linked server accounts, fix packaged plugin bundles and UI scaling * fix: set blacksmith builder cache-key to stop broken gha cache fallback * fix: link plugin-sdk workspace before npm ci in docker deps stage * fix: link every plugin workspace before npm ci in docker deps stage * fix(host-metrics): exclude image and firmware filesystems (#1469) * fix(host-metrics): exclude image and firmware filesystems * fix(ci): build plugin SDK before dependent checks * fix(mysql): keep plugin settings scope indexes within limits * test(mysql): refresh reviewed plugin upgrade SQL * fix(hosts): normalize imported jump host references (#1470) * fix(hosts): normalize imported jump host references * fix(ci): build plugin SDK before dependent checks * fix(mysql): keep plugin settings scope indexes within limits * test(mysql): refresh reviewed plugin upgrade SQL * fix(ci): build plugin SDK and repair MySQL settings migration (#1471) * fix(ci): build plugin SDK before dependent checks * fix(mysql): keep plugin settings scope indexes within limits * test(mysql): refresh reviewed plugin upgrade SQL * fix(file-manager): keep inline rename consistent (#1476) * fix(ci): build plugin SDK before dependent checks * fix(mysql): keep plugin settings scope indexes within limits * test(mysql): refresh reviewed plugin upgrade SQL * fix(file-manager): keep inline rename consistent * fix(dashboard): reuse translated host status labels (#1475) * fix(ci): build plugin SDK before dependent checks * fix(mysql): keep plugin settings scope indexes within limits * test(mysql): refresh reviewed plugin upgrade SQL * fix(dashboard): reuse translated host status labels * docs(api): clarify local and remote version fields (#1474) * fix(ci): build plugin SDK before dependent checks * fix(mysql): keep plugin settings scope indexes within limits * test(mysql): refresh reviewed plugin upgrade SQL * docs(api): clarify local and remote version fields * fix(file-manager): preserve selected backgrounds on hover (#1473) * fix(ci): build plugin SDK before dependent checks * fix(mysql): keep plugin settings scope indexes within limits * test(mysql): refresh reviewed plugin upgrade SQL * fix(file-manager): preserve selection feedback on hover * test(ui): await dialog focus cleanup before teardown * fix(file-manager): restore Ctrl/Cmd+F file search (#1472) * fix(ci): build plugin SDK before dependent checks * fix(mysql): keep plugin settings scope indexes within limits * test(mysql): refresh reviewed plugin upgrade SQL * fix(file-manager): focus file search with Ctrl or Cmd F * fix: keep rounded-full circular in production builds * fix(file-manager): cancel uploads and stop remote writes (#1477) * fix(file-manager): cancel uploads and stop remote writes * test(css): exercise the configured PostCSS plugin chain * fix(file-manager): apply compact density to directory tree (#1478) * fix(file-manager): apply compact density to directory tree * test(css): exercise the configured PostCSS plugin chain * fix(file-manager): preserve font sizes in compact mode (#1480) * fix(file-manager): preserve font sizes in compact mode * test(css): exercise the configured PostCSS plugin chain * fix(file-manager): prioritize file names in narrow lists (#1483) * fix(file-manager): prioritize file names in narrow lists * test(css): exercise the configured PostCSS plugin chain * test(identity): preserve full Ed25519 public keys in fixtures * test(remote-desktop): always mutate ciphertext in tamper test * fix(remote-desktop): probe the saved host guacd endpoint (#1481) * fix(remote-desktop): probe the saved host guacd endpoint * test(css): exercise the configured PostCSS plugin chain * test(identity): preserve full Ed25519 public keys in fixtures * fix(homepage): check allowlisted private service reachability (#1479) * fix(homepage): check allowlisted private service reachability * test(css): exercise the configured PostCSS plugin chain * fix(remote-desktop): stop unsolicited clipboard read prompts (#1482) * fix(remote-desktop): read clipboard only on explicit paste * test(css): exercise the configured PostCSS plugin chain * test(identity): preserve full Ed25519 public keys in fixtures * test(remote-desktop): always mutate ciphertext in tamper test * chore: simplify plugin readmes, changelogs and manifest descriptions * fix: keep plugins loaded after signing in from the login screen * fix(file-manager): accept OS file drops over existing rows (#1484) * fix(file-manager): accept OS file drops over existing rows * test(file-manager): target the file label in drop tests * test(css): exercise the configured PostCSS plugin chain * test(identity): preserve full Ed25519 public keys in fixtures * test(remote-desktop): always mutate ciphertext in tamper test * fix(file-manager): pipeline SFTP download reads (#1485) * feat: add plugin sdk build to beta release * fix: make link-store secret check immune to random base64 matches * fix(ldap): preserve the directory-provided bind DN (#1486) * fix: compute beta changes across dev branches and move the beta tag * chore: untrack plugin sdk ARCHITECTURE.md * chore: remove references to plugin sdk ARCHITECTURE.md * feat: merge host editor terminal tabs into one owned by ssh-terminal * feat: add descriptions to plugin host enable toggles * fix(file-manager): show download progress in file viewers (#1487) * fix(electron): signal backend readiness over IPC (#1488) * fix(split-screen): allow layout creation without randomUUID (#1490) * fix(split-screen): allow layout creation without randomUUID * test(credentials): avoid flaky Ed25519 key generation * fix(sidebar): remeasure visible rows after density changes (#1489) * fix(sidebar): remeasure visible rows after density changes * test(credentials): avoid flaky Ed25519 key generation * feat(split-screen): redesign split screen with free-form panes and pane picker * feat(sidebar): add host click behavior setting, default to always opening a new tab * feat(snippets): redesign panel to match the host list * fix(session-recording): stop session logs panel from refetching in a loop * feat(snippets): bring back sharing, target hosts and drag reorder * feat(ssh-terminal): add toolbar position, start state, display and fade host settings * feat(ssh-terminal): add host setting to turn off password prompt auto-fill * fix(ai): stop streams getting cut off and keep tool steps across messages * feat: improve quick connect system using plugin api * fix: proxmox guest sync, startup snippet sync, drop dead cloudflare ssh transport * feat: move terminal settings, look and ssh tools into ssh-terminal plugin * feat: move snippets, keybinding actions and macros out of core into plugins * feat: store rdp, vnc and telnet logins in a generic per-protocol table * feat: type the plugin host record, move plugin strings out of core and add lint checks * feat: replace core homepage widget registry with generic extension points * feat: plugins only see their own host settings in the browser * feat: harden plugin api for separate repos, signed updates and generic external login * fix: keep plugin css below core utilities and version plugin assets by their css * fix: load and save plugin host settings in the editor and tighten settings row spacing * feat: redesign user host defaults system * fix(remote-desktop): release held keys on focus loss (#1498) * fix(session-sharing): replace local presentation after takeover (#1500) * fix(file-manager): refresh disk usage with directory listing (#1503) * fix(ssh-terminal): preserve input order during local echo reconciliation (#1505) * feat(remote-desktop): expose display zoom controls for RDP (#1514) * fix(file-manager): restore text selection and copying in Markdown previews (#1518) * fix(sidebar): keep compact host addresses visible (#1524) * fix(hosts): preserve plugin settings when reopening the editor (#1499) * fix(ssh-terminal): close owner sockets when presentations unmount (#1501) * fix(session-sharing): synchronize shared SSH terminal dimensions (#1502) * fix(session-sharing): show participant presence in member terminals (#1504) * fix(ai): sync provider configuration and keys across linked devices (#1506) * feat(ssh-terminal): add a duplicate tab action (#1510) * feat(file-manager): allow disabling move-to-trash confirmation (#1511) * feat(file-manager): default to the remote login directory (#1512) * feat(homepage): synchronize canvas layouts across devices (#1515) * fix(shortcuts): prevent accidental double-Shift palette activation (#1519) * feat(tmux-monitor): add a unified multi-host view (#1520) * fix(electron): allow explicit quit with active connections (#1522) * feat: reconnect all disconnected terminal tabs (#1523) * fix(hosts): preserve recording and sharing settings in the dev editor (#1509) * fix(database): preserve RDP domain during startup backfill (#1497) * feat(sidebar): add keyboard type-ahead search for hosts (#1516) * feat(automations): add per-host maintenance mode and recurring schedules (#1521) * feat(tmux): add a per-host mouse toggle and preserve remote configuration (#1513) * fix(session-sharing): use the linked server for desktop meetings and links (#1507) * fix(tunnels): support TOTP for client tunnels and jump hosts (#1508) * fix: type errors and lint failures from merged plugin prs * feat(installer): make the Windows desktop shortcut optional (#1517) * fix: ship the plugin sdk and serialport in desktop builds * fix: prefer ipv4 when resolving ssh host names (#1365) * fix: readable terminal selection with the light theme (#1319) * fix: build desktop session share links on the linked server (#1350) * fix: show meeting guests to members and hide the roster from guests (#1353) * fix: reliable file manager saves with sudo prompt and no base64 guessing (#1335) * fix: show disk usage for the mount being browsed (#1347) * fix: load the linux tray icon reliably and log tray failures (#1332) * fix: cover the gnome close path in the desktop quit test (#1332) * fix: prompt for jump host TOTP in terminal, file manager and metrics (#1312) * feat: optional auto reconnect for dropped ssh sessions (#1321) * feat: tighter compact host rows with inline tags (#1325) * feat: bring back the alert feed homepage widget * feat: pick target terminals for snippets again * feat: share button on connection tabs again * feat: recent servers list when linking the desktop app * feat: list the fixed app shortcuts in keyboard shortcuts * fix: translate hardcoded toasts and drop em dashes from ui text * fix: translate leftover hardcoded ui text * fix: toolbar files button opens at the shell directory again * fix: show the remote desktop note under connection origin again * chore: openapi docs for host metrics manager routes * chore: openapi docs for undocumented routes and fix two broken doc blocks * fix: declare terminal.listSessions use for snippet targets * revert: drop the alert feed widget, the notification center replaces it * feat: restore the alert feed homepage widget * fix: quick connect fills the host address from plugin auth editors like tailscale * fix: docker container logs use the base background color * chore: fix dependabot alerts and apply safe npm upgrades * fix: proxmox stats tab reads its switch from plugin host settings * fix: count plugin ssh logins toward host status and stop showing reachable as a warning * fix: hide the built-in source pill in the host editor * fix: host status shows online when the port answers and only warns on a failed login * fix: drop the top border on the split layout menu * fix: host defaults tabs sit where the host editor puts them and skip plugins with nothing to default * fix: remote desktop auth method labels and notes for vnc and telnet * fix: add description to the web endpoint enable switch * fix: crowdin sync and pretranslate for plugin locales, run plugin tests on release * feat: move telemetry out of core into a usage statistics plugin * fix: recent activity card no longer cuts off host names early * fix: remove duplicate top border on split screen menu * fix: redesign session log player controls, fix tooltip overlap and drop dot separators * fix: file manager and sftp text showing raw i18n keys * fix: onboarding rerunning for existing users after upgrading * fix: fleet detail buttons overflowing the sidebar * fix: session log player scrolling off screen horizontally * fix: network graph lag when adding hosts and on every render * fix: maintenance index name, shared host read only view and badge polling * fix: meeting tabs, workspace tab merging, rail panels as tabs and general ui lag * chore: update release notes * fix: remote desktop tabs reconnecting on every tab switch * fix: build plugin sdk before linting in release workflow * chore: lint, format, and bump version to 2.9.0 * chore: skip crowdin pre-translate in release for now * chore: sync Crowdin translations for 2.9.0 --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Koi <38512047+datlt4@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com>
This commit is contained in:
co-authored by
Koi
dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
ZacharyZcR
parent
49fa488093
commit
3643e7af97
@@ -0,0 +1,74 @@
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { Bookmark, ExternalLink } from "lucide-react";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { BookmarkListConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
|
||||
function BookmarkListWidget({
|
||||
config,
|
||||
widget,
|
||||
isReadOnly,
|
||||
}: WidgetComponentProps<BookmarkListConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { links } = config;
|
||||
|
||||
return (
|
||||
<div className="w-full h-full flex flex-col overflow-hidden">
|
||||
{widget.title && (
|
||||
<div className="flex items-center gap-1.5 px-3 py-2 border-b border-border shrink-0">
|
||||
<Bookmark size={11} className="text-accent-brand shrink-0" />
|
||||
<span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider truncate">
|
||||
{widget.title}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1 overflow-auto p-3 gap-1 flex flex-col">
|
||||
{links.length === 0 && (
|
||||
<span className="text-xs text-muted-foreground italic">
|
||||
{t("homepage.noBookmarks")}
|
||||
</span>
|
||||
)}
|
||||
{links.map((link, i) =>
|
||||
isReadOnly ? (
|
||||
<div
|
||||
key={i}
|
||||
className="flex items-center gap-2 text-xs text-foreground py-1"
|
||||
>
|
||||
<Bookmark size={10} className="text-muted-foreground shrink-0" />
|
||||
<span className="truncate">{link.label || link.url}</span>
|
||||
</div>
|
||||
) : (
|
||||
<a
|
||||
key={i}
|
||||
href={link.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 text-xs text-foreground hover:text-primary py-1 no-underline group"
|
||||
>
|
||||
<Bookmark size={10} className="text-muted-foreground shrink-0" />
|
||||
<span className="truncate flex-1">{link.label || link.url}</span>
|
||||
<ExternalLink
|
||||
size={8}
|
||||
className="text-muted-foreground/0 group-hover:text-muted-foreground/60 shrink-0"
|
||||
/>
|
||||
</a>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<BookmarkListConfig>({
|
||||
id: "bookmark_list",
|
||||
name: "Bookmarks",
|
||||
description: "A list of quick links",
|
||||
category: "links",
|
||||
icon: <Bookmark size={14} />,
|
||||
defaultConfig: { links: [] },
|
||||
defaultSize: { w: GRID_SIZE * 9, h: GRID_SIZE * 10 },
|
||||
minSize: { w: GRID_SIZE * 2, h: GRID_SIZE * 2 },
|
||||
component: BookmarkListWidget,
|
||||
});
|
||||
|
||||
export { BookmarkListWidget };
|
||||
@@ -0,0 +1,161 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { CalendarDays, ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { CalendarConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
|
||||
import { WidgetTitle, runVisibleInterval } from "@termix/plugin-sdk/ui";
|
||||
|
||||
function getMonthData(year: number, month: number, startOnMonday: boolean) {
|
||||
const firstDay = new Date(year, month, 1).getDay();
|
||||
const daysInMonth = new Date(year, month + 1, 0).getDate();
|
||||
const offset = startOnMonday ? (firstDay === 0 ? 6 : firstDay - 1) : firstDay;
|
||||
return { daysInMonth, offset };
|
||||
}
|
||||
|
||||
function CalendarWidget({
|
||||
widget,
|
||||
config,
|
||||
}: WidgetComponentProps<CalendarConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { startOnMonday } = config;
|
||||
const [now, setNow] = useState(new Date());
|
||||
const [viewYear, setViewYear] = useState(now.getFullYear());
|
||||
const [viewMonth, setViewMonth] = useState(now.getMonth());
|
||||
|
||||
useEffect(() => {
|
||||
return runVisibleInterval(() => setNow(new Date()), 60_000);
|
||||
}, []);
|
||||
|
||||
const { daysInMonth, offset } = getMonthData(
|
||||
viewYear,
|
||||
viewMonth,
|
||||
startOnMonday,
|
||||
);
|
||||
const today = now;
|
||||
const isCurrentMonth =
|
||||
viewYear === today.getFullYear() && viewMonth === today.getMonth();
|
||||
|
||||
const dayNames = startOnMonday
|
||||
? [
|
||||
t("homepage.calMon"),
|
||||
t("homepage.calTue"),
|
||||
t("homepage.calWed"),
|
||||
t("homepage.calThu"),
|
||||
t("homepage.calFri"),
|
||||
t("homepage.calSat"),
|
||||
t("homepage.calSun"),
|
||||
]
|
||||
: [
|
||||
t("homepage.calSun"),
|
||||
t("homepage.calMon"),
|
||||
t("homepage.calTue"),
|
||||
t("homepage.calWed"),
|
||||
t("homepage.calThu"),
|
||||
t("homepage.calFri"),
|
||||
t("homepage.calSat"),
|
||||
];
|
||||
|
||||
const monthLabel = new Intl.DateTimeFormat("en-US", {
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
}).format(new Date(viewYear, viewMonth, 1));
|
||||
|
||||
const cells: (number | null)[] = [
|
||||
...Array(offset).fill(null),
|
||||
...Array.from({ length: daysInMonth }, (_, i) => i + 1),
|
||||
];
|
||||
|
||||
const prevMonth = () => {
|
||||
if (viewMonth === 0) {
|
||||
setViewMonth(11);
|
||||
setViewYear((y) => y - 1);
|
||||
} else setViewMonth((m) => m - 1);
|
||||
};
|
||||
const nextMonth = () => {
|
||||
if (viewMonth === 11) {
|
||||
setViewMonth(0);
|
||||
setViewYear((y) => y + 1);
|
||||
} else setViewMonth((m) => m + 1);
|
||||
};
|
||||
|
||||
const accent =
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--accent-brand")
|
||||
.trim() || "#f59145";
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden select-none">
|
||||
<WidgetTitle title={widget.title} icon={<CalendarDays size={11} />} />
|
||||
<div className="flex flex-col flex-1 p-2 gap-1 overflow-hidden">
|
||||
<div className="flex items-center justify-between shrink-0">
|
||||
<button
|
||||
onClick={prevMonth}
|
||||
className="p-0.5 text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ChevronLeft size={12} />
|
||||
</button>
|
||||
<span className="text-[10px] font-semibold text-foreground">
|
||||
{monthLabel}
|
||||
</span>
|
||||
<button
|
||||
onClick={nextMonth}
|
||||
className="p-0.5 text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ChevronRight size={12} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-7 gap-0 shrink-0">
|
||||
{dayNames.map((d) => (
|
||||
<div
|
||||
key={d}
|
||||
className="text-center text-[8px] font-semibold text-muted-foreground/70 uppercase py-0.5"
|
||||
>
|
||||
{d}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-7 gap-0 flex-1 content-start">
|
||||
{cells.map((day, i) => {
|
||||
if (day === null) return <div key={`e-${i}`} />;
|
||||
const isToday = isCurrentMonth && day === today.getDate();
|
||||
return (
|
||||
<div
|
||||
key={`d-${day}`}
|
||||
className="flex items-center justify-center aspect-square"
|
||||
>
|
||||
<span
|
||||
className="text-[9px] font-medium w-5 h-5 flex items-center justify-center rounded-full"
|
||||
style={
|
||||
isToday
|
||||
? { background: accent, color: "#fff" }
|
||||
: { color: "var(--text-primary, currentColor)" }
|
||||
}
|
||||
>
|
||||
{day}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<CalendarConfig>({
|
||||
id: "calendar",
|
||||
name: "Calendar",
|
||||
description: "A month calendar with today highlighted",
|
||||
category: "info",
|
||||
icon: <CalendarDays size={14} />,
|
||||
defaultConfig: { startOnMonday: true },
|
||||
defaultSize: { w: GRID_SIZE * 10, h: GRID_SIZE * 9 },
|
||||
minSize: { w: GRID_SIZE * 7, h: GRID_SIZE * 7 },
|
||||
component: CalendarWidget,
|
||||
});
|
||||
|
||||
export { CalendarWidget };
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useState } from "react";
|
||||
import { Clock } from "lucide-react";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import {
|
||||
GRID_SIZE,
|
||||
type ClockConfig,
|
||||
type WidgetComponentProps,
|
||||
} from "../types.js";
|
||||
|
||||
import { usePageVisibleInterval } from "../use-page-visible-interval.js";
|
||||
import { isValidTimezone } from "../clock-timezone";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
|
||||
function ClockWidget({ widget, config }: WidgetComponentProps<ClockConfig>) {
|
||||
const { showSeconds, format } = config;
|
||||
// Configs saved before the edit dialog validated timezones can still hold an
|
||||
// unusable one (e.g. "America/New York"), which makes toLocaleTimeString throw.
|
||||
const timezone =
|
||||
config.timezone && isValidTimezone(config.timezone)
|
||||
? config.timezone
|
||||
: undefined;
|
||||
const [now, setNow] = useState(new Date());
|
||||
|
||||
// Minute-level is enough without seconds; pause when the tab is backgrounded.
|
||||
usePageVisibleInterval(
|
||||
() => setNow(new Date()),
|
||||
showSeconds ? 1_000 : 30_000,
|
||||
);
|
||||
|
||||
const opts: Intl.DateTimeFormatOptions = {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
...(showSeconds ? { second: "2-digit" } : {}),
|
||||
hour12: format === "12h",
|
||||
...(timezone ? { timeZone: timezone } : {}),
|
||||
};
|
||||
|
||||
const dateOpts: Intl.DateTimeFormatOptions = {
|
||||
weekday: "long",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
...(timezone ? { timeZone: timezone } : {}),
|
||||
};
|
||||
|
||||
const timeStr = now.toLocaleTimeString(undefined, opts);
|
||||
const dateStr = now.toLocaleDateString(undefined, dateOpts);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden select-none">
|
||||
<WidgetTitle title={widget.title} icon={<Clock size={11} />} />
|
||||
<div className="flex flex-col items-center justify-center flex-1 gap-1 p-3 overflow-auto">
|
||||
<span className="text-2xl font-bold tabular-nums text-accent-brand">
|
||||
{timeStr}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">{dateStr}</span>
|
||||
{timezone && (
|
||||
<span className="text-[10px] text-muted-foreground/60">
|
||||
{timezone}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<ClockConfig>({
|
||||
id: "clock",
|
||||
name: "Clock",
|
||||
description: "A live clock with configurable timezone",
|
||||
category: "info",
|
||||
icon: <Clock size={14} />,
|
||||
defaultConfig: { showSeconds: true, format: "24h" },
|
||||
defaultSize: { w: GRID_SIZE * 8, h: GRID_SIZE * 5 },
|
||||
minSize: { w: GRID_SIZE * 2, h: GRID_SIZE * 2 },
|
||||
component: ClockWidget,
|
||||
});
|
||||
|
||||
export { ClockWidget };
|
||||
@@ -0,0 +1,169 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Timer } from "lucide-react";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { CountdownConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
|
||||
function getAccentColor(): string {
|
||||
return (
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--accent-brand")
|
||||
.trim() || "#f59145"
|
||||
);
|
||||
}
|
||||
|
||||
function decompose(ms: number): {
|
||||
days: number;
|
||||
hours: number;
|
||||
minutes: number;
|
||||
seconds: number;
|
||||
} {
|
||||
const total = Math.max(0, Math.floor(ms / 1000));
|
||||
const days = Math.floor(total / 86400);
|
||||
const hours = Math.floor((total % 86400) / 3600);
|
||||
const minutes = Math.floor((total % 3600) / 60);
|
||||
const seconds = total % 60;
|
||||
return { days, hours, minutes, seconds };
|
||||
}
|
||||
|
||||
function UnitBlock({ value, label }: { value: number; label: string }) {
|
||||
const accent = getAccentColor();
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-0.5">
|
||||
<span
|
||||
className="text-2xl font-bold tabular-nums leading-none"
|
||||
style={{ color: accent }}
|
||||
>
|
||||
{String(value).padStart(2, "0")}
|
||||
</span>
|
||||
<span className="text-[9px] text-muted-foreground uppercase tracking-wider">
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CountdownWidget({
|
||||
widget,
|
||||
config,
|
||||
}: WidgetComponentProps<CountdownConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { targetDate, label, showDays, showHours } = config;
|
||||
const [remaining, setRemaining] = useState(0);
|
||||
const [past, setPast] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const update = () => {
|
||||
const diff = new Date(targetDate).getTime() - Date.now();
|
||||
if (diff <= 0) {
|
||||
setRemaining(0);
|
||||
setPast(true);
|
||||
} else {
|
||||
setRemaining(diff);
|
||||
setPast(false);
|
||||
}
|
||||
};
|
||||
update();
|
||||
|
||||
let intervalId: ReturnType<typeof setInterval> | null = null;
|
||||
const start = () => {
|
||||
if (intervalId !== null) return;
|
||||
intervalId = setInterval(update, 1000);
|
||||
};
|
||||
const stop = () => {
|
||||
if (intervalId === null) return;
|
||||
clearInterval(intervalId);
|
||||
intervalId = null;
|
||||
};
|
||||
const onVisibility = () => {
|
||||
if (document.visibilityState === "hidden") {
|
||||
stop();
|
||||
return;
|
||||
}
|
||||
update();
|
||||
start();
|
||||
};
|
||||
|
||||
if (document.visibilityState !== "hidden") start();
|
||||
document.addEventListener("visibilitychange", onVisibility);
|
||||
return () => {
|
||||
stop();
|
||||
document.removeEventListener("visibilitychange", onVisibility);
|
||||
};
|
||||
}, [targetDate]);
|
||||
|
||||
const titleBar = (
|
||||
<WidgetTitle title={widget.title} icon={<Timer size={11} />} />
|
||||
);
|
||||
|
||||
if (!targetDate) {
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
{titleBar}
|
||||
<div className="flex items-center justify-center flex-1 text-xs text-muted-foreground">
|
||||
{t("homepage.countdownNoDate")}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (past) {
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
{titleBar}
|
||||
<div className="flex flex-col items-center justify-center flex-1 gap-1">
|
||||
<Timer size={16} className="text-muted-foreground" />
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("homepage.countdownPast")}
|
||||
</span>
|
||||
{label && (
|
||||
<span className="text-[10px] text-muted-foreground/60">
|
||||
{label}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const { days, hours, minutes, seconds } = decompose(remaining);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
{titleBar}
|
||||
<div className="flex flex-col items-center justify-center flex-1 gap-2 p-2">
|
||||
{label && (
|
||||
<span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider">
|
||||
{label}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex items-center gap-3 flex-wrap justify-center">
|
||||
{showDays && (
|
||||
<UnitBlock value={days} label={t("homepage.countdownDays")} />
|
||||
)}
|
||||
{showHours && (
|
||||
<UnitBlock value={hours} label={t("homepage.countdownHours")} />
|
||||
)}
|
||||
<UnitBlock value={minutes} label={t("homepage.countdownMinutes")} />
|
||||
<UnitBlock value={seconds} label={t("homepage.countdownSeconds")} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<CountdownConfig>({
|
||||
id: "countdown",
|
||||
name: "Countdown",
|
||||
description: "Counts down to a target date and time",
|
||||
category: "info",
|
||||
icon: <Timer size={14} />,
|
||||
defaultConfig: { targetDate: "", label: "", showDays: true, showHours: true },
|
||||
defaultSize: { w: GRID_SIZE * 8, h: GRID_SIZE * 5 },
|
||||
minSize: { w: GRID_SIZE * 4, h: GRID_SIZE * 3 },
|
||||
component: CountdownWidget,
|
||||
});
|
||||
|
||||
export { CountdownWidget };
|
||||
@@ -0,0 +1,200 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Braces } from "lucide-react";
|
||||
import { usePluginApi, useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { CustomApiConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import { WidgetTitle, runVisibleInterval } from "@termix/plugin-sdk/ui";
|
||||
|
||||
function resolvePath(obj: unknown, path: string): unknown {
|
||||
return path.split(".").reduce((acc: unknown, key) => {
|
||||
if (acc && typeof acc === "object")
|
||||
return (acc as Record<string, unknown>)[key];
|
||||
return undefined;
|
||||
}, obj);
|
||||
}
|
||||
|
||||
function resolveArray(
|
||||
obj: unknown,
|
||||
path: string | undefined,
|
||||
): unknown[] | null {
|
||||
if (!path) {
|
||||
if (Array.isArray(obj)) return obj as unknown[];
|
||||
return null;
|
||||
}
|
||||
const val = resolvePath(obj, path);
|
||||
return Array.isArray(val) ? (val as unknown[]) : null;
|
||||
}
|
||||
|
||||
function CustomApiWidget({
|
||||
widget,
|
||||
config,
|
||||
}: WidgetComponentProps<CustomApiConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const api = usePluginApi();
|
||||
const {
|
||||
url,
|
||||
displayField,
|
||||
label,
|
||||
unit,
|
||||
refreshInterval,
|
||||
displayMode,
|
||||
jsonPath,
|
||||
} = config;
|
||||
const [data, setData] = useState<unknown>(null);
|
||||
const [error, setError] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const interval = Math.max(10, refreshInterval || 60);
|
||||
|
||||
const fetchData = async () => {
|
||||
if (!url) return;
|
||||
try {
|
||||
const res = await api.get("/proxy", { params: { url, ttl: interval } });
|
||||
setData(res.data);
|
||||
setError(false);
|
||||
} catch {
|
||||
setError(true);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
return runVisibleInterval(() => {
|
||||
void fetchData();
|
||||
}, interval * 1000);
|
||||
}, [url, interval]);
|
||||
|
||||
const accent =
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--accent-brand")
|
||||
.trim() || "#f59145";
|
||||
|
||||
if (!url) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("homepage.customApiNoUrl")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-red-400">
|
||||
{t("homepage.customApiError")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const titleBar = (
|
||||
<WidgetTitle title={widget.title} icon={<Braces size={11} />} />
|
||||
);
|
||||
|
||||
if (displayMode === "value") {
|
||||
const val = displayField ? resolvePath(data, displayField) : data;
|
||||
const display =
|
||||
typeof val === "object" ? JSON.stringify(val) : String(val ?? "—");
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
{titleBar}
|
||||
<div className="flex flex-col items-center justify-center flex-1 gap-1 p-2">
|
||||
{label && (
|
||||
<span className="text-[10px] text-muted-foreground uppercase tracking-wider">
|
||||
{label}
|
||||
</span>
|
||||
)}
|
||||
<span
|
||||
className="text-2xl font-bold tabular-nums"
|
||||
style={{ color: accent }}
|
||||
>
|
||||
{display}
|
||||
</span>
|
||||
{unit && (
|
||||
<span className="text-[10px] text-muted-foreground">{unit}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (displayMode === "table") {
|
||||
const arr = resolveArray(data, jsonPath);
|
||||
if (!arr) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("homepage.customApiNotArray")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
{titleBar}
|
||||
<div className="flex-1 overflow-auto p-2">
|
||||
<table className="w-full text-[9px]">
|
||||
<tbody>
|
||||
{arr.slice(0, 50).map((row, i) => {
|
||||
if (typeof row !== "object" || row === null) {
|
||||
return (
|
||||
<tr key={i}>
|
||||
<td className="py-0.5 pr-2 text-foreground">
|
||||
{String(row)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<tr key={i} className="border-b border-border/30">
|
||||
{Object.entries(row as Record<string, unknown>)
|
||||
.slice(0, 4)
|
||||
.map(([k, v]) => (
|
||||
<td key={k} className="py-0.5 pr-2">
|
||||
<span className="text-muted-foreground">{k}: </span>
|
||||
<span className="text-foreground">
|
||||
{String(v ?? "")}
|
||||
</span>
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// json mode
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
{titleBar}
|
||||
<div className="flex-1 overflow-auto p-2">
|
||||
<pre className="text-[9px] text-foreground whitespace-pre-wrap break-all leading-relaxed font-mono">
|
||||
{JSON.stringify(data, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<CustomApiConfig>({
|
||||
id: "custom_api",
|
||||
name: "Custom API",
|
||||
description: "Fetch and display data from any JSON API",
|
||||
category: "info",
|
||||
icon: <Braces size={14} />,
|
||||
defaultConfig: { url: "", refreshInterval: 60, displayMode: "value" },
|
||||
defaultSize: { w: GRID_SIZE * 10, h: GRID_SIZE * 7 },
|
||||
minSize: { w: GRID_SIZE * 4, h: GRID_SIZE * 3 },
|
||||
component: CustomApiWidget,
|
||||
});
|
||||
|
||||
export { CustomApiWidget };
|
||||
@@ -0,0 +1,151 @@
|
||||
import { useEffect, useState, useRef } from "react";
|
||||
import { Link, ExternalLink } from "lucide-react";
|
||||
import { usePluginApi, useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type {
|
||||
DashboardLinksConfig,
|
||||
ServiceLinkRecord,
|
||||
WidgetComponentProps,
|
||||
} from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
|
||||
function getFaviconUrl(url: string): string {
|
||||
try {
|
||||
const domain = new URL(url).hostname;
|
||||
return `https://www.google.com/s2/favicons?sz=32&domain_url=${encodeURIComponent(domain)}`;
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function LinkTile({
|
||||
link,
|
||||
showIcons,
|
||||
isReadOnly,
|
||||
}: {
|
||||
link: ServiceLinkRecord;
|
||||
showIcons: boolean;
|
||||
isReadOnly?: boolean;
|
||||
}) {
|
||||
const [imgFailed, setImgFailed] = useState(false);
|
||||
const mouseDownRef = useRef<{ x: number; y: number } | null>(null);
|
||||
const faviconUrl = showIcons ? getFaviconUrl(link.url) : null;
|
||||
|
||||
const content = (
|
||||
<div className="group flex items-center gap-2 px-2 py-1.5 hover:bg-muted/40 transition-colors overflow-hidden border-b border-border/30">
|
||||
{showIcons &&
|
||||
(faviconUrl && !imgFailed ? (
|
||||
<img
|
||||
src={faviconUrl}
|
||||
alt=""
|
||||
className="w-4 h-4 shrink-0 object-contain"
|
||||
onError={() => setImgFailed(true)}
|
||||
/>
|
||||
) : (
|
||||
<ExternalLink size={12} className="shrink-0 text-muted-foreground" />
|
||||
))}
|
||||
<span className="text-[10px] font-medium text-foreground truncate flex-1">
|
||||
{link.label}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (isReadOnly || !link.url) return content;
|
||||
|
||||
return (
|
||||
<a
|
||||
href={link.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block no-underline"
|
||||
onMouseDown={(e) => {
|
||||
mouseDownRef.current = { x: e.clientX, y: e.clientY };
|
||||
}}
|
||||
onClick={(e) => {
|
||||
const s = mouseDownRef.current;
|
||||
if (
|
||||
s &&
|
||||
(Math.abs(e.clientX - s.x) > 4 || Math.abs(e.clientY - s.y) > 4)
|
||||
)
|
||||
e.preventDefault();
|
||||
mouseDownRef.current = null;
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
function DashboardLinksWidget({
|
||||
widget,
|
||||
config,
|
||||
isReadOnly,
|
||||
}: WidgetComponentProps<DashboardLinksConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const api = usePluginApi();
|
||||
const { showIcons, columns, maxItems } = config;
|
||||
const [links, setLinks] = useState<ServiceLinkRecord[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
api
|
||||
.get("/service-links")
|
||||
.then((res) => {
|
||||
const data = res.data as ServiceLinkRecord[];
|
||||
setLinks(maxItems ? data.slice(0, maxItems) : data);
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => setLoading(false));
|
||||
}, [maxItems]);
|
||||
|
||||
if (loading)
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
);
|
||||
if (links.length === 0)
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("homepage.noDashboardLinks")}
|
||||
</div>
|
||||
);
|
||||
|
||||
const colClass =
|
||||
columns === 1
|
||||
? "grid-cols-1"
|
||||
: columns === 2
|
||||
? "grid-cols-2"
|
||||
: "grid-cols-3";
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle title={widget.title} icon={<Link size={11} />} />
|
||||
<div className={`grid ${colClass} flex-1 overflow-auto content-start`}>
|
||||
{links.map((link) => (
|
||||
<LinkTile
|
||||
key={link.id}
|
||||
link={link}
|
||||
showIcons={showIcons}
|
||||
isReadOnly={isReadOnly}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<DashboardLinksConfig>({
|
||||
id: "dashboard_links",
|
||||
name: "Dashboard Links",
|
||||
description: "Shows your saved dashboard service links",
|
||||
category: "links",
|
||||
icon: <Link size={14} />,
|
||||
defaultConfig: { showIcons: true, columns: 1 },
|
||||
defaultSize: { w: GRID_SIZE * 10, h: GRID_SIZE * 8 },
|
||||
minSize: { w: GRID_SIZE * 4, h: GRID_SIZE * 3 },
|
||||
component: DashboardLinksWidget,
|
||||
});
|
||||
|
||||
export { DashboardLinksWidget };
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Folder } from "lucide-react";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { FolderConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
|
||||
function FolderWidget({ widget, config }: WidgetComponentProps<FolderConfig>) {
|
||||
const accentColor =
|
||||
config.color ||
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--accent-brand")
|
||||
.trim() ||
|
||||
"#f59145";
|
||||
|
||||
return (
|
||||
<div
|
||||
className="w-full h-full flex flex-col"
|
||||
style={{
|
||||
background: `${accentColor}10`,
|
||||
borderTop: `2px solid ${accentColor}60`,
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-1.5 px-2 py-1.5 select-none">
|
||||
<Folder size={11} style={{ color: accentColor }} className="shrink-0" />
|
||||
<span className="text-xs font-semibold text-foreground truncate">
|
||||
{widget.title || "Folder"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<FolderConfig>({
|
||||
id: "folder",
|
||||
name: "Folder",
|
||||
description: "A background card for grouping widgets visually",
|
||||
category: "links",
|
||||
icon: <Folder size={14} />,
|
||||
defaultConfig: { isExpanded: true },
|
||||
defaultSize: { w: GRID_SIZE * 14, h: GRID_SIZE * 12 },
|
||||
minSize: { w: GRID_SIZE * 2, h: GRID_SIZE * 2 },
|
||||
component: FolderWidget as unknown as React.ComponentType<
|
||||
WidgetComponentProps<FolderConfig>
|
||||
>,
|
||||
});
|
||||
|
||||
export { FolderWidget };
|
||||
@@ -0,0 +1,125 @@
|
||||
import { LayoutGrid } from "lucide-react";
|
||||
import {
|
||||
useTranslation,
|
||||
useHostStatus,
|
||||
useHosts,
|
||||
type PluginHostRecord,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { HostGridConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
|
||||
function getAccentColor(): string {
|
||||
return (
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--accent-brand")
|
||||
.trim() || "#f59145"
|
||||
);
|
||||
}
|
||||
|
||||
function StatusDot({ status }: { status: string }) {
|
||||
const color =
|
||||
status === "online"
|
||||
? getAccentColor()
|
||||
: status === "reachable"
|
||||
? "#fbbf24"
|
||||
: status === "offline"
|
||||
? "#ef4444"
|
||||
: "#6b7280";
|
||||
return (
|
||||
<span
|
||||
className="w-1.5 h-1.5 rounded-full shrink-0 inline-block"
|
||||
style={{ background: color }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function HostGridRow({
|
||||
host,
|
||||
showIp,
|
||||
}: {
|
||||
host: PluginHostRecord;
|
||||
showIp: boolean;
|
||||
}) {
|
||||
const status = useHostStatus(Number(host.id));
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 p-1.5 bg-muted/30 border border-border/40 overflow-hidden">
|
||||
<StatusDot status={status?.status ?? "unknown"} />
|
||||
<div className="flex flex-col min-w-0">
|
||||
<span className="text-[10px] font-medium text-foreground truncate">
|
||||
{host.name}
|
||||
</span>
|
||||
{showIp && (
|
||||
<span className="text-[9px] text-muted-foreground truncate">
|
||||
{host.ip}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function HostGridWidget({
|
||||
widget,
|
||||
config,
|
||||
}: WidgetComponentProps<HostGridConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { hostIds, showIp, columns } = config;
|
||||
const { hosts: allHosts, loaded } = useHosts();
|
||||
const hosts =
|
||||
hostIds.length > 0
|
||||
? allHosts.filter((h) => hostIds.includes(Number(h.id)))
|
||||
: allHosts;
|
||||
|
||||
if (!loaded) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (hosts.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("homepage.noHosts")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const gridCols =
|
||||
columns === 2
|
||||
? "grid-cols-2"
|
||||
: columns === 3
|
||||
? "grid-cols-3"
|
||||
: "grid-cols-4";
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle title={widget.title} icon={<LayoutGrid size={11} />} />
|
||||
<div
|
||||
className={`grid ${gridCols} gap-1.5 p-2 flex-1 content-start overflow-auto`}
|
||||
>
|
||||
{hosts.map((host) => (
|
||||
<HostGridRow key={String(host.id)} host={host} showIp={showIp} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<HostGridConfig>({
|
||||
id: "host_grid",
|
||||
name: "Host Grid",
|
||||
description: "Live status overview grid for all your SSH hosts",
|
||||
category: "monitoring",
|
||||
icon: <LayoutGrid size={14} />,
|
||||
defaultConfig: { hostIds: [], showIp: false, columns: 3 },
|
||||
defaultSize: { w: GRID_SIZE * 12, h: GRID_SIZE * 8 },
|
||||
minSize: { w: GRID_SIZE * 4, h: GRID_SIZE * 3 },
|
||||
component: HostGridWidget,
|
||||
});
|
||||
|
||||
export { HostGridWidget };
|
||||
@@ -0,0 +1,122 @@
|
||||
import { Server } from "lucide-react";
|
||||
import {
|
||||
useTranslation,
|
||||
useHost,
|
||||
useHostStatus,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
|
||||
import { ComponentSlot, WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type {
|
||||
HostStatusConfig,
|
||||
HostMetricKey,
|
||||
WidgetComponentProps,
|
||||
} from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
|
||||
function getAccentColor(): string {
|
||||
return (
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--accent-brand")
|
||||
.trim() || "#f59145"
|
||||
);
|
||||
}
|
||||
|
||||
const DEFAULT_METRICS: HostMetricKey[] = ["cpu", "memory"];
|
||||
|
||||
function migrateConfig(config: HostStatusConfig): HostMetricKey[] {
|
||||
if (config.shownMetrics?.length) return config.shownMetrics;
|
||||
if (config.showMetrics === false) return [];
|
||||
const metrics: HostMetricKey[] = ["cpu", "memory"];
|
||||
if (config.showDisk) metrics.push("disk");
|
||||
return metrics;
|
||||
}
|
||||
|
||||
function HostStatusWidget({
|
||||
widget,
|
||||
config,
|
||||
}: WidgetComponentProps<HostStatusConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const shownMetrics = migrateConfig(config);
|
||||
const { hostId } = config;
|
||||
const host = useHost(hostId || undefined);
|
||||
const statusInfo = useHostStatus(hostId || undefined);
|
||||
|
||||
const needsMetrics = shownMetrics.length > 0;
|
||||
|
||||
if (!hostId) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("homepage.noHostSelected")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const online = statusInfo?.status === "online";
|
||||
const reachable = statusInfo?.status === "reachable";
|
||||
|
||||
const onlineColor = !statusInfo
|
||||
? "#6b7280"
|
||||
: online
|
||||
? getAccentColor()
|
||||
: reachable
|
||||
? "#fbbf24"
|
||||
: "#ef4444";
|
||||
const onlineLabel = !statusInfo
|
||||
? t("common.unknown")
|
||||
: online
|
||||
? t("common.online")
|
||||
: reachable
|
||||
? t("common.signInFailed")
|
||||
: t("common.offline");
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle title={widget.title} icon={<Server size={11} />} />
|
||||
<div
|
||||
className={`flex flex-col gap-2.5 p-3 flex-1 overflow-auto ${!needsMetrics ? "justify-center" : ""}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Server size={14} className="text-muted-foreground shrink-0" />
|
||||
<span className="text-xs font-semibold text-foreground truncate flex-1">
|
||||
{host?.name ?? `Host #${hostId}`}
|
||||
</span>
|
||||
<span className="flex items-center gap-1 shrink-0">
|
||||
<span
|
||||
className="w-1.5 h-1.5 shrink-0 rounded-full"
|
||||
style={{ background: onlineColor }}
|
||||
/>
|
||||
<span
|
||||
className="text-[10px] font-medium"
|
||||
style={{ color: onlineColor }}
|
||||
>
|
||||
{onlineLabel}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Plugins such as host metrics fill in the live numbers. */}
|
||||
{needsMetrics && (
|
||||
<ComponentSlot
|
||||
slotId="homepage.hostMetrics"
|
||||
props={{ hostId, shownMetrics, online }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<HostStatusConfig>({
|
||||
id: "host_status",
|
||||
name: "Host Status",
|
||||
description: "Shows live status and metrics for an SSH host",
|
||||
category: "system",
|
||||
icon: <Server size={14} />,
|
||||
defaultConfig: { hostId: 0, shownMetrics: DEFAULT_METRICS },
|
||||
defaultSize: { w: GRID_SIZE * 9, h: GRID_SIZE * 6 },
|
||||
minSize: { w: GRID_SIZE * 2, h: GRID_SIZE * 2 },
|
||||
component: HostStatusWidget,
|
||||
});
|
||||
|
||||
export { HostStatusWidget };
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { Globe } from "lucide-react";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { IframeConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
|
||||
function IframeWidget({
|
||||
widget,
|
||||
config,
|
||||
isReadOnly,
|
||||
}: WidgetComponentProps<IframeConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { url, scrolling } = config;
|
||||
|
||||
if (!url) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center w-full h-full gap-2 text-muted-foreground/50">
|
||||
<Globe size={24} />
|
||||
<span className="text-xs">{t("homepage.configureUrl")}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle title={widget.title} icon={<Globe size={11} />} />
|
||||
<div className="relative flex-1">
|
||||
<iframe
|
||||
src={url}
|
||||
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
|
||||
scrolling={scrolling ? "yes" : "no"}
|
||||
className="w-full h-full border-0"
|
||||
title={t("homepage.embeddedContent")}
|
||||
/>
|
||||
{/* Block interaction in read-only mode so the canvas can still pan */}
|
||||
{isReadOnly && <div className="absolute inset-0 pointer-events-none" />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<IframeConfig>({
|
||||
id: "iframe_embed",
|
||||
name: "iFrame Embed",
|
||||
description: "Embed any URL in an iframe",
|
||||
category: "info",
|
||||
icon: <Globe size={14} />,
|
||||
defaultConfig: { url: "", scrolling: true },
|
||||
defaultSize: { w: GRID_SIZE * 14, h: GRID_SIZE * 12 },
|
||||
minSize: { w: GRID_SIZE * 2, h: GRID_SIZE * 2 },
|
||||
component: IframeWidget,
|
||||
});
|
||||
|
||||
export { IframeWidget };
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useState, useRef } from "react";
|
||||
import { ImageIcon } from "lucide-react";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { ImageWidgetConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
|
||||
const FIT_MAP = {
|
||||
contain: "object-contain",
|
||||
cover: "object-cover",
|
||||
fill: "object-fill",
|
||||
};
|
||||
|
||||
function ImageWidget({
|
||||
widget,
|
||||
config,
|
||||
isReadOnly,
|
||||
}: WidgetComponentProps<ImageWidgetConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { imageUrl, fit, alt, linkUrl } = config;
|
||||
const [failed, setFailed] = useState(false);
|
||||
const mouseDownRef = useRef<{ x: number; y: number } | null>(null);
|
||||
|
||||
const titleBar = widget.title ? (
|
||||
<WidgetTitle title={widget.title} icon={<ImageIcon size={11} />} />
|
||||
) : null;
|
||||
|
||||
const content = (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
{titleBar}
|
||||
<div className="flex-1 flex items-center justify-center overflow-hidden">
|
||||
{imageUrl && !failed ? (
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt={alt ?? ""}
|
||||
className={`w-full h-full ${FIT_MAP[fit]}`}
|
||||
onError={() => setFailed(true)}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-1 text-muted-foreground/40">
|
||||
<ImageIcon size={24} />
|
||||
<span className="text-[10px]">{t("homepage.noImage")}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (isReadOnly || !linkUrl) return content;
|
||||
|
||||
return (
|
||||
<a
|
||||
href={linkUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block w-full h-full"
|
||||
onMouseDown={(e) => {
|
||||
mouseDownRef.current = { x: e.clientX, y: e.clientY };
|
||||
}}
|
||||
onClick={(e) => {
|
||||
const s = mouseDownRef.current;
|
||||
if (
|
||||
s &&
|
||||
(Math.abs(e.clientX - s.x) > 4 || Math.abs(e.clientY - s.y) > 4)
|
||||
)
|
||||
e.preventDefault();
|
||||
mouseDownRef.current = null;
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<ImageWidgetConfig>({
|
||||
id: "image_widget",
|
||||
name: "Image",
|
||||
description: "Display any image from a URL",
|
||||
category: "info",
|
||||
icon: <ImageIcon size={14} />,
|
||||
defaultConfig: { imageUrl: "", fit: "contain" },
|
||||
defaultSize: { w: GRID_SIZE * 10, h: GRID_SIZE * 8 },
|
||||
minSize: { w: GRID_SIZE * 2, h: GRID_SIZE * 2 },
|
||||
component: ImageWidget,
|
||||
});
|
||||
|
||||
export { ImageWidget };
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { useRef } from "react";
|
||||
import { List, ExternalLink } from "lucide-react";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type {
|
||||
LinkTreeConfig,
|
||||
LinkTreeLink,
|
||||
WidgetComponentProps,
|
||||
} from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
|
||||
function TreeLink({
|
||||
link,
|
||||
compact,
|
||||
isReadOnly,
|
||||
}: {
|
||||
link: LinkTreeLink;
|
||||
compact: boolean;
|
||||
isReadOnly?: boolean;
|
||||
}) {
|
||||
const mouseDownRef = useRef<{ x: number; y: number } | null>(null);
|
||||
|
||||
const content = (
|
||||
<div
|
||||
className={`group flex items-center gap-1.5 ${compact ? "py-0.5" : "py-1"} pl-2 pr-1 hover:bg-muted/40 transition-colors overflow-hidden`}
|
||||
>
|
||||
<ExternalLink
|
||||
size={9}
|
||||
className="shrink-0 text-muted-foreground group-hover:text-accent-brand transition-colors"
|
||||
/>
|
||||
<div className="flex flex-col min-w-0">
|
||||
<span className="text-[10px] font-medium text-foreground truncate">
|
||||
{link.label}
|
||||
</span>
|
||||
{!compact && link.description && (
|
||||
<span className="text-[9px] text-muted-foreground truncate">
|
||||
{link.description}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (isReadOnly || !link.url) return content;
|
||||
|
||||
return (
|
||||
<a
|
||||
href={link.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block no-underline"
|
||||
onMouseDown={(e) => {
|
||||
mouseDownRef.current = { x: e.clientX, y: e.clientY };
|
||||
}}
|
||||
onClick={(e) => {
|
||||
const s = mouseDownRef.current;
|
||||
if (
|
||||
s &&
|
||||
(Math.abs(e.clientX - s.x) > 4 || Math.abs(e.clientY - s.y) > 4)
|
||||
)
|
||||
e.preventDefault();
|
||||
mouseDownRef.current = null;
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
function LinkTreeWidget({
|
||||
widget,
|
||||
config,
|
||||
isReadOnly,
|
||||
}: WidgetComponentProps<LinkTreeConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { sections, compact } = config;
|
||||
|
||||
if (sections.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("homepage.noSections")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle title={widget.title} icon={<List size={11} />} />
|
||||
<div className="flex-1 overflow-auto">
|
||||
{sections.map((section, si) => (
|
||||
<div key={si}>
|
||||
{section.heading && (
|
||||
<div className="flex items-center gap-1.5 px-2 pt-2 pb-0.5 border-b border-border/30">
|
||||
<span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider truncate">
|
||||
{section.heading}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{section.links.map((link, li) => (
|
||||
<TreeLink
|
||||
key={li}
|
||||
link={link}
|
||||
compact={compact}
|
||||
isReadOnly={isReadOnly}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<LinkTreeConfig>({
|
||||
id: "link_tree",
|
||||
name: "Link Tree",
|
||||
description: "Grouped links organized into labeled sections",
|
||||
category: "links",
|
||||
icon: <List size={14} />,
|
||||
defaultConfig: { sections: [], compact: false },
|
||||
defaultSize: { w: GRID_SIZE * 10, h: GRID_SIZE * 12 },
|
||||
minSize: { w: GRID_SIZE * 4, h: GRID_SIZE * 4 },
|
||||
component: LinkTreeWidget,
|
||||
});
|
||||
|
||||
export { LinkTreeWidget };
|
||||
@@ -0,0 +1,124 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import { FileText } from "lucide-react";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { MarkdownNotesConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import { updateHomepageItem } from "../api.js";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
|
||||
function renderMarkdown(src: string): string {
|
||||
return src
|
||||
.split("\n")
|
||||
.map((line) => {
|
||||
if (/^### /.test(line))
|
||||
return `<h3 class="text-[11px] font-bold mt-2 mb-0.5 text-foreground">${esc(line.slice(4))}</h3>`;
|
||||
if (/^## /.test(line))
|
||||
return `<h2 class="text-xs font-bold mt-2 mb-0.5 text-foreground">${esc(line.slice(3))}</h2>`;
|
||||
if (/^# /.test(line))
|
||||
return `<h1 class="text-sm font-bold mt-2 mb-0.5 text-foreground">${esc(line.slice(2))}</h1>`;
|
||||
if (/^- /.test(line))
|
||||
return `<li class="text-[10px] ml-3 list-disc text-foreground">${inlineFormat(line.slice(2))}</li>`;
|
||||
if (/^\d+\. /.test(line))
|
||||
return `<li class="text-[10px] ml-3 list-decimal text-foreground">${inlineFormat(line.replace(/^\d+\. /, ""))}</li>`;
|
||||
if (line.trim() === "") return "<br/>";
|
||||
return `<p class="text-[10px] text-foreground leading-relaxed">${inlineFormat(line)}</p>`;
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
|
||||
function esc(s: string): string {
|
||||
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
}
|
||||
|
||||
function inlineFormat(s: string): string {
|
||||
return esc(s)
|
||||
.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>")
|
||||
.replace(/\*(.+?)\*/g, "<em>$1</em>")
|
||||
.replace(
|
||||
/`(.+?)`/g,
|
||||
'<code class="bg-muted px-0.5 font-mono text-[9px]">$1</code>',
|
||||
);
|
||||
}
|
||||
|
||||
function MarkdownNotesWidget({
|
||||
widget,
|
||||
config,
|
||||
isReadOnly,
|
||||
onConfigUpdate,
|
||||
}: WidgetComponentProps<MarkdownNotesConfig>) {
|
||||
const { content, backgroundColor, renderMarkdown: doRender } = config;
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState(content);
|
||||
|
||||
const commitEdit = useCallback(async () => {
|
||||
setEditing(false);
|
||||
if (draft === content) return;
|
||||
try {
|
||||
await updateHomepageItem(widget.id, {
|
||||
config: { ...config, content: draft } as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
>,
|
||||
});
|
||||
onConfigUpdate?.({ ...config, content: draft } as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
>);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}, [draft, content, widget.id, config, onConfigUpdate]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex flex-col w-full h-full overflow-hidden"
|
||||
style={backgroundColor ? { background: backgroundColor } : undefined}
|
||||
>
|
||||
<WidgetTitle title={widget.title} icon={<FileText size={11} />} />
|
||||
<div className="flex-1 overflow-auto p-2 relative">
|
||||
{editing ? (
|
||||
<textarea
|
||||
autoFocus
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onBlur={commitEdit}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
className="w-full h-full bg-transparent text-[10px] text-foreground resize-none outline-none border-none leading-relaxed"
|
||||
style={{ minHeight: "100%" }}
|
||||
/>
|
||||
) : doRender ? (
|
||||
<div
|
||||
className="text-[10px] leading-relaxed cursor-text"
|
||||
onDoubleClick={() => {
|
||||
if (!isReadOnly) setEditing(true);
|
||||
}}
|
||||
dangerouslySetInnerHTML={{ __html: renderMarkdown(content || "") }}
|
||||
/>
|
||||
) : (
|
||||
<pre
|
||||
className="text-[10px] text-foreground leading-relaxed whitespace-pre-wrap break-words font-sans cursor-text"
|
||||
onDoubleClick={() => {
|
||||
if (!isReadOnly) setEditing(true);
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<MarkdownNotesConfig>({
|
||||
id: "markdown_notes",
|
||||
name: "Markdown Notes",
|
||||
description: "Notes with optional Markdown rendering and inline editing",
|
||||
category: "info",
|
||||
icon: <FileText size={14} />,
|
||||
defaultConfig: { content: "", renderMarkdown: true },
|
||||
defaultSize: { w: GRID_SIZE * 10, h: GRID_SIZE * 8 },
|
||||
minSize: { w: GRID_SIZE * 3, h: GRID_SIZE * 3 },
|
||||
component: MarkdownNotesWidget,
|
||||
});
|
||||
|
||||
export { MarkdownNotesWidget };
|
||||
@@ -0,0 +1,42 @@
|
||||
import { StickyNote } from "lucide-react";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import {
|
||||
GRID_SIZE,
|
||||
type NotesConfig,
|
||||
type WidgetComponentProps,
|
||||
} from "../types.js";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
|
||||
function NotesWidget({ widget, config }: WidgetComponentProps<NotesConfig>) {
|
||||
const { content, backgroundColor } = config;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex flex-col w-full h-full overflow-hidden"
|
||||
style={{ background: backgroundColor || undefined }}
|
||||
>
|
||||
<WidgetTitle title={widget.title} icon={<StickyNote size={11} />} />
|
||||
<div className="flex-1 overflow-auto p-3">
|
||||
<pre className="text-xs text-foreground whitespace-pre-wrap break-words font-sans leading-relaxed select-text w-full">
|
||||
{content || (
|
||||
<span className="text-muted-foreground italic">Empty note...</span>
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<NotesConfig>({
|
||||
id: "notes",
|
||||
name: "Notes",
|
||||
description: "A text notes widget",
|
||||
category: "info",
|
||||
icon: <StickyNote size={14} />,
|
||||
defaultConfig: { content: "" },
|
||||
defaultSize: { w: GRID_SIZE * 10, h: GRID_SIZE * 8 },
|
||||
minSize: { w: GRID_SIZE * 2, h: GRID_SIZE * 2 },
|
||||
component: NotesWidget,
|
||||
});
|
||||
|
||||
export { NotesWidget };
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Wifi } from "lucide-react";
|
||||
import { usePluginApi, useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { PingStatusConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import { WidgetTitle, runVisibleInterval } from "@termix/plugin-sdk/ui";
|
||||
|
||||
interface PingResult {
|
||||
ok: boolean;
|
||||
statusCode: number | null;
|
||||
latencyMs: number;
|
||||
}
|
||||
|
||||
function StatusDot({ ok, pending }: { ok: boolean | null; pending: boolean }) {
|
||||
if (pending)
|
||||
return (
|
||||
<span className="w-2 h-2 rounded-full bg-muted-foreground/40 shrink-0 inline-block" />
|
||||
);
|
||||
return (
|
||||
<span
|
||||
className="w-2 h-2 rounded-full shrink-0 inline-block"
|
||||
style={{ background: ok ? "var(--accent-brand, #f59145)" : "#ef4444" }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function PingStatusWidget({
|
||||
widget,
|
||||
config,
|
||||
}: WidgetComponentProps<PingStatusConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const api = usePluginApi();
|
||||
const { urls, refreshInterval, showLatency } = config;
|
||||
const [results, setResults] = useState<Record<string, PingResult | null>>({});
|
||||
const [pending, setPending] = useState<Record<string, boolean>>({});
|
||||
|
||||
const fetchAll = async () => {
|
||||
if (urls.length === 0) return;
|
||||
const newPending: Record<string, boolean> = {};
|
||||
urls.forEach((u) => {
|
||||
newPending[u.url] = true;
|
||||
});
|
||||
setPending(newPending);
|
||||
|
||||
await Promise.all(
|
||||
urls.map(async (u) => {
|
||||
try {
|
||||
const res = await api.get("/ping", { params: { url: u.url } });
|
||||
const r = res.data as PingResult;
|
||||
setResults((prev) => ({ ...prev, [u.url]: r }));
|
||||
} catch {
|
||||
setResults((prev) => ({
|
||||
...prev,
|
||||
[u.url]: { ok: false, statusCode: null, latencyMs: 0 },
|
||||
}));
|
||||
} finally {
|
||||
setPending((prev) => ({ ...prev, [u.url]: false }));
|
||||
}
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const interval = Math.max(10, refreshInterval || 30);
|
||||
|
||||
useEffect(() => {
|
||||
fetchAll();
|
||||
return runVisibleInterval(() => {
|
||||
void fetchAll();
|
||||
}, interval * 1000);
|
||||
}, [JSON.stringify(urls), interval]);
|
||||
|
||||
if (urls.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("homepage.noPingUrls")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle
|
||||
title={widget.title || t("homepage.widgetPingStatusName")}
|
||||
icon={<Wifi size={11} />}
|
||||
/>
|
||||
<div className="flex-1 overflow-auto">
|
||||
{urls.map((u) => {
|
||||
const r = results[u.url];
|
||||
const isPending = pending[u.url] ?? false;
|
||||
return (
|
||||
<div
|
||||
key={u.url}
|
||||
className="flex items-center gap-2 px-2 py-1.5 border-b border-border/30"
|
||||
>
|
||||
<StatusDot ok={r?.ok ?? null} pending={isPending} />
|
||||
<div className="flex flex-col min-w-0 flex-1">
|
||||
<span className="text-[10px] font-medium text-foreground truncate">
|
||||
{u.label || u.url}
|
||||
</span>
|
||||
{r && (
|
||||
<span className="text-[9px] text-muted-foreground">
|
||||
{r.statusCode ?? (r.ok ? "OK" : "ERR")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{showLatency && r && r.latencyMs > 0 && (
|
||||
<span className="text-[9px] text-muted-foreground shrink-0 tabular-nums">
|
||||
{r.latencyMs}ms
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<PingStatusConfig>({
|
||||
id: "ping_status",
|
||||
name: "Ping Status",
|
||||
description: "Check if URLs or services are reachable",
|
||||
category: "monitoring",
|
||||
icon: <Wifi size={14} />,
|
||||
defaultConfig: { urls: [], refreshInterval: 30, showLatency: true },
|
||||
defaultSize: { w: GRID_SIZE * 9, h: GRID_SIZE * 7 },
|
||||
minSize: { w: GRID_SIZE * 3, h: GRID_SIZE * 2 },
|
||||
component: PingStatusWidget,
|
||||
});
|
||||
|
||||
export { PingStatusWidget };
|
||||
@@ -0,0 +1,132 @@
|
||||
import { Zap } from "lucide-react";
|
||||
import {
|
||||
useTranslation,
|
||||
useHostActions,
|
||||
useHostStatus,
|
||||
useHosts,
|
||||
useTabs,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type {
|
||||
QuickConnectConfig,
|
||||
QuickConnectType,
|
||||
WidgetComponentProps,
|
||||
} from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
|
||||
import { quickConnectTargets } from "../quick-connect-targets.js";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
|
||||
function StatusDot({ hostId }: { hostId: number }) {
|
||||
const status = useHostStatus(hostId);
|
||||
const cls =
|
||||
status?.status === "online"
|
||||
? "bg-green-500"
|
||||
: status?.status === "offline"
|
||||
? "bg-red-500"
|
||||
: "bg-muted-foreground/30";
|
||||
return <span className={`size-1.5 rounded-full shrink-0 ${cls}`} />;
|
||||
}
|
||||
|
||||
function QuickConnectWidget({
|
||||
widget,
|
||||
config,
|
||||
}: WidgetComponentProps<QuickConnectConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { hosts: allHosts, loaded } = useHosts();
|
||||
const tabs = useTabs();
|
||||
const targets = quickConnectTargets(useHostActions());
|
||||
|
||||
const hosts =
|
||||
config.hostIds.length > 0
|
||||
? allHosts.filter((h) => config.hostIds.includes(Number(h.id)))
|
||||
: allHosts;
|
||||
|
||||
// An empty list means the first tools plugins offer, in their order.
|
||||
const types =
|
||||
config.connectionTypes.length > 0
|
||||
? config.connectionTypes
|
||||
: (targets
|
||||
.slice(0, 2)
|
||||
.map((target) => target.type) as QuickConnectType[]);
|
||||
|
||||
if (!loaded) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground/60">
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (hosts.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center w-full h-full gap-2 text-muted-foreground/60">
|
||||
<Zap size={18} />
|
||||
<span className="text-xs">{t("homepage.noHosts")}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle title={widget.title} icon={<Zap size={11} />} />
|
||||
<div className="flex-1 overflow-y-auto p-2 flex flex-col gap-1">
|
||||
{hosts.map((host) => {
|
||||
const availableTypes = types.flatMap((type) => {
|
||||
const target = targets.find((item) => item.type === type);
|
||||
return target && target.enabled(host) ? [target] : [];
|
||||
});
|
||||
if (availableTypes.length === 0) return null;
|
||||
return (
|
||||
<div
|
||||
key={String(host.id)}
|
||||
className={`flex items-center gap-2 py-1.5 border-b border-border/20 last:border-0 ${config.layout === "grid" ? "flex-col items-start" : ""}`}
|
||||
>
|
||||
<div className="flex items-center gap-1.5 flex-1 min-w-0">
|
||||
{config.showStatus && <StatusDot hostId={Number(host.id)} />}
|
||||
<span className="text-xs font-medium text-foreground truncate">
|
||||
{host.name || host.ip}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 shrink-0 flex-wrap">
|
||||
{availableTypes.map((target) => (
|
||||
<button
|
||||
key={target.type}
|
||||
title={t(target.labelKey, target.type)}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
tabs.connectHost(host, target.type);
|
||||
}}
|
||||
className="p-1.5 text-muted-foreground hover:text-accent-brand hover:bg-accent-brand/10 transition-colors border border-transparent hover:border-accent-brand/20"
|
||||
>
|
||||
<target.icon size={12} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<QuickConnectConfig>({
|
||||
id: "quick_connect",
|
||||
name: "Quick Connect",
|
||||
description:
|
||||
"Launch terminal, files, docker, tunnels, and more for your hosts",
|
||||
category: "system",
|
||||
icon: <Zap size={14} />,
|
||||
defaultConfig: {
|
||||
hostIds: [],
|
||||
connectionTypes: [],
|
||||
showStatus: true,
|
||||
layout: "list",
|
||||
},
|
||||
defaultSize: { w: GRID_SIZE * 10, h: GRID_SIZE * 8 },
|
||||
minSize: { w: GRID_SIZE * 4, h: GRID_SIZE * 3 },
|
||||
component: QuickConnectWidget,
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Activity } from "lucide-react";
|
||||
import { useTranslation, activityTarget } from "@termix/plugin-sdk/frontend";
|
||||
|
||||
import {
|
||||
WidgetTitle,
|
||||
getRecentActivity,
|
||||
runVisibleInterval,
|
||||
type RecentActivityItem,
|
||||
} from "@termix/plugin-sdk/ui";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type {
|
||||
RecentActivityConfig,
|
||||
ActivityType,
|
||||
WidgetComponentProps,
|
||||
} from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
|
||||
function relativeTime(ts: string): string {
|
||||
const diff = Date.now() - new Date(ts).getTime();
|
||||
const m = Math.floor(diff / 60_000);
|
||||
if (m < 1) return "just now";
|
||||
if (m < 60) return `${m}m ago`;
|
||||
const h = Math.floor(m / 60);
|
||||
if (h < 24) return `${h}h ago`;
|
||||
return `${Math.floor(h / 24)}d ago`;
|
||||
}
|
||||
|
||||
function ActivityIcon({ type }: { type: string }) {
|
||||
const Icon = activityTarget(type)?.icon ?? Activity;
|
||||
return <Icon className="size-2.5 shrink-0 text-accent-brand" />;
|
||||
}
|
||||
|
||||
function RecentActivityWidget({
|
||||
widget,
|
||||
config,
|
||||
}: WidgetComponentProps<RecentActivityConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { maxItems, filterTypes, showTimestamp } = config;
|
||||
const [items, setItems] = useState<RecentActivityItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const data = await getRecentActivity(maxItems * 3);
|
||||
const filtered =
|
||||
filterTypes.length > 0
|
||||
? data.filter((i) => filterTypes.includes(i.type as ActivityType))
|
||||
: data;
|
||||
setItems(filtered.slice(0, maxItems));
|
||||
} catch {
|
||||
/* ignore */
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
return runVisibleInterval(() => {
|
||||
void fetchData();
|
||||
}, 60_000);
|
||||
}, [maxItems, filterTypes.join(",")]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (items.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("homepage.noActivity")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle
|
||||
title={widget.title || t("homepage.widgetRecentActivityName")}
|
||||
icon={<Activity size={11} />}
|
||||
/>
|
||||
<div className="flex-1 overflow-auto">
|
||||
{items.map((item) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className="flex items-center gap-2 px-2 py-1.5 border-b border-border/30"
|
||||
>
|
||||
<ActivityIcon type={item.type} />
|
||||
<div className="flex flex-col min-w-0 flex-1">
|
||||
<span className="text-[10px] font-medium text-foreground truncate">
|
||||
{item.hostName}
|
||||
</span>
|
||||
<span className="text-[9px] text-muted-foreground capitalize">
|
||||
{item.type.replace("_", " ")}
|
||||
</span>
|
||||
</div>
|
||||
{showTimestamp && (
|
||||
<span className="text-[9px] text-muted-foreground shrink-0">
|
||||
{relativeTime(item.timestamp)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<RecentActivityConfig>({
|
||||
id: "recent_activity",
|
||||
name: "Recent Activity",
|
||||
description: "Shows recent terminal, Docker, file, and tunnel activity",
|
||||
category: "system",
|
||||
icon: <Activity size={14} />,
|
||||
defaultConfig: { maxItems: 10, filterTypes: [], showTimestamp: true },
|
||||
defaultSize: { w: GRID_SIZE * 10, h: GRID_SIZE * 9 },
|
||||
minSize: { w: GRID_SIZE * 4, h: GRID_SIZE * 3 },
|
||||
component: RecentActivityWidget,
|
||||
});
|
||||
|
||||
export { RecentActivityWidget };
|
||||
@@ -0,0 +1,154 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Rss, ExternalLink } from "lucide-react";
|
||||
import { usePluginApi, useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { RssFeedConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
|
||||
interface RssItem {
|
||||
title: string;
|
||||
link: string;
|
||||
pubDate: string | null;
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
function formatDate(dateStr: string | null): string {
|
||||
if (!dateStr) return "";
|
||||
try {
|
||||
const d = new Date(dateStr);
|
||||
const diffMs = Date.now() - d.getTime();
|
||||
const diffH = Math.floor(diffMs / 3_600_000);
|
||||
if (diffH < 1) return "just now";
|
||||
if (diffH < 24) return `${diffH}h ago`;
|
||||
const diffD = Math.floor(diffH / 24);
|
||||
if (diffD < 7) return `${diffD}d ago`;
|
||||
return d.toLocaleDateString(undefined, { month: "short", day: "numeric" });
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function RssFeedWidget({
|
||||
widget,
|
||||
config,
|
||||
isReadOnly,
|
||||
}: WidgetComponentProps<RssFeedConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const api = usePluginApi();
|
||||
const { feedUrl, maxItems, showDescription } = config;
|
||||
const [items, setItems] = useState<RssItem[]>([]);
|
||||
const [error, setError] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!feedUrl) return;
|
||||
let cancelled = false;
|
||||
const fetchFeed = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(false);
|
||||
const res = await api.get<RssItem[]>("/rss", {
|
||||
params: { url: feedUrl, max: maxItems ?? 10 },
|
||||
});
|
||||
if (!cancelled) setItems(res.data);
|
||||
} catch {
|
||||
if (!cancelled) setError(true);
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
};
|
||||
fetchFeed();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [feedUrl, maxItems]);
|
||||
|
||||
if (!feedUrl) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center w-full h-full gap-2 text-muted-foreground/50">
|
||||
<Rss size={24} />
|
||||
<span className="text-xs">{t("homepage.rssNoFeedUrl")}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (loading && items.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground/50">
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-destructive/70 p-3 text-center">
|
||||
{t("homepage.rssLoadError")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle
|
||||
title={widget.title || t("homepage.widgetRssName")}
|
||||
icon={<Rss size={11} />}
|
||||
/>
|
||||
|
||||
{/* Items */}
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{items.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-full text-xs text-muted-foreground/50">
|
||||
{t("homepage.rssNoItems")}
|
||||
</div>
|
||||
) : (
|
||||
items.map((item, i) => (
|
||||
<div key={i} className="border-b border-border/60 last:border-0">
|
||||
<a
|
||||
href={item.link}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={`flex flex-col px-3 py-2 gap-0.5 hover:bg-muted/40 transition-colors no-underline ${isReadOnly ? "pointer-events-none" : ""}`}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<span className="text-xs font-medium text-foreground line-clamp-2 leading-snug flex-1">
|
||||
{item.title}
|
||||
</span>
|
||||
<ExternalLink
|
||||
size={9}
|
||||
className="text-muted-foreground/40 shrink-0 mt-0.5"
|
||||
/>
|
||||
</div>
|
||||
{showDescription && item.description && (
|
||||
<span className="text-[10px] text-muted-foreground/70 line-clamp-2">
|
||||
{item.description.replace(/<[^>]+>/g, "")}
|
||||
</span>
|
||||
)}
|
||||
{item.pubDate && (
|
||||
<span className="text-[9px] text-muted-foreground/50">
|
||||
{formatDate(item.pubDate)}
|
||||
</span>
|
||||
)}
|
||||
</a>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<RssFeedConfig>({
|
||||
id: "rss_feed",
|
||||
name: "RSS Feed",
|
||||
description: "Display items from an RSS or Atom feed",
|
||||
category: "links",
|
||||
icon: <Rss size={14} />,
|
||||
defaultConfig: { feedUrl: "", maxItems: 10, showDescription: false },
|
||||
defaultSize: { w: GRID_SIZE * 10, h: GRID_SIZE * 10 },
|
||||
minSize: { w: GRID_SIZE * 2, h: GRID_SIZE * 2 },
|
||||
component: RssFeedWidget,
|
||||
});
|
||||
|
||||
export { RssFeedWidget };
|
||||
@@ -0,0 +1,103 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { Search } from "lucide-react";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type {
|
||||
SearchBarConfig,
|
||||
SearchEngine,
|
||||
WidgetComponentProps,
|
||||
} from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
|
||||
const ENGINE_URLS: Record<SearchEngine, string> = {
|
||||
google: "https://www.google.com/search?q={q}",
|
||||
duckduckgo: "https://duckduckgo.com/?q={q}",
|
||||
bing: "https://www.bing.com/search?q={q}",
|
||||
custom: "",
|
||||
};
|
||||
|
||||
const ENGINE_LABELS: Record<SearchEngine, string> = {
|
||||
google: "Google",
|
||||
duckduckgo: "DuckDuckGo",
|
||||
bing: "Bing",
|
||||
custom: "Custom",
|
||||
};
|
||||
|
||||
function buildUrl(
|
||||
engine: SearchEngine,
|
||||
customUrl: string | undefined,
|
||||
query: string,
|
||||
): string {
|
||||
const template =
|
||||
engine === "custom" ? (customUrl ?? "") : ENGINE_URLS[engine];
|
||||
return template.replace("{q}", encodeURIComponent(query));
|
||||
}
|
||||
|
||||
function SearchBarWidget({
|
||||
widget,
|
||||
config,
|
||||
isReadOnly,
|
||||
}: WidgetComponentProps<SearchBarConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { engine, customUrl, placeholder, openInNewTab } = config;
|
||||
const [query, setQuery] = useState("");
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!query.trim()) return;
|
||||
const url = buildUrl(engine, customUrl, query.trim());
|
||||
if (!url) return;
|
||||
if (openInNewTab) window.open(url, "_blank", "noopener,noreferrer");
|
||||
else window.location.href = url;
|
||||
setQuery("");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle title={widget.title} icon={<Search size={11} />} />
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className="flex items-center gap-1.5 flex-1 px-2"
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Search size={12} className="text-muted-foreground shrink-0" />
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="search"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={
|
||||
placeholder ||
|
||||
`${t("homepage.searchPlaceholder")} ${ENGINE_LABELS[engine]}...`
|
||||
}
|
||||
disabled={isReadOnly}
|
||||
className="flex-1 bg-transparent text-xs text-foreground placeholder:text-muted-foreground/60 outline-none border-none min-w-0"
|
||||
/>
|
||||
{query.trim() && (
|
||||
<button
|
||||
type="submit"
|
||||
className="shrink-0 text-[10px] font-medium text-accent-brand hover:opacity-80 transition-opacity"
|
||||
>
|
||||
{t("homepage.searchGo")}
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<SearchBarConfig>({
|
||||
id: "search_bar",
|
||||
name: "Search Bar",
|
||||
description: "Quick search with Google, DuckDuckGo, Bing, or a custom engine",
|
||||
category: "info",
|
||||
icon: <Search size={14} />,
|
||||
defaultConfig: { engine: "google", openInNewTab: true },
|
||||
defaultSize: { w: GRID_SIZE * 12, h: GRID_SIZE * 3 },
|
||||
minSize: { w: GRID_SIZE * 6, h: GRID_SIZE * 2 },
|
||||
component: SearchBarWidget,
|
||||
});
|
||||
|
||||
export { SearchBarWidget };
|
||||
@@ -0,0 +1,129 @@
|
||||
import { useState } from "react";
|
||||
import { SearchCode } from "lucide-react";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type {
|
||||
SearchLinksConfig,
|
||||
SearchLinkShortcut,
|
||||
WidgetComponentProps,
|
||||
} from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
|
||||
function SearchLinksWidget({
|
||||
widget,
|
||||
config,
|
||||
isReadOnly,
|
||||
}: WidgetComponentProps<SearchLinksConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { shortcuts } = config;
|
||||
const [activeIdx, setActiveIdx] = useState<number | null>(null);
|
||||
const [query, setQuery] = useState("");
|
||||
|
||||
const handleOpen = (shortcut: SearchLinkShortcut) => {
|
||||
if (!query.trim()) return;
|
||||
const url = shortcut.queryTemplate.replace(
|
||||
"{q}",
|
||||
encodeURIComponent(query.trim()),
|
||||
);
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
setQuery("");
|
||||
setActiveIdx(null);
|
||||
};
|
||||
|
||||
const handleButtonClick = (i: number) => {
|
||||
if (isReadOnly) return;
|
||||
if (activeIdx === i) {
|
||||
setActiveIdx(null);
|
||||
setQuery("");
|
||||
} else {
|
||||
setActiveIdx(i);
|
||||
setQuery("");
|
||||
}
|
||||
};
|
||||
|
||||
if (shortcuts.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("homepage.noSearchShortcuts")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle title={widget.title} icon={<SearchCode size={11} />} />
|
||||
<div className="flex flex-col flex-1 p-2 gap-1.5 overflow-auto">
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{shortcuts.map((s, i) => {
|
||||
const accent =
|
||||
s.accentColor ||
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--accent-brand")
|
||||
.trim() ||
|
||||
"#f59145";
|
||||
const isActive = activeIdx === i;
|
||||
return (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => handleButtonClick(i)}
|
||||
className="flex items-center gap-1 px-2 py-1 text-[10px] font-medium border transition-colors"
|
||||
style={
|
||||
isActive
|
||||
? { background: accent, borderColor: accent, color: "#fff" }
|
||||
: {
|
||||
borderColor: `${accent}50`,
|
||||
color: "var(--text-primary, currentColor)",
|
||||
}
|
||||
}
|
||||
>
|
||||
{s.icon && <span className="text-xs">{s.icon}</span>}
|
||||
{s.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{activeIdx !== null && (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
handleOpen(shortcuts[activeIdx]);
|
||||
}}
|
||||
className="flex items-center gap-1.5 border border-border/60 px-2 py-1"
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<input
|
||||
autoFocus
|
||||
type="text"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={t("homepage.searchQueryPlaceholder")}
|
||||
className="flex-1 bg-transparent text-[10px] text-foreground placeholder:text-muted-foreground/60 outline-none border-none"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="text-[9px] font-medium text-accent-brand hover:opacity-80"
|
||||
>
|
||||
{t("homepage.searchGo")}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<SearchLinksConfig>({
|
||||
id: "search_links",
|
||||
name: "Search Shortcuts",
|
||||
description: "Quick buttons to search different engines",
|
||||
category: "links",
|
||||
icon: <SearchCode size={14} />,
|
||||
defaultConfig: { shortcuts: [] },
|
||||
defaultSize: { w: GRID_SIZE * 10, h: GRID_SIZE * 7 },
|
||||
minSize: { w: GRID_SIZE * 4, h: GRID_SIZE * 3 },
|
||||
component: SearchLinksWidget,
|
||||
});
|
||||
|
||||
export { SearchLinksWidget };
|
||||
@@ -0,0 +1,162 @@
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { useRef, useState, useEffect } from "react";
|
||||
import { Grid3x3, ExternalLink } from "lucide-react";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type {
|
||||
ServiceGridConfig,
|
||||
ServiceGridItem,
|
||||
WidgetComponentProps,
|
||||
} from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
|
||||
function getAccentColor(): string {
|
||||
return (
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--accent-brand")
|
||||
.trim() || "#f59145"
|
||||
);
|
||||
}
|
||||
|
||||
function getFaviconUrl(url: string): string {
|
||||
try {
|
||||
const domain = new URL(url).hostname;
|
||||
return `https://www.google.com/s2/favicons?sz=64&domain_url=${encodeURIComponent(domain)}`;
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
const ICON_SIZE_MAP = { sm: 16, md: 24, lg: 32 };
|
||||
|
||||
function ServiceTile({
|
||||
item,
|
||||
iconSize,
|
||||
showLabels,
|
||||
isReadOnly,
|
||||
}: {
|
||||
item: ServiceGridItem;
|
||||
iconSize: number;
|
||||
showLabels: boolean;
|
||||
isReadOnly?: boolean;
|
||||
}) {
|
||||
const [imgFailed, setImgFailed] = useState(false);
|
||||
const mouseDownRef = useRef<{ x: number; y: number } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setImgFailed(false);
|
||||
}, [item.imageUrl, item.url]);
|
||||
|
||||
const accent = item.accentColor || getAccentColor();
|
||||
const imageUrl = item.imageUrl || (item.url ? getFaviconUrl(item.url) : null);
|
||||
|
||||
const content = (
|
||||
<div
|
||||
className="group flex flex-col items-center justify-center gap-1 p-1.5 w-full h-full border border-border/40 border-t-2 hover:bg-muted/40 transition-colors overflow-hidden"
|
||||
style={{ borderTopColor: `${accent}60`, background: "var(--color-card)" }}
|
||||
>
|
||||
{imageUrl && !imgFailed ? (
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt=""
|
||||
style={{ width: iconSize, height: iconSize }}
|
||||
className="object-contain shrink-0"
|
||||
onError={() => setImgFailed(true)}
|
||||
/>
|
||||
) : (
|
||||
<ExternalLink
|
||||
size={iconSize * 0.6}
|
||||
className="text-accent-brand shrink-0"
|
||||
/>
|
||||
)}
|
||||
{showLabels && (
|
||||
<span className="text-[9px] font-medium text-foreground text-center truncate w-full leading-tight">
|
||||
{item.label || item.url}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
if (isReadOnly || !item.url) return content;
|
||||
|
||||
return (
|
||||
<a
|
||||
href={item.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block w-full h-full no-underline"
|
||||
onMouseDown={(e) => {
|
||||
mouseDownRef.current = { x: e.clientX, y: e.clientY };
|
||||
}}
|
||||
onClick={(e) => {
|
||||
const s = mouseDownRef.current;
|
||||
if (
|
||||
s &&
|
||||
(Math.abs(e.clientX - s.x) > 4 || Math.abs(e.clientY - s.y) > 4)
|
||||
)
|
||||
e.preventDefault();
|
||||
mouseDownRef.current = null;
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
function ServiceGridWidget({
|
||||
widget,
|
||||
config,
|
||||
isReadOnly,
|
||||
}: WidgetComponentProps<ServiceGridConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { services, columns, showLabels, iconSize } = config;
|
||||
|
||||
if (services.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("homepage.noServices")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const gridCols =
|
||||
columns === 2
|
||||
? "grid-cols-2"
|
||||
: columns === 3
|
||||
? "grid-cols-3"
|
||||
: "grid-cols-4";
|
||||
const size = ICON_SIZE_MAP[iconSize];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle title={widget.title} icon={<Grid3x3 size={11} />} />
|
||||
<div
|
||||
className={`grid ${gridCols} gap-1.5 p-1.5 flex-1 overflow-auto content-start`}
|
||||
>
|
||||
{services.map((s, i) => (
|
||||
<ServiceTile
|
||||
key={i}
|
||||
item={s}
|
||||
iconSize={size}
|
||||
showLabels={showLabels}
|
||||
isReadOnly={isReadOnly}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<ServiceGridConfig>({
|
||||
id: "service_grid",
|
||||
name: "Service Grid",
|
||||
description: "A grid of service tiles with icons and links",
|
||||
category: "links",
|
||||
icon: <Grid3x3 size={14} />,
|
||||
defaultConfig: { services: [], columns: 3, showLabels: true, iconSize: "md" },
|
||||
defaultSize: { w: GRID_SIZE * 14, h: GRID_SIZE * 10 },
|
||||
minSize: { w: GRID_SIZE * 4, h: GRID_SIZE * 4 },
|
||||
component: ServiceGridWidget,
|
||||
});
|
||||
|
||||
export { ServiceGridWidget };
|
||||
@@ -0,0 +1,128 @@
|
||||
import { useRef, useState, useEffect } from "react";
|
||||
import { ExternalLink } from "lucide-react";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { ServiceLinkConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
|
||||
function getAccentColor(): string {
|
||||
return (
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--accent-brand")
|
||||
.trim() || "#f59145"
|
||||
);
|
||||
}
|
||||
|
||||
function getFaviconUrl(url: string): string {
|
||||
try {
|
||||
const domain = new URL(url).hostname;
|
||||
return `https://www.google.com/s2/favicons?sz=64&domain_url=${encodeURIComponent(domain)}`;
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function ServiceLinkWidget({
|
||||
widget,
|
||||
config,
|
||||
isReadOnly,
|
||||
}: WidgetComponentProps<ServiceLinkConfig>) {
|
||||
const { url, description, accentColor, imageUrl, showImage = true } = config;
|
||||
const resolvedImageUrl = showImage
|
||||
? imageUrl || (url ? getFaviconUrl(url) : null)
|
||||
: null;
|
||||
const mouseDownPosRef = useRef<{ x: number; y: number } | null>(null);
|
||||
const [imgFailed, setImgFailed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setImgFailed(false);
|
||||
}, [resolvedImageUrl]);
|
||||
|
||||
let displayLabel = widget.title;
|
||||
if (!displayLabel && url) {
|
||||
try {
|
||||
displayLabel = new URL(url).hostname;
|
||||
} catch {
|
||||
displayLabel = url;
|
||||
}
|
||||
}
|
||||
|
||||
const accentBorder = accentColor || getAccentColor();
|
||||
const imgSize = Math.min(48, widget.h * 0.3);
|
||||
|
||||
const content = (
|
||||
<div
|
||||
className="group flex flex-col items-center justify-center gap-1.5 w-full h-full p-2 select-none border-t-2 relative overflow-hidden"
|
||||
style={{ borderTopColor: `${accentBorder}80` }}
|
||||
>
|
||||
{resolvedImageUrl && !imgFailed ? (
|
||||
<img
|
||||
src={resolvedImageUrl}
|
||||
alt=""
|
||||
className="shrink-0 transition-transform duration-150 group-hover:scale-110 object-contain"
|
||||
style={{ width: imgSize, height: imgSize }}
|
||||
onError={() => setImgFailed(true)}
|
||||
/>
|
||||
) : showImage ? (
|
||||
<ExternalLink
|
||||
className="shrink-0 text-accent-brand transition-transform duration-150 group-hover:scale-110"
|
||||
style={{ width: imgSize * 0.75, height: imgSize * 0.75 }}
|
||||
/>
|
||||
) : null}
|
||||
<span className="text-xs font-semibold text-foreground text-center leading-tight w-full truncate px-1">
|
||||
{displayLabel}
|
||||
</span>
|
||||
{description && (
|
||||
<span className="text-[10px] text-muted-foreground text-center w-full truncate px-1">
|
||||
{description}
|
||||
</span>
|
||||
)}
|
||||
{!isReadOnly && url && (
|
||||
<ExternalLink
|
||||
size={10}
|
||||
className="absolute top-1.5 right-1.5 text-muted-foreground/0 group-hover:text-muted-foreground/60 transition-colors duration-150"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
if (isReadOnly || !url) return content;
|
||||
|
||||
return (
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block w-full h-full no-underline"
|
||||
onMouseDown={(e) => {
|
||||
mouseDownPosRef.current = { x: e.clientX, y: e.clientY };
|
||||
}}
|
||||
onClick={(e) => {
|
||||
const start = mouseDownPosRef.current;
|
||||
if (
|
||||
start &&
|
||||
(Math.abs(e.clientX - start.x) > 4 ||
|
||||
Math.abs(e.clientY - start.y) > 4)
|
||||
) {
|
||||
e.preventDefault();
|
||||
}
|
||||
mouseDownPosRef.current = null;
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<ServiceLinkConfig>({
|
||||
id: "service_link",
|
||||
name: "Service Link",
|
||||
description: "A clickable tile linking to a service URL",
|
||||
category: "links",
|
||||
icon: <ExternalLink size={14} />,
|
||||
defaultConfig: { url: "", description: "", showImage: true },
|
||||
defaultSize: { w: GRID_SIZE * 8, h: GRID_SIZE * 6 },
|
||||
minSize: { w: GRID_SIZE * 2, h: GRID_SIZE * 2 },
|
||||
component: ServiceLinkWidget,
|
||||
});
|
||||
|
||||
export { ServiceLinkWidget };
|
||||
@@ -0,0 +1,141 @@
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
import { Terminal as TerminalIcon, Play } from "lucide-react";
|
||||
import {
|
||||
useTranslation,
|
||||
useHost,
|
||||
type TabHandle as TerminalHandle,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
|
||||
import { PluginComponent, WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { SshTerminalConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
|
||||
function SshTerminalWidget({
|
||||
widget,
|
||||
config,
|
||||
}: WidgetComponentProps<SshTerminalConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const host = useHost(config.hostId || undefined);
|
||||
const [started, setStarted] = useState(false);
|
||||
const terminalRef = useRef<TerminalHandle>(null);
|
||||
const terminalWrapRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const el = terminalWrapRef.current;
|
||||
if (!el || !started) return;
|
||||
const stopWheel = (e: WheelEvent) => e.stopPropagation();
|
||||
el.addEventListener("wheel", stopWheel, { capture: true, passive: true });
|
||||
return () => el.removeEventListener("wheel", stopWheel, { capture: true });
|
||||
}, [started]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!started) return;
|
||||
const blurOnOutsideClick = (e: MouseEvent) => {
|
||||
if (!terminalWrapRef.current?.contains(e.target as Node)) {
|
||||
const textarea = terminalWrapRef.current?.querySelector("textarea");
|
||||
textarea?.blur();
|
||||
}
|
||||
};
|
||||
document.addEventListener("mousedown", blurOnOutsideClick, {
|
||||
capture: true,
|
||||
});
|
||||
return () =>
|
||||
document.removeEventListener("mousedown", blurOnOutsideClick, {
|
||||
capture: true,
|
||||
});
|
||||
}, [started]);
|
||||
|
||||
// auto-connect after the host loads if configured
|
||||
useEffect(() => {
|
||||
if (host && config.autoConnect) setStarted(true);
|
||||
}, [host, config.autoConnect]);
|
||||
|
||||
if (!config.hostId) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center w-full h-full gap-2 text-muted-foreground/60">
|
||||
<TerminalIcon size={20} />
|
||||
<span className="text-xs">{t("homepage.sshTerminalNoHost")}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!host) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground/60">
|
||||
{t("homepage.sshTerminalNoHost")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const hostConfig = {
|
||||
id: Number(host.id),
|
||||
ip: host.ip,
|
||||
port: (host.sshPort as number | undefined) ?? host.port ?? 22,
|
||||
username: host.username,
|
||||
authType: host.authType,
|
||||
};
|
||||
|
||||
if (!started) {
|
||||
return (
|
||||
<div
|
||||
className="flex flex-col items-center justify-center w-full h-full gap-3"
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1">
|
||||
<TerminalIcon size={16} className="text-muted-foreground/60" />
|
||||
<span className="text-xs font-medium text-foreground">
|
||||
{host.name || host.ip}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground/50">
|
||||
{host.username}@{host.ip}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 bg-accent-brand text-white text-xs font-medium hover:opacity-90 transition-opacity"
|
||||
onClick={() => setStarted(true)}
|
||||
>
|
||||
<Play size={11} />
|
||||
{t("homepage.sshTerminalConnect")}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={terminalWrapRef}
|
||||
className="flex flex-col w-full h-full overflow-hidden"
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<WidgetTitle title={widget.title} icon={<TerminalIcon size={11} />} />
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<PluginComponent
|
||||
id="terminal.view"
|
||||
handleRef={terminalRef}
|
||||
hostConfig={hostConfig}
|
||||
isVisible={true}
|
||||
showTitle={false}
|
||||
splitScreen={false}
|
||||
disableAutoFocus={true}
|
||||
onClose={() => setStarted(false)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<SshTerminalConfig>({
|
||||
id: "ssh_terminal",
|
||||
name: "SSH Terminal",
|
||||
description: "An inline SSH terminal connected to a configured host",
|
||||
category: "system",
|
||||
icon: <TerminalIcon size={14} />,
|
||||
defaultConfig: {
|
||||
hostId: 0,
|
||||
autoConnect: false,
|
||||
},
|
||||
defaultSize: { w: GRID_SIZE * 16, h: GRID_SIZE * 12 },
|
||||
minSize: { w: GRID_SIZE * 8, h: GRID_SIZE * 6 },
|
||||
component: SshTerminalWidget,
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Server } from "lucide-react";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { SystemOverviewConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import {
|
||||
WidgetTitle,
|
||||
getDatabaseHealth,
|
||||
getUptime,
|
||||
getVersionInfo,
|
||||
runVisibleInterval,
|
||||
} from "@termix/plugin-sdk/ui";
|
||||
|
||||
interface InfoRowProps {
|
||||
label: string;
|
||||
value: string | null | undefined;
|
||||
valueColor?: string;
|
||||
}
|
||||
|
||||
function InfoRow({ label, value, valueColor }: InfoRowProps) {
|
||||
if (!value) return null;
|
||||
return (
|
||||
<div className="flex justify-between text-[10px] gap-2">
|
||||
<span className="text-muted-foreground shrink-0">{label}</span>
|
||||
<span
|
||||
className="text-foreground truncate text-right font-medium"
|
||||
style={valueColor ? { color: valueColor } : undefined}
|
||||
>
|
||||
{value}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SystemOverviewWidget({
|
||||
widget,
|
||||
config,
|
||||
}: WidgetComponentProps<SystemOverviewConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { showVersion, showDbHealth, showUptime } = config;
|
||||
const [version, setVersion] = useState<string | null>(null);
|
||||
const [updateAvailable, setUpdateAvailable] = useState(false);
|
||||
const [dbStatus, setDbStatus] = useState<string | null>(null);
|
||||
const [uptimeFormatted, setUptimeFormatted] = useState<string | null>(null);
|
||||
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
if (showVersion) {
|
||||
// `checkRemote=false` makes /version return early with just
|
||||
// {localVersion, status: "update_check_disabled"}, and the response has
|
||||
// no `updateAvailable` field in either mode -- so the previous read was
|
||||
// false twice over. `status` is what the endpoint actually answers with,
|
||||
// and what the dashboard and profile badges already read.
|
||||
const info = await getVersionInfo();
|
||||
setVersion((info?.localVersion as string) ?? null);
|
||||
setUpdateAvailable(info?.status === "requires_update");
|
||||
}
|
||||
if (showDbHealth) {
|
||||
const health = await getDatabaseHealth();
|
||||
setDbStatus((health?.status as string) ?? "unknown");
|
||||
}
|
||||
if (showUptime) {
|
||||
const up = await getUptime();
|
||||
setUptimeFormatted(up.formatted);
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
return runVisibleInterval(() => {
|
||||
void fetchData();
|
||||
}, 300_000);
|
||||
}, [showVersion, showDbHealth, showUptime]);
|
||||
|
||||
const accent =
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--accent-brand")
|
||||
.trim() || "#f59145";
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle
|
||||
title={widget.title}
|
||||
icon={<Server size={11} />}
|
||||
fallback="Termix"
|
||||
/>
|
||||
<div className="flex flex-col gap-1.5 p-3 flex-1 overflow-auto">
|
||||
{showVersion && (
|
||||
<InfoRow
|
||||
label={t("homepage.overviewVersion")}
|
||||
value={version ?? t("common.loading")}
|
||||
valueColor={updateAvailable ? "#f97316" : undefined}
|
||||
/>
|
||||
)}
|
||||
{showVersion && updateAvailable && (
|
||||
<InfoRow
|
||||
label={t("homepage.overviewUpdateLabel")}
|
||||
value={t("homepage.overviewUpdateAvailable")}
|
||||
valueColor="#f97316"
|
||||
/>
|
||||
)}
|
||||
{showDbHealth && (
|
||||
<InfoRow
|
||||
label={t("homepage.overviewDatabase")}
|
||||
value={dbStatus ? dbStatus.toUpperCase() : t("common.loading")}
|
||||
valueColor={
|
||||
dbStatus === "ok" || dbStatus === "healthy"
|
||||
? accent
|
||||
: dbStatus
|
||||
? "#ef4444"
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{showUptime && (
|
||||
<InfoRow
|
||||
label={t("homepage.overviewUptime")}
|
||||
value={uptimeFormatted ?? t("common.loading")}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<SystemOverviewConfig>({
|
||||
id: "system_overview",
|
||||
name: "System Overview",
|
||||
description: "Termix version, database health, and uptime at a glance",
|
||||
category: "system",
|
||||
icon: <Server size={14} />,
|
||||
defaultConfig: { showVersion: true, showDbHealth: true, showUptime: true },
|
||||
defaultSize: { w: GRID_SIZE * 10, h: GRID_SIZE * 6 },
|
||||
minSize: { w: GRID_SIZE * 4, h: GRID_SIZE * 3 },
|
||||
component: SystemOverviewWidget,
|
||||
});
|
||||
|
||||
export { SystemOverviewWidget };
|
||||
@@ -0,0 +1,143 @@
|
||||
import { useEffect, useState, useRef } from "react";
|
||||
import { Clock4 } from "lucide-react";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { TermixUptimeConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
import {
|
||||
WidgetTitle,
|
||||
getUptime,
|
||||
runVisibleInterval,
|
||||
} from "@termix/plugin-sdk/ui";
|
||||
|
||||
function formatUptime(seconds: number): {
|
||||
days: number;
|
||||
hours: number;
|
||||
minutes: number;
|
||||
secs: number;
|
||||
} {
|
||||
const days = Math.floor(seconds / 86400);
|
||||
const hours = Math.floor((seconds % 86400) / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
const secs = Math.floor(seconds % 60);
|
||||
return { days, hours, minutes, secs };
|
||||
}
|
||||
|
||||
function TermixUptimeWidget({
|
||||
widget,
|
||||
config,
|
||||
}: WidgetComponentProps<TermixUptimeConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { showDetailed } = config;
|
||||
const [seconds, setSeconds] = useState<number | null>(null);
|
||||
const [error, setError] = useState(false);
|
||||
const baseRef = useRef<number | null>(null);
|
||||
const startRef = useRef<number>(Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
getUptime()
|
||||
.then((info) => {
|
||||
baseRef.current = info.uptimeSeconds;
|
||||
startRef.current = Date.now();
|
||||
setSeconds(info.uptimeSeconds);
|
||||
})
|
||||
.catch(() => setError(true));
|
||||
|
||||
return runVisibleInterval(() => {
|
||||
if (baseRef.current !== null) {
|
||||
const elapsed = (Date.now() - startRef.current) / 1000;
|
||||
setSeconds(Math.floor(baseRef.current + elapsed));
|
||||
}
|
||||
}, 1000);
|
||||
}, []);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("homepage.uptimeUnavailable")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (seconds === null) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground">
|
||||
{t("common.loading")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const { days, hours, minutes, secs } = formatUptime(seconds);
|
||||
const accent =
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--accent-brand")
|
||||
.trim() || "#f59145";
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle title={widget.title} icon={<Clock4 size={11} />} />
|
||||
<div className="flex flex-col items-center justify-center flex-1 gap-1 p-2">
|
||||
<Clock4 size={14} className="text-muted-foreground" />
|
||||
<div className="flex items-baseline gap-1 flex-wrap justify-center">
|
||||
{days > 0 && (
|
||||
<span
|
||||
className="text-xl font-bold tabular-nums"
|
||||
style={{ color: accent }}
|
||||
>
|
||||
{days}
|
||||
<span className="text-xs font-normal text-muted-foreground ml-0.5">
|
||||
d
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
<span
|
||||
className="text-xl font-bold tabular-nums"
|
||||
style={{ color: accent }}
|
||||
>
|
||||
{String(hours).padStart(2, "0")}
|
||||
<span className="text-xs font-normal text-muted-foreground ml-0.5">
|
||||
h
|
||||
</span>
|
||||
</span>
|
||||
<span
|
||||
className="text-xl font-bold tabular-nums"
|
||||
style={{ color: accent }}
|
||||
>
|
||||
{String(minutes).padStart(2, "0")}
|
||||
<span className="text-xs font-normal text-muted-foreground ml-0.5">
|
||||
m
|
||||
</span>
|
||||
</span>
|
||||
{showDetailed && (
|
||||
<span
|
||||
className="text-xl font-bold tabular-nums"
|
||||
style={{ color: accent }}
|
||||
>
|
||||
{String(secs).padStart(2, "0")}
|
||||
<span className="text-xs font-normal text-muted-foreground ml-0.5">
|
||||
s
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{t("homepage.uptimeLabel")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<TermixUptimeConfig>({
|
||||
id: "termix_uptime",
|
||||
name: "Termix Uptime",
|
||||
description: "Shows how long the Termix server has been running",
|
||||
category: "system",
|
||||
icon: <Clock4 size={14} />,
|
||||
defaultConfig: { showDetailed: false },
|
||||
defaultSize: { w: GRID_SIZE * 8, h: GRID_SIZE * 4 },
|
||||
minSize: { w: GRID_SIZE * 3, h: GRID_SIZE * 2 },
|
||||
component: TermixUptimeWidget,
|
||||
});
|
||||
|
||||
export { TermixUptimeWidget };
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { Type } from "lucide-react";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { TextBannerConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
|
||||
const FONT_SIZE_MAP = {
|
||||
sm: "text-xs",
|
||||
md: "text-sm",
|
||||
lg: "text-base",
|
||||
xl: "text-xl",
|
||||
};
|
||||
|
||||
const FONT_WEIGHT_MAP = {
|
||||
normal: "font-normal",
|
||||
semibold: "font-semibold",
|
||||
bold: "font-bold",
|
||||
};
|
||||
|
||||
const TEXT_ALIGN_MAP = {
|
||||
left: "text-left",
|
||||
center: "text-center",
|
||||
right: "text-right",
|
||||
};
|
||||
|
||||
function TextBannerWidget({ config }: WidgetComponentProps<TextBannerConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { text, fontSize, textAlign, fontWeight, backgroundColor } = config;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`flex items-center w-full h-full px-3 py-2 overflow-hidden ${FONT_SIZE_MAP[fontSize]} ${FONT_WEIGHT_MAP[fontWeight]} ${TEXT_ALIGN_MAP[textAlign]}`}
|
||||
style={backgroundColor ? { background: backgroundColor } : undefined}
|
||||
>
|
||||
<span className="whitespace-pre-wrap break-words w-full text-foreground leading-tight">
|
||||
{text || t("homepage.bannerTextPlaceholder")}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<TextBannerConfig>({
|
||||
id: "text_banner",
|
||||
name: "Text Banner",
|
||||
description: "A styled text label for sections and headings",
|
||||
category: "info",
|
||||
icon: <Type size={14} />,
|
||||
defaultConfig: {
|
||||
text: "",
|
||||
fontSize: "lg",
|
||||
textAlign: "center",
|
||||
fontWeight: "semibold",
|
||||
},
|
||||
defaultSize: { w: GRID_SIZE * 14, h: GRID_SIZE * 3 },
|
||||
minSize: { w: GRID_SIZE * 3, h: GRID_SIZE * 2 },
|
||||
component: TextBannerWidget,
|
||||
});
|
||||
|
||||
export { TextBannerWidget };
|
||||
@@ -0,0 +1,200 @@
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
Cloud,
|
||||
CloudRain,
|
||||
Sun,
|
||||
CloudSnow,
|
||||
Wind,
|
||||
Thermometer,
|
||||
} from "lucide-react";
|
||||
import { registerWidget } from "./WidgetRegistry";
|
||||
import type { WeatherConfig, WidgetComponentProps } from "../types.js";
|
||||
import { GRID_SIZE } from "../types.js";
|
||||
|
||||
import { WidgetTitle, runVisibleInterval } from "@termix/plugin-sdk/ui";
|
||||
|
||||
interface WttrCurrent {
|
||||
temp_C: string;
|
||||
FeelsLikeC: string;
|
||||
weatherDesc: { value: string }[];
|
||||
weatherCode: string;
|
||||
}
|
||||
|
||||
interface WttrDay {
|
||||
mintempC: string;
|
||||
maxtempC: string;
|
||||
hourly: { weatherDesc: { value: string }[]; weatherCode: string }[];
|
||||
}
|
||||
|
||||
interface WttrResponse {
|
||||
nearest_area: {
|
||||
areaName: { value: string }[];
|
||||
country: { value: string }[];
|
||||
}[];
|
||||
current_condition: WttrCurrent[];
|
||||
weather: WttrDay[];
|
||||
}
|
||||
|
||||
function weatherIcon(code: string, size = 20) {
|
||||
const n = Number(code);
|
||||
if (n === 113) return <Sun size={size} className="text-yellow-400" />;
|
||||
if (n <= 119) return <Cloud size={size} className="text-gray-400" />;
|
||||
if (n <= 143) return <Cloud size={size} className="text-gray-400" />;
|
||||
if (n <= 266) return <CloudRain size={size} className="text-blue-400" />;
|
||||
if (n <= 335) return <CloudSnow size={size} className="text-blue-200" />;
|
||||
if (n <= 389) return <CloudRain size={size} className="text-blue-500" />;
|
||||
return <Wind size={size} className="text-muted-foreground" />;
|
||||
}
|
||||
|
||||
function celsiusToF(c: number) {
|
||||
return Math.round((c * 9) / 5 + 32);
|
||||
}
|
||||
|
||||
function WeatherWidget({
|
||||
widget,
|
||||
config,
|
||||
}: WidgetComponentProps<WeatherConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { location, unit, showForecast } = config;
|
||||
const [data, setData] = useState<WttrResponse | null>(null);
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!location) return;
|
||||
let cancelled = false;
|
||||
const fetchWeather = async () => {
|
||||
try {
|
||||
setError(false);
|
||||
const res = await fetch(
|
||||
`https://wttr.in/${encodeURIComponent(location)}?format=j1`,
|
||||
);
|
||||
if (!res.ok) throw new Error("bad response");
|
||||
const json: WttrResponse = await res.json();
|
||||
if (!cancelled) setData(json);
|
||||
} catch {
|
||||
if (!cancelled) setError(true);
|
||||
}
|
||||
};
|
||||
fetchWeather();
|
||||
const stop = runVisibleInterval(
|
||||
() => {
|
||||
void fetchWeather();
|
||||
},
|
||||
10 * 60 * 1000,
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
stop();
|
||||
};
|
||||
}, [location]);
|
||||
|
||||
if (!location) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground/60 p-3 text-center">
|
||||
{t("homepage.configureLocation")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-destructive/70 p-3 text-center">
|
||||
Could not load weather for "{location}"
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return (
|
||||
<div className="flex items-center justify-center w-full h-full text-xs text-muted-foreground/50">
|
||||
Loading...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const current = data.current_condition[0];
|
||||
const area = data.nearest_area[0];
|
||||
const cityName = area?.areaName[0]?.value ?? location;
|
||||
const tempC = Number(current.temp_C);
|
||||
const feelsC = Number(current.FeelsLikeC);
|
||||
const displayTemp = unit === "F" ? `${celsiusToF(tempC)}°F` : `${tempC}°C`;
|
||||
const displayFeels = unit === "F" ? `${celsiusToF(feelsC)}°F` : `${feelsC}°C`;
|
||||
const desc = current.weatherDesc[0]?.value ?? "";
|
||||
const code = current.weatherCode;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle title={widget.title} icon={<Sun size={11} />} />
|
||||
<div className="flex flex-col flex-1 p-3 gap-2 overflow-auto">
|
||||
{/* Current conditions */}
|
||||
<div className="flex items-center gap-3 flex-1 min-h-0">
|
||||
<div className="shrink-0">{weatherIcon(code, 32)}</div>
|
||||
<div className="flex flex-col min-w-0">
|
||||
<span className="text-2xl font-bold text-foreground leading-none">
|
||||
{displayTemp}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground truncate">
|
||||
{desc}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground/70">
|
||||
Feels like {displayFeels}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Thermometer
|
||||
size={10}
|
||||
className="text-muted-foreground/60 shrink-0"
|
||||
/>
|
||||
<span className="text-[11px] font-semibold text-foreground truncate">
|
||||
{cityName}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 3-day forecast */}
|
||||
{showForecast && data.weather.length >= 3 && (
|
||||
<div className="flex gap-1 border-t border-border pt-2 mt-auto shrink-0">
|
||||
{data.weather.slice(0, 3).map((day, i) => {
|
||||
const hourly = day.hourly[4] ?? day.hourly[0];
|
||||
const minC = Number(day.mintempC);
|
||||
const maxC = Number(day.maxtempC);
|
||||
const lo = unit === "F" ? `${celsiusToF(minC)}°` : `${minC}°`;
|
||||
const hi = unit === "F" ? `${celsiusToF(maxC)}°` : `${maxC}°`;
|
||||
const dayLabel = i === 0 ? "Today" : i === 1 ? "Tmrw" : "+2";
|
||||
return (
|
||||
<div
|
||||
key={i}
|
||||
className="flex-1 flex flex-col items-center gap-0.5"
|
||||
>
|
||||
<span className="text-[9px] text-muted-foreground/70">
|
||||
{dayLabel}
|
||||
</span>
|
||||
{weatherIcon(hourly?.weatherCode ?? "113", 12)}
|
||||
<span className="text-[9px] text-foreground">{hi}</span>
|
||||
<span className="text-[9px] text-muted-foreground/60">
|
||||
{lo}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
registerWidget<WeatherConfig>({
|
||||
id: "weather",
|
||||
name: "Weather",
|
||||
description: "Live weather for any location",
|
||||
category: "info",
|
||||
icon: <Sun size={14} />,
|
||||
defaultConfig: { location: "", unit: "C", showForecast: true },
|
||||
defaultSize: { w: GRID_SIZE * 10, h: GRID_SIZE * 7 },
|
||||
minSize: { w: GRID_SIZE * 2, h: GRID_SIZE * 2 },
|
||||
component: WeatherWidget,
|
||||
});
|
||||
|
||||
export { WeatherWidget };
|
||||
@@ -0,0 +1,71 @@
|
||||
import {
|
||||
getExtension,
|
||||
useExtensions,
|
||||
type ExtensionContribution,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import { useMemo } from "react";
|
||||
import type { WidgetTypeDefinition, WidgetTypeId } from "../types.js";
|
||||
|
||||
/**
|
||||
* Other plugins add widgets with app.registerExtension(WIDGET_POINT, ...),
|
||||
* putting the widget under components.view and its edit form under
|
||||
* components.editForm. Core only stores the list, so a plugin's widgets
|
||||
* stay registered while this plugin is off.
|
||||
*/
|
||||
export const WIDGET_POINT = "homepage.widgets";
|
||||
|
||||
/**
|
||||
* Each widget module calls this at import time (before activate(app) runs),
|
||||
* so the definitions are queued here and registered from activate.
|
||||
*/
|
||||
const queued: WidgetTypeDefinition[] = [];
|
||||
|
||||
export function registerWidget<C>(def: WidgetTypeDefinition<C>): void {
|
||||
queued.push(def as unknown as WidgetTypeDefinition);
|
||||
}
|
||||
|
||||
/** Called once from activate(app); drains the queue. */
|
||||
export function drainQueuedWidgets(): WidgetTypeDefinition[] {
|
||||
return queued.splice(0, queued.length);
|
||||
}
|
||||
|
||||
export function toExtension(def: WidgetTypeDefinition): ExtensionContribution {
|
||||
const { component, editFormComponent, ...rest } = def;
|
||||
return {
|
||||
...rest,
|
||||
components: editFormComponent
|
||||
? { view: component, editForm: editFormComponent }
|
||||
: { view: component },
|
||||
};
|
||||
}
|
||||
|
||||
function toDefinition(
|
||||
extension: ExtensionContribution | undefined,
|
||||
): WidgetTypeDefinition | undefined {
|
||||
const view = extension?.components?.view;
|
||||
if (!extension || !view) return undefined;
|
||||
const { components, ...rest } = extension;
|
||||
return {
|
||||
...(rest as unknown as WidgetTypeDefinition),
|
||||
component: view,
|
||||
editFormComponent: components?.editForm,
|
||||
labelComponent: components?.label,
|
||||
};
|
||||
}
|
||||
|
||||
export function getWidgetType(
|
||||
id: WidgetTypeId,
|
||||
): WidgetTypeDefinition | undefined {
|
||||
return toDefinition(getExtension(WIDGET_POINT, id));
|
||||
}
|
||||
|
||||
export function useWidgetTypes(): WidgetTypeDefinition[] {
|
||||
const extensions = useExtensions(WIDGET_POINT);
|
||||
return useMemo(
|
||||
() =>
|
||||
extensions
|
||||
.map(toDefinition)
|
||||
.filter((def): def is WidgetTypeDefinition => !!def),
|
||||
[extensions],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { useState } from "react";
|
||||
import { Pencil, Trash2, GripVertical } from "lucide-react";
|
||||
import type { CanvasWidget } from "../types.js";
|
||||
import { getWidgetType, useWidgetTypes } from "./WidgetRegistry";
|
||||
import { PluginViewPlaceholder } from "@termix/plugin-sdk/ui";
|
||||
|
||||
interface WidgetShellProps {
|
||||
widget: CanvasWidget;
|
||||
isLocked?: boolean;
|
||||
isReadOnly?: boolean;
|
||||
isDragging?: boolean;
|
||||
isResizing?: boolean;
|
||||
onStartDrag?: (e: React.MouseEvent, widget: CanvasWidget) => void;
|
||||
onStartResize?: (e: React.MouseEvent, widget: CanvasWidget) => void;
|
||||
onDelete?: (id: number) => void;
|
||||
onEdit?: (id: number) => void;
|
||||
onConfigUpdate?: (config: Record<string, unknown>) => void;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function WidgetShell({
|
||||
widget,
|
||||
isLocked,
|
||||
isReadOnly,
|
||||
isDragging,
|
||||
isResizing,
|
||||
onStartDrag,
|
||||
onStartResize,
|
||||
onDelete,
|
||||
onEdit,
|
||||
onConfigUpdate,
|
||||
children,
|
||||
}: WidgetShellProps) {
|
||||
const [hovered, setHovered] = useState(false);
|
||||
// A plugin widget appears once its plugin starts.
|
||||
useWidgetTypes();
|
||||
const typeDef = getWidgetType(widget.typeId);
|
||||
const showControls =
|
||||
hovered && !isLocked && !isReadOnly && !isDragging && !isResizing;
|
||||
|
||||
const WidgetComponent = typeDef?.component;
|
||||
|
||||
return (
|
||||
<div
|
||||
data-widget={widget.id}
|
||||
className={`absolute overflow-hidden select-none transition-shadow duration-150 ${
|
||||
hovered && !isLocked && !isReadOnly
|
||||
? "ring-1 ring-accent-brand/30 shadow-md"
|
||||
: "ring-1 ring-border/60"
|
||||
}`}
|
||||
style={{
|
||||
left: widget.x,
|
||||
top: widget.y,
|
||||
width: widget.w,
|
||||
height: widget.h,
|
||||
background: "var(--color-card)",
|
||||
opacity: isDragging ? 0.85 : 1,
|
||||
transform: isDragging ? "scale(1.02)" : undefined,
|
||||
boxShadow:
|
||||
isDragging || isResizing ? "0 8px 32px rgba(0,0,0,0.25)" : undefined,
|
||||
cursor:
|
||||
isLocked || isReadOnly ? "default" : isDragging ? "grabbing" : "grab",
|
||||
}}
|
||||
onWheel={(e) => {
|
||||
// Find the nearest scrollable ancestor within this widget
|
||||
let el = e.target as HTMLElement | null;
|
||||
while (el && el !== e.currentTarget) {
|
||||
const canScrollY = el.scrollHeight > el.clientHeight;
|
||||
const canScrollX = el.scrollWidth > el.clientWidth;
|
||||
if (canScrollY || canScrollX) {
|
||||
e.stopPropagation();
|
||||
break;
|
||||
}
|
||||
el = el.parentElement;
|
||||
}
|
||||
}}
|
||||
onMouseEnter={() => setHovered(true)}
|
||||
onMouseLeave={() => setHovered(false)}
|
||||
onMouseDown={
|
||||
!isLocked && !isReadOnly ? (e) => onStartDrag?.(e, widget) : undefined
|
||||
}
|
||||
>
|
||||
{/* Widget content */}
|
||||
{children ??
|
||||
(WidgetComponent ? (
|
||||
<WidgetComponent
|
||||
widget={widget}
|
||||
config={widget.config as Record<string, unknown>}
|
||||
isReadOnly={isReadOnly}
|
||||
onConfigUpdate={onConfigUpdate}
|
||||
/>
|
||||
) : (
|
||||
<PluginViewPlaceholder kind="card" viewId={widget.typeId} compact />
|
||||
))}
|
||||
|
||||
{/* Hover controls */}
|
||||
{showControls && (
|
||||
<>
|
||||
{/* Top-right action bar */}
|
||||
<div
|
||||
className="absolute top-1 right-1 flex items-center gap-0.5 z-10"
|
||||
style={{ opacity: hovered ? 1 : 0, transition: "opacity 0.1s" }}
|
||||
>
|
||||
<div className="p-1 text-muted-foreground/40 cursor-grab">
|
||||
<GripVertical size={10} />
|
||||
</div>
|
||||
<button
|
||||
className="p-1 bg-background/90 hover:bg-background border border-border text-muted-foreground hover:text-foreground transition-colors"
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onEdit?.(widget.id);
|
||||
}}
|
||||
title="Edit"
|
||||
>
|
||||
<Pencil size={10} />
|
||||
</button>
|
||||
<button
|
||||
className="p-1 bg-background/90 hover:bg-destructive border border-border text-muted-foreground hover:text-destructive-foreground transition-colors"
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onDelete?.(widget.id);
|
||||
}}
|
||||
title="Delete"
|
||||
>
|
||||
<Trash2 size={10} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Resize handle — bottom right */}
|
||||
<div
|
||||
className="absolute bottom-0 right-0 w-5 h-5 cursor-se-resize z-10 flex items-end justify-end pb-0.5 pr-0.5"
|
||||
onMouseDown={(e) => {
|
||||
e.stopPropagation();
|
||||
onStartResize?.(e, widget);
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
width="10"
|
||||
height="10"
|
||||
viewBox="0 0 10 10"
|
||||
className="text-muted-foreground/50"
|
||||
>
|
||||
<line
|
||||
x1="2"
|
||||
y1="10"
|
||||
x2="10"
|
||||
y2="2"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<line
|
||||
x1="6"
|
||||
y1="10"
|
||||
x2="10"
|
||||
y2="6"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user