Compare commits

..
Author SHA1 Message Date
Graham SteffaniakandCursor 5512d188ac feat(upload): type uploadStallTimeoutSeconds end to end
- store/types: UserObject.fileLoading.uploadStallTimeoutSeconds
- store/mutations: default 10s for new + existing users
- utils/upload: progressTimeoutMs nullish-guards the option
- api/resources: document the onsent callback on post/postPublic signatures

Splits be2b16b0d's upload-stall hunk; base is 493f8f741 (post-merge lockfix).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-14 20:31:34 -06:00
Graham SteffaniakandCursor 493f8f7417 fix(frontend): restore cross-platform rolldown entries in package-lock
Regenerate the lockfile from dev's baseline so npm ci installs native
@rolldown bindings on arm64 Docker builders (slim image frontend build).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-14 18:30:18 -06:00
Graham SteffaniakandCursor 449f39ddf9 Merge branch 'main' into dev/v2.2.0
Bring v2.1.5 security and bugfixes into v2.2.0 while keeping go-media,
embedded previews, and virtual-scroll frontend architecture.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-14 15:45:47 -06:00
Graham Steffaniak 885adcb3a2 Beta/v2.1.5 (#3389) 2026-11-13 19:32:18 -05:00
Graham Steffaniak aaa34e9bb3 Fix generation counters (#3391) 2026-11-13 18:17:06 -06:00
Graham Steffaniak 844f8f9fdd address coderabbit blocker comments (#3390) 2026-11-13 18:03:02 -06:00
Graham Steffaniak 9aba7b55ca updated dependencies (#3387) 2026-11-13 15:54:19 -06:00
Graham Steffaniak 7964b30e5d Fix checksum authenticated users on shares (#3386) 2026-11-13 15:19:53 -06:00
Graham Steffaniak 618de3fbcc Fix GHSA-823x-gh7f-grmf (#3385) 2026-11-13 14:49:39 -06:00
Graham Steffaniak a68fa0ea15 fix GHSA-jg32-ppcc-ph62 archive extraction symlink gap (#3384) 2026-11-13 14:14:10 -06:00
Graham Steffaniak 3bf3d2ce92 fix GHSA-2546-vf4j-vh9v symlink previews (#3383) 2026-11-13 14:03:44 -06:00
Graham Steffaniak f6cc16d1c8 fix subtitles GHSA-hfvf-2639-p2mq (#3382) 2026-11-13 13:45:38 -06:00
Graham Steffaniak 8a1b735e0d add more cache invalidaton for realpath (#3381) 2026-11-13 13:00:15 -06:00
A-d-r-iandGraham Steffaniak 10a26832dd fix(i18n): improve French translations (#3356)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-11-13 11:44:14 -06:00
Kevin B. 0dfab77d6d update frontend deps v2.1.5 (#3378) 2026-11-13 11:43:57 -06:00
Vladimir 7bd9c67eb7 fix(sidebar): keep source selector stationary during horizontal tree scrolling (#3368) 2026-11-13 11:40:09 -06:00
009be1a06d fix(http): restore Unix socket reverse-proxy behavior after #3309 (#3365)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-11-13 11:39:42 -06:00
danielroizen 272a0fab9d fix(preview): respect EXIF orientation on embedded JPEG thumbnails (#3358) 2026-11-13 11:39:28 -06:00
Lykinandxunguangzlj-cloud 63a517de1f fix(picker): open the parent folder on a single click (#3355)
Co-authored-by: xunguangzlj-cloud <293371022+xunguangzlj-cloud@users.noreply.github.com>
2026-11-13 11:39:04 -06:00
Lykinandxunguangzlj-cloud e39b534531 fix(users): show password-change requirement in edit preferences (#3354)
Co-authored-by: xunguangzlj-cloud <293371022+xunguangzlj-cloud@users.noreply.github.com>
2026-11-13 11:38:14 -06:00
Graham Steffaniak 5d25220e94 fix advanced user toggle duplicate (#3353) 2026-11-07 10:52:59 -06:00
8355682773 fix(upload): don't pause while the server saves, and make the stall timeout a setting (#3346)
Co-authored-by: FandacqkaCorp <275647464+FandacqkaCorp@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-11-07 10:49:55 -06:00
Graham Steffaniak 48c1ce709b updated changelog v2.1.5 (#3350) 2026-11-06 17:34:04 -06:00
Graham Steffaniak 43682dc809 fix(users): keep requested profile values when creating a user (#3349) 2026-11-06 16:09:36 -06:00
Xyleme-git 80fba42076 Update fr.json (#3343) 2026-11-06 15:51:28 -06:00
Hromad-aandClaude Opus 5.5 a01ab6901c i18n(cz): fix Czech translations (#3333)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 15:27:14 -06:00
Geekice1andGeekice1 e652538ea8 i18n: fix and improve Italian translation (it.json) (#3332)
Co-authored-by: Geekice1 <geekice1@users.noreply.github.com>
2026-11-06 15:26:49 -06:00
Peter Gao c974da7002 fix(i18n):Update Chinese translations for UI elements (#3330) 2026-11-06 15:26:37 -06:00
Konstantinos Chatzikokolakis eaee271b96 Square image previews: avoid the full-resolution crop copy in imaging.Fill (#3340) 2026-11-06 15:13:20 -06:00
HaneandClaude Opus 5.5 0d6b592046 fix(upload): serialize directory creation before uploading files (#3321)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 15:10:52 -06:00
1791bb7a36 feat(cache): add server.cacheDirMaxSizeMB to cap the preview cache size (#3314)
Co-authored-by: FandacqkaCorp <275647464+FandacqkaCorp@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 15:08:40 -06:00
86d4994152 fix(preview): open RAW, HEIC and rendered documents in the viewer when previews are disabled (#3313)
Co-authored-by: FandacqkaCorp <275647464+FandacqkaCorp@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 15:03:43 -06:00
Graham Steffaniak 8415d5f1ff Fix install button (#3312) 2026-10-31 08:27:12 -05:00
Graham Steffaniak 85f934208c replace button with link 2026-10-31 08:20:44 -05:00
1022ecafef fix(frontend): address CodeRabbit follow-ups from #3276 and #3303 (#3311)
Co-authored-by: FandacqkaCorp <275647464+FandacqkaCorp@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-31 08:17:44 -05:00
Graham Steffaniak 062ac9fb2d Beta/v2.1.4 (#3307) 2026-10-30 19:14:33 -05:00
Graham SteffaniakandGraham Steffaniak cecdd79fcc Restrict Unix socket forwarded-header trust with peer credentials (#3309)
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-30 18:40:10 -05:00
Graham Steffaniak ac50ecfd18 fix: CodeRabbit follow-ups from #3307 (quick-win bugfixes) (#3308) 2026-10-30 17:56:50 -05:00
Graham Steffaniak 71cc2f3f1b fixed linting 2026-10-30 16:30:00 -05:00
Graham Steffaniak 1b3f47f176 fix sensitive data GHSA-892f-9h5p-mfc8 (#3306) 2026-10-30 16:25:25 -05:00
Graham Steffaniak 219b64b5ec addressed deep copy issue 2026-10-30 15:37:45 -05:00
Graham Steffaniak 3ef4928ed7 fix: prevent visible border in generated maskable PWA icons (#3300) 2026-10-30 15:33:33 -05:00
Graham Steffaniak df0a5ad10c fix sensitive data GHSA-892f-9h5p-mfc8 2026-10-30 15:22:46 -05:00
Graham Steffaniak a43d0ab2d3 updated changelog 2026-10-30 15:05:34 -05:00
Graham Steffaniak 9de09e5ec8 feat(search): sidebar File actions and close button in advanced search (#3303) 2026-10-30 15:02:51 -05:00
Graham Steffaniak 9d38c686a1 updated changelog 2026-10-30 15:01:15 -05:00
Graham Steffaniak 1cfca112e4 fix empty view after login if source named 'Files' (#3304) 2026-10-30 14:51:04 -05:00
Graham Steffaniak f540e22dc9 fix(quotas): complete delete accounting for bulk and nested resets (#3305) 2026-10-30 13:26:38 -05:00
Graham Steffaniak dade856ebe fix(move-copy): require choosing a destination when none can be inferred (advanced search) (#3276) 2026-10-30 13:19:15 -05:00
Graham SteffaniakandCursor 2f1da21253 fix(quotas): complete delete accounting for bulk and nested resets
Follow-up to #3235 / #3163: reset accounted folder quotas inside deleted
directories without index lookups, wire the same prepare/apply path into
bulk and public delete handlers, and dedupe scope quota selection.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-30 13:04:16 -05:00
Kevin B. de8d2acd43 fix empty view after login 2026-10-30 13:04:15 -05:00
Graham Steffaniak 6375be202e fix: release nested folder quotas when deleting their ancestor (#3235) 2026-10-30 12:59:12 -05:00
FandacqkaCorpandClaude Sonnet 5.5 816b99cee0 feat(search): add a close button to advanced search
On tool pages the top bar button only toggles the sidebar, so the only ways
out of advanced search were the sidebar or the browser back button.

Add an icon-only grey X at the top-left of the advanced search page (first
element of the tools wrapper); the top bar button is left as it is. It clears
the selection and goes back to the page the search was opened from, or to
/files when there is none (e.g. the URL was opened directly).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 16:14:12 +01:00
FandacqkaCorpandClaude Sonnet 5.5 bf349a7dcd feat(search): show the sidebar File actions in advanced search
The sidebar File actions button only exists in the listing, so in advanced
search the actions on the selected results (select all, download, copy, move)
were only reachable through the context menu, which is hard to find, especially
on touch devices.

Show the same sidebar button in advanced search. There it opens the context
menu on the current selection instead of the create-only menu, and it doesn't
depend on create permissions (the menu already checks permissions per
source). The menu now always offers Select multiple in advanced search, so
single results can be selected when "open with a single click" is on, and hides
the create (+) toggle, since results have no single folder to create in.

The button still honours the "hide sidebar file actions" preference and isn't
shown in shares.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 15:55:48 +01:00
Matt Van Horn db6504bf80 fix: prevent visible border in generated maskable PWA icons
Maskable icon generation now alpha-composites the resized artwork over
the opaque background using `OverlayCenter`. Added tests covering
transparent padding and opaque edges, verifying the output dimensions,
opacity, and background pixels outside the artwork.

Fixes #3187
2026-10-30 03:59:21 -07:00
FandacqkaCorpandClaude Sonnet 5.5 2019d573f8 fix(move-copy): require choosing a destination when there is no source to fall back to
In advanced search the open request is the list of results and has no source.
The Copy/Move prompt then showed "Choose a source" but, if the button was
pressed without choosing anything, silently sent the items to the root of the
first selected item's source.

Disable the Copy/Move button until a destination source is chosen in that
case (no destination yet and no source in the open request, outside shares),
and use the existing "Choose a source" text as its tooltip. Normal listings
and shares are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 11:05:37 +01:00
Matt Van Horn d716fc15ec test: share the nested quota delete fixture between API and WebDAV tests
TestResourceDeleteNestedQuota and TestWebDAVDeleteNestedQuota seeded the
same files, quotas and usage deltas. Move that setup into
seedNestedQuotaFixture and call it from both.
2026-10-30 00:28:00 -07:00
Graham Steffaniak 56e16608e4 fix(frontend): keep video loading spinner off when the fetch stalls mid-playback (#3289) 2026-10-29 19:19:47 -05:00
Graham Steffaniak c471fc135b fix(frontend): use native video fullscreen on iPhone (#3288) 2026-10-29 19:18:33 -05:00
Graham Steffaniak 5112cf87b1 fix(analytics): report freebsd instead of "other" in system.os (#3284) 2026-10-29 19:17:23 -05:00
Graham Steffaniak 3d7bac47ee fix(stream): play single-file share media on Windows (#3271) 2026-10-29 19:10:22 -05:00
vulragrag-star 2a38d2fa1e fix(users): enforce lockPassword on self-service password changes (#3283) 2026-10-29 19:01:34 -05:00
Matt Van Horn 82e110c08d test: cover scoped users in the API nested quota delete test
The API path is scope-relative while quota paths and the index are
source-relative. Run the test for a user scoped to /scoped as well as /,
which fails if the delete looks up the unscoped path.
2026-10-29 08:14:00 -07:00
Matt Van Horn f4c96078a1 Merge remote-tracking branch 'upstream/main' into fix/3163-release-nested-folder-quotas-on-delete
# Conflicts:
#	backend/internal/web/resource.go
#	backend/internal/web/webdav.go
#	backend/internal/web/webdav_test.go
2026-10-29 08:14:00 -07:00
975adedabb Address directory indexing bugs (#3292)
Co-authored-by: Lucas Siqueira <lucas.morais.siqueira@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 10:29:42 -05:00
Graham Steffaniak 14ec0eba0d Fix indexing regressions (#3260) 2026-10-27 19:41:12 -05:00
Lucas de Morais SiqueiraandGraham Steffaniak 307d5f6591 fix(indexing): skip unreadable directory entries instead of failing the listing (#3184)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-27 19:25:01 -05:00
Get The Fork Off ff9df43356 fix(frontend): keep video loading spinner off when the fetch stalls mid-playback 2026-10-27 20:50:30 -03:00
Get The Fork Off 802e91aa05 fix(frontend): use native video fullscreen on iPhone 2026-10-27 20:48:46 -03:00
NefelibateLGandZCode Scout 28ef44cdec fix(analytics): report freebsd instead of "other" in system.os
The analytics snapshot classified every GOOS outside {linux, windows,
darwin} as "other", so the shipped freebsd-amd64 release binary
reported "os": "other" in the analytics payload even though
backend/.goreleaser.yaml builds freebsd as a first-class target
(#3244).

Add freebsd to the mapSystemOS whitelist, matching the release build
matrix, and add a table-driven test covering all four shipped GOOS
values plus the unsupported and empty fallbacks.

Fixes #3244

Co-authored-by: ZCode Scout <noreply@zcode.local>
Signed-off-by: NefelibateLG <3453510037@qq.com>
2026-10-27 09:16:06 +08:00
sarankumar1325 0ee0f35301 fix(stream): play single-file share media on Windows
shareRelativeDisplayName ran filepath.Base on slash-separated paths. On
Windows filepath.Base("/") returns "\", which passed the "/" check, so a
single-file share streamed with file=/ got "\" as its name instead of the
shared file's name. IsMediaStreamFile then rejected it and the stream
endpoint answered 403 "stream endpoint supports audio and video only".

Use path.Base, since both the share-relative path and the share path are
slash-separated.

Fixes #3270
2026-10-25 11:30:00 +05:30
Graham Steffaniak cc99aa542e updated with symlink extraction change (#3265) 2026-10-23 15:36:09 -05:00
8514da4a9a fix(auth): API token permission handling for customized tokens (#3255)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-23 14:48:18 -05:00
Graham SteffaniakandDevin 4625b89528 fix webp preview support (#3259)
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-22 15:34:57 -05:00
Jay Hemnani b2a07196b7 fix(archive): extract tar hard links instead of dropping them (#3234) 2026-10-22 15:26:16 -05:00
Graham Steffaniak 0a8698ee4d updated changelog 2026-10-22 15:24:08 -05:00
ec8ad36c95 Feature/html preview navigation and media (#3131)
Co-authored-by: Graham Steffaniak <graham.steffaniak@autodesk.com>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-22 15:13:31 -05:00
vulragrag-star 2c0c1b4bb2 fix(frontend): show the share banner to public visitors (#3250) 2026-10-22 13:38:49 -05:00
Thorsten Liborius 6fa71bd13d fix(frontend): show correct relative expiration time for sharesFix/share expiry relative time (#3247) 2026-10-21 18:47:44 -05:00
Graham Steffaniakandcoderabbitai[bot] 06aa16e7d7 fix raw embedded image support - rtf rw2 raw rwl (#3243)
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-10-20 17:43:38 -05:00
Graham Steffaniak b0f6d53f49 fix arm32 build in v2.1.3 (#3242) 2026-10-20 14:57:09 -05:00
Graham Steffaniak d27ab6a00b fix arm32 build in v2.1.3 2026-10-20 14:56:36 -05:00
Graham Steffaniak f0fb859479 updated package dependencies and replaced katex with temml (#3241) 2026-10-20 13:51:58 -05:00
Graham Steffaniak 4c8a913377 updated backage dependencies and replaced katex with temml 2026-10-20 13:31:43 -05:00
Graham Steffaniak c1684baffd Beta/v2.1.3 (#3238) 2026-10-20 12:47:40 -05:00
Matt Van Horn bb45ebcce1 fix: avoid shadowing err in nested quota delete tests 2026-10-20 10:41:27 -07:00
18138b1ab5 Fix CodeRabbit findings from PR #3238 (#3240)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
2026-10-20 12:31:48 -05:00
Matt Van Horn 26665efc13 fix: release nested folder quotas when deleting their ancestor
Adds shared preparation and application helpers for API and WebDAV
deletion accounting. Before deletion removes index metadata, each nested
accounted quota is measured independently, while covering, scope, and
share quotas use the deleted item's size. Adjustments are applied only
after deletion succeeds, and unknown sizes are omitted. API deletion
also derives the source index path from the item's real path.

Fixes #3163
2026-10-20 04:39:51 -07:00
Graham SteffaniakandDevin 98851e029f fix(access): match lowercase rule keys in path existence and rule updates (#3237)
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-19 13:50:08 -05:00
4a1a3bbe09 fix(access): lowercase access-rule keys with migration (GHSA-4vrc-935w-xxq2) (#3232)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Graham Steffaniak <gtsteffaniak@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-10-19 13:50:08 -05:00
Graham Steffaniak a6d7f7c64c fix(auth): password-gate passkey enrollment changes (GHSA-r744-4vm3-2px3) (#3198) 2026-10-19 13:50:08 -05:00
Graham Steffaniak ada7a18620 Use statx reduce redundant calls (#3230) 2026-10-19 13:50:08 -05:00
Graham Steffaniak 4f4ea2370e updated linting and tests on macos (#3231) 2026-10-19 13:50:08 -05:00
Graham Steffaniak 52aa314e1d fix(quota): count upload usage against accounted limits (GHSA-m57f-66qj-8jxg) (#3201) 2026-10-19 13:50:08 -05:00
Kevin B.andGraham Steffaniak 1d6f67cc20 update frontend deps (v2.1.3) (#3228)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-19 13:50:08 -05:00
Graham Steffaniak d89b7e7deb fix(events): hold client locks during SSE sends (GHSA-p9wm-f5jj-75pj) (#3227) 2026-10-19 12:37:04 -05:00
Graham Steffaniak e26bd29848 fix(archive): enforce access on unarchive extraction (GHSA-p93p-v944-4p44) (#3203) 2026-10-19 12:37:04 -05:00
Graham Steffaniak 9c2b98655a fix: enforce readOnly on WebDAV, archive and OnlyOffice (GHSA-4v62-884x-2466) (#3202) 2026-10-19 12:37:04 -05:00
Paolo VallettaandGraham Steffaniak a379f047d1 fix(indexing): resume the persisted scan schedule on startup (#3225)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-19 12:37:04 -05:00
Kevin B.andGraham Steffaniak f4879be6bf fix path picker list on shares (#3223)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-19 12:23:45 -05:00
Kevin B.andGraham Steffaniak 7751da745d Hide activity, quota, access buttons in Info prompt in shares (#3224)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-19 12:23:17 -05:00
Graham Steffaniak 80cedcb4d5 fix(frontend): clear stale upload navigation approval when idle (#3222) 2026-10-18 13:48:38 -05:00
Graham Steffaniak ac19abf7d2 fix(frontend): restore upload guards while uploads are paused (#3220) 2026-10-18 13:48:38 -05:00
Graham Steffaniak 38e868e5af fix(frontend): resolve /files/ to default source for single-source installs (#3215) 2026-10-18 13:48:38 -05:00
anonymous-writerandGraham Steffaniak b3af5cc2d7 Fix upload session not released after successful single-file upload (#3186)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-18 13:48:38 -05:00
Paolo VallettaandGraham Steffaniak b399de3d92 fix(webdav): free the deleted bytes from the quota counters (#3160)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-18 13:45:50 -05:00
Graham Steffaniak 99f1a14e7b fix(shares): correct share path updates on folder move (GHSA-26fh-r34c-qxh6) (#3197) 2026-10-18 13:07:33 -05:00
Graham Steffaniak 84afd8b0b7 fix(webdav): require Create permission for new PUT files (GHSA-8655-2ph3-q7q7) (#3196) 2026-10-18 13:07:33 -05:00
Graham Steffaniak 78be5d8c0f fix(preview): enforce scoped symlink resolution (GHSA-g2q5-r6ch-v25f) (#3195) 2026-10-18 13:07:33 -05:00
Graham Steffaniak 5e29e1ee60 fix(auth): use rightmost X-Forwarded-For for client IP (GHSA-wjp8-g49g-xrhx) (#3191) 2026-10-18 13:07:33 -05:00
Graham Steffaniak 367a7f019c fix(tools): per-user duplicate finder cache (GHSA-4fhx-8pf6-5gmr) (#3190) 2026-10-18 13:07:33 -05:00
Graham Steffaniak fa9c094160 fix(view): block share view tokens on authenticated view route (GHSA-wxj5-g3qp-g732) (#3194) 2026-10-18 13:07:33 -05:00
Graham Steffaniak 36a9a6dc49 fix(events): prevent SSE EventRouter concurrent map panic (GHSA-p9wm-f5jj-75pj) (#3189) 2026-10-18 13:07:33 -05:00
Kevin B.andGraham Steffaniak 8fe6f1d5c3 Refactor Tooltip and generic to avoid v-html usage (GHSA-rmjp-pfrq-cc3v) (#3199)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-18 13:07:33 -05:00
JUSHUANGHUI LIandGraham Steffaniak 6dc3935c57 fix: preserve file permissions when saving edits (#3159)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-17 11:28:25 -05:00
Graham Steffaniak 5e73036657 fix(users): partial global permissions on API create (on top of #3171) (#3165) 2026-10-17 11:24:46 -05:00
Jay HemnaniandGraham Steffaniak e505900975 fix(activity): record uploads and deletes made through a share (#3166)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-17 11:24:46 -05:00
HawkForgeandGraham Steffaniak 26f320ee43 fix(settings): don't panic when config has no server map (#3176)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-16 16:23:41 -05:00
Kevin B. 184ae798c4 make listing highlight follow nextPrevious (#3156) 2026-10-15 15:26:59 -05:00
Graham Steffaniak 7ae8bab062 fix scope issues for archive extraction (#3177) 2026-10-15 15:26:59 -05:00
Graham Steffaniak 1af606e751 fix dev script 2026-10-15 15:26:59 -05:00
Graham Steffaniak 3683bc607c fixed markdown screenshots (#3171) 2026-10-15 15:26:59 -05:00
Som SamantrayandGraham Steffaniak 08d3e43c22 fix(auth): preserve admin source scope with createUserDir (#3125)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-15 15:26:59 -05:00
Kevin B.andGraham Steffaniak d76f9373c4 Fix missing creation time and tiny font on md viewer code blocks (#3157)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-15 15:00:55 -05:00
Kevin B.andGraham Steffaniak a72651e7aa Add alphabetical order + pinned indicators to file tree (#3154)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-15 15:00:28 -05:00
Kevin B.andGraham Steffaniak 73d0b20821 Fix: vite warnings and restricted origin (#3155)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-15 15:00:00 -05:00
Anatolii PrylutskyiandGraham Steffaniak 3e447307f7 fix(frontend): hide write actions in read-only sources (#3149)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-14 18:50:09 -05:00
vulragrag-starandGraham Steffaniak 264cc81c41 fix(share): honor userDefaults singleClick for anonymous shares (#3147)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-14 18:46:13 -05:00
Graham Steffaniak aa5b24119a updated changelog 2026-10-14 16:07:31 -05:00
Graham Steffaniak 52cf624711 add file modify logging (#3152) 2026-10-14 16:07:31 -05:00
Graham Steffaniak 5753f63970 updated webdav hardening (#3151) 2026-10-14 16:07:31 -05:00
Jay HemnaniandGraham Steffaniak 8f1cf54cb0 fix(users): keep requested permissions when creating a user (#3130)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-14 16:07:31 -05:00
Paolo VallettaandGraham Steffaniak a8cfcdd6eb feat(webdav): chunked uploads for large files (rclone --owncloud-chunk-size) (#3112)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
2026-10-14 16:05:49 -05:00
318 changed files with 22679 additions and 23091 deletions

No files matched your search

+1
View File
@@ -30,6 +30,7 @@
"extensions": [
"golang.go",
"Vue.volar",
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"ms-azuretools.vscode-docker"
]
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
with:
go-version: 'stable'
- working-directory: backend
run: go test -race -v ./... -timeout 45s
run: go test -race -v ./... -timeout 30s
lint-backend:
runs-on: ubuntu-24.04-arm
timeout-minutes: 5
-1
View File
@@ -93,7 +93,6 @@ func TestFillCenter_MatchesImagingFill(t *testing.T) {
for _, tg := range targets {
for fname, f := range filters {
t.Run(fmt.Sprintf("%s/%dx%d/%s", name, tg[0], tg[1], fname), func(t *testing.T) {
t.Parallel()
want := imaging.Fill(src, tg[0], tg[1], imaging.Center, f)
got := fillCenter(src, tg[0], tg[1], f)
require.Equal(t, fmt.Sprintf("%T", want), fmt.Sprintf("%T", got), "image type")
-1
View File
@@ -26,7 +26,6 @@ func TestMain(m *testing.M) {
if fileutils.PermDir == 0 {
fileutils.SetFsPermissions(0644, 0755)
}
configureImagingParallelism()
// Run the tests
code := m.Run()
+8 -21
View File
@@ -1,8 +1,6 @@
package utils
import (
"errors"
"io"
"net/http"
"os"
"unicode/utf8"
@@ -16,15 +14,20 @@ import (
func IsTextFile(realPath string) (bool, error) {
const sampleSize = 8192 // Read first 8KB to check
const maxNullByteRatio = 0.05 // Reject if more than 5% null bytes
// Read only the sample: never load the whole file, which can be several GB.
sample, err := readSample(realPath, sampleSize)
// Read sample from file
content, err := os.ReadFile(realPath)
if err != nil {
return false, err
}
// Empty files are considered text
if len(sample) == 0 {
if len(content) == 0 {
return true, nil
}
// Use sample for large files to avoid reading entire file into memory
sample := content
if len(content) > sampleSize {
sample = content[:sampleSize]
}
// Check 1: Reject PDFs. A PDF with a long ASCII text layer looks like text
// for far more than sampleSize bytes.
if http.DetectContentType(sample) == "application/pdf" {
@@ -67,19 +70,3 @@ func IsTextFile(realPath string) (bool, error) {
return true, nil
}
// readSample returns at most n bytes from the start of the file.
func readSample(realPath string, n int) ([]byte, error) {
f, err := os.Open(realPath)
if err != nil {
return nil, err
}
defer f.Close()
buf := make([]byte, n)
read, err := io.ReadFull(f, buf)
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
return nil, err
}
return buf[:read], nil
}
-37
View File
@@ -3,7 +3,6 @@ package utils
import (
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
@@ -47,39 +46,3 @@ func TestIsTextFile(t *testing.T) {
})
}
}
// TestIsTextFileReadsOnlySample guards against loading the whole file into memory:
// on a multi-GB file (e.g. a video opened in the file watcher) that exhausts RAM.
func TestIsTextFileReadsOnlySample(t *testing.T) {
const fileSize = 256 << 20 // 256 MiB, sparse: no real disk usage
path := filepath.Join(t.TempDir(), "large.log")
f, err := os.Create(path)
if err != nil {
t.Fatalf("creating sample: %v", err)
}
if _, err = f.WriteString(strings.Repeat("log line\n", 1024)); err != nil {
t.Fatalf("writing sample: %v", err)
}
if err = f.Truncate(fileSize); err != nil {
t.Fatalf("growing sample: %v", err)
}
if err = f.Close(); err != nil {
t.Fatalf("closing sample: %v", err)
}
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
got, err := IsTextFile(path)
runtime.ReadMemStats(&after)
if err != nil {
t.Fatalf("IsTextFile: %v", err)
}
if !got {
t.Fatalf("IsTextFile(large text file) = false, want true")
}
if allocated := after.TotalAlloc - before.TotalAlloc; allocated > 1<<20 {
t.Fatalf("IsTextFile allocated %d bytes for a %d-byte file, want only the sample", allocated, fileSize)
}
}
@@ -13,15 +13,14 @@ import (
func withMediaHandlerSettings(t *testing.T) {
t.Helper()
originalMedia := settings.CurrentMediaSettings()
originalTranscode := settings.Config.Integrations.Media.Transcode
originalFFmpeg := settings.Env.FFmpegAvailable
t.Cleanup(func() {
settings.Config.Integrations.Media.Transcode = originalTranscode
settings.Env.FFmpegAvailable = originalFFmpeg
settings.ApplyMediaSettings(originalMedia)
})
settings.Env.FFmpegAvailable = true
media := originalMedia
media.Transcode = settings.FullAdminTranscode{
settings.Config.Integrations.Media.Transcode = settings.FullAdminTranscode{
UserTranscode: settings.UserTranscode{
Enabled: true,
MaxConcurrentPerUser: 2,
@@ -29,7 +28,6 @@ func withMediaHandlerSettings(t *testing.T) {
MaxConcurrent: 3,
Profiles: settings.DefaultTranscodeProfiles(),
}
settings.ApplyMediaSettings(media)
}
func mediaHandlerContext(admin bool) *Context {
@@ -156,9 +154,7 @@ func TestSettingsMediaHandlerFullPayloadForAdmin(t *testing.T) {
// Disabling transcoding at runtime must be visible to non-admin players.
func TestSettingsMediaHandlerReflectsDisabledTranscode(t *testing.T) {
withMediaHandlerSettings(t)
disabled := settings.CurrentMediaSettings()
disabled.Transcode.Enabled = false
settings.ApplyMediaSettings(disabled)
settings.Config.Integrations.Media.Transcode.Enabled = false
transcode := objectField(t, callMediaGet(t, false), "transcode")
if enabled, ok := transcode["enabled"].(bool); !ok || enabled {
+17 -27
View File
@@ -13,31 +13,21 @@ import (
const settingsRedactSentinel = "SENTINEL-SETTINGS-SECRET"
func swapSettingsConfigForTest(t *testing.T, mutate func(*settings.Settings)) {
t.Helper()
cfg := settings.Config
if mutate != nil {
mutate(&cfg)
}
prev := settings.SwapConfigForTest(cfg)
t.Cleanup(func() { settings.SwapConfigForTest(prev) })
}
// TestSettingsGetHandler_redactsSecrets is the end-to-end regression guard for
// GHSA-892f-9h5p-mfc8: GET /api/settings (and ?property=auth) must not return cleartext secrets.
func TestSettingsGetHandler_redactsSecrets(t *testing.T) {
setupTestEnv(t)
swapSettingsConfigForTest(t, func(cfg *settings.Settings) {
cfg.Auth.Key = settingsRedactSentinel
cfg.Auth.TotpSecret = settingsRedactSentinel
cfg.Auth.Methods.PasswordAuth.AdminPassword = settingsRedactSentinel
cfg.Auth.Methods.PasswordAuth.Recaptcha.Secret = settingsRedactSentinel
cfg.Auth.Methods.OidcAuth.ClientSecret = settingsRedactSentinel
cfg.Auth.Methods.LdapAuth.UserPassword = settingsRedactSentinel
cfg.Auth.Methods.JwtAuth.Secret = settingsRedactSentinel
cfg.Integrations.OnlyOffice.Secret = settingsRedactSentinel
})
prev := settings.Config
t.Cleanup(func() { settings.Config = prev })
settings.Config.Auth.Key = settingsRedactSentinel
settings.Config.Auth.TotpSecret = settingsRedactSentinel
settings.Config.Auth.Methods.PasswordAuth.AdminPassword = settingsRedactSentinel
settings.Config.Auth.Methods.PasswordAuth.Recaptcha.Secret = settingsRedactSentinel
settings.Config.Auth.Methods.OidcAuth.ClientSecret = settingsRedactSentinel
settings.Config.Auth.Methods.LdapAuth.UserPassword = settingsRedactSentinel
settings.Config.Auth.Methods.JwtAuth.Secret = settingsRedactSentinel
settings.Config.Integrations.OnlyOffice.Secret = settingsRedactSentinel
admin := &users.User{
FrontendUser: users.FrontendUser{
@@ -72,9 +62,9 @@ func TestSettingsGetHandler_redactsSecrets(t *testing.T) {
func TestSettingsGetHandler_doesNotMutateLiveConfig(t *testing.T) {
setupTestEnv(t)
swapSettingsConfigForTest(t, func(cfg *settings.Settings) {
cfg.Auth.Key = settingsRedactSentinel
})
prev := settings.Config
t.Cleanup(func() { settings.Config = prev })
settings.Config.Auth.Key = settingsRedactSentinel
admin := &users.User{
FrontendUser: users.FrontendUser{
@@ -102,10 +92,10 @@ func TestSettingsGetHandler_doesNotMutateLiveConfig(t *testing.T) {
func TestSettingsGetHandler_keepsNonSecretAuthFields(t *testing.T) {
setupTestEnv(t)
swapSettingsConfigForTest(t, func(cfg *settings.Settings) {
cfg.Auth.Key = settingsRedactSentinel
cfg.Auth.TokenExpirationHours = 7
})
prev := settings.Config
t.Cleanup(func() { settings.Config = prev })
settings.Config.Auth.Key = settingsRedactSentinel
settings.Config.Auth.TokenExpirationHours = 7
admin := &users.User{
FrontendUser: users.FrontendUser{
+138 -331
View File
@@ -1,333 +1,140 @@
{
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true,
"root": "../"
},
"files": {
"ignoreUnknown": true,
"includes": [
"**",
"!dist",
"!public/config.generated.yaml",
"!public/index.html",
"!node_modules",
"!test-results"
]
},
"formatter": { "enabled": false },
"linter": {
"enabled": true,
"rules": {
"preset": "recommended",
"a11y": {
"noAutofocus": "off",
"noNoninteractiveElementToInteractiveRole": "off",
"noStaticElementInteractions": "off",
"noSvgWithoutTitle": "off",
"useAriaPropsSupportedByRole": "off",
"useGenericFontNames": "off",
"useKeyWithClickEvents": "off",
"useMediaCaption": "off",
"useSemanticElements": "off",
"useValidAnchor": "off"
},
"complexity": {
"noForEach": "on",
"noImportantStyles": "off",
"noRedundantDefaultExport": "warn",
"noUnnecessaryTemplateExpression": "error",
"noUselessStringConcat": "warn",
"useMathMinMax": "warn",
"useRegexpTest": "warn"
},
"correctness": {
"noInvalidDirectionInLinearGradient": "error",
"noInvalidGridAreas": "error",
"noInvalidPositionAtImportRule": "error",
"noMissingVarFunction": "error",
"noUnknownFunction": "error",
"noUnknownMediaFeatureName": "error",
"noUnknownProperty": "error",
"noUnknownPseudoClass": "error",
"noUnknownPseudoElement": "error",
"noUnknownTypeSelector": "error",
"noUnknownUnit": "error",
"noUnmatchableAnbSelector": "error",
"noVueDuplicateKeys": "error",
"noVueImportCompilerMacros": "error",
"noVueRefAsOperand": "error",
"noVueVIfWithVFor": "error",
"noVueVOnNumberValues": "error",
"useVueValidVFor": "error"
},
"nursery": {
"noArgumentsCallerOrCallee": "warn",
"noArrayForEach": "error",
"noBooleanSortComparator": "error",
"noBufferConstructor": "warn",
"noChainedComparison": "error",
"noConfusingArraySplice": "warn",
"noDoubleComparison": "on",
"noDynamicDelete": "warn",
"noDynamicRequire": "error",
"noFloatingPromises": "error",
"noImpliedEval": "error",
"noJsonUnsafeValues": "error",
"noLateCurrentTargetAccess": "error",
"noLateEventControl": "error",
"noMisusedPromises": "error",
"noNestedSwitch": "on",
"noObjectLiteralComparison": "error",
"noObsoleteAttributes": "error",
"noPlaywrightUnsafeReferences": "error",
"noPromiseExecutorReturn": "warn",
"noRedundantTypeConstituents": "warn",
"noReturnArrayPush": "warn",
"noUnnecessaryStringTrim": "warn",
"noUnsafeReturn": "warn",
"noUselessLengthCheck": "info",
"noUselessRecursion": "error",
"noUselessSplice": "warn",
"noUselessSpread": "warn",
"noUselessTypeAssertion": "warn",
"noVueAsyncComputed": "error",
"noVueChildContent": "error",
"noVueComputedPropertiesInData": "error",
"noVueDefineModelDefault": "warn",
"noVueDeprecatedConfigKeyCodes": "info",
"noVueDeprecatedDeleteSet": "error",
"noVueDeprecatedEventsApi": "error",
"noVueDeprecatedHtmlElementIs": "error",
"noVueDeprecatedListeners": "error",
"noVueDeprecatedModelDefinition": "error",
"noVueDeprecatedPropsDefaultThis": "error",
"noVueDeprecatedRouterLinkTagProp": "error",
"noVueDeprecatedScopedSlots": "error",
"noVueDeprecatedVBindSync": "error",
"noVueDeprecatedVIs": "error",
"noVueExportInScriptSetup": "error",
"noVueExposeAfterAwait": "error",
"noVueLifecycleAfterAwait": "error",
"noVueLoneTemplate": "error",
"noVueMixin": "error",
"noVueMultipleObjectsInClass": "warn",
"noVueMultipleSlotArgs": "warn",
"noVueMutatingProps": "error",
"noVueRefObjectReactivityLoss": "error",
"noVueRequiredPropWithDefault": "warn",
"noVueRestrictedCallAfterAwait": "error",
"noVueRestrictedVOn": "warn",
"noVueShadowNativeEvents": "warn",
"noVueSideEffectsInComputed": "error",
"noVueTemplateKey": "error",
"noVueTemplateShadow": "warn",
"noVueThisInTemplate": "warn",
"noVueUndeclaredDirectives": "off",
"noVueUndeclaredEmits": "warn",
"noVueUndeclaredProperties": "error",
"noVueUndeclaredSlots": "warn",
"noVueUnusedEmitDeclarations": "error",
"noVueUnusedRefs": "error",
"noVueUselessTemplateAttributes": "error",
"noVueUselessVBind": "warn",
"noVueVForTemplateKeyOnChild": "error",
"noVueVHtml": "error",
"noVueVText": "warn",
"noVueVTextVHtmlOnComponent": "error",
"noVueWatchAfterAwait": "error",
"useConsistentLightnessNotation": {
"level": "error",
"options": { "notation": "percentage" }
},
"useConsistentObjectKeys": "error",
"useMathAbs": "warn",
"useMathTrunc": "warn",
"useObjectFromEntries": "warn",
"useSimplifiedBooleanReturn": "warn",
"useValidNamespaceImports": "error",
"useVueBaseImport": "warn",
"useVueBlockOrder": {
"level": "on",
"options": { "order": ["template", "script", "style"] }
},
"useVueBooleanPropTypeFirst": "warn",
"useVueComponentIs": "error",
"useVueComputedPropertyReturn": "error",
"useVueConsistentEventHyphenation": "warn",
"useVueEmitValidator": "warn",
"useVueEmitsValidatorReturn": "error",
"useVuePropTypeConstructor": "error",
"useVueRenderReturn": "error",
"useVueSingleEventPayload": "warn",
"useVueTemplateRef": "warn",
"useVueTypedObjectProps": "warn",
"useVueTypedProps": "warn",
"useVueTypedRef": "error",
"useVueVModel": "warn",
"useVueValidDefaultProp": "error",
"useVueValidDefineEmits": "error",
"useVueValidDefineOptions": "error",
"useVueValidDefineProps": "error",
"useVueValidNextTick": "error",
"useVueValidVIs": "error",
"useVueValidVModel": "error",
"useVueValidVShow": "error",
"useVueValidVSlot": "error",
"noInvalidPropertyInitValue": "warn",
"noPseudoElementInFunctionalPseudoClass": "error",
"noSelfNestedLayer": "warn",
"noVueDeprecatedDestroyedLifecycle": "error",
"noVueDeprecatedFilter": "error",
"noVueDeprecatedFunctionalTemplate": "error",
"noVueDeprecatedInlineTemplate": "error",
"noVueDeprecatedScopeAttribute": "error",
"noVueDeprecatedSlotAttribute": "error",
"noVueDeprecatedSlotScope": "error",
"noVueDeprecatedVOnNativeModifier": "error",
"noObsoleteTags": "error",
"noNonScalableViewport": "warn",
"noShortTimeValues": "warn",
"useNamedLayer": "warn",
"useVueDefineOptions": "warn",
"useVueConsistentDefineEmitsDeclaration": "warn",
"useVueConsistentVSlotStyle": "warn",
"useVueSlotsAsFunctions": "warn",
"useVueMacroVariableName": "warn",
"useVueVOnExact": "warn",
"useConsistentFontWeightNotation": "warn",
"useIncludes": "warn",
"useStringStartsEndsWith": "warn",
"useModernMathApis": "warn"
},
"performance": { "useVueVapor": "off" },
"security": { "preset": "recommended", "useIframeSandbox": "off" },
"style": {
"noCommonJs": "warn",
"noDescendingSpecificity": "error",
"noTopLevelLiterals": "error",
"noVueOptionsApi": "off",
"useDomQuerySelector": "warn",
"useImportsFirst": "off",
"useVarsOnTop": "on",
"useVueConsistentDefinePropsDeclaration": "on",
"useVueConsistentVBindStyle": "warn",
"useVueDefineMacrosOrder": "warn",
"useVueHyphenatedAttributes": "off",
"useVueMultiWordComponentNames": "off",
"useVueNextTickPromise": "warn",
"noValueAtRule": "warn",
"noHexColors": "off",
"useObjectSpread": "warn",
"useSpreadOverApply": "warn",
"noSubstr": "warn",
"useNumberNamespace": "warn",
"useAtIndex": "warn",
"useForOf": "warn"
},
"suspicious": {
"noConfusingVoidType": "warn",
"noDeprecatedMediaType": "error",
"noDuplicateAtImportRules": "error",
"noDuplicateCustomProperties": "error",
"noDuplicateFontNames": "error",
"noDuplicateProperties": "error",
"noDuplicateSelectors": "error",
"noDuplicateSelectorsKeyframeBlock": "error",
"noEmptyBlock": "error",
"noEmptyObjectKeys": "error",
"noEmptySource": "error",
"noExplicitAny": "warn",
"noImportCycles": "off",
"noImportantInKeyframe": "error",
"noIrregularWhitespace": "error",
"noNestedPromises": "error",
"noParametersOnlyUsedInRecursion": "error",
"noShadow": "error",
"noShorthandPropertyOverrides": "error",
"noUnknownAtRules": "error",
"noUnnecessaryConditions": "off",
"useArraySortCompare": "error",
"useScopedStyles": "off",
"noUselessEscapeInString": "warn",
"noVar": "error",
"noForIn": "warn"
}
},
"domains": { "vue": "all", "project": "all", "types": "all" }
},
"css": {
"formatter": {
"enabled": true,
"indentStyle": "space",
"indentWidth": 2
},
"linter": { "enabled": true },
"assist": { "enabled": true }
},
"html": {
"experimentalFullSupportEnabled": true,
"parser": { "interpolation": true, "vue": true },
"linter": { "enabled": true }
},
"overrides": [
{
"includes": ["tests/playwright/**"],
"linter": {
"rules": {
"complexity": { "noPlaywrightUselessAwait": "error" },
"correctness": {
"noPlaywrightMissingAwait": "error",
"noUnresolvedImports": "off",
"usePlaywrightValidDescribeCallback": "error"
},
"style": {
"noPlaywrightElementHandle": "error",
"noPlaywrightEval": "error",
"noPlaywrightWaitForSelector": "error"
},
"suspicious": {
"noEmptyObjectKeys": "error",
"noPlaywrightForceOption": "error",
"noPlaywrightNetworkidle": "error",
"noPlaywrightPagePause": "error",
"noPlaywrightWaitForNavigation": "error",
"noPlaywrightWaitForTimeout": "warn"
}
}
}
},
{
"includes": ["**/*.js"],
"linter": { "rules": { "nursery": { "noUnsafeReturn": "off" } } }
},
{
"includes": [
"scripts/postcss-strip-legacy.ts",
"playwright.config.ts",
"playwright.performance.config.ts",
"**/*.test.js",
"**/*.test.ts"
],
"linter": {
"rules": {
"correctness": {
"noUndeclaredDependencies": "off",
"noUnresolvedImports": "off"
}
}
}
}
],
"plugins": ["./scripts/biome/css-legacy.grit"],
"assist": {
"actions": {
"source": {
"organizeImports": "off",
"useGraphqlSortedDefinitions": "on"
}
}
}
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
"files": {
"ignoreUnknown": true,
"includes": [
"**",
"!dist",
"!public/config.generated.yaml",
"!public/index.html",
"!node_modules",
"!test-results"
]
},
"formatter": {
"enabled": false
},
"assist": {
"enabled": true,
"actions": { "source": { "organizeImports": "off" } }
},
"css": {
"linter": { "enabled": false },
"formatter": { "enabled": false },
"assist": { "enabled": false }
},
"html": {
"experimentalFullSupportEnabled": true,
"parser": { "interpolation": true },
"linter": { "enabled": true }
},
"linter": {
"enabled": true,
"domains": { "vue": "all", "project": "all", "types": "all" },
"rules": {
"performance": {
"useVueVapor": "off"
},
"security": {
"preset": "recommended"
},
"a11y": {
"noAutofocus": "off",
"noNoninteractiveElementToInteractiveRole": "off",
"noStaticElementInteractions": "off",
"noSvgWithoutTitle": "off",
"useAriaPropsSupportedByRole": "off",
"useGenericFontNames": "off",
"useKeyWithClickEvents": "off",
"useMediaCaption": "off",
"useSemanticElements": "off",
"useValidAnchor": "off"
},
"complexity": {
"noForEach": "on",
"noImportantStyles": "off",
"noRedundantDefaultExport": "warn"
},
"correctness": {
"noUnknownPseudoClass": "off"
},
"nursery": {
"noEmptyObjectKeys": "error",
"noFloatingPromises": "error",
"noImpliedEval": "error",
"noJsonUnsafeValues": "error",
"noMisusedPromises": "error",
"noTopLevelLiterals": "error",
"noVueDeprecatedScopedSlots": "error",
"noVueImportCompilerMacros": "error",
"noVueRefAsOperand": "error",
"noVueUndeclaredDirectives": "off",
"noVueVOnNumberValues": "error",
"useConsistentObjectKeys": "error",
"useVueBaseImport": "warn",
"useVueConsistentDefinePropsDeclaration": "off",
"useVueNextTickPromise": "warn",
"useVueValidVFor": "error"
},
"style": {
"noDescendingSpecificity": "off",
"noVueOptionsApi": "off",
"useVueConsistentVBindStyle": "off",
"useVueHyphenatedAttributes": "off",
"useVueMultiWordComponentNames": "off"
},
"suspicious": {
"noExplicitAny": "warn",
"noImportCycles": "off",
"noNestedPromises": "error",
"noParametersOnlyUsedInRecursion": "error",
"noShadow": "off",
"noUnnecessaryConditions": "off",
"useArraySortCompare": "error"
}
}
},
"overrides": [
{
"includes": ["tests/playwright/**"],
"linter": {
"rules": {
"correctness": {
"noEmptyPattern": "off",
"noUnresolvedImports": "off"
},
"nursery": {
"noPlaywrightElementHandle": "error",
"noPlaywrightEval": "error",
"noPlaywrightForceOption": "error",
"noPlaywrightMissingAwait": "error",
"noPlaywrightNetworkidle": "error",
"noPlaywrightPagePause": "error",
"noPlaywrightUselessAwait": "error",
"noPlaywrightWaitForNavigation": "error",
"noPlaywrightWaitForSelector": "error",
"noPlaywrightWaitForTimeout": "warn",
"usePlaywrightValidDescribeCallback": "error"
}
}
}
},
{
"includes": [
"scripts/postcss-strip-legacy.ts",
"playwright.config.ts",
"playwright.performance.config.ts",
"**/*.test.js",
"**/*.test.ts"
],
"linter": {
"rules": {
"correctness": {
"noUnresolvedImports": "off",
"noUndeclaredDependencies": "off"
}
}
}
}
]
}
+70
View File
@@ -0,0 +1,70 @@
import { defineConfig } from "eslint/config";
import * as tsParser from "@typescript-eslint/parser";
import pluginVue from "eslint-plugin-vue";
import vueI18n from "@intlify/eslint-plugin-vue-i18n";
export default defineConfig(
{ ignores: ["**/dist/**", "tests/playwright-files/**"] },
...pluginVue.configs["flat/essential"],
...vueI18n.configs.recommended,
// js/ts is parsed for vue-i18n to check t() calls
{ files: ["**/*.js", "**/*.ts"], languageOptions: { parser: tsParser } },
{ files: ["**/*.vue"], languageOptions: { parserOptions: { parser: tsParser } } },
{
settings: {
"vue-i18n": {
localeDir: "src/i18n/en.json",
messageSyntaxVersion: "^11.0.0",
},
},
rules: {
"@intlify/vue-i18n/no-missing-keys": "error",
"@intlify/vue-i18n/no-unused-keys": ["error", {
src: "./src",
extensions: [".js", ".vue", ".ts"],
ignores: ["/^languages\\./"],
}],
"@intlify/vue-i18n/no-raw-text": ["error", {
ignoreNodes: ["i", "v-icon"],
}],
"@intlify/vue-i18n/no-missing-keys-in-other-locales": "warn",
},
},
{
files: ["**/*.vue"],
rules: {
// this are the most common ones that likely biome also has
// we can add more to the list or if some if buggy in biome better enable it here.
"vue/no-duplicate-attributes": "off",
"vue/no-use-v-if-with-v-for": "off",
"vue/require-v-for-key": "off",
"vue/valid-template-root": "off",
"vue/valid-v-bind": "off",
"vue/valid-v-cloak": "off",
"vue/valid-v-else": "off",
"vue/valid-v-else-if": "off",
"vue/valid-v-for": "off",
"vue/valid-v-html": "off",
"vue/valid-v-if": "off",
"vue/valid-v-on": "off",
"vue/valid-v-once": "off",
"vue/valid-v-pre": "off",
"vue/valid-v-text": "off",
"vue/no-deprecated-v-on-number-modifiers": "off",
"vue/no-dupe-keys": "off",
"vue/no-reserved-keys": "off",
"vue/no-reserved-props": "off",
"vue/no-deprecated-data-object-declaration": "off",
"vue/no-arrow-functions-in-watch": "off",
"vue/no-ref-as-operand": "off",
"vue/prefer-import-from-vue": "off",
"vue/multi-word-component-names": "off",
"vue/no-reserved-component-names": "off",
"vue/no-parsing-error": "off",
"vue/no-unused-components": "warn",
"vue/no-v-text-v-html-on-component": "warn",
},
},
);
+2721 -780
View File
File diff suppressed because it is too large. Load diff
+41 -27
View File
@@ -4,7 +4,7 @@
"private": true,
"type": "module",
"engines": {
"npm": ">=10.9.0",
"npm": ">=9.0.0",
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
"scripts": {
@@ -13,27 +13,30 @@
"dev": "vite",
"watch": "vite build --watch",
"typecheck": "vue-tsc --build",
"lint": "biome check && npm run i18n:check",
"lint:fix": "biome check --write",
"lint": "biome check && eslint src/",
"lint:fix": "biome check --write && eslint --fix src/",
"lint:biome": "biome check",
"lint:biome:fix": "biome check --write",
"lint:eslint": "eslint src/",
"format": "biome format --write",
"i18n:check": "node scripts/i18n/index.ts check",
"i18n:check:strict": "node scripts/i18n/index.ts check --strict",
"i18n:types": "node scripts/i18n/index.ts types",
"i18n:sync": "node scripts/i18n/index.ts sync",
"i18n:cleanup": "node scripts/i18n/index.ts sync --cleanup",
"i18n:enforce-order": "node scripts/i18n/index.ts sync --enforce-order",
"lint:css": "stylelint \"**/*.{css,vue}\"",
"lint:css:fix": "stylelint --fix \"**/*.{css,vue}\"",
"i18n:sync": "node ./scripts/sync-translations.js",
"i18n:check": "node ./scripts/sync-translations.js --check",
"i18n:enforce-order": "node scripts/sync-translations.js --enforce-order",
"i18n:cleanup": "node scripts/sync-translations.js --cleanup",
"icons:sync": "node ./scripts/build-icon-subset.js",
"icons:check": "node ./scripts/build-icon-subset.js --check",
"test": "vitest run "
},
"dependencies": {
"@likecoin/epub-ts": "^0.7.4",
"@likecoin/epub-ts": "^0.7.3",
"@onlyoffice/document-editor-vue": "^1.7.0",
"ace-builds": "^1.45.2",
"chart.js": "^4.6.1",
"dompurify": "^3.4.18",
"dompurify": "^3.4.17",
"highlight.js": "^11.12.0",
"hls.js": "^1.7.4",
"hls.js": "^1.7.2",
"js-yaml": "^5.5.0",
"mammoth": "^1.13.0",
"marked": "^18.2.0",
@@ -42,10 +45,11 @@
"temml": "^0.14.0",
"three": "^0.187.0",
"vue": "^3.5.45",
"vue-i18n": "^11.4.20",
"vue-router": "^5.5.1"
"vue-i18n": "^11.4.19",
"vue-router": "^5.5.0"
},
"overrides": {
"stylelint-config-recommended": "^19.0.0",
"minimatch": "^11.0.8",
"@xmldom/xmldom": "^0.8.15",
"mammoth": {
@@ -54,24 +58,34 @@
"@intlify/vue-i18n-extensions": {
"vue-i18n": "$vue-i18n"
},
"glob": "^14.0.6"
"@intlify/eslint-plugin-vue-i18n": {
"glob": "^14.0.6"
}
},
"devDependencies": {
"@biomejs/biome": "2.6.8",
"@intlify/unplugin-vue-i18n": "^11.2.8",
"@playwright/test": "^1.65.1",
"@types/node": "^26.6.6",
"@vitejs/plugin-vue": "^6.0.11",
"deepl-node": "^1.29.0",
"@biomejs/biome": "2.5.15",
"@intlify/eslint-plugin-vue-i18n": "^4.5.1",
"@intlify/unplugin-vue-i18n": "^11.2.7",
"@playwright/test": "^1.64.1",
"@types/node": "^26.6.4",
"@typescript-eslint/parser": "^8.72.0",
"@vitejs/plugin-vue": "^6.0.10",
"deepl-node": "^1.28.1",
"esbuild": "^0.28.2",
"eslint": "^10.13.0",
"eslint-plugin-vue": "^10.11.1",
"fs-extra": "^11.4.1",
"jsdom": "^31.0.1",
"jsdom": "^30.1.3",
"stylelint": "^18.0.0",
"stylelint-config-standard": "^41.0.0",
"stylelint-config-standard-vue": "^2.0.0",
"typescript": "^6.0.3",
"vite": "^8.3.8",
"vite-plugin-checker": "^1.0.0",
"vite-plugin-compression2": "^2.5.4",
"vitest": "^5.1.0",
"vue-tsc": "^3.3.14",
"vite": "^8.3.4",
"vite-plugin-checker": "^0.14.5",
"vite-plugin-compression2": "^2.5.3",
"vitest": "^5.0.5",
"vue-eslint-parser": "^10.4.1",
"vue-tsc": "^3.3.13",
"wawoff2": "^2.0.1"
}
}
+2 -7
View File
@@ -50,7 +50,6 @@ server:
configured: false # true when explicitly set (allows intentional deny-all)
cacheDir: "tmp" # path to the cache directory, used for thumbnails and other cached files
cacheDirCleanup: false # whether to automatically cleanup the cache directory. Note: docker must also mount a persistent volume to persist the cache (default: false)
cacheDirMaxSizeMB: 0 # maximum size in MB of the preview cache (cacheDir/diskcache). Past it, the least recently used files are deleted. 0 means no limit (default: 0)
maxArchiveSize: 20 # maximum archive/unarchive size in GB. 0 means no limit. (default: 20)
filesystem: # filesystem settings
createFilePermission: "644" # Unix permissions like 644, 755, 2755 (default: 644) validate:required,file_permission
@@ -225,7 +224,6 @@ userDefaults: # optional signup/CLI defaults; per-us
uploadChunkSizeMb: 10
clearAll: false
downloadChunkSizeMb: 0
uploadStallTimeoutSeconds: 10 # seconds without progress before an upload is paused, 0 uses the default (10)
account:
permissions:
api: false # allow api access
@@ -298,12 +296,9 @@ http:
trustProxyHeaders: false # honor X-Forwarded-* and X-Real-IP from a reverse proxy (default: false)
trustedProxies: # IPs/CIDRs of trusted proxies; forwarded client headers are only honored when the socket peer matches one of these (default: empty = forwarded headers ignored)
unixSocketTrustedUIDs: # UnixSocketTrustedUIDs and UnixSocketTrustedGIDs list peer credentials (Linux SO_PEERCRED) allowed to
# present X-Forwarded-* on a filesystem http.socket listener. When both are empty, peers are not trusted
# unless UnixSocketTrustAllLocalPeers is true (legacy; startup logs a warning). A GID allowlist trusts
# every peer with that GID, not only a single reverse-proxy process. Abstract sockets (@name) never trust
# forwarded headers.
# present X-Forwarded-* on a filesystem http.socket listener. When both are empty, forwarded headers
# are not trusted on Unix sockets. Abstract sockets (@name) never trust forwarded headers.
unixSocketTrustedGIDs:
unixSocketTrustAllLocalPeers: false # default false: set true to trust forwarded headers from any local filesystem socket peer when allowlists are empty
socketFileMode: "" # octal mode for filesystem http.socket (default "0660"); ignored for abstract sockets
socketGroup: "" # optional group name or numeric gid for the socket file (filesystem sockets only)
disableRateLimit: false # turns off built-in auth route rate limiting and failed-login lockout (default false).
+198 -204
View File
@@ -11,13 +11,13 @@
/* -------------------------------------------------------------------------- */
.loader {
box-sizing: border-box;
margin: 0 auto;
border: none;
overflow: visible;
position: relative;
display: block;
border-radius: 50%;
box-sizing: border-box;
margin: 0 auto;
border: none;
overflow: visible;
position: relative;
display: block;
border-radius: 50%;
}
/* -------------------------------------------------------------------------- */
@@ -26,33 +26,33 @@
/* -------------------------------------------------------------------------- */
.loader__comet {
pointer-events: none;
position: absolute;
inset: 0;
display: block;
direction: ltr;
/* The concrete fallback keeps the spinner visible before the app stylesheet loads,
pointer-events: none;
position: absolute;
inset: 0;
display: block;
direction: ltr;
/* The concrete fallback keeps the spinner visible before the app stylesheet loads,
when neither --spinner-color nor --primaryColor is defined (initial index.html shell). */
background-color: var(--spinner-color, var(--primaryColor, #2196f3));
/* Mirrored annulus-sector polygon, 120° sweep, viewBox 0 0 100 100 */
--fb-loader-taper-mask: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20100%20100%22%3E%3Cpath%20fill%3D%22black%22%20d%3D%22M57.47%2C7.65%20L54.99%2C7.29%20L52.50%2C7.07%20L50.00%2C7.00%20L47.50%2C7.07%20L45.01%2C7.29%20L42.53%2C7.65%20L40.08%2C8.16%20L37.67%2C8.81%20L35.29%2C9.59%20L32.97%2C10.52%20L30.70%2C11.57%20L28.50%2C12.76%20L26.37%2C14.07%20L24.32%2C15.51%20L22.36%2C17.06%20L20.49%2C18.72%20L18.72%2C20.49%20L17.06%2C22.36%20L15.51%2C24.32%20L14.07%2C26.37%20L12.76%2C28.50%20L11.57%2C30.70%20L10.52%2C32.97%20L9.59%2C35.29%20L8.81%2C37.67%20L8.16%2C40.08%20L7.65%2C42.53%20L7.29%2C45.01%20L7.07%2C47.50%20L7.00%2C50.00%20L7.07%2C52.50%20L7.29%2C54.99%20L7.65%2C57.47%20L8.16%2C59.92%20L8.81%2C62.33%20L9.59%2C64.71%20L10.16%2C64.50%20L9.56%2C62.11%20L9.12%2C59.69%20L8.81%2C57.26%20L8.65%2C54.83%20L8.63%2C52.41%20L8.75%2C50.00%20L9.01%2C47.61%20L9.41%2C45.26%20L9.94%2C42.94%20L10.61%2C40.66%20L11.40%2C38.44%20L12.32%2C36.28%20L13.36%2C34.19%20L14.51%2C32.18%20L15.77%2C30.24%20L17.14%2C28.39%20L18.60%2C26.63%20L20.16%2C24.96%20L21.81%2C23.40%20L23.53%2C21.95%20L25.33%2C20.60%20L27.20%2C19.37%20L29.12%2C18.26%20L31.10%2C17.26%20L33.12%2C16.39%20L35.18%2C15.64%20L37.27%2C15.02%20L39.38%2C14.52%20L41.50%2C14.15%20L43.64%2C13.91%20L45.77%2C13.79%20L47.89%2C13.79%20L50.00%2C13.92%20L52.09%2C14.18%20L54.14%2C14.55%20L56.16%2C15.04Z%22%2F%3E%3C%2Fsvg%3E");
background-color: var(--spinner-color, var(--primaryColor, #2196f3));
/* Mirrored annulus-sector polygon, 120° sweep, viewBox 0 0 100 100 */
--fb-loader-taper-mask: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20100%20100%22%3E%3Cpath%20fill%3D%22black%22%20d%3D%22M57.47%2C7.65%20L54.99%2C7.29%20L52.50%2C7.07%20L50.00%2C7.00%20L47.50%2C7.07%20L45.01%2C7.29%20L42.53%2C7.65%20L40.08%2C8.16%20L37.67%2C8.81%20L35.29%2C9.59%20L32.97%2C10.52%20L30.70%2C11.57%20L28.50%2C12.76%20L26.37%2C14.07%20L24.32%2C15.51%20L22.36%2C17.06%20L20.49%2C18.72%20L18.72%2C20.49%20L17.06%2C22.36%20L15.51%2C24.32%20L14.07%2C26.37%20L12.76%2C28.50%20L11.57%2C30.70%20L10.52%2C32.97%20L9.59%2C35.29%20L8.81%2C37.67%20L8.16%2C40.08%20L7.65%2C42.53%20L7.29%2C45.01%20L7.07%2C47.50%20L7.00%2C50.00%20L7.07%2C52.50%20L7.29%2C54.99%20L7.65%2C57.47%20L8.16%2C59.92%20L8.81%2C62.33%20L9.59%2C64.71%20L10.16%2C64.50%20L9.56%2C62.11%20L9.12%2C59.69%20L8.81%2C57.26%20L8.65%2C54.83%20L8.63%2C52.41%20L8.75%2C50.00%20L9.01%2C47.61%20L9.41%2C45.26%20L9.94%2C42.94%20L10.61%2C40.66%20L11.40%2C38.44%20L12.32%2C36.28%20L13.36%2C34.19%20L14.51%2C32.18%20L15.77%2C30.24%20L17.14%2C28.39%20L18.60%2C26.63%20L20.16%2C24.96%20L21.81%2C23.40%20L23.53%2C21.95%20L25.33%2C20.60%20L27.20%2C19.37%20L29.12%2C18.26%20L31.10%2C17.26%20L33.12%2C16.39%20L35.18%2C15.64%20L37.27%2C15.02%20L39.38%2C14.52%20L41.50%2C14.15%20L43.64%2C13.91%20L45.77%2C13.79%20L47.89%2C13.79%20L50.00%2C13.92%20L52.09%2C14.18%20L54.14%2C14.55%20L56.16%2C15.04Z%22%2F%3E%3C%2Fsvg%3E");
mask-image: var(--fb-loader-taper-mask);
mask-size: contain;
mask-repeat: no-repeat;
mask-position: center;
transform-origin: 50% 50%;
transform-box: fill-box;
animation: fb-spinner-rotation var(--animation-duration, 1s) linear infinite;
mask-image: var(--fb-loader-taper-mask);
mask-size: contain;
mask-repeat: no-repeat;
mask-position: center;
transform-origin: 50% 50%;
transform-box: fill-box;
animation: fb-spinner-rotation var(--animation-duration, 1s) linear infinite;
}
@keyframes fb-spinner-rotation {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
/* -------------------------------------------------------------------------- */
@@ -60,23 +60,23 @@
/* -------------------------------------------------------------------------- */
.loader--xsmall {
width: 12px;
height: 12px;
width: 12px;
height: 12px;
}
.loader--small {
width: 24px;
height: 24px;
width: 24px;
height: 24px;
}
.loader--medium {
width: 48px;
height: 48px;
width: 48px;
height: 48px;
}
.loader--large {
width: 96px;
height: 96px;
width: 96px;
height: 96px;
}
/* -------------------------------------------------------------------------- */
@@ -84,59 +84,59 @@
/* -------------------------------------------------------------------------- */
body > .loader {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
transition: 0.1s ease opacity;
pointer-events: none;
border: none;
animation: none;
border-radius: 0;
margin: 0;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
transition: 0.1s ease opacity;
pointer-events: none;
border: none;
animation: none;
border-radius: 0;
margin: 0;
}
body > .loader.loader--xsmall,
body > .loader.loader--small,
body > .loader.loader--medium,
body > .loader.loader--large {
width: 100%;
height: 100%;
width: 100%;
height: 100%;
}
body > .loader .loader__comet {
position: relative;
inset: auto;
flex-shrink: 0;
position: relative;
inset: auto;
flex-shrink: 0;
}
body > .loader.loader--xsmall .loader__comet {
width: 12px;
height: 12px;
width: 12px;
height: 12px;
}
body > .loader.loader--small .loader__comet {
width: 24px;
height: 24px;
width: 24px;
height: 24px;
}
body > .loader.loader--medium .loader__comet {
width: 48px;
height: 48px;
width: 48px;
height: 48px;
}
body > .loader.loader--large .loader__comet {
width: 96px;
height: 96px;
width: 96px;
height: 96px;
}
body > .loader.done {
opacity: 0;
opacity: 0;
}
/* -------------------------------------------------------------------------- */
@@ -144,21 +144,21 @@ body > .loader.done {
/* -------------------------------------------------------------------------- */
.loader--pulse {
border: none;
background: var(--spinner-color, var(--primaryColor, #2196f3));
animation: fb-pulse-scale var(--animation-duration, 0.75s) ease infinite;
border: none;
background: var(--spinner-color, var(--primaryColor, #2196f3));
animation: fb-pulse-scale var(--animation-duration, 0.75s) ease infinite;
}
@keyframes fb-pulse-scale {
0%,
100% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(0.95);
opacity: 0.8;
}
0%,
100% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(0.95);
opacity: 0.8;
}
}
/* -------------------------------------------------------------------------- */
@@ -166,88 +166,86 @@ body > .loader.done {
/* -------------------------------------------------------------------------- */
.loader--bounce {
display: flex;
align-items: center;
justify-content: center;
gap: 0.3em;
border: none;
background: transparent;
animation: none;
display: flex;
align-items: center;
justify-content: center;
gap: 0.3em;
border: none;
background: transparent;
animation: none;
}
.loader--bounce::before,
.loader--bounce::after {
content: "";
width: 0.6em;
height: 0.6em;
/* The concrete fallback keeps the spinner visible before the app stylesheet loads,
content: "";
width: 0.6em;
height: 0.6em;
/* The concrete fallback keeps the spinner visible before the app stylesheet loads,
when neither --spinner-color nor --primaryColor is defined (initial index.html shell). */
background-color: var(--spinner-color, var(--primaryColor, #2196f3));
border-radius: 50%;
display: inline-block;
animation: fb-bounce-scale var(--animation-duration, 0.75s) infinite
ease-in-out both;
background-color: var(--spinner-color, var(--primaryColor, #2196f3));
border-radius: 50%;
display: inline-block;
animation: fb-bounce-scale var(--animation-duration, 0.75s) infinite ease-in-out both;
}
.loader--bounce::before {
animation-delay: -0.32s;
animation-delay: -0.32s;
}
.loader--bounce::after {
animation-delay: -0.16s;
animation-delay: -0.16s;
}
.loader--bounce .bounce-dot {
width: 0.6em;
height: 0.6em;
/* The concrete fallback keeps the spinner visible before the app stylesheet loads,
width: 0.6em;
height: 0.6em;
/* The concrete fallback keeps the spinner visible before the app stylesheet loads,
when neither --spinner-color nor --primaryColor is defined (initial index.html shell). */
background-color: var(--spinner-color, var(--primaryColor, #2196f3));
border-radius: 50%;
display: inline-block;
animation: fb-bounce-scale var(--animation-duration, 0.75s) infinite
ease-in-out both;
background-color: var(--spinner-color, var(--primaryColor, #2196f3));
border-radius: 50%;
display: inline-block;
animation: fb-bounce-scale var(--animation-duration, 0.75s) infinite ease-in-out both;
}
@keyframes fb-bounce-scale {
0%,
80%,
100% {
transform: scale(0);
opacity: 0.5;
}
40% {
transform: scale(1);
opacity: 1;
}
0%,
80%,
100% {
transform: scale(0);
opacity: 0.5;
}
40% {
transform: scale(1);
opacity: 1;
}
}
.loader--bounce.loader--xsmall::before,
.loader--bounce.loader--xsmall::after,
.loader--bounce.loader--xsmall .bounce-dot {
width: 0.3em;
height: 0.3em;
width: 0.3em;
height: 0.3em;
}
.loader--bounce.loader--small::before,
.loader--bounce.loader--small::after,
.loader--bounce.loader--small .bounce-dot {
width: 0.45em;
height: 0.45em;
width: 0.45em;
height: 0.45em;
}
.loader--bounce.loader--medium::before,
.loader--bounce.loader--medium::after,
.loader--bounce.loader--medium .bounce-dot {
width: 0.6em;
height: 0.6em;
width: 0.6em;
height: 0.6em;
}
.loader--bounce.loader--large::before,
.loader--bounce.loader--large::after,
.loader--bounce.loader--large .bounce-dot {
width: 0.9em;
height: 0.9em;
width: 0.9em;
height: 0.9em;
}
/* -------------------------------------------------------------------------- */
@@ -255,106 +253,102 @@ body > .loader.done {
/* -------------------------------------------------------------------------- */
.loader--placeholder {
display: flex;
flex-direction: column;
gap: 0.5em;
border: none;
animation: none;
width: auto;
height: auto;
border-radius: 0;
display: flex;
flex-direction: column;
gap: 0.5em;
border: none;
animation: none;
width: auto;
height: auto;
border-radius: 0;
}
.placeholder-item {
background-color: rgb(128 128 128 / 10%);
animation:
fb-placeholder-ripple 1.8s cubic-bezier(0.25, 0.46, 0.45, 0.94) infinite,
fb-placeholder-bg-fade 2s ease-in-out infinite;
display: block;
border-radius: 0.25em;
margin: 0;
padding: 0;
transition:
transform 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94),
box-shadow 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
background-color: rgb(128 128 128 / 10%);
animation: fb-placeholder-ripple 1.8s cubic-bezier(0.25, 0.46, 0.45, 0.94) infinite,
fb-placeholder-bg-fade 2s ease-in-out infinite;
display: block;
border-radius: 0.25em;
margin: 0;
padding: 0;
transition: transform 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94),
box-shadow 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
.placeholder-item-1 {
animation-delay: 0s;
animation-delay: 0s;
}
.placeholder-item-2 {
animation-delay: 0.36s;
animation-delay: 0.36s;
}
.placeholder-item-3 {
animation-delay: 0.72s;
animation-delay: 0.72s;
}
@keyframes fb-placeholder-ripple {
0% {
transform: scale(1);
box-shadow: none;
opacity: 0.3;
}
25% {
transform: scale(1.07);
box-shadow:
inset 0 -3em 3em rgb(172 172 172 / 21.1%),
0 0 0 2px var(--alt-background),
0 4px 12px rgb(0 0 0 / 15%);
opacity: 0.6;
}
50% {
transform: scale(0.97);
box-shadow: none;
opacity: 0.3;
}
100% {
transform: scale(1);
box-shadow: none;
opacity: 0.3;
}
0% {
transform: scale(1);
box-shadow: none;
opacity: 0.3;
}
25% {
transform: scale(1.07);
box-shadow: inset 0 -3em 3em rgb(172 172 172 / 21.1%),
0 0 0 2px var(--alt-background), 0 4px 12px rgb(0 0 0 / 15%);
opacity: 0.6;
}
50% {
transform: scale(0.97);
box-shadow: none;
opacity: 0.3;
}
100% {
transform: scale(1);
box-shadow: none;
opacity: 0.3;
}
}
@keyframes fb-placeholder-bg-fade {
0% {
background-color: rgb(128 128 128 / 10%);
}
50% {
background-color: rgb(128 128 128 / 40%);
}
100% {
background-color: rgb(128 128 128 / 10%);
}
0% {
background-color: rgb(128 128 128 / 10%);
}
50% {
background-color: rgb(128 128 128 / 40%);
}
100% {
background-color: rgb(128 128 128 / 10%);
}
}
.loader--placeholder.loader--xsmall .placeholder-item {
width: 30px;
height: 7.5px;
min-width: 30px;
min-height: 7.5px;
width: 30px;
height: 7.5px;
min-width: 30px;
min-height: 7.5px;
}
.loader--placeholder.loader--small .placeholder-item {
width: 150px;
height: 12.5px;
min-width: 150px;
min-height: 12.5px;
width: 150px;
height: 12.5px;
min-width: 150px;
min-height: 12.5px;
}
.loader--placeholder.loader--medium .placeholder-item {
width: 200px;
height: 25px;
min-width: 200px;
min-height: 25px;
width: 200px;
height: 25px;
min-width: 200px;
min-height: 25px;
}
.loader--placeholder.loader--large .placeholder-item {
width: 400px;
height: 50px;
min-width: 400px;
min-height: 50px;
width: 400px;
height: 50px;
min-width: 400px;
min-height: 50px;
}
/* -------------------------------------------------------------------------- */
@@ -362,10 +356,10 @@ body > .loader.done {
/* -------------------------------------------------------------------------- */
@media (width <= 768px) {
.loader--placeholder.loader--large .placeholder-item {
width: 100%;
min-width: auto;
}
.loader--placeholder.loader--large .placeholder-item {
width: 100%;
min-width: auto;
}
}
/* -------------------------------------------------------------------------- */
@@ -375,12 +369,12 @@ body > .loader.done {
/* Honor the OS "reduce motion" preference: stop the rotation, pulse, bounce,
and placeholder shimmer. The spinner stays visible as a static shape. */
@media (prefers-reduced-motion: reduce) {
.loader__comet,
.loader--pulse,
.loader--bounce::before,
.loader--bounce::after,
.loader--bounce .bounce-dot,
.placeholder-item {
animation: none;
}
.loader__comet,
.loader--pulse,
.loader--bounce::before,
.loader--bounce::after,
.loader--bounce .bounce-dot,
.placeholder-item {
animation: none;
}
}
+4 -3
View File
@@ -1,3 +1,4 @@
/* `--background` is intentionally set here as a placeholder for stylelint */
:root {
--background: #f5f5f5;
--alt-background: #ddd;
@@ -11,10 +12,10 @@
}
.dark-mode {
--background: #141d24;
--background: #141D24;
--alt-background: #283136;
--surfacePrimary: #20292f;
--surfaceSecondary: #3a4147;
--surfacePrimary: #20292F;
--surfaceSecondary: #3A4147;
--divider: rgb(255 255 255 / 12%);
--textPrimary: rgb(255 255 255 / 87%);
--textSecondary: rgb(255 255 255 / 60%);
-10
View File
@@ -1,10 +0,0 @@
language css;
`$prop: $value` where {
$prop <: r"^(?:-ms-.*|-moz-osx-font-smoothing)$",
register_diagnostic(
span = $prop,
message = "Don't use vendor legacy properties",
severity = "warn"
)
}
+2 -2
View File
@@ -142,7 +142,7 @@ function scanMimetype(icons) {
}
function scanConstants(icons) {
const content = fs.readFileSync(path.join(srcDir, 'utils/constants.ts'), 'utf8');
const content = fs.readFileSync(path.join(srcDir, 'utils/constants.js'), 'utf8');
const iconField = new RegExp(`\\bicon:\\s*["'](${ICON_NAME})["']`, 'g');
for (const match of content.matchAll(iconField)) addIcon(icons, match[1]);
}
@@ -185,7 +185,7 @@ function collectIcons() {
scanSearchFilters(icons);
scanMarkdownViewer(icons);
icons.delete('close_back');
return [...icons].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
return [...icons].sort();
}
function readInventory() {
@@ -1,333 +0,0 @@
/** biome-ignore-all lint/suspicious/noTemplateCurlyInString: the tests need it */
import fs from "node:fs";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { maskJs, maskSource } from "../shared.ts";
import { syncTranslations } from "../sync.ts";
import { checkCall, dynamicCalls, isPassedAround, literalCalls } from "../types.ts";
// The sync reads and writes the locales folder: point it at a temporary one.
const dir = await vi.hoisted(async () => {
const { mkdtempSync } = await import("node:fs");
const { tmpdir } = await import("node:os");
const { join } = await import("node:path");
return mkdtempSync(join(tmpdir(), "i18n-test-"));
});
vi.mock("../shared.ts", async (importOriginal) => {
const actual = await importOriginal<typeof import("../shared.ts")>();
const { readdirSync } = await import("node:fs");
return {
...actual,
localesDir: dir,
translationFiles: () => readdirSync(dir).filter((file) => file.endsWith(".json") && file !== "en.json").sort(),
};
});
vi.mock("deepl-node", () => ({
DeepLClient: class {
async translateText(text: string) {
return { text: `[${text}]` };
}
},
}));
const write = (file: string, content: unknown) => fs.writeFileSync(path.join(dir, file), JSON.stringify(content));
const read = (file: string): unknown => JSON.parse(fs.readFileSync(path.join(dir, file), "utf8"));
describe("sync with a different shape in a locale", () => {
beforeEach(() => {
process.env.DEEPL_API_KEY = "test-key";
vi.spyOn(console, "log").mockImplementation(() => {});
vi.spyOn(console, "warn").mockImplementation(() => {});
});
afterEach(() => {
vi.restoreAllMocks();
for (const file of fs.readdirSync(dir)) fs.rmSync(path.join(dir, file));
});
const run = (options: { enforceOrder?: boolean; cleanup?: boolean } = {}) =>
syncTranslations({ enforceOrder: false, cleanup: false, ...options });
describe("an object where en.json has a string", () => {
beforeEach(() => {
write("en.json", { general: { title: "Title" } });
write("de.json", { general: { title: { old: "Alt" } } });
});
it("replaces the subtree with a translation", async () => {
expect(await run()).toBe(0);
expect(read("de.json")).toEqual({ general: { title: "[Title]" } });
});
it("removes the obsolete subtree on cleanup", async () => {
expect(await run({ cleanup: true })).toBe(0);
expect(read("de.json")).toEqual({ general: {} });
});
it("removes the obsolete subtree when enforcing the order", async () => {
expect(await run({ enforceOrder: true })).toBe(0);
expect(read("de.json")).toEqual({ general: {} });
});
});
describe("a string where en.json has an object", () => {
beforeEach(() => {
write("en.json", { group: { a: "A" } });
write("de.json", { group: "legacy" });
});
it("replaces the string with the translated keys", async () => {
await run();
expect(read("de.json")).toEqual({ group: { a: "[A]" } });
});
it("removes the obsolete string on cleanup", async () => {
await run({ cleanup: true });
expect(read("de.json")).toEqual({});
});
});
});
describe("maskJs", () => {
it("blanks comments and keeps every offset and newline", () => {
const code = `a(); // t("x")\n/* t("y")\n */ b();`;
const masked = maskJs(code);
expect(masked).toHaveLength(code.length);
expect(masked).not.toContain("t(");
expect(masked.split("\n")).toHaveLength(3);
expect(masked).toContain("a();");
expect(masked).toContain("b();");
});
it("keeps `//` inside strings", () => {
expect(maskJs(`const u = "https://example.com"; t("k");`)).toContain("https://example.com");
});
it("blanks the content of quoted strings only on request, and keeps template literals", () => {
const code = `x("a 't(' b", 'c'); y(\`\${t("k")}\`);`;
const bare = maskJs(code, true);
expect(bare).toHaveLength(code.length);
expect(bare).not.toContain("a 't(' b");
expect(bare).toContain('t(" ")');
expect(maskJs(code)).toContain("a 't(' b");
});
it("does not take an apostrophe left open on a line for a string", () => {
expect(maskJs(`don't\nt("k")`, true)).toContain('t("');
});
it("does not take a quote in a regex literal for the start of a string", () => {
const code = `const quote = /"/; t("k");`;
const bare = maskJs(code, true);
expect(bare).toHaveLength(code.length);
expect(bare).toContain('t("');
expect(maskJs(`const a = /[/"]+/g; t("k");`, true)).toContain('t("');
});
it("keeps a division as a division", () => {
expect(maskJs(`const a = (b / 2) + c / 4; t("k"); // x`, true)).toContain('t("');
expect(maskJs(`const a = b / "x" / c; t('k');`, true)).toContain("t('");
});
});
describe("maskJs with template literals", () => {
const masked = (code: string) => maskJs(code, true);
it("template literal keeps its ${} expressions", () => {
const code = 'const example = `t("example.only") ${t("real.key")} end`;';
const bare = masked(code);
expect(bare).toHaveLength(code.length);
expect(bare).not.toContain("example.only");
expect(bare).toContain('t(" ")');
expect(bare.startsWith("const example = `")).toBe(true);
expect(bare.endsWith("`;")).toBe(true);
});
it("keeps the text of a template literal when the strings are not masked", () => {
const code = 'const example = `t("example.only") ${t("real.key")}`; // t("c.d")';
const plain = maskJs(code);
expect(plain).toContain('`t("example.only") ${t("real.key")}`');
expect(plain).not.toContain("c.d");
});
it("keeps the offsets and the newlines of a template literal that spans lines", () => {
const code = "const a = `first t(\"x.y\")\nsecond ${\n t(\"real.key\")\n} third`;\nb();";
const bare = masked(code);
expect(bare).toHaveLength(code.length);
expect(bare.split("\n")).toHaveLength(code.split("\n").length);
expect(bare.indexOf('t(" ")')).toBe(code.indexOf('t("real.key")'));
expect(bare).not.toContain("x.y");
expect(bare).toContain("b();");
});
it("does not take `//` or `/*` in the text of a template for a comment", () => {
const code = "const u = `https://example.com/*path*/` + t('k');";
expect(maskJs(code)).toBe(code);
expect(masked(code)).toMatch(/` \+ t\(' '\);$/);
});
it("masks a comment inside an expression and the text of a template nested in it", () => {
const code = "`${ /* t('c.d') */ cond ? `t(\"nested.text\")` : t('real.key') }`";
const bare = masked(code);
expect(bare).toHaveLength(code.length);
expect(bare).not.toContain("c.d");
expect(bare).not.toContain("nested.text");
expect(bare).toContain("t(' ')");
});
it("closes an expression at its own brace, not at the brace of an object inside it", () => {
const code = "`a ${ fn({ x: 1 }) } t(\"after.only\") ${ t('real.key') }`";
const bare = masked(code);
expect(bare).not.toContain("after.only");
expect(bare).toContain("t(' ')");
});
it("treats an escaped `${` and an escaped backtick as text", () => {
const code = "`\\${t('escaped.key')} \\` t('after.escape')` + t('real.key')";
const bare = masked(code);
expect(bare).toHaveLength(code.length);
expect(bare).not.toContain("escaped.key");
expect(bare).not.toContain("after.escape");
expect(bare).toMatch(/` \+ t\(' +'\)$/);
});
it("copes with a template or an expression that is never closed", () => {
for (const code of ["const a = `t('x.y')", "const a = `${t('x.y')", "const a = `trailing \\"]) {
expect(masked(code)).toHaveLength(code.length);
expect(maskJs(code)).toHaveLength(code.length);
}
});
});
describe("maskSource for .vue files", () => {
const vue = [
"<template>",
" <!-- {{ t('a.b') }} -->",
" <p>{{ t('c.d') }}</p>",
"</template>",
'<script setup lang="ts">',
"// t('e.f')",
"const x = t('g.h');",
"</script>",
"<style>",
".a::after { content: 't(\"i.j\")'; }",
"</style>",
].join("\n");
it("drops comments and styles but keeps the template and script code at the same offsets", () => {
const masked = maskSource("A.vue", vue);
expect(masked).toHaveLength(vue.length);
for (const dropped of ["a.b", "e.f", "i.j"]) expect(masked).not.toContain(dropped);
for (const kept of ["c.d", "g.h"]) expect(masked.indexOf(kept)).toBe(vue.indexOf(kept));
});
it("blanks the strings inside template expressions in the bare output only, and keeps the calls and the attributes", () => {
const source = [
"<template>",
" <p :title=\"t('real.title', { v: 'x' })\" class=\"it's\">{{ t('real.key', { value: \"t('example.only')\" }) }}</p>",
"</template>",
].join("\n");
const bare = maskSource("A.vue", source, true);
expect(bare).toHaveLength(source.length);
expect(bare).not.toContain("example.only");
expect(bare).toContain(":title=\"t('");
expect(bare).toContain('class="it\'s">{{ t(\'');
expect(maskSource("A.vue", source)).toContain("example.only");
const text = maskSource("A.vue", source);
expect([...literalCalls(text, bare)].map((call) => call.key)).toEqual(["real.title", "real.key"]);
});
});
describe("literalCalls", () => {
const calls = (source: string) => [...literalCalls(maskJs(source), maskJs(source, true))];
it("reads a parameter that holds an escaped quote", () => {
const [call] = calls(`t("prompts.uploadSkipped", { count: "a\\"b".length })`);
expect(call?.params).toEqual({ names: new Set(["count"]), dynamic: false });
});
it("skips a key that is concatenated with an expression", () => {
expect(calls(`t('prompts.' + name)`)).toEqual([]);
expect(calls(`t("a" + b, { x: 1 })`)).toEqual([]);
});
it("ignores calls in comments and strings, and finds those in template literals", () => {
const found = calls(`// t('example.key')\nconst s = "t('example.str')";\nconst u = \`\${t("real.key")}\`;`);
expect(found.map((call) => call.key)).toEqual(["real.key"]);
});
it("does not check the text of a template literal as a call", () => {
expect(calls('const example = `t("example.only")`;')).toEqual([]);
expect(calls('const example = `see t("example.only") and ${t("real.key")}`;').map((call) => call.key)).toEqual(["real.key"]);
});
it("finds a call in an expression nested in a template, not in the template nested in that", () => {
const found = calls("const a = `${ cond ? `t('nested.text')` : t('real.key', { count: 1 }) }`;");
expect(found.map((call) => call.key)).toEqual(["real.key"]);
});
it("finds the call after a regex literal that holds a quote", () => {
const [call] = calls(`const quote = /"/; t("missing.key");`);
expect(call?.key).toBe("missing.key");
expect(call && checkCall(call.key, call.params, {})).toEqual(['unknown translation key "missing.key"']);
});
it("is not confused by a comment in the params", () => {
const [call] = calls(`t("k", { count, /* it's */ other })`);
expect(call?.params.names).toEqual(new Set(["count", "other"]));
});
});
describe("dynamicCalls", () => {
const dynamic = (source: string) => [...dynamicCalls(maskJs(source), maskJs(source, true))].map((call) => call.index);
it("flags a key held in a variable or a property", () => {
expect(dynamic("t(key)")).toEqual([0]);
expect(dynamic("this.$t(tool.name)")).toEqual([0]);
expect(dynamic("i18n.global.t(i18nKey || 'a.b')")).toEqual([0]);
});
it("flags a key built from a template literal or a concatenation", () => {
expect(dynamic("t(`tools.${view}View`)")).toEqual([0]);
expect(dynamic("$t('prompts.' + name)")).toEqual([0]);
expect(dynamic("t(`a.b` + suffix)")).toEqual([0]);
});
it("flags a dynamic key whatever its params are", () => {
expect(dynamic('$t(section.label, { suffix: "" })')).toEqual([0]);
});
it("accepts string literals, with or without params", () => {
expect(dynamic("this.$t (\"a.b\")")).toEqual([]);
expect(dynamic("t('a.b')")).toEqual([]);
expect(dynamic('$t("a.b", { count: n })')).toEqual([]);
expect(dynamic("t(`a.b`)")).toEqual([]);
expect(dynamic("this.$t( 'a.b' )")).toEqual([]);
});
it("ignores calls in comments and strings, and names that only end in t", () => {
expect(dynamic('// t(key)\nconst s = "t(key)";')).toEqual([]);
expect(dynamic("list.insert(key); sort(key); a.t(key)")).toEqual([]);
});
it("finds a dynamic call inside a template expression and reports each call", () => {
expect(dynamic("const a = `${t(key)}`;")).toEqual([13]);
expect(dynamic("t(a); t('ok.key'); $t(b)")).toEqual([0, 19]);
});
});
describe("isPassedAround", () => {
it("flags $t used as a value", () => {
expect(isPassedAround("return buildRows(this.info, this.$t, locale);")).toBe(true);
expect(isPassedAround("this.$t.bind(this)")).toBe(true);
expect(isPassedAround("export function label(value, $t) {")).toBe(true);
});
it("accepts calls and unrelated names", () => {
expect(isPassedAround('return this.$t("a.b");')).toBe(false);
expect(isPassedAround("$t ('a.b')")).toBe(false);
expect(isPassedAround("const $total = 1; const a$t = 2;")).toBe(false);
});
});
-116
View File
@@ -1,116 +0,0 @@
import fs from "node:fs";
import { parse } from "vue/compiler-sfc";
import { locales } from "../../src/i18n/locales.ts";
import { isTestFile, maskSource, readLocale, rel, sourceFiles, translationFiles } from "./shared.ts";
const IGNORED_ELEMENTS = new Set(["i", "v-icon", "kbd"]);
const IGNORE_COMMENT = "i18n-ignore";
const TEXT_ATTRIBUTES = new Set(["placeholder", "title", "alt"]);
// Vue's NodeTypes values
const ELEMENT = 1;
const TEXT = 2;
const COMMENT = 3;
export const INTERPOLATION = 5;
const ATTRIBUTE = 6;
const DIRECTIVE = 7;
interface TemplateNode {
type: number;
tag?: string;
content?: unknown;
props?: {
type?: number;
name?: string;
value?: { content: string };
arg?: { content?: string; isStatic?: boolean };
exp?: { content?: string };
loc?: { start: { line: number } };
}[];
children?: TemplateNode[];
loc: { start: { line: number } };
}
/** The code of a source file that can use a key -- comments and <style> blocks are dropped */
const codeOf = (file: string) => maskSource(file, fs.readFileSync(file, "utf8"));
/** Every key in en.json must appear as a string literal in src/ */
export function checkUnusedKeys(): string[] {
const code = [...sourceFiles()].filter((file) => !isTestFile(file)).map(codeOf).join("\n");
const isUsed = (key: string) => ["'", '"', "`"].some((quote) => code.includes(`${quote}${key}${quote}`));
return Object.keys(readLocale("en.json"))
.filter((key) => !isUsed(key))
.map((key) => `en.json: unused key ${key}`);
}
export function checkLocaleRegistry(): string[] {
const files = new Set(["en.json", ...translationFiles()]);
const listed = new Set(Object.values(locales).map(({ file }) => `${file}.json`));
return [
...[...files].filter((file) => !listed.has(file)).map((file) => `${file}: not listed in src/i18n/locales.ts`),
...Object.entries(locales)
.filter(([, { file }]) => !files.has(`${file}.json`))
.map(([id, { file }]) => `locales.ts: ${id} has no file ${file}.json`),
];
}
const isIgnored = (node: TemplateNode) =>
IGNORED_ELEMENTS.has(node.tag ?? "") ||
(node.props ?? []).some((prop) => prop.name === "class" && prop.value?.content.includes("material-symbols"));
const TRANSLATION_CALL = /^\$?t\(.*\)$/s;
function rawAttributeMessage(name: string, value: string): string {
const text = value.trim();
if (TRANSLATION_CALL.test(text)) {
return `${name}="${text}" is a plain string, not a translation, add a colon: :${name}="${text}"`;
}
return `raw ${name} "${text}", use t()`;
}
function stringLiteralOf(expression: string): string | null {
const match = /^\s*(?:'((?:[^'\\\n]|\\['\\])*)'|"((?:[^"\\\n]|\\["\\])*)"|`((?:[^`$\\]|\\[`$\\])*)`)\s*$/.exec(expression);
const text = match ? (match[1] ?? match[2] ?? match[3] ?? "") : null;
return text === null ? null : text.replace(/\\(['"`$\\])/g, "$1");
}
const hasLetters = (text: string) => /\p{L}/u.test(text);
/** Templates shouldn't have plain text, to ignore them we can use <!-- i18n-ignore --> */
export function checkRawText(): string[] {
const problems: string[] = [];
for (const file of sourceFiles()) {
if (!file.endsWith(".vue")) continue;
const ast = parse(fs.readFileSync(file, "utf8"), { filename: file }).descriptor.template?.ast;
const walk = (node: TemplateNode) => {
for (const prop of node.type === ELEMENT ? (node.props ?? []) : []) {
const line = prop.loc?.start.line ?? node.loc.start.line;
if (prop.type === ATTRIBUTE && TEXT_ATTRIBUTES.has(prop.name ?? "") && hasLetters(prop.value?.content ?? "")) {
problems.push(`${rel(file)}:${line}: ${rawAttributeMessage(prop.name ?? "", prop.value?.content ?? "")}`);
} else if (prop.type === DIRECTIVE && prop.name === "bind" && prop.arg?.isStatic && TEXT_ATTRIBUTES.has(prop.arg.content ?? "")) {
const literal = stringLiteralOf(prop.exp?.content ?? "");
if (literal !== null && hasLetters(literal)) {
problems.push(`${rel(file)}:${line}: raw ${prop.arg.content} "${literal.trim()}" bound as a string, use t()`);
}
}
}
if (node.type === ELEMENT && isIgnored(node)) return;
if (node.type === INTERPOLATION) {
const literal = stringLiteralOf((node.content as { content?: string } | undefined)?.content ?? "");
if (literal !== null && hasLetters(literal)) problems.push(`${rel(file)}:${node.loc.start.line}: raw text "${literal.trim()}" in {{ }}, use t()`);
}
if (node.type === TEXT && typeof node.content === "string" && /\p{L}/u.test(node.content)) {
problems.push(`${rel(file)}:${node.loc.start.line}: raw text "${node.content.trim()}", use t()`);
}
let skip = false;
for (const child of node.children ?? []) {
if (!skip) walk(child);
if (child.type === COMMENT) skip = typeof child.content === "string" && child.content.trim() === IGNORE_COMMENT;
else if (child.type === ELEMENT || child.type === INTERPOLATION || (child.type === TEXT && String(child.content).trim())) skip = false;
}
};
if (ast) walk(ast as unknown as TemplateNode);
}
return problems;
}
-40
View File
@@ -1,40 +0,0 @@
/**
* npm run i18n:types regenerate messages.generated.ts
* npm run i18n:sync regenerate the types, translate new keys (DEEPL_API_KEY)
* npm run i18n:enforce-order regenerate the types, reorder locales like en.json
* npm run i18n:cleanup regenerate the types, remove obsolete keys
* npm run i18n:check locale list, translations, types, dynamic keys, unused keys and raw text
* npm run i18n:check:strict checks for raw `$t` and 'vue-i18n' imports, including JS files
*/
import { checkLocaleRegistry, checkRawText, checkUnusedKeys } from "./check.ts";
import { report } from "./shared.ts";
import { checkTranslations, syncTranslations } from "./sync.ts";
import { checkTypes, writeTypes } from "./types.ts";
const [command, ...flags] = process.argv.slice(2);
const has = (flag: string) => flags.includes(flag);
try {
if (command === "types") {
process.exitCode = writeTypes();
} else if (command === "sync") {
process.exitCode = writeTypes() || (await syncTranslations({ enforceOrder: has("--enforce-order"), cleanup: has("--cleanup") }));
} else if (command === "check") {
const translations = checkTranslations();
const problems = [...checkLocaleRegistry(), ...translations, ...checkTypes(has("--strict")), ...checkUnusedKeys(), ...checkRawText()];
if (problems.length) {
report(problems);
if (translations.length) console.error("Run: npm run i18n:sync (or i18n:cleanup)");
process.exitCode = 1;
} else {
console.log("✅ i18n checks passed");
}
} else {
console.error("Usage: node scripts/i18n/index.ts <types | sync [--enforce-order | --cleanup] | check [--strict]>");
process.exitCode = 1;
}
} catch (error) {
console.error("\n❌ i18n script failed:", error);
process.exitCode = 1;
}
-200
View File
@@ -1,200 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { parse } from "vue/compiler-sfc";
import { INTERPOLATION } from "./check.ts"
export const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
export const srcDir = path.join(root, "src");
export const i18nDir = path.join(srcDir, "i18n");
export const localesDir = path.join(i18nDir, "locales");
export const generatedFile = path.join(i18nDir, "messages.generated.ts");
export type Messages = Record<string, string>;
/** Tests t/$t with throwaway keys */
export const isTestFile = (file: string) => /\.test\.[jt]s$/.test(file);
export const rel = (file: string) => path.relative(root, file);
export const readJson = (file: string): unknown => JSON.parse(fs.readFileSync(file, "utf8"));
/** Flat nested messages into `{ "a.b.c": "message" }`; null counts as empty message. */
export function flatten(tree: unknown, prefix = ""): Messages {
const result: Messages = {};
for (const [key, value] of Object.entries(tree as Record<string, unknown>)) {
const fullKey = prefix + key;
if (typeof value === "string") {
result[fullKey] = value;
} else if (value === null) {
result[fullKey] = "";
} else if (typeof value === "object") {
Object.assign(result, flatten(value, `${fullKey}.`));
} else {
throw new Error(`${fullKey}: messages must be strings or objects`);
}
}
return result;
}
export const readLocale = (file: string): Messages => flatten(readJson(path.join(localesDir, file)));
/** File names of every locale except en.json, sorted */
export const translationFiles = (): string[] =>
fs
.readdirSync(localesDir)
.filter((file) => file.endsWith(".json") && file !== "en.json")
.sort();
/** .vue, .ts and .js in src/ without the locales and the generated types */
export function* sourceFiles(skipI18nDir = false, dir = srcDir): Generator<string> {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (full !== localesDir && !(skipI18nDir && full === i18nDir)) yield* sourceFiles(skipI18nDir, full);
} else if (/\.(vue|ts|js)$/.test(entry.name) && full !== generatedFile) {
yield full;
}
}
}
export function report(problems: string[]): void {
for (const problem of problems) console.error(`✗ ${problem}`);
console.error(`\n${problems.length} problem(s) found.`);
}
const blank = (text: string) => text.replace(/[^\n]/g, " ");
// What can precede a regex literal, anything else (an identifier, `)`, a number, a string) makes `/` a division
const REGEX_PRECEDER = /[(,=:[!&|?{};+\-*%<>~^]$/;
const POSTFIX = /(?:\+\+|--)$/;
const REGEX_KEYWORD = /(?:^|[^\w$.])(?:return|typeof|case|do|else|in|of|void|delete|throw|new|instanceof|yield|await)$/;
/** Replaces the comments of JS/TS code by spaces and, with `strings`, the content of '...' and "..." literals too */
export function maskJs(text: string, strings = false): string {
const isRegexStart = (emitted: string) => {
const before = emitted.trimEnd();
if (POSTFIX.test(before)) return false;
return before === "" || REGEX_PRECEDER.test(before) || REGEX_KEYWORD.test(before);
};
const scan = (start: number, inExpression: boolean): [string, number] => {
let out = "";
let i = start;
let depth = 0;
while (i < text.length) {
const ch = text.charAt(i);
const next = text.charAt(i + 1);
if (ch === "/" && (next === "/" || next === "*")) {
const close = next === "/" ? text.indexOf("\n", i) : text.indexOf("*/", i + 2);
const end = close === -1 ? text.length : next === "/" ? close : close + 2;
out += blank(text.slice(i, end));
i = end;
} else if (ch === "/" && isRegexStart(out)) {
let end = i + 1;
let inClass = false;
while (end < text.length && text.charAt(end) !== "\n" && (inClass || text.charAt(end) !== "/")) {
if (text.charAt(end) === "\\") end++;
else if (text.charAt(end) === "[") inClass = true;
else if (text.charAt(end) === "]") inClass = false;
end++;
}
const closed = text.charAt(end) === "/";
const literal = closed ? text.slice(i, end + 1) : ch; // an unclosed one is a division
out += strings && closed ? `/${blank(literal.slice(1, -1))}/` : literal;
i += literal.length;
} else if (ch === "`") {
const [masked, end] = maskTemplate(i);
out += masked;
i = end;
} else if (ch === '"' || ch === "'") {
let end = i + 1;
while (end < text.length && text.charAt(end) !== ch) {
if (text.charAt(end) === "\\") end++;
else if (text.charAt(end) === "\n") break; // it's not a string
end++;
}
const closed = text.charAt(end) === ch;
const literal = text.slice(i, closed ? end + 1 : end);
out += strings && closed ? ch + blank(literal.slice(1, -1)) + ch : literal;
i += literal.length;
} else {
if (inExpression && ch === "{") depth++;
else if (inExpression && ch === "}") {
if (depth === 0) return [out, i];
depth--;
}
out += ch;
i++;
}
}
return [out, i];
};
// A template literal from its opening backtick -- its `${...}` expressions are scanned
const maskTemplate = (start: number): [string, number] => {
const keep = (chunk: string) => (strings ? blank(chunk) : chunk);
let out = "`";
let i = start + 1;
while (i < text.length) {
const ch = text.charAt(i);
if (ch === "\\") {
out += keep(text.slice(i, i + 2));
i += 2;
} else if (ch === "`") {
return [`${out}\``, i + 1];
} else if (ch === "$" && text.charAt(i + 1) === "{") {
const [code, end] = scan(i + 2, true);
out += `\${${code}`;
i = end;
if (text.charAt(i) === "}") {
out += "}";
i++;
}
} else {
out += keep(ch);
i++;
}
}
return [out, i];
};
return scan(0, false)[0];
}
interface Span {
loc: { start: { offset: number }; end: { offset: number } };
}
interface TemplateNode {
type: number;
content?: unknown;
props?: { exp?: Span }[];
children?: TemplateNode[];
}
/**
* The code of a source file without comments at the same offsets as the file. In .vue files only the template and the scripts
* are kept while styles no
*/
export function maskSource(file: string, text: string, strings = false): string {
if (!file.endsWith(".vue")) return maskJs(text, strings);
const { descriptor } = parse(text, { filename: file });
let out = text;
// each replacement keeps the length of what it replaces, so the blocks can be masked one after the other
const mask = ({ start, end }: Span["loc"], apply: (code: string) => string) => {
out = out.slice(0, start.offset) + apply(text.slice(start.offset, end.offset)) + out.slice(end.offset);
};
for (const style of descriptor.styles) mask(style.loc, blank);
for (const script of [descriptor.script, descriptor.scriptSetup]) {
if (script) mask(script.loc, (code) => maskJs(code, strings));
}
if (descriptor.template) mask(descriptor.template.loc, (code) => code.replace(/<!--[\s\S]*?-->/g, blank));
if (strings && descriptor.template?.ast) {
const walk = (node: TemplateNode) => {
if (node.type === INTERPOLATION) mask((node.content as Span).loc, (code) => maskJs(code, true));
for (const prop of node.props ?? []) if (prop.exp) mask(prop.exp.loc, (code) => maskJs(code, true));
for (const child of node.children ?? []) walk(child);
};
walk(descriptor.template.ast as unknown as TemplateNode);
}
return out;
}
-230
View File
@@ -1,230 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import { DeepLClient, type TargetLanguageCode, type TranslateTextOptions } from "deepl-node";
import { localesDir, readJson, readLocale, translationFiles } from "./shared.ts";
type Tree = { [key: string]: unknown };
const MASTER_LANGUAGE = "en";
const DEEPL_LANGUAGES: Record<string, string> = {
"zh-cn": "ZH-HANS",
"zh-tw": "ZH-HANT",
pt: "PT-PT",
"pt-br": "PT-BR",
en: "EN",
"en-us": "EN-US",
"en-gb": "EN-GB",
"sv-se": "SV",
ua: "UK",
"nl-be": "NL",
cz: "CS",
bg: "BG",
};
let translator: DeepLClient | null = null;
const isTree = (value: unknown): value is Tree => typeof value === "object" && value !== null && !Array.isArray(value);
/** Reports what syncTranslations would change */
export function checkTranslations(): string[] {
const master = readLocale("en.json");
const problems: string[] = [];
for (const file of translationFiles()) {
let target: Record<string, string>;
try {
target = readLocale(file);
} catch (error) {
problems.push(`${file}: cannot be read (${error instanceof Error ? error.message : error})`);
continue;
}
for (const [key, message] of Object.entries(master)) {
if (!target[key] && (message || !Object.hasOwn(target, key))) problems.push(`${file}: missing "${key}"`);
}
for (const key of Object.keys(target)) {
if (!Object.hasOwn(master, key)) problems.push(`${file}: obsolete key "${key}"`);
}
}
return problems;
}
async function translateText(text: string, targetLanguage: string, keyPath: string): Promise<string | null> {
if (!text.trim()) {
console.warn(`Skipping translation for empty text: "${text}"`);
return text;
}
const hasPlaceholders = /\{[^}]+\}/.test(text);
let textToTranslate = text;
const options: TranslateTextOptions = {};
if (hasPlaceholders) {
console.log(`Found placeholder in: "${text}". Wrapping for translation.`);
textToTranslate = text.replace(/(\{[^}]+\})/g, "<ph>$1</ph>");
options.tagHandling = "xml";
options.ignoreTags = ["ph"];
}
try {
console.log(`Translating "${text}" from '${MASTER_LANGUAGE}' to '${targetLanguage}'...`);
const deeplTarget = (DEEPL_LANGUAGES[targetLanguage.toLowerCase()] ?? targetLanguage.toUpperCase()) as TargetLanguageCode;
const result = await translator?.translateText(textToTranslate, MASTER_LANGUAGE, deeplTarget, options);
await new Promise((resolve) => {setTimeout(resolve, 100)}); // avoid rate-limiting
let translated = result?.text ?? "";
if (hasPlaceholders) {
// the translator might add spaces around the tags
translated = translated.replace(/<ph>\s*(\{[^}]+\})\s*<\/ph>/g, "$1");
}
if (!translated.trim()) {
console.error(`⚠️ Translation failed for "${text}" (${keyPath}): empty result`);
return null;
}
return translated;
} catch (error) {
console.error(`⚠️ Translation failed for "${text}" (${keyPath}):`, error instanceof Error ? error.message : error);
return null;
}
}
/** Reorders `value` to match the key order of `master`, dropping keys `master` lacks */
function reorderObject(value: unknown, master: unknown): unknown {
if (!isTree(value) || !isTree(master)) return value;
const ordered: Tree = {};
for (const key of Object.keys(master)) {
if (Object.hasOwn(value, key)) ordered[key] = reorderObject(value[key], master[key]);
}
return ordered;
}
/** Add missing keys, remove obsolete ones */
async function processKeys(
master: Tree,
target: Tree,
lang: string,
parents: string[],
enforceOrder: boolean,
cleanup: boolean,
): Promise<boolean | "UNSUPPORTED"> {
let changed = false;
for (const key of Object.keys(master)) {
const masterValue = master[key];
const keyPath = [...parents, key].join(".");
if (Object.hasOwn(target, key) && isTree(masterValue) !== isTree(target[key])) {
console.log(`🗑️ Removing "${keyPath}" from ${lang}.json: its structure differs from en.json`);
Reflect.deleteProperty(target, key);
changed = true;
}
if (isTree(masterValue)) {
if (!cleanup && !isTree(target[key])) {
console.log(`Creating missing object structure for "${keyPath}" in ${lang}.json`);
target[key] = {};
changed = true;
}
const child = target[key];
if (isTree(child)) {
const result = await processKeys(masterValue, child, lang, [...parents, key], enforceOrder, cleanup);
if (result === "UNSUPPORTED") {
console.log(`Skipping translation for "${lang}" due to unsupported structure.`);
return result;
}
if (result) changed = true;
}
} else if (!cleanup) {
if (typeof masterValue === "string") {
const existing = target[key];
if (!Object.hasOwn(target, key) || existing === "" || existing === null) {
if (enforceOrder) {
console.log(`Skipping new key "${keyPath}" for ${lang}.json`);
} else {
const translated = await translateText(masterValue, lang, keyPath);
if (translated === null) return "UNSUPPORTED";
if (target[key] !== translated) {
target[key] = translated;
changed = true;
}
}
}
} else if (!Object.hasOwn(target, key)) {
console.log(`Key "${keyPath}" (non-string) missing in ${lang}.json. Copying from English.`);
target[key] = masterValue;
changed = true;
}
}
}
for (const key of Object.keys(target)) {
if (!Object.hasOwn(master, key)) {
console.log(`🗑️ Removing obsolete key "${[...parents, key].join(".")}" from ${lang}.json`);
Reflect.deleteProperty(target, key);
changed = true;
}
}
return changed;
}
export async function syncTranslations({ enforceOrder, cleanup }: { enforceOrder: boolean; cleanup: boolean }): Promise<number> {
const reorder = enforceOrder && !cleanup;
if (!enforceOrder && !cleanup) {
const apiKey = process.env.DEEPL_API_KEY;
if (!apiKey) {
console.error("❌ Missing DEEPL_API_KEY in environment.");
return 1;
}
translator = new DeepLClient(apiKey);
console.warn("--- Using DeepL API for translation ---");
} else if (cleanup) {
console.warn("--- Only obsolete keys will be removed - No translations, or reordering will happen ---");
} else {
console.warn("--- Enforcing order of all files to match master language (no translations will be performed) ---");
}
const master = readJson(path.join(localesDir, "en.json")) as Tree;
const failed: string[] = [];
for (const file of translationFiles()) {
const targetFile = path.join(localesDir, file);
const lang = path.basename(file, ".json");
let original: Tree;
try {
const parsed = readJson(targetFile);
if (!isTree(parsed)) throw new Error("the root must be an object");
original = parsed;
} catch (error) {
console.error(`❌ Could not read ${targetFile}, leaving it unchanged: ${error instanceof Error ? error.message : error}`);
failed.push(file);
continue;
}
let target = structuredClone(original);
const result = await processKeys(master, target, lang, [], reorder, cleanup);
if (result === "UNSUPPORTED") {
console.error(`❌ ${targetFile} was left unchanged: a translation failed.`);
failed.push(file);
continue;
}
let orderChanged = false;
if (reorder) {
target = reorderObject(target, master) as Tree;
orderChanged = JSON.stringify(original) !== JSON.stringify(target);
if (orderChanged) console.log(`- Reordered keys in ${lang}.json`);
}
if (result || orderChanged) {
fs.writeFileSync(targetFile, `${JSON.stringify(target, null, 2)}\n`);
if (!cleanup && !reorder) console.log(`Successfully updated ${targetFile}`);
} else {
console.log(`No changes needed for ${targetFile}`);
}
}
if (failed.length) {
console.error(`\n❌ Synchronization incomplete, ${failed.length} locale(s) were not changed: ${failed.join(", ")}`);
return 1;
}
if (cleanup) console.log("\n✅ Cleanup complete (obsolete keys removed).");
else if (reorder) console.log("\n✅ Enforce order complete.");
else console.log("\n✅ Translation synchronization complete (via DeepL).");
return 0;
}
-316
View File
@@ -1,316 +0,0 @@
import fs from "node:fs";
import { generatedFile, isTestFile, maskSource, type Messages, readLocale, rel, sourceFiles, translationFiles } from "./shared.ts";
const OPTIONAL_PLACEHOLDERS = new Set(["suffix", "prefix"]);
const NAMED_PLACEHOLDER = /\{([A-Za-z_]\w*)\}/g;
/** vue-i18n literal interpolation, like {'|'} to print a pipe or @ */
const LITERAL_INTERPOLATION = /\{'[^']*'\}/g;
const REGENERATE = "Run: npm run i18n:types";
/** Named placeholders of a message in order */
function placeholders(message: string): string[] {
const names: string[] = [];
for (const match of message.matchAll(NAMED_PLACEHOLDER)) {
const name = match[1] ?? "";
if (!names.includes(name)) names.push(name);
}
return names;
}
/** Returns a description of unsupported vue-i18n syntax, or null. */
function unsupportedSyntax(message: string): string | null {
const rest = message.replace(LITERAL_INTERPOLATION, "").replace(NAMED_PLACEHOLDER, "");
if (/[{}]/.test(rest)) return "braces other than {name} placeholders";
if (rest.includes("|")) return "plural separator '|'";
if (/@[.:]/.test(rest)) return "linked message '@:' / '@.'";
return null;
}
function generate() {
const messages = readLocale("en.json");
const problems: string[] = [];
const lines: string[] = [];
for (const [key, message] of Object.entries(messages)) {
const unsupported = unsupportedSyntax(message);
if (unsupported) problems.push(`en.json: ${key} uses ${unsupported}, which the types do not support`);
const names = placeholders(message);
const params = names.length ? names.map((name) => JSON.stringify(name)).join(" | ") : "never";
lines.push(` ${JSON.stringify(key)}: ${params};`);
}
const content = `// This file is generated by scripts/i18n from src/i18n/locales/en.json.
// Run \`make generate-translation-types\` \`npm run i18n:types\` after changing en.json. Do not edit manually.
/** Every message in en.json mapped to the named placeholders. Used to type-check \`t()\` calls */
export interface MessageParams {
${lines.join("\n")}
}
/** Placeholders that callers may omit */
export type OptionalParam = ${[...OPTIONAL_PLACEHOLDERS].map((name) => JSON.stringify(name)).join(" | ")};
`;
return { content, messages, problems };
}
/** Regenerates messages.generated.ts; returns the exit code. */
export function writeTypes(): number {
const { content, messages, problems } = generate();
if (problems.length) {
for (const problem of problems) console.error(`✗ ${problem}`);
return 1;
}
fs.writeFileSync(generatedFile, content);
console.log(`Wrote ${rel(generatedFile)} (${Object.keys(messages).length} messages).`);
return 0;
}
function checkGeneratedFile(expected: string): string[] {
if (!fs.existsSync(generatedFile)) return [`${rel(generatedFile)} is missing. ${REGENERATE}`];
if (fs.readFileSync(generatedFile, "utf8") !== expected) return [`${rel(generatedFile)} is out of date. ${REGENERATE}`];
return [];
}
function checkLocalePlaceholders(enMessages: Messages): string[] {
const problems: string[] = [];
for (const file of translationFiles()) {
for (const [key, message] of Object.entries(readLocale(file))) {
const english = enMessages[key];
if (english === undefined) continue;
const expected = new Set(placeholders(english));
const actual = new Set(placeholders(message));
for (const name of actual) {
if (!expected.has(name)) problems.push(`${file}: ${key} uses {${name}}, which en.json does not provide`);
}
for (const name of expected) {
if (!actual.has(name) && !OPTIONAL_PLACEHOLDERS.has(name)) problems.push(`${file}: ${key} is missing {${name}}`);
}
const unsupported = unsupportedSyntax(message);
if (unsupported) problems.push(`${file}: ${key} uses ${unsupported}`);
}
}
return problems;
}
/** .ts files and .vue files with <script lang="ts"> are checked by vue-tsc */
function isTypeScript(file: string, text: string): boolean {
if (file.endsWith(".ts")) return true;
return file.endsWith(".vue") && /<script[^>]*lang=["']ts["']/.test(text);
}
const BYPASS_RULES = [
{
pattern: /from\s+["']vue-i18n["']/,
message: "import useI18n from '@/i18n/index.ts' instead of 'vue-i18n'",
inStrings: true,
},
{
pattern: /(^|[^\w$])\$t\b/,
message: "use t(...) from useI18n() in '@/i18n/index.ts' instead of $t(...), so the key and params are type-checked",
inStrings: false,
},
];
/** `$t` that isn't called: `helper(this.$t)`, `this.$t.bind(this)` or a `$t` parameter. The helper keys can't be type-checked */
const PASSED_AROUND = /(^|[^\w$])\$t\b(?!\s*\()/;
export const isPassedAround = (line: string) => PASSED_AROUND.test(line);
function* passedAroundIndexes(bare: string): Generator<number> {
for (const match of bare.matchAll(new RegExp(PASSED_AROUND.source, "g"))) yield match.index + (match[1] ?? "").length;
}
// The start of a t(...) call: t(, $t(, this.$t( or i18n.global.t(
const CALL_START = /(?:(?<![\w$.])(?:\$t|t|i18n\.global\.t)|\bthis\.\$t)\s*\(/g;
interface Params {
names: Set<string>;
dynamic: boolean;
}
const lineOf = (text: string, index: number) => text.slice(0, index).split("\n").length;
function skipSpaces(text: string, index: number): number {
let i = index;
while (i < text.length && /\s/.test(text.charAt(i))) i++;
return i;
}
/** Reads a string literal starting at `index`; returns null for anything else or a dynamic template */
function readStringLiteral(text: string, index: number): { value: string; end: number } | null {
const quote = text.charAt(index);
if (quote !== '"' && quote !== "'" && quote !== "`") return null;
let i = index + 1;
let value = "";
while (i < text.length && text.charAt(i) !== quote) {
if (text.charAt(i) === "\\") {
value += text.charAt(i + 1);
i += 2;
continue;
}
if (quote === "`" && text.charAt(i) === "$" && text.charAt(i + 1) === "{") return null;
value += text.charAt(i);
i++;
}
return i < text.length ? { value, end: i + 1 } : null;
}
const isQuote = (ch: string) => ch === '"' || ch === "'" || ch === "`";
function skipString(text: string, index: number): number {
const quote = text.charAt(index);
let i = index + 1;
while (i < text.length) {
const ch = text.charAt(i);
if (ch === "\\") i++;
else if (ch === quote) return i + 1;
i++;
}
return -1;
}
const CLOSERS: Record<string, string> = { "{": "}", "[": "]", "(": ")" };
/** Finds the index of the bracket closing the one at `index`, skipping strings. */
function findClosing(text: string, index: number): number {
const stack = [CLOSERS[text.charAt(index)]];
let i = index + 1;
while (i < text.length && stack.length) {
const ch = text.charAt(i);
if (isQuote(ch)) {
const end = skipString(text, i);
if (end === -1) return -1;
i = end;
continue;
}
const closer = CLOSERS[ch];
if (closer) stack.push(closer);
else if (ch === stack.at(-1)) stack.pop();
i++;
}
return stack.length ? -1 : i - 1;
}
/** Property names of the object literal at `index`; `dynamic` when a spread or computed key hides some */
function readObjectKeys(text: string, index: number): Params | null {
const close = findClosing(text, index);
if (close === -1) return null;
const names = new Set<string>();
let dynamic = false;
let segmentStart = index + 1;
let i = index + 1;
const flush = (end: number) => {
const segment = text.slice(segmentStart, end).trim();
if (!segment) return;
if (segment.startsWith("...") || segment.startsWith("[")) {
dynamic = true;
return;
}
const match = segment.match(/^(?:([A-Za-z_$][\w$]*)|'([^']*)'|"([^"]*)")\s*(?::|$)/);
const name = match?.[1] ?? match?.[2] ?? match?.[3];
if (name === undefined) dynamic = true;
else names.add(name);
};
while (i < close) {
const ch = text.charAt(i);
if (isQuote(ch)) {
i = skipString(text, i);
continue;
}
if (ch === "{" || ch === "[" || ch === "(") {
i = findClosing(text, i) + 1;
continue;
}
if (ch === ",") {
flush(i);
segmentStart = i + 1;
}
i++;
}
flush(close);
return { names, dynamic };
}
/**
* Yields every t(...) call whose first argument is a literal key. `text` is the source without
* comments, `bare` the same without the content of its strings
*/
export function* literalCalls(text: string, bare: string): Generator<{ key: string; params: Params; index: number }> {
for (const match of bare.matchAll(CALL_START)) {
const keyStart = skipSpaces(text, match.index + match[0].length);
const key = readStringLiteral(text, keyStart);
if (!key) continue; // only vue-tsc can check it
let i = skipSpaces(text, key.end);
if (text.charAt(i) !== "," && text.charAt(i) !== ")") continue; // 'prefix.' + name if the key isn't literal
let params: Params = { names: new Set(), dynamic: false };
if (text.charAt(i) === ",") {
i = skipSpaces(text, i + 1);
if (text.charAt(i) === "{") params = readObjectKeys(text, i) ?? params;
else if (text.charAt(i) !== ")") params = { names: new Set(), dynamic: true };
}
yield { key: key.value, params, index: match.index };
}
}
export function* dynamicCalls(text: string, bare: string): Generator<{ index: number }> {
const literal = new Set<number>();
for (const call of literalCalls(text, bare)) literal.add(call.index);
for (const match of bare.matchAll(CALL_START)) {
if (literal.has(match.index)) continue;
if (text.charAt(skipSpaces(text, match.index + match[0].length)) === ")") continue; // t() without a key, vue-tsc reports it
yield { index: match.index };
}
}
export function checkCall(key: string, params: Params, messages: Messages): string[] {
const expected = messages[key];
if (expected === undefined) return [`unknown translation key "${key}"`];
if (params.dynamic) return []; // spread or variable: names unknown
const known = new Set(placeholders(expected));
const problems: string[] = [];
for (const name of params.names) {
if (!known.has(name)) problems.push(`"${key}" does not take a {${name}} param`);
}
for (const name of known) {
if (!params.names.has(name) && !OPTIONAL_PLACEHOLDERS.has(name)) problems.push(`"${key}" is missing its {${name}} param`);
}
return problems;
}
function checkTypedUsage(messages: Messages, strict: boolean): string[] {
const problems: string[] = [];
for (const file of sourceFiles(true)) {
if (isTestFile(file)) continue; // tests t/$t with throwaway keys
const text = fs.readFileSync(file, "utf8");
const code = maskSource(file, text);
const bare = maskSource(file, text, true);
if (strict || isTypeScript(file, text)) {
const codeLines = code.split("\n");
const bareLines = bare.split("\n");
for (const rule of BYPASS_RULES) {
const lines = rule.inStrings ? codeLines : bareLines;
for (const [index, line] of lines.entries()) {
if (rule.pattern.test(line)) problems.push(`${rel(file)}:${index + 1}: ${rule.message}`);
}
}
}
if (!strict && !isTypeScript(file, text)) {
const lines = new Set([...passedAroundIndexes(bare)].map((index) => lineOf(text, index)));
for (const line of lines) {
problems.push(`${rel(file)}:${line}: $t is passed around as a value, import i18n from '@/i18n/index.ts' and call t() with a literal key in the helper instead`);
}
}
for (const call of literalCalls(code, bare)) {
for (const problem of checkCall(call.key, call.params, messages)) {
problems.push(`${rel(file)}:${lineOf(text, call.index)}: ${problem}`);
}
}
for (const call of dynamicCalls(code, bare)) {
problems.push(`${rel(file)}:${lineOf(text, call.index)}: dynamic translation key, call t() with a string literal so the key is type-checked and found by the unused keys check`);
}
}
return problems;
}
/** Checks the generated types, the placeholders of every locale and the t() calls in src/. With `strict`, raw `$t` and 'vue-i18n' */
export function checkTypes(strict: boolean): string[] {
const { content, messages, problems } = generate();
return [...problems, ...checkGeneratedFile(content), ...checkLocalePlaceholders(messages), ...checkTypedUsage(messages, strict)];
}
+351
View File
@@ -0,0 +1,351 @@
// scripts/sync-translations.js
import path from 'node:path';
import { globSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { DeepLClient } from 'deepl-node';
import fs from 'fs-extra';
// Parse command line arguments
const args = process.argv.slice(2);
const checkOnly = args.includes('--check') || args.includes('-c');
const enforceOrder = args.includes('--enforce-order'); // When using this will force the order of eng, will not perform new translations. If we move keys to a different block will count as new translations and will delete it from all the languages
const cleanupOnly = args.includes('--cleanup'); // Will only delete keys that not longer exist in eng, no translation or reorder, just deletion.
// --- Configuration ---
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const localesDir = path.resolve(__dirname, '../src/i18n');
const masterLocaleFile = path.join(localesDir, 'en.json');
const masterLanguageCode = 'en';
const targetLocaleFiles = globSync(path.join(localesDir, '*.json'))
.filter(file => path.basename(file) !== `${masterLanguageCode}.json`)
const requireApiKey = !checkOnly && !enforceOrder && !cleanupOnly;
const DEEPL_API_KEY = process.env.DEEPL_API_KEY;
if (requireApiKey && !DEEPL_API_KEY) {
console.error("❌ Missing DEEPL_API_KEY in environment.");
process.exit(1);
}
const translator = requireApiKey ? new DeepLClient(DEEPL_API_KEY) : null;
const deeplLangMap = {
'zh-cn': 'ZH-HANS',
'zh-tw': 'ZH-HANT',
'pt': 'PT-PT', // or 'PT-BR' if you want Brazilian Portuguese
'pt-br': 'PT-BR',
'en': 'EN',
'en-us': 'EN-US',
'en-gb': 'EN-GB',
'sv-se': 'SV',
'ua': 'UK',
'nl-be': 'NL',
'cz': 'CS',
'bg': 'BG',
// Add more as needed
};
// --- Translation Function using DeepL ---
async function translateText(text, targetLanguage, keyPath = '') {
if (checkOnly) {
// In check mode, just return the original text to detect changes
return text;
}
if (!text || typeof text !== 'string' || text.trim() === '') {
console.warn(`Skipping translation for empty or non-string text: "${text}"`);
return text;
}
if (keyPath === 'languages' || keyPath.startsWith('languages.')) {
return text;
}
const hasPlaceholders = /\{[^}]+\}/.test(text);
let textToTranslate = text;
const options = {};
if (hasPlaceholders) {
console.log(`Found placeholder in: "${text}". Wrapping for translation.`);
textToTranslate = text.replace(/(\{[^}]+\})/g, '<ph>$1</ph>');
options.tagHandling = 'xml';
options.ignoreTags = ['ph'];
}
try {
console.log(`Translating "${text}" from '${masterLanguageCode}' to '${targetLanguage}'...`);
const deeplTargetLang = deeplLangMap[targetLanguage.toLowerCase()] || targetLanguage.toUpperCase();
const result = await translator.translateText(textToTranslate, masterLanguageCode, deeplTargetLang, options);
// Delay to avoid rate-limiting
await new Promise(resolve => setTimeout(resolve, 100));
let translatedText = result.text;
if (hasPlaceholders) {
// Unwrap the placeholders. The translator might add spaces around tags.
translatedText = translatedText.replace(/<ph>\s*(\{[^}]+\})\s*<\/ph>/g, '$1');
}
return translatedText;
} catch (err) {
console.error(`⚠️ Translation failed for "${text}" (${keyPath}):`, err.message || err);
return ``;
}
}
// Reorder objects to match eng (master lang) key order
function reorderObject(obj, masterObj) {
// If obj is not an object, return as is
if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) return obj;
const newObj = {};
for (const key in masterObj) {
if (Object.hasOwn(masterObj, key)) {
if (Object.hasOwn(obj, key)) {
newObj[key] = reorderObject(obj[key], masterObj[key]);
}
}
}
return newObj;
}
// --- Recursive key processor ---
async function processKeys(masterObj, targetObj, targetLangCode, currentPathParts = [], doEnforceOrder, doCleanupOnly = false) {
let changesMade = false;
let meaningfulChanges = 0; // Only count meaningful changes
// First pass: Add/update keys from master to target
for (const key in masterObj) {
if (Object.hasOwn(masterObj, key)) {
const currentPathPartsNext = [...currentPathParts, key];
const currentKeyPath = currentPathPartsNext.join('.');
const masterValue = masterObj[key];
// Special handling for "languages" key - always copy the entire object from master
if (key === 'languages' && currentPathParts.length === 0 && !doCleanupOnly) {
if (!checkOnly && !doEnforceOrder) {
console.log(`Copying entire "languages" object from master to ${targetLangCode}.json`);
}
targetObj[key] = JSON.parse(JSON.stringify(masterValue)); // Deep copy
changesMade = true;
continue;
}
if (typeof masterValue === 'object' && masterValue !== null && !Array.isArray(masterValue)) {
if (!doCleanupOnly && (!targetObj[key] || typeof targetObj[key] !== 'object')) {
if (checkOnly) {
console.log(`Would create missing object structure for "${currentKeyPath}" in ${targetLangCode}.json`);
meaningfulChanges++; // Creating new object structures is meaningful
// In check mode, create a temporary object for processing
targetObj[key] = {};
} else {
console.log(`Creating missing object structure for "${currentKeyPath}" in ${targetLangCode}.json`);
targetObj[key] = {};
}
changesMade = true;
}
if (targetObj[key] && typeof targetObj[key] === 'object') {
const result = await processKeys( masterValue, targetObj[key], targetLangCode, currentPathPartsNext,
doEnforceOrder, doCleanupOnly);
if (result === "UNSUPPORTED") {
console.log(`Skipping translation for "${targetLangCode}" due to unsupported structure.`);
return "UNSUPPORTED";
}
if (typeof result === 'number') {
meaningfulChanges += result;
changesMade = true;
} else if (result) {
changesMade = true;
}
}
} else if (!doCleanupOnly) {
// Only handle non‑object values
if (typeof masterValue === 'string') {
const existingTargetValue = targetObj[key];
const isMissing = !Object.hasOwn(targetObj, key) || existingTargetValue === '' || existingTargetValue === null;
if (isMissing) {
if (checkOnly) {
console.log(`Would translate "${currentKeyPath}" for ${targetLangCode}.json`);
meaningfulChanges++; // Translation is meaningful
} else if (doEnforceOrder) {
// Skip translations for new keys
console.log(`Skipping new key "${currentKeyPath}" for ${targetLangCode}.json`);
} else {
// Sync translation
const result = await translateText(masterValue, targetLangCode, currentKeyPath);
if (result === "") {
return "UNSUPPORTED";
}
targetObj[key] = result;
changesMade = true;
}
}
} else {
if (!Object.hasOwn(targetObj, key)) {
if (checkOnly) {
console.log(`Would copy key "${currentKeyPath}" (non-string) from English to ${targetLangCode}.json`);
meaningfulChanges++; // Copying non-string values is meaningful
} else {
console.log(`Key "${currentKeyPath}" (non-string) missing in ${targetLangCode}.json. Copying from English.`);
targetObj[key] = masterValue;
}
changesMade = true;
}
}
}
}
}
// Second pass: Remove obsolete keys that exist in target but not in master
const keysToRemove = [];
for (const key in targetObj) {
if (Object.hasOwn(targetObj, key)) {
if (!Object.hasOwn(masterObj, key)) {
keysToRemove.push(key);
}
}
}
for (const key of keysToRemove) {
const currentKeyPath = [...currentPathParts, key].join('.');
if (checkOnly) {
console.log(`Would remove obsolete key "${currentKeyPath}" from ${targetLangCode}.json`);
meaningfulChanges++; // Removing obsolete keys is meaningful
} else {
console.log(`🗑️ Removing obsolete key "${currentKeyPath}" from ${targetLangCode}.json`);
delete targetObj[key];
}
changesMade = true;
}
return checkOnly ? meaningfulChanges : changesMade;
}
// --- Main synchronization ---
async function syncAllTranslations() {
const isSync = !checkOnly && !enforceOrder && !cleanupOnly;
const isEnforceOrder = enforceOrder && !cleanupOnly;
const isCleanup = cleanupOnly;
if (checkOnly) {
console.log("--- Checking for translation changes (no translations will be performed) ---");
} else if (isCleanup) {
console.warn("--- Only obsolete keys will be removed - No translations, or reordering will happen ---");
} else if (isEnforceOrder) {
console.warn("--- Enforcing order of all files to match master language (no translations will be performed) ---");
} else if (isSync) {
console.warn("--- Using DeepL API for translation ---");
}
if (!await fs.pathExists(masterLocaleFile)) {
console.error(`Master locale file not found: ${masterLocaleFile}`);
process.exit(1);
}
const masterContent = await fs.readJson(masterLocaleFile);
console.log(`Loaded master translations from ${masterLocaleFile}`);
let meaningfulChanges = 0;
let hasMeaningfulChanges = false;
for (const targetFile of targetLocaleFiles) {
const targetLangCode = path.basename(targetFile, '.json');
let targetContent = {};
let originalTargetContent = null;
const fileExisted = await fs.pathExists(targetFile);
if (fileExisted) {
try {
originalTargetContent = await fs.readJson(targetFile);
targetContent = JSON.parse(JSON.stringify(originalTargetContent)); // start from original
} catch (e) {
console.warn(`Warning: Could not parse ${targetFile}. Starting fresh. Error: ${e.message}`);
targetContent = {};
originalTargetContent = null;
}
} else {
if (isCleanup) continue;
console.log(`\nTarget file ${targetFile} not found. Will create for language: ${targetLangCode}.`);
}
const result = await processKeys(masterContent, targetContent, targetLangCode, [], isEnforceOrder, isCleanup);
let reorderedContent = targetContent;
let orderChanged = false;
if (isEnforceOrder && originalTargetContent && !checkOnly) {
reorderedContent = reorderObject(targetContent, masterContent);
// Compare the reordered content with the original to see if order changed
const origStr = JSON.stringify(originalTargetContent);
const reorderedStr = JSON.stringify(reorderedContent);
if (origStr !== reorderedStr) {
orderChanged = true;
console.log(`- Reordered keys in ${targetLangCode}.json`);
}
}
if (checkOnly) {
let wouldChange = false;
if (typeof result === 'number' && result > 0) {
meaningfulChanges += result;
wouldChange = true;
console.log(`Found ${result} meaningful changes needed for ${targetLangCode}.json`);
}
if (!fileExisted && !isCleanup) {
wouldChange = true;
console.log(`Would create new file for ${targetLangCode}.json`);
}
if (wouldChange) {
hasMeaningfulChanges = true;
}
} else {
const needsWrite = result || orderChanged || (!isCleanup && !fileExisted);
if (needsWrite) {
const finalContent = (isEnforceOrder && orderChanged) ? reorderedContent : targetContent;
try {
await fs.writeJson(targetFile, finalContent, { spaces: 2 });
if (!isCleanup && !isEnforceOrder) {
console.log(`Successfully ${result ? 'updated' : 'created'} ${targetFile}`);
}
} catch (error) {
console.error(`Error writing to ${targetFile}:`, error);
}
} else {
console.log(`No changes needed for ${targetFile}`);
}
}
}
if (checkOnly) {
if (hasMeaningfulChanges) {
console.log(`\n⚠️ Found ${meaningfulChanges} meaningful translation changes needed. -- update via "make sync-translations"`);
return 1; // Exit code 1 for meaningful changes needed
} else {
console.log('\n✅ No meaningful translation changes needed.');
return 0; // Exit code 0 for no meaningful changes
}
} else {
if (isCleanup) {
console.log('\n✅ Cleanup complete (obsolete keys removed).');
} else if (isEnforceOrder) {
console.log('\n✅ Enforce order complete.');
} else {
console.log('\n✅ Translation synchronization complete (via DeepL).');
}
return 0;
}
}
syncAllTranslations()
.then(exitCode => {
process.exit(exitCode);
})
.catch(error => {
console.error("\n❌ An error occurred during translation synchronization:", error);
process.exit(1);
});
+2 -2
View File
@@ -4,8 +4,8 @@
<script>
import { onMounted } from "vue";
import { mutations } from "@/store/index.ts"; // Import your store's mutations
import { scheduleFullIcons } from "@/utils/loadFullIcons.js";
import { mutations } from "@/store"; // Import your store's mutations
import { scheduleFullIcons } from "@/utils/loadFullIcons";
mutations.setLoading("main-app", true);
export default {
+4 -4
View File
@@ -366,7 +366,7 @@ function passkeyActorPasswordCancelledError() {
return err
}
function promptPasskeyActorPassword() {
function promptPasskeyActorPassword(i18nKey) {
return new Promise((resolve, reject) => {
let settled = false
const finish = (fn, value) => {
@@ -382,7 +382,7 @@ function promptPasskeyActorPassword() {
finish(reject, passkeyActorPasswordCancelledError())
},
props: {
infoText: i18n.global.t('prompts.confirmPasswordToSaveUser'),
infoText: i18n.global.t(i18nKey || 'prompts.confirmPasswordToSaveUser'),
submitLabel: i18n.global.t('general.confirm'),
submitCallback: async (actorPassword) => {
finish(resolve, actorPassword)
@@ -442,7 +442,7 @@ export async function beginPasskeyRegistration(options = {}) {
if (!canRetry) {
throw err
}
const actorPassword = await promptPasskeyActorPassword()
const actorPassword = await promptPasskeyActorPassword(options.actorPasswordPromptI18nKey)
return beginPasskeyRegistration({
...options,
actorPassword,
@@ -479,7 +479,7 @@ export async function deletePasskeyCredential(credentialId, options = {}) {
if (!canRetry) {
throw err
}
const actorPassword = await promptPasskeyActorPassword()
const actorPassword = await promptPasskeyActorPassword(options.actorPasswordPromptI18nKey)
return deletePasskeyCredential(credentialId, {
...options,
actorPassword,
+1 -1
View File
@@ -93,7 +93,7 @@ export function getDirectoryMetadataMap(path: string, { source }: { source?: str
path,
async () => {
const payload = await fetchMetadata(scope, path);
const withMetadata = (payload.items ?? []).filter((i) => i.metadata);
const withMetadata = (payload.items || []).filter((i) => i.metadata);
return new Map(withMetadata.map((i) => [i.name, i.metadata as object]));
},
async (name) => {
+18 -18
View File
@@ -1,6 +1,6 @@
import { notify } from "@/notify/index.ts"
import { getters, mutations, state } from "@/store/index.ts"
import { globalVars } from "@/utils/constants.ts"
import { globalVars } from "@/utils/constants.js"
import { downloadManager } from "@/utils/downloadManager.ts"
import {
notifyDownloadComplete,
@@ -34,7 +34,7 @@ function parseMockDataCount(value, defaultCount) {
if (value === undefined || value === null || value === '') {
return defaultCount;
}
const n = Math.trunc(Number(value));
const n = parseInt(String(value), 10);
if (!Number.isFinite(n) || n < 0) {
return defaultCount;
}
@@ -396,7 +396,7 @@ function totalFromContentRange(headerVal) {
if (!headerVal || typeof headerVal !== 'string') return 0
const idx = headerVal.lastIndexOf('/')
if (idx === -1) return 0
const n = Number.parseInt(headerVal.slice(idx + 1), 10)
const n = parseInt(headerVal.slice(idx + 1), 10)
return Number.isFinite(n) ? n : 0
}
@@ -414,7 +414,7 @@ async function resolveDownloadContentLength(url) {
token = res.headers.get('X-Archive-Token')
const cl = res.headers.get('Content-Length')
if (cl) {
const n = Number.parseInt(cl, 10)
const n = parseInt(cl, 10)
if (Number.isFinite(n) && n > 0) {
return { size: n, token }
}
@@ -438,7 +438,7 @@ async function resolveDownloadContentLength(url) {
if (res.ok) {
const cl = res.headers.get('Content-Length')
if (cl) {
const n = Number.parseInt(cl, 10)
const n = parseInt(cl, 10)
if (Number.isFinite(n) && n > 0) {
cancelBody()
return { size: n, token }
@@ -466,7 +466,7 @@ function archiveDisplayFileName(format, files) {
if (first?.path) {
const parts = first.path.split('/').filter(Boolean)
if (parts.length >= 2) {
return `${parts.at(-2)}${ext}`
return `${parts[parts.length - 2]}${ext}`
}
if (parts.length === 1) {
return `${parts[0]}${ext}`
@@ -496,8 +496,8 @@ async function chunkedRangeDownloadToBlob(
let totalSize = fileSize
while (offset < totalSize) {
const downloadItem = downloadManager.findById(downloadId)
if (downloadItem?.status === 'cancelled') {
const download = downloadManager.findById(downloadId)
if (download?.status === 'cancelled') {
return null
}
@@ -536,7 +536,7 @@ async function chunkedRangeDownloadToBlob(
} else if (response.status === 200) {
const clFull = response.headers.get('Content-Length')
if (clFull) {
const n = Number.parseInt(clFull, 10)
const n = parseInt(clFull, 10)
if (Number.isFinite(n) && n > 0) {
totalSize = n
const dl = downloadManager.findById(downloadId)
@@ -550,7 +550,7 @@ async function chunkedRangeDownloadToBlob(
const cl = response.headers.get('Content-Length')
let expectedChunkSize = end - offset + 1
if (cl) {
const n = Number.parseInt(cl, 10)
const n = parseInt(cl, 10)
if (Number.isFinite(n) && n > 0) {
expectedChunkSize = n
}
@@ -586,8 +586,8 @@ async function chunkedRangeDownloadToBlob(
}
}
} catch (readError) {
const currentDownload = downloadManager.findById(downloadId)
if (readError.name === 'AbortError' || (currentDownload?.status === 'cancelled')) {
const download = downloadManager.findById(downloadId)
if (readError.name === 'AbortError' || (download?.status === 'cancelled')) {
downloadManager.setStatus(downloadId, 'cancelled')
return null
}
@@ -689,8 +689,8 @@ async function downloadChunkedArchive(url, format, files, filePaths, source, sha
URL.revokeObjectURL(blobUrl)
}, 100)
} catch (error) {
const downloadItem = downloadManager.findById(downloadId)
if (error.name === 'AbortError' || (downloadItem?.status === 'cancelled')) {
const download = downloadManager.findById(downloadId)
if (error.name === 'AbortError' || (download?.status === 'cancelled')) {
downloadManager.setStatus(downloadId, 'cancelled')
return
}
@@ -744,9 +744,9 @@ async function downloadChunked(file, shareHash = "") {
mutations.showPrompt({ name: 'download' })
}
const downloadItem = downloadManager.findById(downloadId)
const download = downloadManager.findById(downloadId)
const abortController = new AbortController()
downloadItem.abortController = abortController
download.abortController = abortController
try {
const blob = await chunkedRangeDownloadToBlob(
@@ -781,8 +781,8 @@ async function downloadChunked(file, shareHash = "") {
}, 100)
} catch (error) {
// Check if download was cancelled by user
const currentDownload = downloadManager.findById(downloadId);
if (error.name === 'AbortError' || (currentDownload?.status === "cancelled")) {
const download = downloadManager.findById(downloadId);
if (error.name === 'AbortError' || (download?.status === "cancelled")) {
downloadManager.setStatus(downloadId, "cancelled")
// Don't throw error or show notification for user-initiated cancellation
return;
+12 -3
View File
@@ -33,6 +33,7 @@ export async function get(username, options = {}) {
// POST /api/users (create user)
// Password-login: tries without X-Password first; on 401 requiring X-Password, opens the prompt and retries.
// options.skipActorPasswordConfirm / pre-set X-Password skip that flow.
// options.actorPasswordPromptI18nKey — optional vue-i18n key (default: confirmPasswordToSaveUser).
export async function create(user, options = {}) {
const mergedHeaders = { ...(options.headers || {}) }
const apiPath = getApiPath('users')
@@ -63,11 +64,13 @@ export async function create(user, options = {}) {
if (!needsActorPasswordRetry(e)) {
throw e
}
const promptKey =
options.actorPasswordPromptI18nKey || 'prompts.confirmPasswordToSaveUser'
return new Promise((resolve, reject) => {
mutations.showPrompt({
name: 'password',
props: {
infoText: i18n.global.t('prompts.confirmPasswordToSaveUser'),
infoText: i18n.global.t(promptKey),
submitLabel: i18n.global.t('general.confirm'),
submitCallback: async (actorPassword) => {
try {
@@ -93,6 +96,7 @@ export async function create(user, options = {}) {
// PATCH /api/users (update user)
// Password-login: tries without X-Password first; on 401 requiring X-Password, opens the prompt and retries.
// options.skipActorPasswordConfirm / pre-set X-Password skip that flow.
// options.actorPasswordPromptI18nKey — optional vue-i18n key (default: confirmPasswordToSaveUser).
export async function update(user, which, options = {}) {
if (!Array.isArray(which) || which.length === 0) {
throw new Error('users.update requires a non-empty which array of field names')
@@ -141,11 +145,13 @@ export async function update(user, which, options = {}) {
if (!needsActorPasswordRetry(e)) {
throw e
}
const promptKey =
options.actorPasswordPromptI18nKey || 'prompts.confirmPasswordToSaveUser'
return new Promise((resolve, reject) => {
mutations.showPrompt({
name: 'password',
props: {
infoText: i18n.global.t('prompts.confirmPasswordToSaveUser'),
infoText: i18n.global.t(promptKey),
submitLabel: i18n.global.t('general.confirm'),
submitCallback: async (actorPassword) => {
try {
@@ -181,6 +187,7 @@ export async function patchPinnedItem({ source, path, name, action = 'add' }) {
// DELETE /api/users (remove user)
// Password-login: tries without X-Password first; on 401 requiring X-Password, opens the prompt and retries.
// options.skipActorPasswordConfirm / pre-set X-Password skip that flow.
// options.actorPasswordPromptI18nKey — optional vue-i18n key (default: confirmPasswordToSaveUser).
export async function deleteUser(username, options = {}) {
const mergedHeaders = { ...(options.headers || {}) }
const apiPath = getApiPath('users', { username: username })
@@ -202,11 +209,13 @@ export async function deleteUser(username, options = {}) {
if (!needsActorPasswordRetry(e)) {
throw e
}
const promptKey =
options.actorPasswordPromptI18nKey || 'prompts.confirmPasswordToSaveUser'
return new Promise((resolve, reject) => {
mutations.showPrompt({
name: 'password',
props: {
infoText: i18n.global.t('prompts.confirmPasswordToSaveUser'),
infoText: i18n.global.t(promptKey),
submitLabel: i18n.global.t('general.confirm'),
submitCallback: async (actorPassword) => {
try {
+1 -1
View File
@@ -51,7 +51,7 @@ function readCacheForScope(scope) {
if (!parsed?.viewToken || !parsed?.expiresAt) {
return null;
}
return { viewToken: parsed.viewToken, expiresAt: parsed.expiresAt };
return parsed;
} catch {
return null;
}
+3 -6
View File
@@ -18,7 +18,7 @@
close: multistate === 'close',
}"
>
<title id="toggle-navbar-title">{{ t('general.close') }}</title>
<title id="toggle-navbar-title">{{ $t('general.close') }}</title>
<path class="line top" d="M 30,33 H 70" />
<path class="line middle" d="M 30,50 H 70" />
<path class="line bottom" d="M 30,67 H 70" />
@@ -56,9 +56,8 @@ export function actionIconClass(icon: string, customIconClass?: string): string
<script setup lang="ts">
import { computed } from "vue";
import { getters, mutations } from "@/store/index.ts";
import type { Prompt } from "@/store/types.ts";
import { useI18n } from "@/i18n/index.ts";
import { getters, mutations } from "@/store";
import type { Prompt } from "@/store/types";
const props = withDefaults(
defineProps<{
@@ -83,8 +82,6 @@ const emit = defineEmits<{
action: [];
}>();
const { t } = useI18n();
const multistate = computed(() => getters.multibuttonState());
const iconClass = computed(() => actionIconClass(props.icon, props.customIconClass));
+3 -8
View File
@@ -44,12 +44,6 @@ export default {
default: false,
},
},
emits: {
"button-clicked": (_value) => true,
"remove-button-clicked": (_value) => true,
disableAll: () => true,
enableAll: () => true,
},
data() {
return {
activeButton: null, // Initially no button is active
@@ -83,11 +77,12 @@ export default {
this.$emit("remove-button-clicked", value);
} else {
// Emit remove-button-clicked for all other indexes
for (const [idx, button] of this.buttons.entries()) {
this.buttons.forEach((button, idx) => {
if (idx !== index) {
this.$emit("remove-button-clicked", button.value);
}
}
});
this.activeButton = index;
this.$emit("button-clicked", value);
}
@@ -0,0 +1,75 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const { store } = vi.hoisted(() => ({ store: { tool: null, showSelectMultiple: false, mobile: false } }));
vi.mock("@/store", () => ({
state: {
get user() {
return { showSelectMultiple: store.showSelectMultiple };
},
},
mutations: {},
getters: {
currentTool: () => store.tool,
isMobile: () => store.mobile,
},
}));
vi.mock("@/api", () => ({ resourcesApi: {}, shareApi: {}, usersApi: {} }));
vi.mock("@/components/Action.vue", () => ({ default: { render: () => null } }));
vi.mock("@/notify", () => ({ notify: {} }));
vi.mock("@/utils/tooltipHelp.js", () => ({ hideInteractiveTooltip: vi.fn(), showHoverTooltip: vi.fn() }));
vi.mock("@/utils", () => ({ url: {} }));
vi.mock("@/utils/clipboard", () => ({ copyToClipboard: vi.fn() }));
vi.mock("@/utils/constants.js", () => ({ globalVars: {} }));
vi.mock("@/utils/download", () => ({ default: vi.fn() }));
vi.mock("@/utils/nativeShare", () => ({ canNativeShare: vi.fn(), nativeShareFile: vi.fn() }));
vi.mock("@/utils/mimetype", () => ({ isRichTextPreviewMimeType: vi.fn(), getTypeInfoFromExt: vi.fn() }));
vi.mock("@/utils/mediaFile", () => ({ isMediaRequest: vi.fn() }));
vi.mock("@/utils/expandTransition", () => ({ expandBeforeEnter: vi.fn(), expandEnter: vi.fn(), expandLeave: vi.fn() }));
import ContextMenu from "./ContextMenu.vue";
const { computed } = ContextMenu;
const inAdvancedSearch = () => computed.isAdvancedSearch.call({});
describe("ContextMenu in advanced search", () => {
beforeEach(() => {
store.tool = null;
store.showSelectMultiple = false;
store.mobile = false;
});
it("detects the advanced search tool", () => {
expect(inAdvancedSearch()).toBe(false);
store.tool = { component: "DuplicateFinder" };
expect(inAdvancedSearch()).toBe(false);
store.tool = { component: "AdvancedSearch" };
expect(inAdvancedSearch()).toBe(true);
});
it("offers Select multiple on desktop even when the user preference is off", () => {
const menu = (isAdvancedSearch) => ({ showLimitedOptions: false, isMultiple: false, isSearchActive: false, isAdvancedSearch });
expect(computed.showSelectMultiple.call(menu(false))).toBe(false);
expect(computed.showSelectMultiple.call(menu(true))).toBe(true);
});
it("doesn't offer Select multiple once multiple mode is on", () => {
expect(
computed.showSelectMultiple.call({ showLimitedOptions: false, isMultiple: true, isSearchActive: false, isAdvancedSearch: true }),
).toBe(false);
});
it("hides the create (+) toggle, since results have no single folder to create in", () => {
const toggle = (isAdvancedSearch) =>
computed.showCreateToggle.call({ showLimitedOptions: false, createOnly: false, isSearchActive: false, isAdvancedSearch });
expect(toggle(false)).toBe(true);
expect(toggle(true)).toBe(false);
});
it("hides Share when nothing is selected, since the results listing has no folder to share", () => {
const share = (isAdvancedSearch, selectedCount) =>
computed.showShareAction.call({ showLimitedOptions: false, isAdvancedSearch, selectedCount, showShare: true });
expect(share(true, 0)).toBe(false);
expect(share(true, 1)).toBe(true);
expect(share(true, 2)).toBe(false);
expect(share(false, 0)).toBe(true);
});
});
@@ -1,176 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createApp, h, type App } from "vue";
const { store } = vi.hoisted(() => ({
store: {
tool: null as null | { component: string },
showSelectMultiple: false,
mobile: false,
share: false,
multiple: false,
selected: [] as string[],
selectedCount: 0,
perms: { view: true, download: true, modify: true, create: true, delete: true, share: true },
},
}));
vi.mock("@/store", () => ({
state: {
selected: [],
multiple: false,
isSearchActive: false,
shareInfo: {},
navigation: {},
sources: { current: "data" },
req: { items: [], source: "data", path: "/" },
user: {
get showSelectMultiple() {
return store.showSelectMultiple;
},
get templates() {
return [];
},
},
},
mutations: {
setContextMenuHasItems: vi.fn(),
setMultiple: vi.fn(),
closeHovers: vi.fn(),
closeTopPrompt: vi.fn(),
showPrompt: vi.fn(),
selectAllItems: vi.fn(),
},
getters: {
isShare: () => store.share,
canCreateInSource: () => true,
globalPermissions: () => ({ share: true, admin: false, create: true }),
sourcePermissions: () => store.perms,
currentPromptName: () => "ContextMenu",
currentPrompt: () => ({ props: {} }),
currentTool: () => store.tool,
currentView: () => "listingView",
isMobile: () => store.mobile,
isAdmin: () => false,
isLoggedIn: () => true,
isPreviewView: () => false,
isSplitViewActive: () => false,
},
}));
vi.mock("@/i18n/index.ts", () => ({
default: { global: { t: (key: string) => key } },
useI18n: () => ({ t: (key: string) => key }),
}));
vi.mock("vue-router", () => ({ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }) }));
vi.mock("@/api", () => ({ resourcesApi: {}, shareApi: {}, usersApi: {} }));
vi.mock("@/notify", () => ({ notify: {} }));
vi.mock("@/utils/tooltipHelp.js", () => ({ hideInteractiveTooltip: vi.fn(), showHoverTooltip: vi.fn() }));
vi.mock("@/utils", () => ({ url: {} }));
vi.mock("@/utils/url.js", () => ({ goToItem: vi.fn(), getParentDir: vi.fn(), removeLastDir: vi.fn() }));
vi.mock("@/utils/clipboard", () => ({ copyToClipboard: vi.fn() }));
vi.mock("@/utils/download", () => ({ default: vi.fn() }));
vi.mock("@/utils/nativeShare", () => ({ canNativeShare: () => false, nativeShareFile: vi.fn() }));
vi.mock("@/utils/mimetype", () => ({
isRichTextPreviewMimeType: () => false,
getTypeInfoFromExt: () => ({ materialSymbol: "", classes: "" }),
}));
vi.mock("@/utils/mediaFile", () => ({ isMediaRequest: () => false }));
vi.mock("@/utils/expandTransition", () => ({ expandBeforeEnter: vi.fn(), expandEnter: vi.fn(), expandLeave: vi.fn() }));
// transitions import (popEnter/popLeave on mount) — leave real, WAAPI absent in jsdom.
import ContextMenu from "./ContextMenu.vue";
let app: App | null = null;
let host: HTMLElement | null = null;
/** Icons of the actions the menu offers, like ContextMenu.copy.test.ts does. */
function offeredIcons(items?: Array<{ name: string; path: string; source: string; isDir?: boolean }>): string[] {
host = document.createElement("div");
document.body.append(host);
app = createApp({
render: () =>
h(ContextMenu, {
items: items ?? [
{ name: "a.txt", path: "/a.txt", source: "data" },
{ name: "b.txt", path: "/b.txt", source: "data" },
],
}),
});
app.mount(host);
return [...host.querySelectorAll("#context-menu .action > i")].map((el) => el.textContent ?? "");
}
const FILE_ITEMS = [
{ name: "a.txt", path: "/a.txt", source: "data" },
{ name: "b.txt", path: "/b.txt", source: "data" },
];
describe("ContextMenu in advanced search", () => {
beforeEach(() => {
store.tool = null;
store.showSelectMultiple = false;
store.mobile = false;
store.share = false;
store.multiple = false;
store.perms = { view: true, download: true, modify: true, create: true, delete: true, share: true };
});
afterEach(() => {
app?.unmount();
host?.remove();
app = null;
host = null;
});
it("detects the advanced search tool", () => {
expect(offeredIcons(FILE_ITEMS)).not.toContain("check_circle");
store.tool = { component: "DuplicateFinder" };
expect(offeredIcons(FILE_ITEMS)).not.toContain("check_circle");
store.tool = { component: "AdvancedSearch" };
expect(offeredIcons(FILE_ITEMS)).toContain("check_circle");
});
it("offers Select multiple on desktop even when the user preference is off", () => {
store.tool = { component: "AdvancedSearch" };
store.showSelectMultiple = false;
expect(offeredIcons(FILE_ITEMS)).toContain("check_circle");
});
it("offers Select multiple with a single or multiple results", () => {
store.tool = { component: "AdvancedSearch" };
store.showSelectMultiple = false;
const one = [{ name: "a.txt", path: "/a.txt", source: "data" }];
expect(offeredIcons(one)).toContain("check_circle");
expect(offeredIcons(FILE_ITEMS)).toContain("check_circle");
});
it("shows Archive in advanced search (create exits stay hidden)", () => {
store.tool = { component: "AdvancedSearch" };
store.perms.create = true;
// Archive needs showCreate=true (createOnly) — advanced search forces it off, so
// archive surfaces when the create panel is open. We assert the observable surface:
// new-folder/file/upload stay hidden while archive/unarchive become available.
const icons = offeredIcons(FILE_ITEMS);
expect(icons).not.toContain("create_new_folder");
expect(icons).not.toContain("note_add");
expect(icons).not.toContain("file_upload");
});
it("hides Share when nothing is selected, since the results listing has no folder to share", () => {
// selectedCount<=1 gate: one item is shareable, two are not; zero is not in adv search.
const one = [{ name: "a.txt", path: "/a.txt", source: "data" }];
store.tool = { component: "AdvancedSearch" };
store.perms.share = true;
expect(offeredIcons(one)).toContain("share");
expect(offeredIcons(FILE_ITEMS)).not.toContain("share");
expect(offeredIcons([])).not.toContain("share");
});
it("in the listing, offers Share even with no items selected", () => {
const one = [{ name: "a.txt", path: "/a.txt", source: "data" }];
store.tool = null;
store.perms.share = true;
expect(offeredIcons(one)).toContain("share");
expect(offeredIcons(FILE_ITEMS)).not.toContain("share");
// Listing allows selectedCount===0 (share the current folder).
expect(offeredIcons([])).toContain("share");
});
});
@@ -0,0 +1,55 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const { store } = vi.hoisted(() => ({
store: { share: false, creatable: [], user: { scopes: [{ name: "data" }, { name: "inbox" }] } },
}));
vi.mock("@/store", () => ({
state: { get user() { return store.user; } },
mutations: {},
getters: {
isShare: () => store.share,
canCreateInSource: (source) => store.creatable.includes(source),
},
}));
vi.mock("@/api", () => ({ resourcesApi: {}, shareApi: {}, usersApi: {} }));
vi.mock("@/components/Action.vue", () => ({ default: { render: () => null } }));
vi.mock("@/notify", () => ({ notify: {} }));
vi.mock("@/utils/tooltipHelp.js", () => ({ hideInteractiveTooltip: vi.fn(), showHoverTooltip: vi.fn() }));
vi.mock("@/utils", () => ({ url: {} }));
vi.mock("@/utils/clipboard", () => ({ copyToClipboard: vi.fn() }));
vi.mock("@/utils/constants.js", () => ({ globalVars: {} }));
vi.mock("@/utils/download", () => ({ default: vi.fn() }));
vi.mock("@/utils/nativeShare", () => ({ canNativeShare: vi.fn(), nativeShareFile: vi.fn() }));
vi.mock("@/utils/mimetype", () => ({ isRichTextPreviewMimeType: vi.fn(), getTypeInfoFromExt: vi.fn() }));
vi.mock("@/utils/mediaFile", () => ({ isMediaRequest: vi.fn() }));
vi.mock("@/utils/expandTransition", () => ({ expandBeforeEnter: vi.fn(), expandEnter: vi.fn(), expandLeave: vi.fn() }));
import ContextMenu from "./ContextMenu.vue";
const showCopy = (permissions) =>
ContextMenu.computed.showCopy.call({ showLimitedOptions: false, showCreate: false, selectedCount: 1, permissions });
describe("ContextMenu Copy", () => {
beforeEach(() => {
store.share = false;
store.creatable = ["inbox"];
});
it("is offered in a read-only source, since copying only reads it", () => {
expect(showCopy({ download: true, modify: false })).toBe(true);
});
it("is hidden when no source accepts the copy", () => {
store.creatable = [];
expect(showCopy({ download: true, modify: false })).toBe(false);
});
it("is hidden without download", () => {
expect(showCopy({ download: false, modify: true })).toBe(false);
});
it("in a share, still requires modify, which the server checks for every change", () => {
store.share = true;
expect(showCopy({ download: true, modify: false })).toBe(false);
expect(showCopy({ download: true, modify: true })).toBe(true);
});
});
@@ -47,10 +47,7 @@ vi.mock("@/store", () => ({
isSplitViewActive: () => false,
},
}));
vi.mock("@/i18n/index.ts", () => ({
default: { global: { t: (key: string) => key } },
useI18n: () => ({ t: (key: string) => key }),
}));
vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
vi.mock("vue-router", () => ({ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }) }));
vi.mock("@/api", () => ({ resourcesApi: {}, shareApi: {}, usersApi: {} }));
vi.mock("@/notify", () => ({ notify: {} }));
+15 -15
View File
@@ -22,7 +22,7 @@
</div>
<hr class="divider">
<p v-if="newFileTemplates.length === 0 && isLoggedIn" class="context-menu-empty-message">
{{ t('prompts.noTemplate') }}
{{ $t('prompts.noTemplate') }}
</p>
<button
v-for="(item, index) in newFileTemplateItems"
@@ -39,12 +39,12 @@
<button
type="button"
class="action no-select"
:aria-label="t('files.emptyFile')"
:title="t('files.emptyFile')"
:aria-label="$t('files.emptyFile')"
:title="$t('files.emptyFile')"
@click="createEmptyFile"
>
<i :class="actionIconClass('insert_drive_file')">insert_drive_file</i>
<span>{{ t('files.emptyFile') }}</span>
<span>{{ $t('files.emptyFile') }}</span>
</button>
</template>
<template v-else>
@@ -66,7 +66,7 @@
<div
v-if="selectedCount > 0"
@mouseleave="hideInteractiveTooltip()"
@mouseenter="showHoverTooltip(t('buttons.selectedCount'), $event)"
@mouseenter="showHoverTooltip($t('buttons.selectedCount'), $event)"
class="button selected-count-header"
:class="{ 'selected-count-header--circle': selectedCount <= 99 }"
>
@@ -112,21 +112,21 @@
<script setup lang="ts">
import { computed, markRaw, onBeforeUnmount, onMounted, ref, toRaw, watch } from "vue";
import { useI18n } from "@/i18n/index.ts";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { resourcesApi, shareApi, usersApi } from "@/api/index.js";
import { notify } from "@/notify/index.ts";
import { getters, mutations, state } from "@/store/index.ts";
import { resourcesApi, shareApi, usersApi } from "@/api";
import { notify } from "@/notify";
import { getters, mutations, state } from "@/store/index.js";
import type { FileListItem, ReqObject } from "@/store/types.ts";
import { hideInteractiveTooltip, showHoverTooltip } from "@/utils/tooltipHelp.js";
import { goToItem, getParentDir, removeLastDir } from "@/utils/url.js";
import { copyToClipboard } from "@/utils/clipboard.js";
import downloadFiles from "@/utils/download.js";
import { canNativeShare, nativeShareFile } from "@/utils/nativeShare.js";
import { isRichTextPreviewMimeType, getTypeInfoFromExt } from "@/utils/mimetype.js";
import { isMediaRequest } from "@/utils/mediaFile.js";
import { copyToClipboard } from "@/utils/clipboard";
import downloadFiles from "@/utils/download";
import { canNativeShare, nativeShareFile } from "@/utils/nativeShare";
import { isRichTextPreviewMimeType, getTypeInfoFromExt } from "@/utils/mimetype";
import { isMediaRequest } from "@/utils/mediaFile";
import { actionIconClass } from "@/components/Action.vue";
import { popEnter, popLeave } from "@/utils/transitions.ts";
import { popEnter, popLeave } from "@/utils/transitions";
type MenuItem = FileListItem & { isDir?: boolean; from?: string };
@@ -27,7 +27,7 @@ import {
createLightningStrike,
prefersReducedMotion,
type LightningStrike,
} from "@/utils/lightning-bolt.ts";
} from "@/utils/lightning-bolt";
type Bolt = LightningStrike & { id: number };
+1 -1
View File
@@ -8,7 +8,7 @@
</template>
<script>
import { notify } from "@/notify/index.ts";
import { notify } from "@/notify";
export default {
name: "load-failed",
+5 -7
View File
@@ -11,7 +11,7 @@
@keydown.esc.prevent="$emit('close')"
/>
</div>
<div class="menu-option-list-scroll" :style="scrollStyle">
<div ref="scroll" class="menu-option-list-scroll" :style="scrollStyle">
<button
v-for="option in filteredOptions"
:key="optionKey(option.value)"
@@ -24,7 +24,7 @@
}"
:aria-selected="isSelected(option.value) ? 'true' : 'false'"
:disabled="option.disabled"
@click="$emit('option-select', option)"
@click="$emit('select', option)"
>
<span>{{ option.label }}</span>
</button>
@@ -69,11 +69,9 @@ export default {
default: undefined,
},
},
emits: {
"option-select": (_option) => true,
"update:searchQuery": (_query) => true,
close: () => true,
},
emits: ["select", "update:searchQuery", "close"],
computed: {
resolvedSearchPlaceholder() {
return this.searchPlaceholder || this.$t("general.search");
+1 -1
View File
@@ -55,7 +55,7 @@
</template>
<script>
import { notify } from "@/notify/index.ts";
import { notify } from "@/notify";
export default {
name: "notifications",
+12 -16
View File
@@ -47,15 +47,12 @@ export default {
default: 0,
},
max: {
type: [Number, String],
default: 100,
},
valBackground: {
type: [Number, String],
"val-background": {
default: null,
},
valText: {
type: [Number, String],
"val-text": {
default: null,
},
unit: {
@@ -63,24 +60,23 @@ export default {
default: "",
},
size: {
type: [Number, String],
// either a number (pixel width/height) or 'tiny', 'small',
// 'medium', 'large', 'huge', 'massive' for common sizes
default: "big",
},
bgColor: {
"bg-color": {
type: String,
default: "#eee",
},
barColor: {
"bar-color": {
type: String,
default: "var(--primaryColor)", // match .blue color to Material Design's 'Blue 500' color
},
barTransition: {
"bar-transition": {
type: String,
default: "all 0.5s ease",
},
barBorderRadius: {
"bar-border-radius": {
type: Number,
default: 8, // ~0.5em at default font size
},
@@ -92,19 +88,19 @@ export default {
type: String,
default: "",
},
textAlign: {
"text-align": {
type: String,
default: "center", // 'left', 'right'
},
textPosition: {
"text-position": {
type: String,
default: "inside", // 'bottom', 'top', 'middle', 'inside'
},
fontSize: {
"font-size": {
type: Number,
default: 13,
},
textFgColor: {
"text-fg-color": {
type: String,
default: "#000",
},
@@ -112,7 +108,7 @@ export default {
type: String,
default: 'default',
},
helpText: {
"help-text": {
type: String,
default: "",
},
@@ -137,7 +133,7 @@ export default {
displayed_text() {
// Use valText if provided (for hybrid mode text override), otherwise use val
const displayVal = this.valText !== null ? this.valText : this.val;
if (!isNumber(displayVal)) return displayVal;
// Cap % like the bar fill so nested-mount indexed size > partition total
+24 -23
View File
@@ -3,8 +3,8 @@
<!-- Search input section -->
<div class="search-input-container">
<!-- Close button visible when search is active -->
<button v-if="active" type="button" class="action" @click="close" :aria-label="t('general.close')"
:title="t('general.close')">
<button v-if="active" type="button" class="action" @click="close" :aria-label="$t('general.close')"
:title="$t('general.close')">
<i class="material-symbols">close</i>
</button>
<!-- Search icon when search is not active -->
@@ -12,13 +12,13 @@
<!-- Input field for search -->
<input id="search-input" type="text"
@keyup.exact="keyup" @input="onInput" ref="input" :autofocus="active" v-model.trim="value"
aria-label="search input" :placeholder="t('general.search', { suffix: '...' })" />
aria-label="search input" :placeholder="$t('general.search', { suffix: '...' })" />
<div v-if="eventTheme === 'halloween'" class="halloween-eyes" aria-hidden="true">
<div class="eye"><div class="pupil"></div></div>
<div class="eye right"><div class="pupil"></div></div>
</div>
</div>
<div v-show="active" id="results">
<div v-show="active" id="results" ref="result">
<div class="inputWrapper">
<ExpandDropdown
v-if="multipleSources"
@@ -27,13 +27,13 @@
transparent
:options="searchSourceOptions"
all-value="__all__"
:all-selected-label="t('general.all')"
:all-selected-label="$t('general.all')"
aria-label="search sources dropdown"
@update:model-value="updateSource"
/>
<!-- Formatted display of selected value -->
<div class="searchContext">{{ t("search.searchContext", { context: getContext }) }}</div>
<div class="searchContext">{{ $t("search.searchContext", { context: getContext }) }}</div>
</div>
<div id="result-list" ref="resultListEl">
@@ -48,8 +48,8 @@
<ToggleSwitch
class="item"
v-model="showPreviewImages"
:name="t('search.showPreviewImages')"
:description="t('search.showPreviewImagesDescription')"
:name="$t('search.showPreviewImages')"
:description="$t('search.showPreviewImagesDescription')"
/>
</template>
</SearchFilters>
@@ -90,6 +90,7 @@
:thumbnail-url="showPreviewImages ? getThumbnailUrl(s) : ''"
/>
<span class="text-container">
<!-- eslint-disable-next-line @intlify/vue-i18n/no-raw-text -->
{{ basePath(s.path, s.type === "directory") }}{{ baseName(s.path) }}
</span>
<div class="filesize">{{ humanSize(s.size) }}</div>
@@ -104,7 +105,7 @@
class="button open-advanced-search-button"
@click.stop.prevent="openInAdvancedSearch"
>
{{ t("search.openInAdvancedSearch") }}
{{ $t("search.openInAdvancedSearch") }}
</button>
</div>
</div>
@@ -112,26 +113,26 @@
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, toRefs, useTemplateRef, watch, type Ref } from "vue";
import { useI18n } from "@/i18n/index.ts";
import { useListingContextMenu } from "@/composables/useListingContextMenu.ts";
import { useSearchFilters } from "@/composables/useSearchFilters.ts";
import { useSearchRequest } from "@/composables/useSearchRequest.ts";
import { resourcesApi, toolsApi } from "@/api/index.js";
import { computed, nextTick, onBeforeUnmount, onMounted, ref, toRefs, watch, type Ref } from "vue";
import { useI18n } from "vue-i18n";
import { useListingContextMenu } from "@/composables/useListingContextMenu";
import { useSearchFilters } from "@/composables/useSearchFilters";
import { useSearchRequest } from "@/composables/useSearchRequest";
import { resourcesApi, toolsApi } from "@/api";
import HelpTooltipIcon from "@/components/HelpTooltipIcon.vue";
import Icon from "@/components/files/Icon.vue";
import LoadingSpinner from "@/components/LoadingSpinner.vue";
import SearchFilters from "@/components/tools/SearchFilters.vue";
import ExpandDropdown from "@/components/settings/ExpandDropdown.vue";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
import { router } from "@/router/index.ts";
import { getters, mutations, state } from "@/store/index.ts";
import type { FileListItem } from "@/store/types.ts";
import { url } from "@/utils/index.ts";
import { globalVars } from "@/utils/constants.ts";
import { router } from "@/router";
import { getters, mutations, state } from "@/store";
import type { FileListItem } from "@/store/types";
import { url } from "@/utils/";
import { globalVars } from "@/utils/constants";
import { debounce } from "@/utils/debounce.js";
import { sortedItems } from "@/utils/sort.ts";
import { getHumanReadableFilesize } from "@/utils/filesizes.js";
import { getHumanReadableFilesize } from "@/utils/filesizes";
import { isTypeAheadSessionActive } from "@/utils/listingTypeAhead.js";
import { shouldIgnoreOutsideTap } from "@/utils/tooltipHelp.js";
@@ -149,8 +150,8 @@ interface SearchResult {
const { t } = useI18n();
const resultListEl = useTemplateRef<HTMLElement>("resultListEl");
const input = useTemplateRef<HTMLInputElement>("input");
const resultListEl = ref<HTMLElement | null>(null);
const input = ref<HTMLInputElement | null>(null);
const noneMessage = ref(t("search.typeToSearch", { minSearchLength: globalVars.minSearchLength }));
const showPreviewImages = ref(false);
const advancedOptionsExpanded = ref(false);
+2 -2
View File
@@ -23,8 +23,8 @@
import Breadcrumbs from "@/components/files/Breadcrumbs.vue";
import ListingHeader from "@/components/files/ListingHeader.vue";
import DuplicateFinderActions from "@/components/tools/DuplicateFinderActions.vue";
import { getters, state } from "@/store/index.ts";
import { eventBus } from "@/store/eventBus.ts";
import { getters, state } from "@/store";
import { eventBus } from "@/store/eventBus";
export default {
name: "Shelf",
+5 -6
View File
@@ -36,8 +36,7 @@
max="24"
step="1"
/>
<!-- i18n-ignore -->
<span class="size-label">{{ editorFontSize }}px</span>
<span class="size-label">{{ editorFontSize }}px</span> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
</div>
</div>
@@ -45,8 +44,8 @@
</template>
<script>
import { getters, mutations, state } from "@/store/index.ts";
import { getHumanReadableFilesize } from "@/utils/filesizes.js";
import { getters, mutations, state } from "@/store";
import { getHumanReadableFilesize } from "@/utils/filesizes";
export default {
name: "StatusBar",
@@ -169,7 +168,7 @@ export default {
},
methods: {
updateGallerySize(event) {
const newValue = Number.parseInt(event.target.value, 10);
const newValue = parseInt(event.target.value, 10);
this.gallerySize = newValue;
},
commitGallerySize() {
@@ -278,7 +277,7 @@ export default {
.button {
padding: 0 0.5em;
font-size: 0.9em;
font-weight: 700;
font-weight: bold;
cursor: unset;
}
+2 -1
View File
@@ -12,13 +12,14 @@
</template>
<script>
import { getIconClass } from "@/utils/material-symbols.js";
import { getIconClass } from "@/utils/material-symbols";
export default {
name: "Toast",
props: {
toasts: {
type: Array,
required: true,
default: () => [],
},
},
+3 -3
View File
@@ -19,16 +19,16 @@
</template>
<script setup lang="ts">
import { computed, nextTick, ref, useTemplateRef, watch } from "vue";
import { computed, nextTick, ref, watch } from "vue";
import type { CSSProperties } from "vue";
import { useRoute } from "vue-router";
import { state } from "@/store/index.ts";
import { state } from "@/store";
import { hideInteractiveTooltip } from "@/utils/tooltipHelp.js";
const margin = 15;
const adjustedX = ref(0);
const adjustedY = ref(0);
const tooltipRef = useTemplateRef<HTMLElement>("tooltipRef");
const tooltipRef = ref<HTMLElement | null>(null);
const route = useRoute();
const tooltip = computed(() => state.tooltip);
+23 -27
View File
@@ -18,7 +18,7 @@
position-mode="absolute"
:edge-offset="{ top: '0.5em', right: '0.5em' }"
:auto-hide="false"
@press="lyricsScrollLocked = !lyricsScrollLocked"
@click="lyricsScrollLocked = !lyricsScrollLocked"
:label="lyricsLockToggleLabel"
/>
<!-- Scrollable area -->
@@ -61,7 +61,7 @@
position-mode="absolute"
:edge-offset="{ top: '0.5em', right: '0.5em' }"
:auto-hide="false"
@press="showVisualizerSettings"
@click="showVisualizerSettings"
:label="visualizerSettingsLabel"
/>
<canvas ref="visualizerCanvas" class="visualizer-canvas"></canvas>
@@ -74,7 +74,7 @@
import SlidingTabs from "@/components/settings/SlidingTabs.vue";
import PlaybackQueue from "@/components/prompts/PlaybackQueue.vue";
import FloatingActionButton from "@/components/settings/FloatingActionButton.vue";
import { mutations, state } from "@/store/index.ts";
import { mutations, state } from "@/store";
import { visualizerConfig } from "@/utils/visualizerConfig.js";
const LAST_TAB_KEY = 'plyrSidePanelActiveTab';
@@ -111,10 +111,7 @@ export default {
audioContext: { type: Object, default: null },
audioSource: { type: Object, default: null }, // MediaElementAudioSourceNode, see https://developer.mozilla.org/en-US/docs/Web/API/MediaElementAudioSourceNode
},
emits: {
seek: (timestamp) => typeof timestamp === "number",
"needs-audio-graph": () => true,
},
emits: ["seek", "needs-audio-graph"],
data() {
return {
activeTab: (() => {
@@ -122,7 +119,6 @@ export default {
return stored && ['queue', 'lyrics', 'visualizer'].includes(stored) ? stored : 'queue';
})(),
lyricsScrollLocked: false,
resizeObserver: null,
// Visualizer state
visualizerAnalyserLeft: null,
visualizerAnalyserRight: null,
@@ -248,8 +244,19 @@ export default {
this.resizeObserver = new ResizeObserver(() => {
if (this.activeTab === 'visualizer' && this.visualizerAnalyserLeft) this.resizeVisualizer();
});
window.addEventListener('resize', this.onWindowResize);
document.addEventListener('visibilitychange', this.onVisibilityChange);
this.windowResizeHandler = () => {
if (this.activeTab === 'visualizer' && this.visualizerAnalyserLeft) this.resizeVisualizer();
};
window.addEventListener('resize', this.windowResizeHandler);
this.visibilityChangeHandler = () => {
if (this.activeTab !== 'visualizer') return;
if (document.hidden) {
this.stopVisualizer();
} else {
this.startVisualizer();
}
};
document.addEventListener('visibilitychange', this.visibilityChangeHandler);
await this.$nextTick();
const container = this.$el?.querySelector('.tab-visualizer');
if (container) this.resizeObserver.observe(container);
@@ -257,23 +264,12 @@ export default {
beforeUnmount() {
document.removeEventListener('keydown', this.onKeyDown);
this.resizeObserver?.disconnect();
window.removeEventListener('resize', this.onWindowResize);
document.removeEventListener('visibilitychange', this.onVisibilityChange);
window.removeEventListener('resize', this.windowResizeHandler);
document.removeEventListener('visibilitychange', this.visibilityChangeHandler);
this.stopVisualizer();
this.fullCleanup();
},
methods: {
onWindowResize() {
if (this.activeTab === 'visualizer' && this.visualizerAnalyserLeft) this.resizeVisualizer();
},
onVisibilityChange() {
if (this.activeTab !== 'visualizer') return;
if (document.hidden) {
this.stopVisualizer();
} else {
this.startVisualizer();
}
},
scrollToActiveLine() {
if (this.lyricsScrollLocked) return;
const el = this.$refs.lyricsScrollable;
@@ -675,7 +671,7 @@ export default {
};
// right half - ascending hz means x increases (center to right edge)
let lastXRight = Number.NEGATIVE_INFINITY;
let lastXRight = -Infinity;
for (const { hz, label } of visibleTicks) {
const x = hzToBarX(hz, halfCount);
if (x === null || x - lastXRight < 20) continue; // if too near on this side, skip
@@ -686,7 +682,7 @@ export default {
}
// left half - ascending hz means x decreases (center to left edge)
let lastXLeft = Number.POSITIVE_INFINITY;
let lastXLeft = Infinity;
for (const { hz, label } of visibleTicks) {
const x = hzToBarX(hz, 0);
if (x === null || lastXLeft - x < 20) continue;
@@ -716,7 +712,7 @@ export default {
const decay = 0.98;
const prev = peaks.at(index) ?? 0;
const newValue = Math.max(currentNorm, prev * decay);
peaks[index] = newValue;
peaks.splice(index, 1, newValue);
},
drawPeaks(ctx) {
const { showPeaks } = this.visualizerConfig;
@@ -864,7 +860,7 @@ export default {
.lyric-line.active {
opacity: 1;
font-weight: 700;
font-weight: bold;
color: var(--primaryColor);
font-size: 1.33rem;
animation: lyric-line-in 0.3s ease;
+10 -15
View File
@@ -32,13 +32,13 @@
</template>
<script>
import { resourcesApi } from "@/api/index.js";
import { notify } from "@/notify/index.ts";
import { getters, mutations, state } from "@/store/index.ts";
import { url } from "@/utils/index.ts";
import { resourcesApi } from "@/api";
import { notify } from "@/notify";
import { getters, mutations, state } from "@/store";
import { url } from "@/utils";
import { getObjectProperty } from '@/utils/object.js';
import { goToItemNotificationButton } from "@/utils/notificationActions.js";
import { notifyMoveCopyFailure } from "@/utils/appNotifications.js";
import { goToItemNotificationButton } from "@/utils/notificationActions";
import { notifyMoveCopyFailure } from "@/utils/appNotifications";
export default {
name: "breadcrumbs",
@@ -48,12 +48,7 @@ export default {
dragOverItem: null, // Track which breadcrumb is being dragged over
};
},
props: {
noLink: {
type: Boolean,
default: false,
},
},
props: ["noLink"],
mounted() {
this.updatePaths();
window.addEventListener('dragend', this.clearDragState);
@@ -102,7 +97,7 @@ export default {
originalParts.shift();
encodedParts.shift();
}
if (originalParts.at(-1) === "") {
if (originalParts[originalParts.length - 1] === "") {
originalParts.pop();
encodedParts.pop();
}
@@ -309,10 +304,10 @@ export default {
mutations.showPrompt({
name: "replace-rename",
pinned: true,
confirm: (e, option) => {
confirm: (event, option) => {
const overwrite = option === "overwrite";
const rename = option === "rename";
e.preventDefault();
event.preventDefault();
mutations.closeTopPrompt();
void moveAction(overwrite, rename);
},
@@ -104,8 +104,8 @@
ref="extraMenuTrigger"
type="button"
class="editor-toolbar-btn"
:title="t('editor.md.moreOptions')"
:aria-label="t('editor.md.moreOptions')"
:title="$t('editor.md.moreOptions')"
:aria-label="$t('editor.md.moreOptions')"
@mousedown.prevent
@click="toggleMenu('extra')"
>
@@ -134,16 +134,16 @@
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, reactive, ref, useTemplateRef, watch } from "vue";
import { useI18n } from "@/i18n/index.ts";
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import ace from "ace-builds";
import type { Ace } from "ace-builds";
import { mutations, state, getters } from "@/store/index.ts";
import { eventBus } from "@/store/eventBus.ts";
import { mutations, state, getters } from "@/store";
import { eventBus } from "@/store/eventBus";
import { removeLastDir } from "@/utils/url.js";
import { popEnter, popLeave } from "@/utils/transitions.ts";
import { copyToClipboard } from "@/utils/clipboard.js";
import { notify } from "@/notify/index.ts";
import { notify } from "@/notify";
interface AnchorRange {
start: Ace.Anchor;
@@ -221,8 +221,8 @@ const lastColors = reactive(new Map<string, string>([
const colorInputRefs = new Map<string, HTMLInputElement>();
const iconMenuTriggerEls = new Map<"align" | "clipboard", HTMLElement>();
const iconMenuEls = new Map<"align" | "clipboard", HTMLElement>();
const extraMenuTrigger = useTemplateRef<HTMLElement>("extraMenuTrigger");
const extraMenu = useTemplateRef<HTMLElement>("extraMenu");
const extraMenuTrigger = ref<HTMLElement | null>(null);
const extraMenu = ref<HTMLElement | null>(null);
const toolbarButtons = computed((): ToolbarButton[] => {
// alwaysAvailable are for buttons that will be available for all filetypes, not just markdown.
+12 -14
View File
@@ -6,6 +6,7 @@
v-if="thumbnailSrc && !fullImageLoaded && !isTiff"
:src="thumbnailSrc"
class="image-ex-img"
ref="thumbnail"
aria-hidden="true"
/>
@@ -37,13 +38,13 @@
<script>
import LoadingSpinner from "@/components/LoadingSpinner.vue";
import { notify } from "@/notify/index.ts";
import { getters, mutations, state } from "@/store/index.ts";
import { notify } from "@/notify";
import { getters, mutations, state } from '@/store';
import { acquireBestCachedThumbnailBlob, getBestCachedImage, releaseThumbnailBlob } from "@/utils/cache/imageCache.ts";
import { isRawImageMimeType } from "@/utils/mimetype.js";
import { resourcesApi } from "@/api/index.js";
import { isRawImageMimeType } from "@/utils/mimetype";
import { resourcesApi } from "@/api";
import { refreshViewToken, requestViewIdentity } from "@/api/viewToken.js";
import throttle from "@/utils/throttle.js";
import throttle from "@/utils/throttle";
export default {
components: {
@@ -55,14 +56,8 @@ export default {
default: null,
},
},
emits: {
"navigate-previous": () => true,
"navigate-next": () => true,
"close-preview": () => true,
},
data() {
return {
thumbBlobKey: null, // only read in lifecycle/sync code, never during render
moveDisabledTime: 200,
classList: [],
zoomStep: 0.25,
@@ -218,6 +213,9 @@ export default {
return this.edgeDy >= this.edgeCommitY && ay >= ax;
},
},
beforeCreate() {
this.thumbBlobKey = null;
},
created() {
this.syncThumbnailBlob();
},
@@ -527,7 +525,7 @@ export default {
this.showDismissHint = false;
} else {
this.dragOffsetX = 0;
const downward = Math.max(this.edgeDy, 0);
const downward = this.edgeDy > 0 ? this.edgeDy : 0;
this.dragOffsetY = this.rubberband(downward, this.edgeRubberMax);
this.showDismissHint = this.edgeDy >= this.edgeHintPx;
this.showNavHint = false;
@@ -551,7 +549,7 @@ export default {
this.showDismissHint = false;
} else {
this.dragOffsetX = 0;
const downward = Math.max(this.edgeDy, 0);
const downward = this.edgeDy > 0 ? this.edgeDy : 0;
this.dragOffsetY = this.rubberband(downward, this.edgeRubberMax);
this.showDismissHint = this.edgeDy >= this.edgeHintPx;
this.showNavHint = false;
@@ -815,7 +813,7 @@ export default {
const p1 = event.targetTouches[0];
const p2 = event.targetTouches[1];
const touchDistance = Math.hypot(p2.pageX - p1.pageX, p2.pageY - p1.pageY);
const touchDistance = Math.sqrt((p2.pageX - p1.pageX) ** 2 + (p2.pageY - p1.pageY) ** 2);
if (!this.lastTouchDistance) {
this.lastTouchDistance = touchDistance;
@@ -0,0 +1,112 @@
import { createApp, h, nextTick } from "vue";
import { afterEach, describe, expect, it, vi } from "vitest";
const { fetchFiles, state } = vi.hoisted(() => ({
fetchFiles: vi.fn(),
state: { req: {}, prompts: [], selected: [], sources: { info: { data: {} } } },
}));
vi.mock("@/api", () => ({ resourcesApi: { fetchFiles } }));
vi.mock("@/store", () => ({
state,
mutations: {},
getters: {
isShare: () => false,
isMobile: () => false,
currentPromptName: () => null,
pickerSorting: () => ({ by: "name", asc: true }),
},
}));
vi.mock("@/utils", async () => {
const { removeLastDir } = await import("@/utils/url.js");
return { url: { removeLastDir } };
});
vi.mock("@/router/index.ts", () => ({ router: {} }));
vi.mock("@/components/files/ListingHeader.vue", () => ({ default: { render: () => null } }));
vi.mock("@/components/files/ListingItem.vue", () => ({
default: {
props: ["name"],
render() {
return h("button", {}, this.name);
},
},
}));
import FileList from "./FileList.vue";
let app, root;
const selection = vi.fn();
function mount(items = [], path = "/child/") {
state.req = { source: "data", path, items };
root = document.createElement("div");
document.body.append(root);
app = createApp(FileList, { hidePathChrome: true, "onUpdate:selected": selection });
app.config.globalProperties.$t = (key) => key;
app.mount(root);
}
function row(name) {
return Array.from(root.querySelectorAll("button")).find((button) => button.textContent === name);
}
afterEach(() => {
app?.unmount();
root?.remove();
fetchFiles.mockReset();
selection.mockReset();
});
describe("file picker parent navigation", () => {
it("loads the parent and shows sibling folders after one click on '..'", async () => {
mount();
fetchFiles.mockResolvedValue({
source: "data",
items: [{ name: "sibling", path: "/sibling/", type: "directory" }],
});
await nextTick();
row("..").click();
expect(selection).toHaveBeenLastCalledWith(expect.objectContaining({ path: "/", source: "data" }));
expect(fetchFiles).toHaveBeenCalledExactlyOnceWith("data", "/");
await vi.waitFor(() => expect(row("sibling")).toBeDefined());
});
it("keeps single-click selection and double-click navigation for ordinary folders", async () => {
mount([{ name: "nested", path: "/child/nested/", type: "directory" }]);
fetchFiles.mockResolvedValue({ source: "data", items: [] });
await nextTick();
row("nested").click();
expect(fetchFiles).not.toHaveBeenCalled();
row("nested").dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
expect(fetchFiles).toHaveBeenCalledExactlyOnceWith("data", "/child/nested/");
});
it("does not fetch the parent again when the same row receives a double-click", async () => {
mount();
fetchFiles.mockResolvedValue({ source: "data", items: [] });
await nextTick();
const parent = row("..");
parent.click();
parent.click();
parent.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
expect(fetchFiles).toHaveBeenCalledExactlyOnceWith("data", "/");
});
it("ignores the rest of a double-click on a replacement parent row", async () => {
mount([], "/parent/child/");
fetchFiles.mockResolvedValue({ source: "data", items: [] });
await nextTick();
const firstParent = row("..");
firstParent.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 }));
await vi.waitFor(() => {
expect(row("..")).toBeDefined();
expect(row("..")).not.toBe(firstParent);
});
const nextParent = row("..");
nextParent.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 2 }));
nextParent.dispatchEvent(new MouseEvent("dblclick", { bubbles: true, detail: 2 }));
expect(fetchFiles).toHaveBeenCalledExactlyOnceWith("data", "/parent/");
nextParent.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 }));
expect(fetchFiles).toHaveBeenLastCalledWith("data", "/");
expect(fetchFiles).toHaveBeenCalledTimes(2);
});
});
@@ -1,171 +0,0 @@
import { createApp, h, nextTick, type App } from "vue";
import { afterEach, describe, expect, it, vi } from "vitest";
const { fetchFiles, state } = vi.hoisted(() => ({
fetchFiles: vi.fn(),
state: { req: {}, prompts: [], selected: [], sources: { info: { data: {} } } },
}));
// The virtual composable needs measured DOM (jsdom has none), so it just forwards
// groups() as all-items — same seam as the real `useListingVirtualization`.
vi.mock("@/api", () => ({ resourcesApi: { fetchFiles } }));
vi.mock("@/i18n/index.ts", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
vi.mock("@/composables/useListingVirtualization.ts", () => ({
findScrollParents: () => [],
findScroller: () => null,
useListingVirtualization: (options: { groups: () => Array<{ key: string; count: number; at: (index: number) => unknown }> }) => ({
active: { value: false },
group: (key: string) => {
const group = options.groups().find((g) => g.key === key);
if (!group) return { items: [], position: 0, style: undefined };
const items: unknown[] = [];
for (let i = 0; i < group.count; i++) items.push(group.at(i));
return { items, position: 0, style: undefined };
},
scrollToIndex: vi.fn(),
}),
}));
vi.mock("@/store", () => ({
state,
mutations: {
resetSelected: vi.fn(),
setSelected: vi.fn(),
setMultiple: vi.fn(),
closeTopPrompt: vi.fn(),
setNavigationTransitioning: vi.fn(),
},
getters: {
isShare: () => false,
isMobile: () => false,
shareHash: () => "",
currentPromptName: () => null,
pickerSorting: () => ({ by: "name", asc: true }),
navigationSorting: () => ({ by: "name", asc: true }),
sorting: () => ({ by: "name", asc: true }),
searchNavigationItems: () => null,
},
}));
vi.mock("@/utils", async () => {
const { removeLastDir } = await import("@/utils/url.js");
return { url: { removeLastDir } };
});
vi.mock("@/router/index.ts", () => ({ router: {} }));
vi.mock("@/utils/sort.ts", () => ({
sortedItems: (entries: unknown[]) => entries,
}));
vi.mock("@/components/files/ListingHeader.vue", () => ({ default: { render: () => null } }));
vi.mock("@/components/files/ListingItem.vue", () => ({
default: {
props: ["name"],
render(props: { name: string }) {
return h("button", {}, props.name);
},
},
}));
vi.mock("@/components/LoadingSpinner.vue", () => ({ default: { render: () => null } }));
vi.mock("@/components/settings/ExpandDropdown.vue", () => ({ default: { render: () => null } }));
import FileList from "./FileList.vue";
let app: App | null = null;
let root: HTMLElement | null = null;
const selection = vi.fn();
function mount(items: unknown[] = [], path = "/child/") {
state.req = { source: "data", path, items };
root = document.createElement("div");
document.body.append(root);
app = createApp(FileList as never, { hidePathChrome: true, "onUpdate:selected": selection });
app.mount(root);
}
function row(name: string): HTMLElement | undefined {
return Array.from(root?.querySelectorAll("button") ?? []).find(
(button) => button.textContent === name,
) as HTMLElement | undefined;
}
/** Assert-and-return: every spec clicks a row that must exist after mount. */
function mustRow(name: string): HTMLElement {
const found = row(name);
expect(found).toBeDefined();
return found as HTMLElement;
}
afterEach(() => {
app?.unmount();
root?.remove();
app = null;
root = null;
fetchFiles.mockReset();
selection.mockReset();
});
describe("file picker parent navigation", () => {
it("loads the parent and shows sibling folders after one click on '..'", async () => {
mount();
fetchFiles.mockResolvedValue({
source: "data",
items: [{ name: "sibling", path: "/sibling/", type: "directory" }],
});
await nextTick();
mustRow("..").click();
expect(selection).toHaveBeenLastCalledWith(expect.objectContaining({ path: "/", source: "data" }));
expect(fetchFiles).toHaveBeenCalledTimes(1);
expect(fetchFiles).toHaveBeenCalledWith("data", "/");
await vi.waitFor(() => expect(row("sibling")).toBeDefined());
});
it("keeps single-click selection and double-click navigation for ordinary folders", async () => {
mount([{ name: "nested", path: "/child/nested/", type: "directory" }]);
fetchFiles.mockResolvedValue({ source: "data", items: [] });
await nextTick();
mustRow("nested").click();
expect(fetchFiles).not.toHaveBeenCalled();
mustRow("nested").dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
expect(fetchFiles).toHaveBeenCalledTimes(1);
expect(fetchFiles).toHaveBeenCalledWith("data", "/child/nested/");
});
it("does not fetch the parent again when the same row receives a double-click", async () => {
mount();
fetchFiles.mockResolvedValue({ source: "data", items: [] });
await nextTick();
const parent = mustRow("..");
parent.click();
parent.click();
parent.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
expect(fetchFiles).toHaveBeenCalledTimes(1);
expect(fetchFiles).toHaveBeenCalledWith("data", "/");
});
it("ignores the rest of a double-click on a replacement parent row", async () => {
mount([], "/parent/child/");
fetchFiles.mockResolvedValue({ source: "data", items: [] });
await nextTick();
const firstParent = mustRow("..");
firstParent.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 }));
// `withLoading` keeps `loading=true` for 200ms, so the listing container is
// unmounted — the `..` row only returns once it clears, then Vue re-renders it.
await vi.waitFor(() => {
expect(row("..")).toBeDefined();
expect(row("..")).not.toBe(firstParent);
});
// The second click of the double-click lands on the *new* `..` row whose path
// is the parent itself, so it must not refetch the parent — the row still
// carries `path="/parent/"`. The count stays at the single "/parent/" fetch.
const nextParent = mustRow("..");
nextParent.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 2 }));
nextParent.dispatchEvent(new MouseEvent("dblclick", { bubbles: true, detail: 2 }));
expect(fetchFiles.mock.calls).toEqual([["data", "/parent/"]]);
// A fresh single click on the still-mounted `..` row navigates up again,
// to root.
nextParent.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 }));
expect(fetchFiles.mock.calls).toEqual([
["data", "/parent/"],
["data", "/"],
]);
});
});
+13 -33
View File
@@ -2,22 +2,22 @@
<div ref="root" class="card-content" aria-label="file-list-prompt">
<!-- Source Selection Dropdown (hidden when browsing a fixed source, e.g. user scope row) -->
<div v-if="!hidePathChrome && showSourceSelector" class="source-selector" style="margin-bottom: 1rem;">
<label for="destinationSource" style="display: block; margin-bottom: 0.5rem; font-weight: 700;">
{{ t("prompts.destinationSource") }}
<label for="destinationSource" style="display: block; margin-bottom: 0.5rem; font-weight: bold;">
{{ $t("prompts.destinationSource") }}
</label>
<ExpandDropdown
input-id="destinationSource"
v-model="currentSource"
:options="sourceOptions"
:aria-label="t('prompts.destinationSource')"
:aria-label="$t('prompts.destinationSource')"
/>
</div>
<!-- Sortable Column Header (opt-in via sortable prop, e.g. destination pickers) -->
<div v-if="(!hidePathChrome && !fileList) || sortable || $slots.sticky" class="sticky-header" :class="{ 'header-hidden': headerHidden }">
<div v-if="(!hidePathChrome && !fileList) || sortable || $slots.pinned" class="sticky-header" :class="{ 'header-hidden': headerHidden }">
<!-- Current Path Display -->
<div v-if="!hidePathChrome && !fileList" aria-label="filelist-path" class="searchContext button clickable">
{{ t('general.path', { suffix: ':' }) }} {{ sourcePath.path }}
{{ $t('general.path', { suffix: ':' }) }} {{ sourcePath.path }}
</div>
<slot name="sticky" />
<ListingHeader v-if="sortable && !loading" :use-picker-sorting="!fileList" :use-navigation-sorting="!!fileList" />
@@ -68,25 +68,24 @@
</div>
<h2 v-if="filterQuery && !visibleItems.some((item) => item.name !== '..')" class="no-results">
<i class="material-symbols-outlined">search_off</i>
<span>{{ t("tools.advancedSearch.noResults") }}</span>
<span>{{ $t("tools.advancedSearch.noResults") }}</span>
</h2>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, useTemplateRef, watch } from "vue";
import { state, mutations, getters } from "@/store/index.ts";
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { state, mutations, getters } from "@/store";
import type { FileListItem, MediaMetadata } from "@/store/types.ts";
import { url } from "@/utils/index.ts";
import { resourcesApi } from "@/api/index.js";
import { url } from "@/utils";
import { resourcesApi } from "@/api";
import ListingHeader from "@/components/files/ListingHeader.vue";
import ListingItem from "@/components/files/ListingItem.vue";
import LoadingSpinner from "@/components/LoadingSpinner.vue";
import ExpandDropdown from "@/components/settings/ExpandDropdown.vue";
import { sortedItems } from "@/utils/sort.ts";
import { findScrollParents, findScroller, useListingVirtualization } from "@/composables/useListingVirtualization.ts";
import { useI18n } from "@/i18n/index.ts";
type ItemInfo = FileListItem & { isDir?: boolean; hasDuration?: boolean };
@@ -162,14 +161,8 @@ const emit = defineEmits<{
"update:filterQuery": [value: string];
}>();
defineSlots<{
sticky?(): unknown;
}>();
const { t } = useI18n();
const root = useTemplateRef<HTMLElement>("root");
const list = useTemplateRef<HTMLElement>("list");
const root = ref<HTMLElement | null>(null);
const list = ref<HTMLElement | null>(null);
const fallbackModified = new Date().toISOString();
const initialSource = props.browseSource || state.req.source;
@@ -380,7 +373,7 @@ async function withLoading(operation: () => Promise<unknown>) {
} finally {
const elapsed = Date.now() - startTime;
const remaining = Math.max(0, 200 - elapsed);
await new Promise((resolve) => { setTimeout(resolve, remaining); });
await new Promise((resolve) => setTimeout(resolve, remaining));
loading.value = false;
}
}
@@ -561,16 +554,6 @@ function handleItemClick(item: ListEntry, _index: number, event: MouseEvent) {
navigateToItem(item);
return;
}
// Picker #3355: the ".." row is the parent-folder shortcut; a single click
// navigates to it so the copy/move destination picker can go up a level.
// `event.detail > 1` swallows the second half of a double-click, and the
// path check swallows clicks on a stale row that was replaced.
if (item.name === "..") {
if (event.detail > 1 || path.value === item.path) return;
select(item.path);
next(item.path);
return;
}
// Browse mode: single click selects only, emit selected, do not navigate
select(item.path);
}
@@ -578,9 +561,6 @@ function handleItemClick(item: ListEntry, _index: number, event: MouseEvent) {
function handleItemDblClick(item: ListEntry, _index: number, event: MouseEvent) {
event.preventDefault();
event.stopPropagation();
// In browse mode ".." is the single-click parent shortcut; a double-click on it
// navigates nothing extra (main's `if (.. && (!fileList || path === item.path)) return`).
if (item.name === ".." && (!props.fileList || path.value === item.path)) return;
next(item.path);
}
+15 -15
View File
@@ -7,7 +7,7 @@
<!-- Error state -->
<div v-if="error" class="tree-error">
<i class="material-symbols">error</i>
<span>{{ t("prompts.error") }}</span>
<span>{{ $t("prompts.error") }}</span>
</div>
<div v-if="rootNodes.length" ref="listEl" class="tree-list">
<div data-virtual-group="rows" :style="virtual.group('rows').style">
@@ -60,7 +60,7 @@
</a>
<div v-else-if="row.kind === 'empty'" class="tree-empty-folder">
<i class="material-symbols-outlined">sentiment_dissatisfied</i>
<span>{{ t('files.lonely') }}</span>
<span>{{ $t('files.lonely') }}</span>
</div>
<div v-else-if="row.kind === 'loading'" class="tree-loading">
<LoadingSpinner size="small" mode="placeholder" />
@@ -74,24 +74,24 @@
<!-- Empty state -->
<div v-if="rootNodes.length === 0 && !loading && !error" class="tree-empty">
<i class="material-symbols-outlined">sentiment_dissatisfied</i>
{{ t('files.lonely') }}
{{ $t('files.lonely') }}
</div>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, useTemplateRef, watch } from 'vue';
import { resourcesApi } from "@/api/index.js";
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { resourcesApi } from '@/api';
import Icon from '@/components/files/Icon.vue';
import LoadingSpinner from '@/components/LoadingSpinner.vue';
import i18n from '@/i18n/index.ts';
import { state, getters, mutations } from "@/store/index.ts";
import { eventBus } from "@/store/eventBus.ts";
import { state, getters, mutations } from '@/store';
import { eventBus } from '@/store/eventBus';
import type { FileListItem } from '@/store/types.ts';
import { buildItemUrl, goToItem, joinPath } from "@/utils/url.js";
import { goToItemNotificationButton } from "@/utils/notificationActions.js";
import { notify } from "@/notify/index.ts";
import { notifyMoveCopyFailure } from "@/utils/appNotifications.js";
import { buildItemUrl, goToItem, joinPath } from '@/utils/url';
import { goToItemNotificationButton } from '@/utils/notificationActions';
import { notify } from '@/notify';
import { notifyMoveCopyFailure } from '@/utils/appNotifications';
import { getObjectProperty } from '@/utils/object.js';
import { sortedItems } from '@/utils/sort.ts';
import { findScrollParents, useListingVirtualization } from '@/composables/useListingVirtualization.ts';
@@ -162,8 +162,8 @@ const props = withDefaults(
const t = i18n.global.t.bind(i18n.global);
const treeEl = useTemplateRef<HTMLElement>("treeEl");
const listEl = useTemplateRef<HTMLElement>("listEl");
const treeEl = ref<HTMLElement | null>(null);
const listEl = ref<HTMLElement | null>(null);
const rootNodes = ref<TreeNode[]>([]);
const loading = ref(false);
const error = ref<string | null>(null);
@@ -730,10 +730,10 @@ async function handleDrop(event: DragEvent, node: TreeNode) {
mutations.showPrompt({
name: 'replace-rename',
pinned: true,
confirm: async (e: Event, option: string) => {
confirm: async (event: Event, option: string) => {
const overwrite = option === 'overwrite';
const rename = option === 'rename';
e.preventDefault();
event.preventDefault();
mutations.closeTopPrompt();
try {
await performAction(overwrite, rename);
+9 -9
View File
@@ -18,12 +18,12 @@
:fbdata="threeDFbdata"
:is-thumbnail="true"
:add-load-delay="true"
@load-error="handle3DError" />
@error="handle3DError" />
<TextPreview v-else-if="shouldUseTextPreview"
:url="textPreviewUrl"
:language="textPreviewLanguage"
:modified="modified"
@load-error="handleTextPreviewError" />
@error="handleTextPreviewError" />
</span>
<!-- Regular material icon (no preview) -->
<span v-else ref="tileEl" class="image-preview" @mouseenter="hasTextPreview && handleMouseEnter()" @mouseleave="hasTextPreview && handleMouseLeave()">
@@ -40,11 +40,11 @@
</template>
<script setup lang="ts">
import { computed, inject, onBeforeUnmount, onMounted, ref, unref, useTemplateRef, watch, type Ref } from "vue";
import { fetchPreviewImage } from "@/api/resources.js";
import { computed, inject, onBeforeUnmount, onMounted, ref, unref, watch, type Ref } from "vue";
import { fetchPreviewImage } from "@/api/resources";
import { createAsyncComponent } from "@/utils/asyncComponent.js";
import { getTypeInfo } from "@/utils/mimetype.js";
import { getters, mutations, state } from "@/store/index.ts";
import { getTypeInfo } from "@/utils/mimetype";
import { getters, mutations, state } from "@/store";
import {
acquireThumbnailBlob,
getThumbnailBlobKey,
@@ -234,7 +234,7 @@ const textPreviewLanguage = computed(() => languageFromPath(props.filename));
// Measured tile width; only observed for text-previewable files so image tiles pay nothing.
const tileWidth = ref(0);
const tileEl = useTemplateRef<HTMLElement>("tileEl");
const tileEl = ref<HTMLElement | null>(null);
let tileResizeObserver: ResizeObserver | null = null;
function observeTileWidth(el: HTMLElement | null): void {
@@ -319,7 +319,7 @@ function clearPopupHoverTimeout(): void {
function cancelPreloadRequests(): void {
clearPopupHoverTimeout();
for (const timeoutId of previewTimeouts) clearTimeout(timeoutId);
previewTimeouts.forEach(clearTimeout);
previewTimeouts = [];
for (const controller of preloadAbortControllers) {
controller.abort();
@@ -483,7 +483,7 @@ function showPopupPreview(): void {
const updateThumbnail = () => {
if (!state.popupPreviewSourceInfo || state.popupPreviewSourceInfo.path !== props.path) {
for (const timeoutId of previewTimeouts) clearTimeout(timeoutId);
previewTimeouts.forEach(clearTimeout);
previewTimeouts = [];
return;
}
+28 -31
View File
@@ -10,9 +10,8 @@
</template>
<script>
import i18n from "@/i18n/index.ts";
import { state } from "@/store/index.ts";
import { fromNow } from "@/utils/moment.ts";
import { state } from "@/store";
import { fromNow } from "@/utils/moment";
import SettingsTable from "@/components/settings/Table.vue";
export default {
@@ -34,31 +33,29 @@ export default {
];
},
rows() {
return buildIndexInfoRows(this.info, state.user?.locale);
return buildIndexInfoRows(this.info, this.$t, state.user?.locale);
},
},
};
const t = i18n.global.t.bind(i18n.global);
// Export utility functions for use in other components (e.g., generating tooltip HTML)
export function getComplexityLabel(complexity) {
export function getComplexityLabel(complexity, $t) {
// Frontend interprets: 0=unknown, 1=simple, 2-6=normal, 7-9=complex, 10=highlyComplex
if (complexity === 0) return t("general.unknown");
if (complexity === 1) return t("general.simple");
if (complexity >= 2 && complexity <= 6) return t("general.normal");
if (complexity >= 7 && complexity <= 9) return t("general.complex");
if (complexity === 10) return t("index.highlyComplex");
return t("general.unknown");
if (complexity === 0) return $t("general.unknown");
if (complexity === 1) return $t("general.simple");
if (complexity >= 2 && complexity <= 6) return $t("general.normal");
if (complexity >= 7 && complexity <= 9) return $t("general.complex");
if (complexity === 10) return $t("index.highlyComplex");
return $t("general.unknown");
}
export function getStatusLabel(status) {
export function getStatusLabel(status, $t) {
switch (status) {
case "ready": return t("index.ready");
case "indexing": return t("index.indexing");
case "unavailable": return t("index.unavailable");
case "error": return t("general.error");
default: return t("general.unknown");
case "ready": return $t("index.ready");
case "indexing": return $t("index.indexing");
case "unavailable": return $t("index.unavailable");
case "error": return $t("general.error");
default: return $t("general.unknown");
}
}
@@ -74,22 +71,22 @@ export function formatDuration(seconds) {
return Number(seconds);
}
export function formatBooleanYesNo(value) {
return value ? t("general.yes") : t("general.no");
export function formatBooleanYesNo(value, $t) {
return value ? $t("general.yes") : $t("general.no");
}
/** @returns {{ id: string, label: string, value: string | number }[]} */
export function buildIndexInfoRows(info, locale) {
export function buildIndexInfoRows(info, $t, locale) {
return [
{ id: "status", label: t("general.status"), value: getStatusLabel(info.status) },
{ id: "readOnly", label: t("general.readOnly"), value: formatBooleanYesNo(info.readOnly) },
{ id: "private", label: t("general.private"), value: formatBooleanYesNo(info.private) },
{ id: "assessment", label: t("index.assessment"), value: getComplexityLabel(info.complexity || 0) },
{ id: "files", label: t("general.files"), value: info.files || 0 },
{ id: "folders", label: t("general.folders"), value: info.folders || 0 },
{ id: "lastScanned", label: t("index.lastScanned"), value: getHumanReadableTime(info.lastIndex, locale) },
{ id: "quickScan", label: t("index.quickScan"), value: formatDuration(info.quickScanDurationSeconds) },
{ id: "fullScan", label: t("index.fullScan"), value: formatDuration(info.fullScanDurationSeconds) },
{ id: "status", label: $t("general.status"), value: getStatusLabel(info.status, $t) },
{ id: "readOnly", label: $t("general.readOnly"), value: formatBooleanYesNo(info.readOnly, $t) },
{ id: "private", label: $t("general.private"), value: formatBooleanYesNo(info.private, $t) },
{ id: "assessment", label: $t("index.assessment"), value: getComplexityLabel(info.complexity || 0, $t) },
{ id: "files", label: $t("general.files"), value: info.files || 0 },
{ id: "folders", label: $t("general.folders"), value: info.folders || 0 },
{ id: "lastScanned", label: $t("index.lastScanned"), value: getHumanReadableTime(info.lastIndex, locale) },
{ id: "quickScan", label: $t("index.quickScan"), value: formatDuration(info.quickScanDurationSeconds) },
{ id: "fullScan", label: $t("index.fullScan"), value: formatDuration(info.fullScanDurationSeconds) },
];
}
</script>
@@ -7,6 +7,7 @@
:aria-label="open ? $t('general.cancel') : $t('general.search')"
:title="open ? $t('general.cancel') : $t('general.search')"
>
<!-- eslint-disable-next-line @intlify/vue-i18n/no-raw-text -->
<i class="material-symbols">{{ open ? "close" : "search" }}</i>
</button>
<input
@@ -36,9 +37,7 @@ export default {
default: false,
},
},
emits: {
"update:modelValue": (value) => typeof value === "string",
},
emits: ["update:modelValue"],
data() {
return {
open: false,
@@ -97,7 +97,7 @@
</template>
<script>
import { state, getters, mutations } from "@/store/index.ts";
import { state, getters, mutations } from "@/store";
export default {
name: "ListingHeader",
@@ -286,6 +286,7 @@ span {
/* Column widths are shared with the list/compact rows (see listing.css) so the
header lines up with the items and the name column gets the remaining space. */
/* stylelint-disable no-unknown-custom-properties -- defined in css/listing.css */
.desktop-view {
/* same right inset as the list/compact rows */
padding-right: var(--listing-col-gap);
@@ -338,6 +339,7 @@ span {
.desktop-view .duration {
width: var(--listing-col-duration);
}
/* stylelint-enable no-unknown-custom-properties */
i {
font-size: 1.2em;
@@ -356,6 +358,6 @@ p:hover i,
.active,
p:hover {
font-weight: 700;
font-weight: bold;
}
</style>
+47 -47
View File
@@ -53,7 +53,7 @@
class="material-symbols overlay-icon overlay-icon--bottom clickable"
aria-label="Download"
@click.stop.prevent="downloadFile"
>file_download</button>
>file_download</button> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
<div class="text">
@@ -93,23 +93,23 @@
</template>
<script>
import { computed, provide, shallowRef } from "vue";
import { globalVars } from "@/utils/constants.ts";
import downloadFiles from "@/utils/download.js";
import { getHumanReadableFilesize } from "@/utils/filesizes.js";
import { getKindKey } from "@/utils/mimetype.js";
import { isTextPreviewableType } from "@/utils/textPreview.ts";
import { computed, shallowRef } from "vue";
import { globalVars } from "@/utils/constants";
import downloadFiles from "@/utils/download";
import { getHumanReadableFilesize } from "@/utils/filesizes";
import { getKindKey } from "@/utils/mimetype";
import { isTextPreviewableType } from "@/utils/textPreview";
import { hasCachedThumbnailBlob } from "@/utils/cache/imageCache.ts";
import { formatDuration } from "@/utils/files.js";
import { getObjectProperty } from '@/utils/object.js';
import { resourcesApi } from "@/api/index.js";
import { checkConflict } from "@/utils/upload.ts";
import { state, getters, mutations } from "@/store/index.ts"; // Import your custom store
import { url } from "@/utils/index.ts";
import { formatTimestamp, fromNow } from "@/utils/moment.ts";
import { notify } from "@/notify/index.ts";
import { goToItemNotificationButton } from "@/utils/notificationActions.js";
import { notifyMoveCopyFailure } from "@/utils/appNotifications.js";
import { resourcesApi } from "@/api";
import { checkConflict } from "@/utils/upload";
import { state, getters, mutations } from "@/store"; // Import your custom store
import { url } from "@/utils";
import { formatTimestamp, fromNow } from "@/utils/moment";
import { notify } from "@/notify";
import { goToItemNotificationButton } from "@/utils/notificationActions";
import { notifyMoveCopyFailure } from "@/utils/appNotifications";
import Icon from "@/components/files/Icon.vue";
const selectedIndexSet = computed(() => {
@@ -204,29 +204,25 @@ export default {
localSelected: false,
};
},
emits: {
"item-select": (payload) => payload != null && "index" in payload,
"select-range": (payload) => payload != null && "startIndex" in payload && "endIndex" in payload,
beforeCreate() {
// runs before provide(), non-reactive holder on purpose
this.viewportRef = shallowRef(false);
},
setup() {
// The Icons inside this item inject it with Icon.vue
// we're using setup for now temporarily as is more easy than convert the whole component to script setup.
const viewportRef = shallowRef(false);
provide("inView", viewportRef);
return {
setInView(visible) {
viewportRef.value = visible;
},
touches: 0,
touchStartX: 0,
touchStartY: 0,
isLongPress: false,
isSwipe: false,
contextTimeout: null,
observedEl: null,
observer: null,
isUnmounted: false,
};
provide() {
// the Icons inside this item inject it, see Icon.vue
return { inView: this.viewportRef };
},
created() {
// non-reactive on purpose, they're never read by the template
this.touches = 0;
this.touchStartX = 0;
this.touchStartY = 0;
this.isLongPress = false;
this.isSwipe = false;
this.contextTimeout = null;
this.observedEl = null;
this.observer = null;
this.isUnmounted = false;
},
props: {
name: String,
@@ -495,7 +491,7 @@ export default {
if (this.$el && this.$el instanceof Element) {
this.observedEl = this.$el;
viewportCallbacks.set(this.$el, (visible) => {
this.setInView(visible);
this.viewportRef.value = visible;
if (visible) {
this.isThumbnailInView = true;
}
@@ -520,7 +516,7 @@ export default {
downloadFiles(state.selected);
} else {
// Emit selection event for local handling
this.$emit('item-select', { index: this.index, selected: true });
this.$emit('select', { index: this.index, selected: true });
}
},
/** @param {TouchEvent} event */
@@ -618,7 +614,7 @@ export default {
} else {
// Emit selection event for local handling
if (!this.localSelected) {
this.$emit('item-select', { index: this.index, selected: true });
this.$emit('select', { index: this.index, selected: true });
}
}
if (event.dataTransfer) {
@@ -691,7 +687,11 @@ export default {
const destinationDir = this.path;
// If destination dir is the same as or contains the source path, skip
return !(fromPath === destinationDir || fromPath.startsWith(`${destinationDir}/`));
if (fromPath === destinationDir || fromPath.startsWith(`${destinationDir}/`)) {
return false;
}
return true;
});
// If all items were filtered out, silently skip the operation
@@ -755,14 +755,14 @@ export default {
name: "replace-rename",
pinned: true,
/**
* @param {Event} confirmEvent
* @param {Event} event
* @param {string} option
*/
confirm: async (confirmEvent, option) => {
confirm: async (event, option) => {
const overwrite = option === "overwrite";
const rename = option === "rename";
confirmEvent.preventDefault();
event.preventDefault();
mutations.closeTopPrompt();
try {
await action(overwrite, rename);
@@ -805,7 +805,7 @@ export default {
mutations.resetSelected();
mutations.addSelected(this.index);
} else {
this.$emit('item-select', { index: this.index, selected: true });
this.$emit('select', { index: this.index, selected: true });
}
}
}
@@ -899,7 +899,7 @@ export default {
// Local selection handling - emit events instead of updating global state
if (event.shiftKey) {
// Shift-click: select range (emit event for parent to handle)
this.$emit('select-range', {
this.$emit('selectRange', {
startIndex: state.lastSelectedIndex !== null ? state.lastSelectedIndex : this.index,
endIndex: this.index
});
@@ -908,7 +908,7 @@ export default {
// Always toggle - parent component will handle the toggle logic
// Just emit the index, parent will check current state and toggle
this.$emit('item-select', { index: this.index });
this.$emit('select', { index: this.index });
}
},
open() {
@@ -20,19 +20,18 @@
v-if="showSplitViewToggle"
icon="vertical_split"
:label="splitViewActionLabel"
@press="toggleSplitView"
@click="toggleSplitView"
/>
</template>
<script lang="ts">
import type { PropType } from "vue";
import type { Ace } from "ace-builds";
import i18n from "@/i18n/index.ts";
import { state, getters, mutations } from "@/store/index.ts";
import { state, getters, mutations } from "@/store";
import { createAsyncComponent } from "@/utils/asyncComponent.js";
import Scrollbar from "@/components/files/Scrollbar.vue";
import FloatingActionButton from "@/components/settings/FloatingActionButton.vue";
import { createScrollSyncGuard } from "@/utils/markdownScrollSync.ts";
import { createScrollSyncGuard } from "@/utils/markdownScrollSync";
const MD_SPLIT_PERCENT_KEY = "mdSplitPercent";
const LIVE_CONTENT_INTERVAL_MS = 185; // Throttle preview updates to avoid performance issues
@@ -63,9 +62,7 @@ export default {
default: null,
},
},
emits: {
resize: (percent: number) => typeof percent === "number",
},
emits: ["resize"],
data: () => ({
liveMarkdownContent: "", // editor current buffer
liveContentTimer: null as ReturnType<typeof setTimeout> | null,
@@ -115,7 +112,7 @@ export default {
return getters.showSplitViewToggle();
},
splitViewActionLabel() {
return getters.isSplitViewActive() ? i18n.global.t("editor.exitSplitView") : i18n.global.t("editor.splitView");
return getters.isSplitViewActive() ? this.$t("editor.exitSplitView") : this.$t("editor.splitView");
},
},
methods: {
@@ -13,8 +13,8 @@
</template>
<script>
import { mutations, state } from "@/store/index.ts";
import { eventBus } from "@/store/eventBus.ts";
import { mutations, state } from "@/store";
import { eventBus } from "@/store/eventBus";
function normalizeContextId() {
return `path-picker-btn-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
@@ -67,11 +67,7 @@ export default {
},
},
emits: {
"update:path": (path) => typeof path === "string",
"update:source": (source) => typeof source === "string",
navigate: () => true,
},
emits: ["update:path", "update:source", "navigate"],
data() {
return {
@@ -13,16 +13,16 @@
:key="sourceInfo.path"
:url="sourceInfo.textUrl"
:modified="sourceInfo.modified"
@load-error="onTextError"
@error="onTextError"
/>
</div>
<img v-else-if="sourceInfo?.url" :src="sourceInfo.url" :alt="$t('profileSettings.popupPreview')" @load="onImageLoad" />
<img v-else-if="sourceInfo?.url" :src="sourceInfo.url" alt="Popup img" @load="onImageLoad" />
</div>
</template>
<script>
import { createAsyncComponent } from "@/utils/asyncComponent.js";
import { state, getters, mutations } from "@/store/index.ts";
import { state, getters, mutations } from "@/store";
import { setImageLoaded } from "@/utils/cache/imageCache.ts";
export default {
@@ -37,11 +37,14 @@ export default {
top: "0px",
left: "0px",
},
cursorX: 0,
cursorY: 0,
rafId: null,
};
},
beforeCreate() {
// Plain fields on purpose cuz nothing in the template reads them
this.cursorX = 0;
this.cursorY = 0;
this.rafId = null;
},
watch: {
async sourceInfo(newVal) {
if (newVal) {
+5 -4
View File
@@ -32,7 +32,7 @@
</template>
<script>
import { state, mutations, getters } from "@/store/index.ts";
import { state, mutations, getters } from "@/store";
import { eventBus } from "@/store/eventBus.ts";
import { isHtmlMimeType } from "@/utils/mimetype.js";
@@ -63,11 +63,12 @@ export default {
canScroll: false,
resizeObserver: null,
mutationObserver: null,
wrapperObserver: null,
wrapperRect: null,
readyTimeout: null,
};
},
created() {
this.wrapperRect = null;
this.readyTimeout = null;
},
computed: {
isScrollable() {
return getters.isScrollable();
+4 -4
View File
@@ -30,9 +30,9 @@
</template>
<script>
import { state, getters } from "@/store/index.ts";
import { getHumanReadableFilesize } from "@/utils/filesizes.js";
import { getTypeInfo } from "@/utils/mimetype.js";
import { state, getters } from "@/store";
import { getHumanReadableFilesize } from "@/utils/filesizes";
import { getTypeInfo } from "@/utils/mimetype";
export default {
name: "ShareInfo",
@@ -121,7 +121,7 @@ export default {
.share-info__box__header {
font-size: 1.2em;
font-weight: 700;
font-weight: bold;
text-align: center;
padding-bottom: 1em;
border-bottom: 1px solid var(--divider);
@@ -1,96 +1,96 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createApp, h, nextTick } from "vue";
vi.mock("@/store", () => ({
getters: { isDarkMode: () => false },
state: { sessionId: "test-session" },
}));
import TextPreview from "./TextPreview.vue";
import { clearTextPreviewCache } from "@/utils/textPreview.ts";
function payload(overrides: Record<string, unknown> = {}) {
return {
content: "",
kind: "plain",
format: "text",
truncated: false,
size: 1,
...overrides,
};
}
function stubFetch(data: unknown) {
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response(JSON.stringify(data), { status: 200 })),
);
}
async function flush() {
// Wait for the fetch promise chain and queued limiter to settle.
await new Promise((resolve) => { setTimeout(resolve, 0); });
await nextTick();
await nextTick();
}
function mount(props: { url: string; modified?: string | null; language?: string | null }) {
const el = document.createElement("div");
document.body.appendChild(el);
const app = createApp({ render: () => h(TextPreview, props) });
app.mount(el);
return { el, app };
}
describe("TextPreview rendering", () => {
afterEach(() => {
clearTextPreviewCache();
vi.unstubAllGlobals();
document.body.innerHTML = "";
});
it("does not render a truncation fade for a truncated payload", async () => {
stubFetch(payload({ content: "<p>hello world</p>", kind: "html", format: "html", truncated: true, size: 99_999 }));
const { el, app } = mount({ url: "/api/resources/preview/text?path=%2Fa.html", modified: "1" });
await flush();
expect(el.querySelector(".text-preview-html")?.textContent).toContain("hello world");
expect(el.querySelector(".text-preview-fade")).toBeNull();
app.unmount();
});
it("uses the language prop to pick the CSV delimiter", async () => {
stubFetch(payload({ content: "a\tb\n1\t2", kind: "csv" }));
const { el, app } = mount({
url: "/api/resources/preview/text?path=%2Fdata.tsv",
modified: "1",
language: "tsv",
});
await flush();
const cells = el.querySelectorAll(".text-preview-table thead th");
expect(cells).toHaveLength(2);
expect(cells[0]?.textContent).toBe("a");
expect(cells[1]?.textContent).toBe("b");
app.unmount();
});
it("reuses the rendered HTML cache for the same url and modified time", async () => {
stubFetch(payload({ content: "<p>cached</p>", kind: "html", format: "html" }));
const props = { url: "/api/resources/preview/text?path=%2Fb.html", modified: "7" };
const first = mount(props);
await flush();
expect(first.el.querySelector(".text-preview-html")?.textContent).toContain("cached");
first.app.unmount();
// A second mount (as happens when the popup reopens) must not re-fetch.
const fetchMock = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
fetchMock.mockClear();
const second = mount(props);
await flush();
expect(second.el.querySelector(".text-preview-html")?.textContent).toContain("cached");
expect(fetchMock).not.toHaveBeenCalled();
second.app.unmount();
});
});
import { afterEach, describe, expect, it, vi } from "vitest";
import { createApp, h, nextTick } from "vue";
vi.mock("@/store", () => ({
getters: { isDarkMode: () => false },
state: { sessionId: "test-session" },
}));
import TextPreview from "./TextPreview.vue";
import { clearTextPreviewCache } from "@/utils/textPreview.ts";
function payload(overrides: Record<string, unknown> = {}) {
return {
content: "",
kind: "plain",
format: "text",
truncated: false,
size: 1,
...overrides,
};
}
function stubFetch(data: unknown) {
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response(JSON.stringify(data), { status: 200 })),
);
}
async function flush() {
// Wait for the fetch promise chain and queued limiter to settle.
await new Promise((resolve) => setTimeout(resolve, 0));
await nextTick();
await nextTick();
}
function mount(props: { url: string; modified?: string | null; language?: string | null }) {
const el = document.createElement("div");
document.body.appendChild(el);
const app = createApp({ render: () => h(TextPreview, props) });
app.mount(el);
return { el, app };
}
describe("TextPreview rendering", () => {
afterEach(() => {
clearTextPreviewCache();
vi.unstubAllGlobals();
document.body.innerHTML = "";
});
it("does not render a truncation fade for a truncated payload", async () => {
stubFetch(payload({ content: "<p>hello world</p>", kind: "html", format: "html", truncated: true, size: 99_999 }));
const { el, app } = mount({ url: "/api/resources/preview/text?path=%2Fa.html", modified: "1" });
await flush();
expect(el.querySelector(".text-preview-html")?.textContent).toContain("hello world");
expect(el.querySelector(".text-preview-fade")).toBeNull();
app.unmount();
});
it("uses the language prop to pick the CSV delimiter", async () => {
stubFetch(payload({ content: "a\tb\n1\t2", kind: "csv" }));
const { el, app } = mount({
url: "/api/resources/preview/text?path=%2Fdata.tsv",
modified: "1",
language: "tsv",
});
await flush();
const cells = el.querySelectorAll(".text-preview-table thead th");
expect(cells).toHaveLength(2);
expect(cells[0]?.textContent).toBe("a");
expect(cells[1]?.textContent).toBe("b");
app.unmount();
});
it("reuses the rendered HTML cache for the same url and modified time", async () => {
stubFetch(payload({ content: "<p>cached</p>", kind: "html", format: "html" }));
const props = { url: "/api/resources/preview/text?path=%2Fb.html", modified: "7" };
const first = mount(props);
await flush();
expect(first.el.querySelector(".text-preview-html")?.textContent).toContain("cached");
first.app.unmount();
// A second mount (as happens when the popup reopens) must not re-fetch.
const fetchMock = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
fetchMock.mockClear();
const second = mount(props);
await flush();
expect(second.el.querySelector(".text-preview-html")?.textContent).toContain("cached");
expect(fetchMock).not.toHaveBeenCalled();
second.app.unmount();
});
});
@@ -1,5 +1,5 @@
<template>
<div class="text-preview" :class="{ 'text-preview--dark': isDark }" aria-hidden="true">
<div ref="root" class="text-preview" :class="{ 'text-preview--dark': isDark }" aria-hidden="true">
<span v-if="status === 'loading'" class="material-symbols text-preview-placeholder">{{ PLACEHOLDER_ICON }}</span>
<div v-else-if="status === 'ready' && csvTable" class="text-preview-body text-preview-table-wrap">
<table class="text-preview-table">
@@ -15,9 +15,7 @@
</tbody>
</table>
</div>
<!-- biome-ignore lint/nursery/noVueVHtml: renderedHtml is sanitized -->
<div v-else-if="status === 'ready' && renderedHtml" class="text-preview-body text-preview-html" v-html="renderedHtml"></div>
<!-- biome-ignore lint/nursery/noVueVHtml: highlighted is sanitized -->
<pre v-else-if="status === 'ready' && highlighted !== null" class="text-preview-body text-preview-plain hljs" v-html="highlighted"></pre>
<pre v-else-if="status === 'ready' && payload" class="text-preview-body text-preview-plain">{{ payload.content }}</pre>
</div>
@@ -25,7 +23,7 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, shallowRef, watch } from "vue";
import { getters } from "@/store/index.ts";
import { getters } from "@/store";
import { applyHighlightTheme, loadHljs } from "@/utils/highlight.ts";
import { parseDelimited } from "@/utils/delimited.ts";
import {
@@ -51,7 +49,7 @@ const props = defineProps<{
language?: string | null;
}>();
const emit = defineEmits<(e: "load-error") => void>();
const emit = defineEmits<(e: "error") => void>();
// Only plain source files are syntax highlighted. Markdown and HTML are rendered instead.
const HIGHLIGHT_KINDS = new Set(["code", "css"]);
@@ -182,7 +180,7 @@ watch(
} catch {
if (current !== requestId) return;
status.value = "error";
emit("load-error");
emit("error");
}
},
{ immediate: true },
+31 -26
View File
@@ -19,6 +19,7 @@
<!-- Previous button -->
<button
v-if="enabled && hasPrevious"
ref="prevButton"
type="button"
:tabindex="showNav ? 0 : -1"
@click.prevent="handlePrevClick"
@@ -43,13 +44,14 @@
:title="$t('general.previous')"
>
<i class="material-symbols">
{{ dragState.type === 'previous' && dragState.atFullExtent ? 'list_alt' : 'chevron_left' }}
{{ dragState.type === 'previous' && dragState.atFullExtent ? 'list_alt' : 'chevron_left' }} <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</i>
</button>
<!-- Next button -->
<button
v-if="enabled && hasNext"
ref="nextButton"
type="button"
:tabindex="showNav ? 0 : -1"
@click.prevent="handleNextClick"
@@ -68,13 +70,14 @@
:title="$t('general.next')"
>
<i class="material-symbols">
{{ dragState.type === 'next' && dragState.atFullExtent ? 'list_alt' : 'chevron_right' }}
{{ dragState.type === 'next' && dragState.atFullExtent ? 'list_alt' : 'chevron_right' }} <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</i>
</button>
<!-- Close preview (same control as swipe-down / back) -->
<button
v-if="enabled && showPreviewCloseButton"
ref="closeButton"
type="button"
:tabindex="showCloseNavChrome ? 0 : -1"
@click.prevent="handleClosePreviewClick"
@@ -96,11 +99,11 @@
</template>
<script>
import { state, getters, mutations } from "@/store/index.ts";
import throttle from "@/utils/throttle.js";
import { previewViews } from "@/utils/constants.ts";
import { url } from "@/utils/index.ts";
import { resourcesApi } from "@/api/index.js";
import { state, getters, mutations } from "@/store";
import throttle from "@/utils/throttle";
import { previewViews } from "@/utils/constants";
import { url } from "@/utils";
import { resourcesApi } from "@/api";
import { navigatePlaybackQueue } from "@/utils/playbackQueue.js";
import {
isInLeftNavHoverZone,
@@ -124,7 +127,6 @@ export default {
threshold: 0, // Will be calculated as 10em in pixels
atFullExtent: false,
triggered: false,
wasDrag: false,
},
// State tracking
navigationTimeout: null,
@@ -218,12 +220,6 @@ export default {
nextRaw() {
return state.navigation.nextRaw;
},
navigationRequestKey() {
return state.req ? `${state.req.source ?? ""}\u0000${state.req.path ?? ""}` : "";
},
navigationParentItems() {
return state.req?.parentDirItems;
},
currentView() {
const view = getters.currentView();
return view;
@@ -285,6 +281,18 @@ export default {
await this.setupNavigationForCurrentItem();
}
},
'state.req': {
async handler() {
this.updateNavigationEnabled();
// Auto-setup navigation when request changes and we're enabled
if (this.enabled) {
await this.$nextTick();
await this.setupNavigationForCurrentItem();
}
},
deep: true,
immediate: false
},
async enabled(newEnabled) {
if (newEnabled && state.req) {
await this.$nextTick();
@@ -301,21 +309,18 @@ export default {
});
}, 100);
},
navigationRequestKey() {
if (this.enabled && state.req) {
void this.setupNavigationForCurrentItem();
}
},
navigationParentItems() {
if (this.enabled && state.req) {
void this.setupNavigationForCurrentItem();
}
},
navigationSortOverride() {
if (this.enabled && state.req) {
void this.setupNavigationForCurrentItem();
}
},
// Watch for when navigation links are set up
'state.navigation.previousLink'() {
this.showInitialNavigation();
},
'state.navigation.nextLink'() {
this.showInitialNavigation();
},
},
async mounted() {
window.addEventListener("keydown", this.keyEvent);
@@ -329,7 +334,7 @@ export default {
window.addEventListener("mousemove", this.handleGlobalMouseMove, true);
// Calculate 10em threshold in pixels
const emSize = Number.parseFloat(getComputedStyle(document.documentElement).fontSize);
const emSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
this.dragState.threshold = 10 * emSize;
this.updateNavigationEnabled();
@@ -726,7 +731,7 @@ export default {
if (!this.dragState.isDragging) {
// Calculate 10em threshold in pixels if not set
if (!this.dragState.threshold) {
const emSize = Number.parseFloat(getComputedStyle(document.documentElement).fontSize);
const emSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
this.dragState.threshold = 10 * emSize;
}
+10 -10
View File
@@ -38,7 +38,7 @@
<!-- Default behavior banner -->
<div class="card item">
<div class="card-content banner-content">
<i class="material-symbols-outlined">{{ sourceDenyDefault ? 'do_not_disturb_on' : 'check_circle' }}</i>
<i class="material-symbols-outlined">{{ sourceDenyDefault ? 'do_not_disturb_on' : 'check_circle' }}</i> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ $t("access.defaultBehavior", { suffix: ":" }) }} {{ sourceDenyDefault ? $t("access.deny") : $t("access.allow")
}}
<HelpTooltipIcon :text="$t('access.defaultBehaviorDescription')" />
@@ -66,7 +66,7 @@
:icon="addType === 'group' ? 'group_add' : 'person_add'"
class="flat-left form-compact"
:exclude="existingNames"
@selected="addEntries"
@select="addEntries"
/>
<button v-else type="button" class="button form-button flat-left form-compact" @click="addEntries([])">
<i class="material-symbols-outlined">add</i>
@@ -115,9 +115,9 @@
</template>
<script>
import { notify } from "@/notify/index.ts";
import { mutations } from "@/store/index.ts";
import { accessApi } from "@/api/index.js";
import { notify } from "@/notify";
import { mutations } from "@/store";
import { accessApi } from "@/api";
import HelpTooltipIcon from "@/components/HelpTooltipIcon.vue";
import FileList from "../files/FileList.vue";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
@@ -127,8 +127,8 @@ import ExpandDropdown from "@/components/settings/ExpandDropdown.vue";
import ActivityViewerButton from "@/components/settings/ActivityViewerButton.vue";
import SettingsTable from "@/components/settings/Table.vue";
import EntityPickerButton from "@/components/settings/EntityPickerButton.vue";
import { activityViewerPresets } from "@/utils/activityViewerLink.js";
import { eventBus } from "@/store/eventBus.ts";
import { activityViewerPresets } from "@/utils/activityViewerLink";
import { eventBus } from "@/store/eventBus";
export default {
name: "access",
@@ -146,7 +146,7 @@ export default {
props: {
promptId: { type: [String, Number], default: null },
sourceName: { type: String, required: true },
path: { type: String, default: "/" },
path: { type: String, required: true, default: "/" },
embedded: { type: Boolean, default: false }
},
data() {
@@ -402,7 +402,7 @@ export default {
this.saving = true;
let failed = false;
try {
for (const op of this.pendingDeletes.slice()) {
for (const op of [...this.pendingDeletes]) {
await accessApi.del(this.currentSource, this.currentPath, {
allow: op.allow,
ruleCategory: op.ruleCategory,
@@ -411,7 +411,7 @@ export default {
});
this.pendingDeletes.splice(this.pendingDeletes.indexOf(op), 1);
}
for (const op of this.pendingAdds.slice()) {
for (const op of [...this.pendingAdds]) {
await accessApi.add(this.currentSource, this.currentPath, {
allow: op.allow,
ruleCategory: op.ruleCategory,
@@ -52,7 +52,7 @@
>
<span class="permission-name">{{ permission }}</span>
<span class="permission-status" :class="{ enabled: isEnabled, disabled: !isEnabled }">
{{ isEnabled ? '✓' : '✗' }}
{{ isEnabled ? '✓' : '✗' }} <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</span>
</div>
</div>
@@ -72,11 +72,11 @@
</template>
<script>
import { mutations } from "@/store/index.ts";
import { notify } from "@/notify/index.ts";
import { authApi } from "@/api/index.js";
import { eventBus } from "@/store/eventBus.ts";
import { copyToClipboard } from "@/utils/clipboard.js";
import { mutations } from "@/store";
import { notify } from "@/notify";
import { authApi } from "@/api";
import { eventBus } from "@/store/eventBus";
import { copyToClipboard } from "@/utils/clipboard";
export default {
name: "ActionApi",
@@ -25,13 +25,13 @@
<script>
import SettingsTable from "@/components/settings/Table.vue";
import { formatTimestamp } from "@/utils/moment.ts";
import { formatTimestamp } from "@/utils/moment";
import {
buildActivityDetailRows,
activityEventLabel,
activityRowPath,
activityRowSource,
} from "@/utils/activityDetails.js";
} from "@/utils/activityDetails";
export default {
name: "ActivityEventDetails",
@@ -50,7 +50,7 @@ export default {
},
computed: {
eventLabel() {
return activityEventLabel(this.row.eventType);
return activityEventLabel(this.row.eventType, this.$t);
},
detailColumns() {
return [
@@ -102,7 +102,7 @@ export default {
return rows;
},
detailRows() {
return buildActivityDetailRows(this.row);
return buildActivityDetailRows(this.row, this.$t);
},
},
};
@@ -4,7 +4,7 @@
<Editor
:viewer-mode="true"
:content="previewContent"
editor-mode="json"
:editor-mode="'json'"
:read-only="true"
/>
</div>
@@ -13,8 +13,8 @@
<script>
import { createAsyncComponent } from "@/utils/asyncComponent.js";
import { notify } from "@/notify/index.ts";
import { getAnalyticsPreview } from "@/api/settings.js";
import { notify } from "@/notify";
import { getAnalyticsPreview } from "@/api/settings";
export default {
name: "AnalyticsDiagnostic",
+4 -4
View File
@@ -142,10 +142,10 @@
</template>
<script>
import { state, mutations, getters } from "@/store/index.ts";
import { notify } from "@/notify/index.ts";
import { resourcesApi } from "@/api/index.js";
import { goToItemNotificationButton } from "@/utils/notificationActions.js";
import { state, mutations, getters } from "@/store";
import { notify } from "@/notify";
import { resourcesApi } from "@/api";
import { goToItemNotificationButton } from "@/utils/notificationActions";
import LoadingSpinner from "@/components/LoadingSpinner.vue";
import FileList from "@/components/files/FileList.vue";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
@@ -24,7 +24,7 @@
</template>
<script>
import { getters } from "@/store/index.ts";
import { getters } from "@/store";
export default {
name: "closeWithActiveUploads",
@@ -41,18 +41,18 @@ export default {
},
created() {
// Listen for ESC key to treat it as "Stay on Prompt"
this.escKeyHandler = (event) => {
if (event.keyCode === 27 && getters.currentPromptName() === "CloseWithActiveUploads") {
event.stopImmediatePropagation();
this.stayOnPrompt();
}
};
window.addEventListener("keydown", this.escKeyHandler, true);
},
beforeUnmount() {
window.removeEventListener("keydown", this.escKeyHandler, true);
},
methods: {
escKeyHandler(event) {
if (event.keyCode === 27 && getters.currentPromptName() === "CloseWithActiveUploads") {
event.stopImmediatePropagation();
this.stayOnPrompt();
}
},
stayOnPrompt() {
if (this.currentPrompt?.cancel) {
this.currentPrompt.cancel();
@@ -4,21 +4,22 @@
<ToggleSwitch
class="item"
v-model="showFull"
@update:model-value="fetchConfig"
@update:modelValue="fetchConfig"
:name="$t('settings.configViewerShowFull')"
/>
<ToggleSwitch
class="item"
v-model="showComments"
@update:model-value="fetchConfig"
@update:modelValue="fetchConfig"
:name="$t('settings.configViewerShowComments')"
/>
</div>
<div class="editor-container">
<Editor
:viewer-mode="true"
:content="configContent"
editor-mode="yaml"
:editor-mode="'yaml'"
:read-only="true"
/>
</div>
@@ -27,7 +28,7 @@
<script>
import { createAsyncComponent } from "@/utils/asyncComponent.js";
import { config } from "@/api/settings.js";
import { config } from "@/api/settings";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
export default {
@@ -44,8 +44,8 @@
</template>
<script>
import { mutations } from "@/store/index.ts";
import { notifyMoveCopyFailure } from "@/utils/appNotifications.js";
import { mutations } from "@/store";
import { notifyMoveCopyFailure } from "@/utils/appNotifications";
export default {
name: "copy-paste-confirm",
@@ -62,12 +62,12 @@
</template>
<script>
import { mutations } from "@/store/index.ts";
import { notify } from "@/notify/index.ts";
import { authApi } from "@/api/index.js";
import { mutations } from "@/store";
import { notify } from "@/notify";
import { authApi } from "@/api";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
import ExpandDropdown from "@/components/settings/ExpandDropdown.vue";
import { eventBus } from "@/store/eventBus.ts";
import { eventBus } from "@/store/eventBus";
import LoadingSpinner from "@/components/LoadingSpinner.vue";
export default {
@@ -53,7 +53,7 @@
</template>
<script>
import { getters, mutations } from "@/store/index.ts";
import { getters, mutations } from "@/store";
import ExpandDropdown from "@/components/settings/ExpandDropdown.vue";
import HelpTooltipIcon from "@/components/HelpTooltipIcon.vue";
+19 -19
View File
@@ -3,14 +3,14 @@
<!-- Loading spinner overlay -->
<div v-show="deleting" class="loading-content">
<LoadingSpinner size="small" />
<p class="loading-text">{{ t("prompts.operationInProgress") }}</p>
<p class="loading-text">{{ $t("prompts.operationInProgress") }}</p>
</div>
<div v-show="!deleting">
<p class="card-message" v-if="itemsToDelete.length === 1">
{{ t("prompts.deleteMessageSingle") }}
{{ $t("prompts.deleteMessageSingle") }}
</p>
<p class="card-message" v-else>
{{ t("prompts.deleteMessageMultiple", { count: itemsToDelete.length }) }}
{{ $t("prompts.deleteMessageMultiple", { count: itemsToDelete.length }) }}
</p>
<div ref="list" class="delete-items-list" @contextmenu.capture.prevent.stop>
<div data-virtual-group="items" :style="virtual.group('items').style">
@@ -52,9 +52,9 @@
@click="closeTopPrompt"
class="button button--flat button--grey"
:disabled="deleting"
:aria-label="t('general.cancel')"
:title="t('general.cancel')">
{{ t("general.cancel") }}
:aria-label="$t('general.cancel')"
:title="$t('general.cancel')">
{{ $t("general.cancel") }}
</button>
<button
type="button"
@@ -62,25 +62,25 @@
class="button button--flat button--red"
:disabled="deleting"
aria-label="Confirm-Delete"
:title="t('general.delete')">
{{ t("general.delete") }}
:title="$t('general.delete')">
{{ $t("general.delete") }}
</button>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, useTemplateRef, watch } from "vue";
import { useI18n } from "@/i18n/index.ts";
import { resourcesApi } from "@/api/index.js";
import buttons from "@/utils/buttons.js";
import { state, getters, mutations } from "@/store/index.ts";
import type { FileListItem } from "@/store/types.ts";
import { notify } from "@/notify/index.ts";
import { computed, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { resourcesApi } from "@/api";
import buttons from "@/utils/buttons";
import { state, getters, mutations } from "@/store";
import type { FileListItem } from "@/store/types";
import { notify } from "@/notify";
import ListingItem from "@/components/files/ListingItem.vue";
import { eventBus } from "@/store/eventBus.ts";
import { eventBus } from "@/store/eventBus";
import LoadingSpinner from "@/components/LoadingSpinner.vue";
import { useListingVirtualization } from "@/composables/useListingVirtualization.ts";
import url from "@/utils/url.js";
import url from "@/utils/url";
import { removeFromFolderLists } from "@/utils/cache/listingCache.ts";
export interface DeleteItem {
@@ -111,7 +111,7 @@ defineOptions({ name: "delete" });
const { t } = useI18n();
const list = useTemplateRef<HTMLElement>("list");
const list = ref<HTMLElement | null>(null);
const failedItems = ref<FailedItem[]>([]);
const deleting = ref(false);
@@ -184,7 +184,7 @@ function closeTopPrompt() {
function getItemName(path: string) {
const parts = path.split("/").filter(p => p);
return parts.at(-1) || path;
return parts[parts.length - 1] || path;
}
function getItemError(item: DeleteItem) {
+16 -16
View File
@@ -1,6 +1,6 @@
<template>
<div v-if="!hasDownloads && currentPrompt && currentPrompt.confirm" class="card-content">
<p>{{ t("prompts.downloadMessage") }}</p>
<p>{{ $t("prompts.downloadMessage") }}</p>
<button
type="button"
@@ -15,7 +15,7 @@
</button>
</div>
<div v-if="!hasDownloads && (!currentPrompt?.confirm)" class="card-content lonely-message">
<span>{{ t("files.lonely") }}</span>
<span>{{ $t("files.lonely") }}</span>
</div>
<div v-if="hasDownloads" class="card-content">
<div ref="list" class="download-list">
@@ -33,9 +33,9 @@
<p class="file-name">{{ download.name }}</p>
<ProgressBar
:val="download.status === 'completed'
? t('prompts.completed')
? $t('prompts.completed')
: download.status === 'error'
? t('prompts.error')
? $t('prompts.error')
: download.loaded
"
:unit="download.status === 'completed' || download.status === 'error' ? '' : 'bytes'"
@@ -51,15 +51,15 @@
v-if="download.status === 'error'"
@click="retryDownload(download.id)"
class="action"
:aria-label="t('general.retry')" :title="t('general.retry')"
:aria-label="$t('general.retry')" :title="$t('general.retry')"
>
<i class="material-symbols">replay</i>
</button>
<button
type="button"
@click="downloadManager.cancel(download.id)"
class="action" :aria-label="t('general.cancel')"
:title="t('general.cancel')"
class="action" :aria-label="$t('general.cancel')"
:title="$t('general.cancel')"
>
<i class="material-symbols">close</i>
</button>
@@ -80,20 +80,20 @@
@click="downloadManager.clearCompleted()"
class="button button--flat"
:disabled="!hasClearable"
:aria-label="t('buttons.clearCompleted')" :title="t('buttons.clearCompleted')"
:aria-label="$t('buttons.clearCompleted')" :title="$t('buttons.clearCompleted')"
>
{{ t("buttons.clearCompleted") }}
{{ $t("buttons.clearCompleted") }}
</button>
</div>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, useTemplateRef, watch } from "vue";
import { useI18n } from "@/i18n/index.ts";
import { getters } from "@/store/index.ts";
import { downloadManager } from "@/utils/downloadManager.ts";
import type { DownloadItem } from "@/utils/downloadManager.ts";
import { resourcesApi } from "@/api/index.js";
import { computed, onBeforeUnmount, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { getters } from "@/store";
import { downloadManager } from "@/utils/downloadManager";
import type { DownloadItem } from "@/utils/downloadManager";
import { resourcesApi } from "@/api";
import ProgressBar from "@/components/ProgressBar.vue";
import { findScrollParents, useListingVirtualization } from "@/composables/useListingVirtualization.ts";
@@ -116,7 +116,7 @@ const vFocus = {
const formats = { zip: "zip", targz: "tar.gz" } as const;
const list = useTemplateRef<HTMLElement>("list");
const list = ref<HTMLElement | null>(null);
const currentPrompt = computed(() => getters.currentPrompt());
const downloads = computed(() => downloadManager.queue);
const hasDownloads = computed(() => downloads.value.length > 0);
@@ -45,26 +45,26 @@
type="button"
class="button button--flat button--grey"
@click="resetEditorConfig"
:aria-label="t('player.visualizer.resetDefaults')"
:title="t('player.visualizer.resetDefaults')"
> {{ t("player.visualizer.resetDefaults") }}
:aria-label="$t('player.visualizer.resetDefaults')"
:title="$t('player.visualizer.resetDefaults')"
> {{ $t("player.visualizer.resetDefaults") }}
</button>
<button
type="button"
class="button button--flat"
@click="closeTopPrompt"
:aria-label="t('general.ok')"
:title="t('general.ok')"
> {{ t("general.ok") }}
:aria-label="$t('general.ok')"
:title="$t('general.ok')"
> {{ $t("general.ok") }}
</button>
</div>
</template>
<script setup lang="ts">
import { computed } from "vue";
import { useI18n } from "@/i18n/index.ts";
import { mutations } from "@/store/index.ts";
import { editorConfig, saveEditorConfig, resetEditorConfig, type EditorConfig } from "@/utils/editorConfig.ts";
import { useI18n } from "vue-i18n";
import { mutations } from "@/store";
import { editorConfig, saveEditorConfig, resetEditorConfig, type EditorConfig } from "@/utils/editorConfig";
import ExpandDropdown from "@/components/settings/ExpandDropdown.vue";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
@@ -80,12 +80,9 @@ interface EditorSettingField {
options?: { value: string | number; label: string }[];
}
withDefaults(
defineProps<{
promptId?: string | number | null;
}>(),
{ promptId: null },
);
defineProps({
promptId: { type: [String, Number], default: null },
});
defineOptions({ name: "EditorSettings" });
@@ -38,8 +38,8 @@
</template>
<script>
import { mutations } from "@/store/index.ts";
import { eventBus } from "@/store/eventBus.ts";
import { mutations } from "@/store";
import { eventBus } from "@/store/eventBus";
import EntityPickerList from "./EntityPickerList.vue";
export default {
@@ -78,9 +78,9 @@
</template>
<script>
import { accessApi, usersApi } from "@/api/index.js";
import { eventBus } from "@/store/eventBus.ts";
import { notify } from "@/notify/index.ts";
import { accessApi, usersApi } from "@/api";
import { eventBus } from "@/store/eventBus";
import { notify } from "@/notify";
import LoadingSpinner from "@/components/LoadingSpinner.vue";
import { groupNameErrorText } from "@/utils/groups.js";
@@ -123,10 +123,7 @@ export default {
default: true,
},
},
emits: {
"update:modelValue": (names) => Array.isArray(names),
enter: () => true,
},
emits: ["update:modelValue", "enter"],
data() {
return {
loading: true,
@@ -24,7 +24,7 @@
<script>
import FileList from "@/components/files/FileList.vue";
import ListingFilter from "@/components/files/ListingFilter.vue";
import { mutations } from "@/store/index.ts";
import { mutations } from "@/store";
export default {
name: "file-list",
@@ -49,10 +49,10 @@
</template>
<script>
import { accessApi } from "@/api/index.js";
import { mutations } from "@/store/index.ts";
import { notify } from "@/notify/index.ts";
import { eventBus } from "@/store/eventBus.ts";
import { accessApi } from "@/api";
import { mutations } from "@/store";
import { notify } from "@/notify";
import { eventBus } from "@/store/eventBus";
import EntityPickerList from "./EntityPickerList.vue";
import { groupNameErrorText } from "@/utils/groups.js";
+35 -35
View File
@@ -12,23 +12,23 @@
<div class="shortcut-section">
<h3 class="section-title">{{ $t("help.functionKeys") }}</h3>
<div class="shortcut-item">
<kbd>F1</kbd>
<kbd>F1</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.f1") }}</span>
</div>
<div class="shortcut-item">
<kbd>F2</kbd>
<kbd>F2</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.f2") }}</span>
</div>
<div class="shortcut-item">
<kbd>F4</kbd>
<kbd>F4</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.f4") }}</span>
</div>
<div class="shortcut-item">
<kbd>DEL</kbd>
<kbd>DEL</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.del") }}</span>
</div>
<div class="shortcut-item">
<kbd>ESC</kbd>
<kbd>ESC</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.esc") }}</span>
</div>
</div>
@@ -37,23 +37,23 @@
<div class="shortcut-section">
<h3 class="section-title">{{ $t("help.mouseActions") }}</h3>
<div class="shortcut-item">
<kbd>CLICK</kbd>
<kbd>CLICK</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.click") }}</span>
</div>
<div class="shortcut-item">
<kbd>DOUBLE CLICK</kbd>
<kbd>DOUBLE CLICK</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.dbClick") }}</span>
</div>
<div class="shortcut-item">
<kbd>CLICK + DRAG</kbd>
<kbd>CLICK + DRAG</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.marqueeSelect") }}</span>
</div>
<div class="shortcut-item">
<kbd>CTRL + CLICK</kbd>
<kbd>CTRL + CLICK</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.ctrl.click") }}</span>
</div>
<div class="shortcut-item">
<kbd>CTRL + SCROLL</kbd>
<kbd>CTRL + SCROLL</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.ctrl.scroll") }}</span>
</div>
</div>
@@ -62,19 +62,19 @@
<div class="shortcut-section">
<h3 class="section-title">{{ $t("help.fileOperations") }}</h3>
<div class="shortcut-item">
<kbd>CTRL + C</kbd>
<kbd>CTRL + C</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.ctrl.c") }}</span>
</div>
<div class="shortcut-item">
<kbd>CTRL + X</kbd>
<kbd>CTRL + X</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.ctrl.x") }}</span>
</div>
<div class="shortcut-item">
<kbd>CTRL + V</kbd>
<kbd>CTRL + V</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.ctrl.v") }}</span>
</div>
<div class="shortcut-item">
<kbd>CTRL + D</kbd>
<kbd>CTRL + D</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.ctrl.d") }}</span>
</div>
@@ -84,39 +84,39 @@
<div class="shortcut-section">
<h3 class="section-title">{{ $t("general.navigation") }}</h3>
<div class="shortcut-item">
<kbd>BACKSPACE {{ $t("general.or") }} ALT + ↑</kbd>
<kbd>BACKSPACE {{ $t("general.or") }} ALT + ↑</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.altArrowUp") }}</span>
</div>
<div class="shortcut-item">
<kbd>ENTER {{ $t("general.or") }} ALT + ↓</kbd>
<kbd>ENTER {{ $t("general.or") }} ALT + ↓</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.altArrowDown") }}</span>
</div>
<div class="shortcut-item">
<kbd>CTRL + B</kbd>
<kbd>CTRL + B</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.ctrl.b") }}</span>
</div>
<div class="shortcut-item">
<kbd>CTRL + ,</kbd>
<kbd>CTRL + ,</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.ctrl.comma") }}</span>
</div>
<div class="shortcut-item">
<kbd>SPACE {{ $t("general.or") }} /</kbd>
<kbd>SPACE {{ $t("general.or") }} /</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.slash") }}</span>
</div>
<div class="shortcut-item">
<kbd>CTRL + E</kbd>
<kbd>CTRL + E</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.ctrl.e") }}</span>
</div>
<div class="shortcut-item">
<kbd>CTRL + F1</kbd>
<kbd>CTRL + F1</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.ctrl.f1") }}</span>
</div>
<div class="shortcut-item">
<kbd>CTRL + F2</kbd>
<kbd>CTRL + F2</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.ctrl.f2") }}</span>
</div>
<div class="shortcut-item">
<kbd>CTRL + F3</kbd>
<kbd>CTRL + F3</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.ctrl.f3") }}</span>
</div>
</div>
@@ -125,47 +125,47 @@
<div class="shortcut-section">
<h3 class="section-title">{{ $t("help.media.title") }}</h3>
<div class="shortcut-item">
<kbd>SPACE / K</kbd>
<kbd>SPACE / K</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.media.playPause") }}</span>
</div>
<div class="shortcut-item">
<kbd>1 {{ $t("general.to") }} 9</kbd>
<kbd>1 {{ $t("general.to") }} 9</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.media.seekPercentage") }}</span>
</div>
<div class="shortcut-item">
<kbd>← / →</kbd>
<kbd>← / →</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.media.seek") }}</span>
</div>
<div class="shortcut-item">
<kbd>↑ / ↓</kbd>
<kbd>↑ / ↓</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.media.volume") }}</span>
</div>
<div class="shortcut-item">
<kbd>Q</kbd>
<kbd>Q</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.media.playbackQueue") }}</span>
</div>
<div class="shortcut-item">
<kbd>E</kbd>
<kbd>E</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.media.switchTabs") }}</span>
</div>
<div class="shortcut-item">
<kbd>L</kbd>
<kbd>L</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.media.loop") }}</span>
</div>
<div class="shortcut-item">
<kbd>P</kbd>
<kbd>P</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.media.playbackModes") }}</span>
</div>
<div class="shortcut-item">
<kbd>F</kbd>
<kbd>F</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.media.fullscreen") }}</span>
</div>
<div class="shortcut-item">
<kbd>M</kbd>
<kbd>M</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.media.mute") }}</span>
</div>
<div class="shortcut-item">
<kbd>C</kbd>
<kbd>C</kbd> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span>{{ $t("help.media.captions") }}</span>
</div>
</div>
@@ -181,7 +181,7 @@
</template>
<script>
import { mutations } from "@/store/index.ts"; // Import the mutations
import { mutations } from "@/store"; // Import the mutations
export default {
name: "help",
@@ -97,8 +97,8 @@
import {
materialSymbols,
getIconClass,
} from "@/utils/material-symbols.js";
import { mutations } from "@/store/index.ts";
} from "@/utils/material-symbols";
import { mutations } from "@/store";
export default {
name: "IconPicker",
+46 -39
View File
@@ -6,40 +6,40 @@
<div class="info-grid" :class="{ 'info-grid--fill': activeTab === 'access' }">
<div class="info-section" v-if="activeTab === 'basic'">
<div class="info-item">
<strong>{{ t("prompts.displayName") }}</strong>
<strong>{{ $t("prompts.displayName") }}</strong>
<span role="group" aria-label="info display name">{{ item.name }}</span>
</div>
<div class="info-item">
<strong>{{ t("general.size") }}</strong>
<strong>{{ $t("general.size") }}</strong>
<span role="group" aria-label="info size">{{ humanSize }}</span>
</div>
<div class="info-item">
<strong>{{ t("general.type") }}</strong>
<strong>{{ $t("general.type") }}</strong>
<span role="group" aria-label="info type">{{ item.type }}</span>
</div>
<div class="info-item" v-if="humanTime">
<strong>{{ t("files.lastModified") }}</strong>
<strong>{{ $t("files.lastModified") }}</strong>
<span role="group" aria-label="info last modified" :title="modTime">{{ humanTime }}</span>
</div>
<div class="info-item" v-if="humanCreatedTime">
<strong>{{ t("files.creationTime") }}</strong>
<strong>{{ $t("files.creationTime") }}</strong>
<span aria-label="info date added" :title="createdTime">{{ humanCreatedTime }}</span>
</div>
<div class="info-item" v-if="source">
<strong>{{ t("general.source") }}</strong>
<strong>{{ $t("general.source") }}</strong>
<span role="group" aria-label="info source">{{ source }}</span>
</div>
<div class="info-item" v-if="filePath">
<strong>{{ t("general.path") }}</strong>
<strong>{{ $t("general.path") }}</strong>
<span role="group" aria-label="info path" class="break-word">{{ filePath }}</span>
</div>
<div class="info-item" v-if="item.hidden !== undefined">
<strong>{{ t("prompts.hidden") }}</strong>
<span role="group" aria-label="info hidden">{{ item.hidden ? "✓" : "✗" }}</span>
<strong>{{ $t("prompts.hidden") }}</strong>
<span role="group" aria-label="info hidden">{{ item.hidden ? "✓" : "✗" }}</span><!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
<div class="info-item" v-if="item.hasPreview !== undefined">
<strong>{{ t("prompts.hasPreview") }}</strong>
<span role="group" aria-label="info has preview">{{ item.hasPreview ? "✓" : "✗" }}</span>
<strong>{{ $t("prompts.hasPreview") }}</strong>
<span role="group" aria-label="info has preview">{{ item.hasPreview ? "✓" : "✗" }}</span><!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
<div class="settings-items" v-if="source && !isShare">
<ActivityViewerButton :href="activityViewerHref" />
@@ -53,27 +53,27 @@
</div>
<!-- Lyrics -->
<div class="info-item" v-if="hasLyrics">
<strong>{{ t("player.lyrics") }}</strong>
<strong>{{ $t("player.lyrics") }}</strong>
<span>
<a class="info-toggle" role="button" tabindex="0" @click="toggleLyrics" @keydown.enter="toggleLyrics">
{{ showLyrics ? t("general.hide") : t("general.show") }}
{{ showLyrics ? $t("general.hide") : $t("general.show") }}
</a>
<span v-if="showLyrics" class="info-multiline">{{ lyricsText }}</span>
</span>
</div>
<!-- Subtitles -->
<div class="info-item" v-for="(track, idx) in subtitleTracks" :key="track.name">
<strong>{{ t("prompts.subtitle", { n: idx + 1 }) }}</strong>
<strong>{{ $t("prompts.subtitle", { n: idx + 1 }) }}</strong>
<span>
{{ subtitleLabel(track) }}
<a class="info-toggle" role="button" tabindex="0" @click="toggleSubtitle(track)" @keydown.enter="toggleSubtitle(track)">
{{ subtitleContent[track.name] !== undefined ? t("general.hide") : t("general.show") }}
{{ subtitleContent[track.name] !== undefined ? $t("general.hide") : $t("general.show") }}
</a>
<span v-if="subtitleContent[track.name] !== undefined" class="info-multiline">{{ subtitleContent[track.name] }}</span>
</span>
</div>
<div class="info-item" v-if="!showMediaContent">
<span>{{ t("general.none") }}</span>
<span>{{ $t("general.none") }}</span>
</div>
</div>
<div v-else-if="activeTab === 'quota'" class="info-section">
@@ -81,13 +81,13 @@
<SettingsButton
class="info-manage-link"
:name="t('quotas.title')"
:description="t('quotas.openDescription')"
@activate="openQuotaPrompt"
:description="$t('quotas.openDescription')"
@click="openQuotaPrompt"
/>
</div>
<div class="info-item">
<strong>{{ t("general.enabled") }}</strong>
<span>{{ quotaEnabled ? t("general.yes") : t("general.no") }}</span>
<strong>{{ $t("general.enabled") }}</strong>
<span>{{ quotaEnabled ? $t("general.yes") : $t("general.no") }}</span>
</div>
<div v-if="quotaEnabled" class="info-quota-usage">
<QuotaFolderBar
@@ -109,33 +109,33 @@
<div class="info-section" v-else-if="activeTab === 'checksums'">
<div class="hash-generator">
<div class="hash-select">
<label for="hash-algo">{{ t("prompts.hashAlgorithm") }}</label>
<label for="hash-algo">{{ $t("prompts.hashAlgorithm") }}</label>
<div class="form-flex-group">
<ExpandDropdown
input-id="hash-algo"
v-model="selectedHashAlgo"
class="form-form flat-right"
:options="hashAlgoOptions"
:aria-label="t('prompts.hashAlgorithm')"
:aria-label="$t('prompts.hashAlgorithm')"
/>
<button type="button" class="button form-button flat-left" @click="generateHash"
:title="t('prompts.generate')" :aria-label="t('prompts.generate')">
{{ t("prompts.generate") }}
:title="$t('prompts.generate')" :aria-label="$t('prompts.generate')">
{{ $t("prompts.generate") }}
</button>
</div>
</div>
<div class="hash-result">
<label for="hash-result">{{ t("prompts.hashValue") }}</label>
<label for="hash-result">{{ $t("prompts.hashValue") }}</label>
<div class="form-flex-group">
<input id="hash-result" class="input form-form flat-right" type="text" :value="hashResult" readonly
:placeholder="t('prompts.selectHashAlgorithm')" />
:placeholder="$t('prompts.selectHashAlgorithm')" />
<button
type="button"
class="button form-button flat-left"
@click="copyHash"
:disabled="!hashResult"
:title="t('buttons.copyToClipboard')"
:aria-label="t('buttons.copyToClipboard')"
:title="$t('buttons.copyToClipboard')"
:aria-label="$t('buttons.copyToClipboard')"
>
<i class="material-symbols-outlined" style="font-size: 16px;">content_copy</i>
</button>
@@ -152,16 +152,16 @@
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useI18n } from "@/i18n/index.ts";
import { getHumanReadableFilesize } from "@/utils/filesizes.js";
import { formatTimestamp, fromNow } from "@/utils/moment.ts";
import { copyToClipboard } from "@/utils/clipboard.js";
import { formatDuration } from "@/utils/files.js";
import { resourcesApi, quotasApi, mediaApi } from "@/api/index.js";
import { getters, mutations, state } from "@/store/index.ts";
import type { InfoItem, SubtitleTrack } from "@/store/types.ts";
import { notify } from "@/notify/index.ts";
import { activityViewerPresets } from "@/utils/activityViewerLink.js";
import { useI18n } from "vue-i18n";
import { getHumanReadableFilesize } from "@/utils/filesizes";
import { formatTimestamp, fromNow } from "@/utils/moment";
import { copyToClipboard } from "@/utils/clipboard";
import { formatDuration } from "@/utils/files";
import { resourcesApi, quotasApi, mediaApi } from "@/api";
import { getters, mutations, state } from "@/store";
import type { FileListItem, SubtitleTrack } from "@/store/types.ts";
import { notify } from "@/notify";
import { activityViewerPresets } from "@/utils/activityViewerLink";
import SlidingTabs from "@/components/settings/SlidingTabs.vue";
import ExpandDropdown from "@/components/settings/ExpandDropdown.vue";
import ActivityViewerButton from "@/components/settings/ActivityViewerButton.vue";
@@ -172,6 +172,13 @@ import Access from "@/components/prompts/Access.vue";
type InfoTab = "basic" | "media" | "quota" | "access" | "additional" | "checksums";
type HashAlgo = "md5" | "sha1" | "sha256" | "sha512";
interface InfoItem extends FileListItem {
subtitles?: SubtitleTrack[];
token?: string;
hash?: string;
onlyOfficeId?: string;
}
interface QuotaSnapshot {
usedBytes?: number;
reservedBytes?: number;
@@ -348,7 +355,7 @@ function subtitleLabel(track: SubtitleTrack) {
// Raw subtitle content are fetched on first show
async function toggleSubtitle(track: SubtitleTrack) {
if (track.name in subtitleContent.value) {
Reflect.deleteProperty(subtitleContent.value, track.name);
delete subtitleContent.value[track.name];
return;
}
try {
@@ -56,10 +56,10 @@
</template>
<script>
import { notify } from "@/notify/index.ts";
import { mutations } from "@/store/index.ts";
import { eventBus } from "@/store/eventBus.ts";
import { getMediaSettings } from "@/api/settings.js";
import { notify } from "@/notify";
import { mutations } from "@/store";
import { eventBus } from "@/store/eventBus";
import { getMediaSettings } from "@/api/settings";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
import LoadingSpinner from "@/components/LoadingSpinner.vue";
import {
@@ -67,7 +67,7 @@ import {
emptyMediaSettings,
mergeMediaSettings,
saveMediaSettingsPatch,
} from "@/utils/mediaSettings.js";
} from "@/utils/mediaSettings";
export default {
name: "MediaConversionFormats",
@@ -53,7 +53,7 @@
</div>
<div v-for="profile in profiles" :key="profile.id" class="settings-items">
<h3>{{ profile.label() }}</h3>
<h3>{{ $t(profile.label) }}</h3>
<ToggleSwitch
class="item"
v-model="media.transcode.profiles[profile.id].enabled"
@@ -97,7 +97,7 @@
:options="backendSelectOptions"
:aria-label="$t('media.encoderBackend')"
:disabled="isLocked(`transcode.profiles.${profile.id}.encoderBackend`)"
@update:model-value="onProfileBackendChange(profile.id, $event)" />
@update:modelValue="onProfileBackendChange(profile.id, $event)" />
</div>
</div>
</template>
@@ -128,10 +128,10 @@
</template>
<script>
import { notify } from "@/notify/index.ts";
import { mutations } from "@/store/index.ts";
import { eventBus } from "@/store/eventBus.ts";
import { getMediaSettings } from "@/api/settings.js";
import { notify } from "@/notify";
import { mutations } from "@/store";
import { eventBus } from "@/store/eventBus";
import { getMediaSettings } from "@/api/settings";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
import ExpandDropdown from "@/components/settings/ExpandDropdown.vue";
import HelpTooltipIcon from "@/components/HelpTooltipIcon.vue";
@@ -142,7 +142,7 @@ import {
emptyMediaSettings,
mergeMediaSettings,
saveMediaSettingsPatch,
} from "@/utils/mediaSettings.js";
} from "@/utils/mediaSettings";
export default {
name: "MediaTranscodeSettings",
+16 -16
View File
@@ -79,24 +79,24 @@
</template>
<script>
import { mutations, state, getters } from "@/store/index.ts";
import { mutations, state, getters } from "@/store";
import FileList from "../files/FileList.vue";
import { resourcesApi } from "@/api/index.js";
import buttons from "@/utils/buttons.js";
import { checkConflict } from "@/utils/upload.ts";
import { url } from "@/utils/index.ts";
import { notify } from "@/notify/index.ts";
import { resourcesApi } from "@/api";
import buttons from "@/utils/buttons";
import { checkConflict } from "@/utils/upload";
import { url } from "@/utils";
import { notify } from "@/notify";
import {
notifyMoveCopyComplete,
notifyOperationError,
notifyMoveCopyFailure,
extractMoveCopyErrorMessage,
} from "@/utils/appNotifications.js";
import { goToItemNotificationButton } from "@/utils/notificationActions.js";
} from "@/utils/appNotifications";
import { goToItemNotificationButton } from "@/utils/notificationActions";
import LoadingSpinner from "@/components/LoadingSpinner.vue";
import PathPickerButton from "@/components/files/PathPickerButton.vue";
import ListingFilter from "@/components/files/ListingFilter.vue";
import { eventBus } from "@/store/eventBus.ts";
import { eventBus } from '@/store/eventBus';
import { removeFromFolderLists } from "@/utils/cache/listingCache.ts";
export default {
@@ -322,13 +322,13 @@ export default {
};
});
// Define the action function
const action = async (shouldOverwrite, shouldRename) => {
const action = async (overwrite, rename) => {
buttons.loading(this.operation);
let result;
if (getters.isShare()) {
result = await resourcesApi.moveCopyPublic(getters.shareHash(), itemsToProcess, this.operation, shouldOverwrite, shouldRename);
result = await resourcesApi.moveCopyPublic(getters.shareHash(), itemsToProcess, this.operation, overwrite, rename);
} else {
result = await resourcesApi.moveCopy(itemsToProcess, this.operation, shouldOverwrite, shouldRename);
result = await resourcesApi.moveCopy(itemsToProcess, this.operation, overwrite, rename);
}
return result; // Return the result to check for failures
};
@@ -362,16 +362,16 @@ export default {
operation: this.operation,
destSource: this.destSource,
},
confirm: async (confirmEvent, option) => {
confirm: async (event, option) => {
overwrite = option === "overwrite";
rename = option === "rename";
confirmEvent.preventDefault();
event.preventDefault();
try {
this.isLoading = true;
result = await action(overwrite, rename);
resolve(); // Resolve the promise if action succeeds
} catch (err) {
reject(err); // Reject the promise if an error occurs
} catch (e) {
reject(e); // Reject the promise if an error occurs
} finally {
this.isLoading = false;
}
+5 -5
View File
@@ -35,11 +35,11 @@
</div>
</template>
<script>
import { resourcesApi } from "@/api/index.js";
import { getters, mutations, state } from "@/store/index.ts"; // Import your custom store
import { url } from "@/utils/index.ts";
import { notify } from "@/notify/index.ts";
import { goToItemNotificationButton } from "@/utils/notificationActions.js";
import { resourcesApi } from "@/api";
import { getters, mutations, state } from "@/store"; // Import your custom store
import { url } from "@/utils";
import { notify } from "@/notify";
import { goToItemNotificationButton } from "@/utils/notificationActions";
import LoadingSpinner from "@/components/LoadingSpinner.vue";
export default {
name: "new-dir",
+10 -10
View File
@@ -12,7 +12,7 @@
<input ref="filenameInput" class="input" aria-label="FileName Field" v-focus type="text" @keyup.enter="submit"
v-model.trim="fileName" @input="updateFullName" />
<template v-if="fileExtension">
<span class="extension-separator">.</span>
<span class="extension-separator">.</span> <!--eslint-disable-line @intlify/vue-i18n/no-raw-text-->
<input
class="input extension-input"
type="text"
@@ -51,13 +51,13 @@
</div>
</template>
<script>
import { state } from "@/store/index.ts";
import { resourcesApi } from "@/api/index.js";
import { getters, mutations } from "@/store/index.ts"; // Import your custom store
import { notify } from "@/notify/index.ts";
import { url } from "@/utils/index.ts";
import { goToItemNotificationButton } from "@/utils/notificationActions.js";
import { getTypeInfoFromExt } from "@/utils/mimetype.js";
import { state } from "@/store";
import { resourcesApi } from "@/api";
import { getters, mutations } from "@/store"; // Import your custom store
import { notify } from "@/notify";
import { url } from "@/utils";
import { goToItemNotificationButton } from "@/utils/notificationActions";
import { getTypeInfoFromExt } from "@/utils/mimetype";
import { getFileExtension, removePrefix } from '@/utils/files.js';
import LoadingSpinner from "@/components/LoadingSpinner.vue";
export default {
@@ -85,7 +85,7 @@ export default {
let fileExtension = "";
if (usesTemplate) {
const ext = getFileExtension(this.initialName);
fileName = this.initialName.slice(0, this.initialName.length - ext.length);
fileName = this.initialName.substring(0, this.initialName.length - ext.length);
fileExtension = removePrefix(ext, ".");
}
return {
@@ -317,7 +317,7 @@ export default {
}
.extension-separator {
font-weight: 700;
font-weight: bold;
}
.file-type-icon {
@@ -89,8 +89,8 @@
</template>
<script>
import { getters, mutations } from "@/store/index.ts";
import { getTypeInfoFromExt } from "@/utils/mimetype.js";
import { getters, mutations } from "@/store";
import { getTypeInfoFromExt } from "@/utils/mimetype";
import { createDragReorder } from "@/utils/dragAndDropReorder.js";
export default {
+32 -31
View File
@@ -2,38 +2,38 @@
<div class="card-content no-buttons">
<div class="debug-tooltip">
<div class="debug-header">
<h3 class="debug-title">🔧 {{ $t("onlyoffice.debugTitle") }}</h3>
<h3 class="debug-title">🔧 {{ $t("onlyoffice.debugTitle") }}</h3> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
<div class="debug-section debug-section-basic">
<div class="debug-section-header">
<strong class="debug-section-title">⚙️ {{ $t("onlyoffice.basicConfiguration") }}</strong>
<strong class="debug-section-title">⚙️ {{ $t("onlyoffice.basicConfiguration") }}</strong> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
{{ $t("onlyoffice.onlyOffice") }} {{ $t("general.path", { suffix: ":" }) }} {{ onlyOfficeUrl }}<br/>
{{ $t("onlyoffice.internalUrl") }}: {{ internalUrlInfo.message }}<br/>
{{ $t("general.path", { suffix: ":" }) }} {{ baseURL }}<br/>
{{ $t("general.source", { suffix: ":" }) }} {{ source }}<br/>
{{ $t("general.path", { suffix: ":" }) }} {{ path }}<br/>
{{ $t("general.name", { suffix: ":" }) }} {{ filename }}<br/>
{{ isShare ? `${shareHashLabel()}: ${shareHash}` : $t("onlyoffice.userRequest") }}<br/>
{{ $t("onlyoffice.onlyOffice") }} {{ $t("general.path", { suffix: ":" }) }} {{ onlyOfficeUrl }}<br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ $t("onlyoffice.internalUrl") }}: {{ internalUrlInfo.message }}<br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ $t("general.path", { suffix: ":" }) }} {{ baseURL }}<br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ $t("general.source", { suffix: ":" }) }} {{ source }}<br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ $t("general.path", { suffix: ":" }) }} {{ path }}<br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ $t("general.name", { suffix: ":" }) }} {{ filename }}<br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ isShare ? `${shareHashLabel()}: ${shareHash}` : $t("onlyoffice.userRequest") }}<br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
<div v-if="clientConfig?.document" class="debug-section debug-section-config">
<div class="debug-section-header">
<strong class="debug-section-title">🔧 {{ $t("onlyoffice.configurationDetails") }}</strong>
<strong class="debug-section-title">🔧 {{ $t("onlyoffice.configurationDetails") }}</strong> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
{{ $t("onlyoffice.documentKey") }}: {{ clientConfig.document.key }}<br/>
{{ $t("onlyoffice.fileType") }}: {{ clientConfig.document.fileType }}<br/>
{{ $t("onlyoffice.editMode") }}: {{ clientConfig.editorConfig ? clientConfig.editorConfig.mode : 'N/A' }}<br/>
{{ $t("onlyoffice.downloadURL") }}: {{ clientConfig.document.url ? `${clientConfig.document.url.slice(0, 80)}...` : 'N/A' }}<br/>
{{ $t("onlyoffice.callbackURL") }}: {{ clientConfig.editorConfig?.callbackUrl ? `${clientConfig.editorConfig.callbackUrl.slice(0, 80)}...` : 'N/A' }}<br/>
{{ $t("onlyoffice.documentKey") }}: {{ clientConfig.document.key }}<br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ $t("onlyoffice.fileType") }}: {{ clientConfig.document.fileType }}<br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ $t("onlyoffice.editMode") }}: {{ clientConfig.editorConfig ? clientConfig.editorConfig.mode : 'N/A' }}<br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ $t("onlyoffice.downloadURL") }}: {{ clientConfig.document.url ? `${clientConfig.document.url.substring(0, 80)}...` : 'N/A' }}<br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ $t("onlyoffice.callbackURL") }}: {{ clientConfig.editorConfig?.callbackUrl ? `${clientConfig.editorConfig.callbackUrl.substring(0, 80)}...` : 'N/A' }}<br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<br/>
<strong>{{ $t("onlyoffice.networkFlow") }}:</strong><br/>
{{ $t("onlyoffice.browser") }} ({{ windowOrigin }}) ↔ {{ $t("onlyoffice.onlyOffice") }}: {{ onlyOfficeUrl }}<br/>
{{ $t("onlyoffice.onlyOffice") }} → {{ $t("onlyoffice.fileBrowser") }}: {{ downloadDomain }}<br/>
<strong>{{ $t("onlyoffice.networkFlow") }}:</strong><br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ $t("onlyoffice.browser") }} ({{ windowOrigin }}) ↔ {{ $t("onlyoffice.onlyOffice") }}: {{ onlyOfficeUrl }}<br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ $t("onlyoffice.onlyOffice") }} → {{ $t("onlyoffice.fileBrowser") }}: {{ downloadDomain }}<br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
<div class="debug-section">
<strong>{{ $t("onlyoffice.processSteps") }}:</strong><br/>
<strong>{{ $t("onlyoffice.processSteps") }}:</strong><br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<div v-for="(step, i) in debugInfo" :key="i">
{{ step.text }}
<template v-for="(line, j) in step.lines" :key="j">
@@ -42,20 +42,20 @@
</template>
<template v-if="step.link">
<br/>
<a :href="wikiLink" target="_blank" rel="noopener noreferrer">📖 {{ $t("onlyoffice.troubleshootingGuide") }}</a>
<a :href="wikiLink" target="_blank" rel="noopener noreferrer">📖 {{ $t("onlyoffice.troubleshootingGuide") }}</a> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</template>
</div>
</div>
<div v-if="onlyOfficeLogs.length > 0" class="debug-section debug-section-logs">
<div class="debug-section-header-logs">
<strong class="debug-section-title-logs">📋 {{ $t("onlyoffice.backendLogs") }}</strong>
<strong class="debug-section-title-logs">📋 {{ $t("onlyoffice.backendLogs") }}</strong> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span class="debug-section-counter">{{ onlyOfficeLogs.length }} {{ $t("onlyoffice.entries") }}</span>
</div>
<div v-for="log in displayedLogs" :key="log.id" class="debug-log-entry">
<span class="debug-log-level" :style="{ color: getLogLevelColor(log.level) }">[{{ log.level }}]</span>
<span class="debug-log-level" :style="{ color: getLogLevelColor(log.level) }">[{{ log.level }}]</span> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span class="debug-log-timestamp">{{ formatTimestamp(log.timestamp) }}</span>
<span class="debug-log-component">[{{ log.component }}]</span>
<span class="debug-log-component">[{{ log.component }}]</span> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<span class="debug-log-message">{{ log.message }}</span>
</div>
</div>
@@ -64,14 +64,15 @@
</div>
<div v-if="overallStatus === 'error'" class="debug-status-error">
<strong>❌ {{ $t("onlyoffice.errorDetected") }}</strong><br/>
<strong>❌ {{ $t("onlyoffice.errorDetected") }}</strong><br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ $t("onlyoffice.integrationFailed") }}<br/>
<a :href="wikiLink" target="_blank" rel="noopener noreferrer">
<!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
📖 {{ $t("onlyoffice.troubleshootingGuide") }}
</a>
</div>
<div v-else-if="overallStatus === 'success'" class="debug-status-success">
<strong>🎉 {{ $t("onlyoffice.documentInitialized") }}</strong><br/>
<strong>🎉 {{ $t("onlyoffice.documentInitialized") }}</strong><br/> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ $t("onlyoffice.integrationSuccess") }}
</div>
</div>
@@ -79,10 +80,10 @@
</template>
<script>
import { state, getters } from "@/store/index.ts";
import { globalVars } from "@/utils/constants.ts";
import { officeApi } from "@/api/index.js";
import { events } from "@/notify/index.ts";
import { state, getters } from "@/store";
import { globalVars } from "@/utils/constants";
import { officeApi } from "@/api";
import { events } from "@/notify";
const wikiLink = "https://filebrowserquantum.com/en/docs/integrations/office/troubleshooting/";
@@ -110,7 +111,7 @@ export default {
return {
debugInfo: [{ text: `⏳ ${this.$t("onlyoffice.startingInit")}` }],
wikiLink,
clientConfig: { document: null, editorConfig: null },
clientConfig: {},
hasErrors: false,
onlyOfficeLogs: [],
documentId: null,
@@ -504,7 +505,7 @@ export default {
}
.debug-log-level {
font-weight: 700;
font-weight: bold;
}
.debug-log-timestamp {
+1 -1
View File
@@ -33,7 +33,7 @@
</template>
<script>
import { mutations } from "@/store/index.ts";
import { mutations } from "@/store";
export default {
name: "password",
@@ -1,6 +1,6 @@
<template>
<div class="card-content">
<file-list @update:selected="updateSelection" :browseSource="listBrowseSource"
<file-list ref="fileList" @update:selected="updateSelection" :browseSource="listBrowseSource"
:browse-path="initialBrowsePath" :hide-destination-source="hideDestinationSource" :showFiles="showFiles"
:showFolders="showFolders" :require-file-selection="requireFileSelection"
:allowed-file-types="allowedFileTypes" :title="listTitle" v-model:filter-query="filterQuery">
@@ -22,10 +22,10 @@
</template>
<script>
import { mutations, getters } from "@/store/index.ts";
import { mutations, getters } from "@/store";
import FileList from "../files/FileList.vue";
import ListingFilter from "@/components/files/ListingFilter.vue";
import { eventBus } from "@/store/eventBus.ts";
import { eventBus } from "@/store/eventBus";
export default {
name: "path-picker",
@@ -16,8 +16,8 @@
type="button"
class="clear-queue-btn"
@click="clearQueue"
:title="t('player.clearQueue')"
:aria-label="t('player.clearQueue')"
:title="$t('player.clearQueue')"
:aria-label="$t('player.clearQueue')"
>
<i class="material-symbols">delete</i>
</button>
@@ -63,6 +63,7 @@
<span v-if="item.fileType" class="file-type-badge">{{ item.fileType }}</span>
<span class="queue-item-indicator">
<span v-if="item.index === currentQueueIndex" class="current-track">
<!-- eslint-disable-next-line @intlify/vue-i18n/no-raw-text -->
<i class="material-symbols">{{ isPlaying ? 'pause' : 'play_arrow' }}</i>
</span>
<span v-else class="track-number">{{ item.index + 1 }}</span>
@@ -75,7 +76,7 @@
<!-- Empty state -->
<div v-else class="empty">
<i class="material-symbols">queue_music</i>
<p>{{ t('player.emptyQueue') }}</p>
<p>{{ $t('player.emptyQueue') }}</p>
</div>
</div>
@@ -95,11 +96,11 @@
</template>
<script setup lang="ts">
import { computed, nextTick, onMounted, useTemplateRef, watch } from "vue";
import { useI18n } from "@/i18n/index.ts";
import { state, mutations, getters } from "@/store/index.ts";
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { state, mutations, getters } from "@/store";
import type { MediaMetadata } from "@/store/types.ts";
import { url } from "@/utils/index.ts";
import { url } from "@/utils";
import {
cyclePlaybackModes,
cycleLoopState,
@@ -113,8 +114,8 @@ import {
} from '@/utils/playbackQueue.js';
import Icon from "@/components/files/Icon.vue";
import SlidingTabs from "@/components/settings/SlidingTabs.vue";
import { resourcesApi } from "@/api/index.js";
import { globalVars } from "@/utils/constants.ts";
import { resourcesApi } from "@/api";
import { globalVars } from "@/utils/constants";
import { formatDuration, getTypeFromMime, removeExtension } from "@/utils/files.js";
import { findScrollParents, useListingVirtualization } from "@/composables/useListingVirtualization.ts";
import type { VirtualItem } from "@/composables/useListingVirtualization.ts";
@@ -144,7 +145,7 @@ const props = withDefaults(
const { t } = useI18n();
const QueueList = useTemplateRef<HTMLElement>("QueueList");
const QueueList = ref<HTMLElement | null>(null);
// Only renders the rows around the screen when the queue is long
const virtual = useListingVirtualization<VirtualItem>({
container: QueueList,
@@ -159,10 +160,10 @@ const currentQueueIndex = computed(() => state.playbackQueue.currentIndex);
const playbackMode = computed(() => state.playbackQueue.mode || 'single');
const loop = computed(() => state.playbackQueue.loop || 'off');
const queueCount = computed(() => playbackQueue.value.length);
const currentModeLabel = computed(() => getModeLabel(playbackMode.value, queueCount.value));
const currentModeLabel = computed(() => getModeLabel(playbackMode.value, t, queueCount.value));
const currentModeIcon = computed(() => getModeIcon(playbackMode.value));
const loopIcon = computed(() => getLoopIcon(loop.value));
const loopLabel = computed(() => getLoopLabel(loop.value));
const loopLabel = computed(() => getLoopLabel(loop.value, t));
const isPlaying = computed(() => state.playbackQueue.isPlaying || false);
const isPromptVisible = computed(() => state.prompts.some(prompt => prompt.name === 'PlaybackQueue'));
const modeTabs = computed(() => [
+8 -8
View File
@@ -139,7 +139,7 @@ import NewFileTemplate from "./NewFileTemplate.vue";
import DefaultViewPrefs from "./DefaultViewPrefs.vue";
import MediaConversionFormats from "./MediaConversionFormats.vue";
import MediaTranscodeSettings from "./MediaTranscodeSettings.vue";
import { state, getters, mutations } from "@/store/index.ts";
import { state, getters, mutations } from "@/store";
import { getObjectProperty, omitObjectProperty, setObjectProperty } from "@/utils/object.js";
export default {
@@ -305,7 +305,7 @@ export default {
},
isTopmost(id) {
const allPrompts = this.prompts;
return allPrompts.at(-1)?.id === id;
return allPrompts[allPrompts.length - 1]?.id === id;
},
isDragging(id) {
return this.draggingIds.has(id);
@@ -524,11 +524,11 @@ export default {
if (!root) {
return null;
}
const buttons = Array.from(root.querySelectorAll('.card-actions button'));
const buttons = root.querySelectorAll('.card-actions button');
if (!buttons.length) {
return null;
}
const last = buttons.at(-1);
const last = buttons[buttons.length - 1];
if (last.disabled) {
return null;
}
@@ -601,8 +601,8 @@ export default {
});
this.draggingIds.add(id);
const move = (moveEvent) => this.onPointerMove(moveEvent, id, type);
const end = (endEvent) => this.onPointerEnd(endEvent, id, type, move, end);
const move = (e) => this.onPointerMove(e, id, type);
const end = (e) => this.onPointerEnd(e, id, type, move, end);
if (type === "mouse") {
window.addEventListener("mousemove", move);
@@ -684,8 +684,8 @@ export default {
clientY: pos.y,
};
const moveHandler = (moveEvent) => this.onResizeMove(moveEvent, type);
const endHandler = (endEvent) => this.onResizeEnd(endEvent, type, moveHandler, endHandler);
const moveHandler = (e) => this.onResizeMove(e, type);
const endHandler = (e) => this.onResizeEnd(e, type, moveHandler, endHandler);
if (type === 'mouse') {
window.addEventListener('mousemove', moveHandler);
+9 -7
View File
@@ -34,9 +34,11 @@
<p>{{ $t("general.limit") }}</p>
<div class="quota-custom-row">
<QuotaCustomLimitInput
v-model:amount="customAmount"
v-model:unit="customUnit"
:amount="customAmount"
:unit="customUnit"
:aria-label="$t('general.limit')"
@update:amount="customAmount = $event"
@update:unit="customUnit = $event"
/>
</div>
</div>
@@ -51,19 +53,19 @@
</template>
<script>
import { mutations, state } from "@/store/index.ts";
import { quotasApi } from "@/api/index.js";
import { mutations, state } from "@/store";
import { quotasApi } from "@/api";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
import ExpandDropdown from "@/components/settings/ExpandDropdown.vue";
import QuotaFolderBar from "@/components/prompts/QuotaFolderBar.vue";
import ActivityViewerButton from "@/components/settings/ActivityViewerButton.vue";
import QuotaCustomLimitInput from "@/components/settings/QuotaCustomLimitInput.vue";
import { activityViewerPresets } from "@/utils/activityViewerLink.js";
import { notify } from "@/notify/index.ts";
import { activityViewerPresets } from "@/utils/activityViewerLink";
import { notify } from "@/notify";
import {
bytesFromCustomAmount,
customAmountFromBytes,
} from "@/utils/quotaUnits.js";
} from "@/utils/quotaUnits";
export default {
name: "Quota",
Loaded 100 of 318 files, more files were not shown because too many files have changed in this diff. Show more