Merge pull request #291 from EdouardVanbelle/refactor/js-import-export
This commit is contained in:
+2
-1
@@ -14,7 +14,8 @@
|
||||
"rules": {
|
||||
"recommended": true,
|
||||
"correctness": {
|
||||
"noUnusedVariables": "warn"
|
||||
"noUnusedVariables": "warn",
|
||||
"noUndeclaredVariables": "error"
|
||||
},
|
||||
"style": {
|
||||
"noDescendingSpecificity": "off"
|
||||
|
||||
@@ -113,15 +113,19 @@ fn process_release(manifest_dir: &Path, static_dir: &Path, out_dir: &Path) {
|
||||
// ── 4. Minify ALL individual CSS in static-dist/ ─────────────────────────
|
||||
minify_tree_css(&dist_dir.join("css"));
|
||||
|
||||
// ── 5. Build JS bundle for index.html ────────────────────────────────────
|
||||
// ── 5. Bundle all ES modules into one IIFE ───────────────────────────────
|
||||
// Walk the import graph starting from every <script type="module"> in index.html,
|
||||
// strip import/export syntax, wrap in an IIFE, then minify as a classic script.
|
||||
let index_html = fs::read_to_string(static_dir.join("index.html")).expect("read index.html");
|
||||
let defer_scripts = extract_defer_scripts(&index_html);
|
||||
let js_bundle = build_js_bundle(static_dir, &defer_scripts);
|
||||
let module_scripts = extract_module_scripts(&index_html);
|
||||
let js_raw = build_js_module_bundle(&module_scripts, static_dir);
|
||||
let js_bundle = js_minify_script_safe(&js_raw);
|
||||
let js_hash = fnv_hash(js_bundle.as_bytes());
|
||||
let js_name = format!("app.{js_hash}.js");
|
||||
fs::create_dir_all(dist_dir.join("js")).expect("js dir");
|
||||
fs::write(dist_dir.join("js").join(&js_name), &js_bundle).expect("write js bundle");
|
||||
|
||||
// ── 6. Minify ALL individual JS in static-dist/ ──────────────────────────
|
||||
// ── 6. Minify ALL individual JS files in static-dist/ ────────────────────
|
||||
minify_tree_js(&dist_dir.join("js"));
|
||||
|
||||
// ── 7. Inline theme-init.js & rewrite index.html ──────────────────────
|
||||
@@ -246,15 +250,15 @@ fn minify_tree_css(dir: &Path) {
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// JS processing
|
||||
// JS bundling (ES module → single IIFE)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/// Collect `<script defer src="…">` paths from HTML.
|
||||
fn extract_defer_scripts(html: &str) -> Vec<String> {
|
||||
/// Collect `<script type="module" src="…">` paths from HTML.
|
||||
fn extract_module_scripts(html: &str) -> Vec<String> {
|
||||
html.lines()
|
||||
.filter_map(|l| {
|
||||
let t = l.trim();
|
||||
if t.starts_with("<script") && t.contains("defer") && t.contains("src=\"") {
|
||||
if t.starts_with("<script") && t.contains("type=\"module\"") && t.contains("src=\"") {
|
||||
let s = t.find("src=\"")? + 5;
|
||||
let e = t[s..].find('"')? + s;
|
||||
Some(t[s..e].to_string())
|
||||
@@ -265,35 +269,275 @@ fn extract_defer_scripts(html: &str) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Minify each script individually, then concatenate (safer than a monolith parse).
|
||||
fn build_js_bundle(static_dir: &Path, script_paths: &[String]) -> String {
|
||||
let mut bundle = String::with_capacity(512 * 1024);
|
||||
for path in script_paths {
|
||||
let file = static_dir.join(path.trim_start_matches('/'));
|
||||
if file.exists() {
|
||||
let src = fs::read_to_string(&file).unwrap_or_default();
|
||||
let min = js_minify_safe(&src);
|
||||
bundle.push_str(&min);
|
||||
bundle.push_str(";\n");
|
||||
} else {
|
||||
eprintln!("cargo:warning=JS not found: {}", file.display());
|
||||
/// Build a single IIFE from all ES-module entry points.
|
||||
///
|
||||
/// Algorithm:
|
||||
/// 1. DFS from each entry point, following `import … from '…'` edges.
|
||||
/// 2. Post-order traversal ensures every dependency is emitted before its importer.
|
||||
/// 3. Cycles are broken by marking files as visited before recursing.
|
||||
/// 4. Each file has its import/export syntax stripped before being appended.
|
||||
/// 5. The result is wrapped in `(function(){"use strict"; …})();`.
|
||||
fn build_js_module_bundle(entry_scripts: &[String], static_dir: &Path) -> String {
|
||||
use std::collections::HashSet;
|
||||
|
||||
let mut order: Vec<PathBuf> = Vec::new();
|
||||
let mut seen: HashSet<PathBuf> = HashSet::new();
|
||||
|
||||
for script in entry_scripts {
|
||||
let path = static_dir.join(script.trim_start_matches('/'));
|
||||
collect_module_deps(&path, &mut order, &mut seen);
|
||||
}
|
||||
|
||||
let mut bundle = String::with_capacity(2 * 1024 * 1024);
|
||||
bundle.push_str("(function(){\n\"use strict\";\n");
|
||||
for file in &order {
|
||||
match fs::read_to_string(file) {
|
||||
Ok(src) => {
|
||||
bundle.push_str(&strip_esm_syntax(&src));
|
||||
bundle.push('\n');
|
||||
}
|
||||
Err(e) => eprintln!("cargo:warning=bundle: cannot read {}: {e}", file.display()),
|
||||
}
|
||||
}
|
||||
bundle.push_str("})();\n");
|
||||
bundle
|
||||
}
|
||||
|
||||
/// Minify JS via oxc — returns original on failure.
|
||||
/// DFS post-order: push `file` to `order` after all its imports.
|
||||
/// Marks files as seen before recursing to break circular dependencies.
|
||||
fn collect_module_deps(
|
||||
file: &Path,
|
||||
order: &mut Vec<PathBuf>,
|
||||
seen: &mut std::collections::HashSet<PathBuf>,
|
||||
) {
|
||||
let canonical = match file.canonicalize() {
|
||||
Ok(p) => p,
|
||||
Err(_) => {
|
||||
eprintln!("cargo:warning=JS import not found: {}", file.display());
|
||||
return;
|
||||
}
|
||||
};
|
||||
if !seen.insert(canonical.clone()) {
|
||||
return; // already visited (or in-progress cycle)
|
||||
}
|
||||
|
||||
let src = fs::read_to_string(file).unwrap_or_default();
|
||||
let base = file.parent().unwrap_or(Path::new("."));
|
||||
|
||||
for rel in extract_esm_import_paths(&src) {
|
||||
if rel.starts_with('.') {
|
||||
collect_module_deps(&base.join(&rel), order, seen);
|
||||
}
|
||||
// Non-relative (bare specifiers like 'react') are ignored — not used here.
|
||||
}
|
||||
|
||||
order.push(file.to_path_buf());
|
||||
}
|
||||
|
||||
/// Return all relative paths found in `import … from '…'` / `export … from '…'` lines.
|
||||
fn extract_esm_import_paths(source: &str) -> Vec<String> {
|
||||
let mut paths = Vec::new();
|
||||
let mut multiline = false;
|
||||
|
||||
for line in source.lines() {
|
||||
let t = line.trim();
|
||||
|
||||
if multiline {
|
||||
// Waiting for the `from '…'` of a multi-line import
|
||||
if let Some(p) = extract_from_clause(t) {
|
||||
paths.push(p);
|
||||
multiline = false;
|
||||
} else if t.ends_with(';') {
|
||||
multiline = false; // malformed, give up on this import
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if !t.starts_with("import ") && !t.starts_with("export ") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(p) = extract_from_clause(t) {
|
||||
paths.push(p);
|
||||
} else if t.starts_with("import ") && !t.ends_with(';') && !t.contains("//") {
|
||||
// Multi-line: `import {\n X,\n Y\n} from '…'`
|
||||
multiline = true;
|
||||
}
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
/// Extract the path string from the `from '…'` or `from "…"` tail of a line.
|
||||
fn extract_from_clause(s: &str) -> Option<String> {
|
||||
let from = s.rfind(" from ")?;
|
||||
let rest = s[from + 6..].trim();
|
||||
let q = rest.chars().next()?;
|
||||
if q != '\'' && q != '"' {
|
||||
return None;
|
||||
}
|
||||
let end = rest[1..].find(q)? + 1;
|
||||
Some(rest[1..end].to_string())
|
||||
}
|
||||
|
||||
/// Strip ES-module syntax from a single file so it can be inlined into an IIFE.
|
||||
///
|
||||
/// | Input | Output |
|
||||
/// |------------------------------------------|------------------------------|
|
||||
/// | `import { X } from './y.js';` | *(empty line)* |
|
||||
/// | `import { X as Y } from './y.js';` | `const Y = X;` |
|
||||
/// | `export { X, Y };` | *(empty line)* |
|
||||
/// | `export { X } from './y.js';` | *(empty line)* |
|
||||
/// | `export const X = …` | `const X = …` |
|
||||
/// | `export function f() {…}` | `function f() {…}` |
|
||||
/// | `export async function f() {…}` | `async function f() {…}` |
|
||||
/// | `export class C {…}` | `class C {…}` |
|
||||
/// | `export default expr;` | `const _default = expr;` |
|
||||
fn strip_esm_syntax(source: &str) -> String {
|
||||
let mut out = String::with_capacity(source.len());
|
||||
// True while we are inside a multi-line import/export-list that has not yet
|
||||
// seen its terminating `;`.
|
||||
let mut skipping = false;
|
||||
|
||||
for line in source.lines() {
|
||||
let t = line.trim();
|
||||
|
||||
if skipping {
|
||||
// Keep skipping until the statement ends
|
||||
if t.ends_with(';') || t.contains(" from ") {
|
||||
skipping = false;
|
||||
}
|
||||
out.push('\n'); // preserve line count for source maps / debugging
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── import … ──────────────────────────────────────────────────────────
|
||||
// Emit `const Y = X;` for any `import { X as Y }` aliases so that code
|
||||
// using the aliased name still resolves inside the IIFE scope.
|
||||
if t.starts_with("import ") {
|
||||
if !t.ends_with(';') && !t.contains(" from ") {
|
||||
skipping = true; // multi-line import
|
||||
}
|
||||
let aliases = collect_import_aliases(t);
|
||||
if aliases.is_empty() {
|
||||
out.push('\n');
|
||||
} else {
|
||||
out.push_str(&aliases);
|
||||
out.push('\n');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── export { … } or export { … } from '…' ────────────────────────────
|
||||
if t.starts_with("export {") || t.starts_with("export{") {
|
||||
if !t.ends_with(';') {
|
||||
skipping = true;
|
||||
}
|
||||
out.push('\n');
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── export const/let/var/function/async function/class ─────────────────
|
||||
if let Some(stripped) = try_strip_export_prefix(line) {
|
||||
out.push_str(&stripped);
|
||||
out.push('\n');
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── export default expr ────────────────────────────────────────────────
|
||||
// Rare in our codebase; keep the value as a named variable.
|
||||
if let Some(rhs) = t.strip_prefix("export default ") {
|
||||
let indent = &line[..line.len() - line.trim_start().len()];
|
||||
out.push_str(&format!("{indent}const _default = {rhs}"));
|
||||
out.push('\n');
|
||||
continue;
|
||||
}
|
||||
|
||||
out.push_str(line);
|
||||
out.push('\n');
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// If `line` (with leading whitespace preserved) begins with `export <decl-keyword>`,
|
||||
/// return the same line with `export ` (7 chars) removed.
|
||||
fn try_strip_export_prefix(line: &str) -> Option<String> {
|
||||
const PREFIXES: &[&str] = &[
|
||||
"export const ",
|
||||
"export let ",
|
||||
"export var ",
|
||||
"export function ",
|
||||
"export async function ",
|
||||
"export class ",
|
||||
];
|
||||
let t = line.trim();
|
||||
for prefix in PREFIXES {
|
||||
if t.starts_with(prefix) {
|
||||
let indent_len = line.len() - line.trim_start().len();
|
||||
// Remove "export " (7 chars) right after the indent
|
||||
return Some(format!(
|
||||
"{}{}",
|
||||
&line[..indent_len],
|
||||
&line[indent_len + 7..]
|
||||
));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// For `import { A, B as C, D as E } from '…'` return `"const C = B;\nconst E = D;"`.
|
||||
/// Returns an empty string when there are no aliases.
|
||||
fn collect_import_aliases(stmt: &str) -> String {
|
||||
let brace_start = match stmt.find('{') {
|
||||
Some(i) => i + 1,
|
||||
None => return String::new(),
|
||||
};
|
||||
let brace_end = match stmt.find('}') {
|
||||
Some(i) => i,
|
||||
None => return String::new(),
|
||||
};
|
||||
let bindings = &stmt[brace_start..brace_end];
|
||||
|
||||
let mut out = String::new();
|
||||
for binding in bindings.split(',') {
|
||||
let b = binding.trim();
|
||||
if let Some(as_pos) = b.find(" as ") {
|
||||
let orig = b[..as_pos].trim();
|
||||
let alias = b[as_pos + 4..].trim();
|
||||
if !out.is_empty() {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(&format!("const {alias} = {orig};"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// JS minification
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/// Minify an ES-module file (contains import/export) — returns original on failure.
|
||||
fn js_minify_safe(source: &str) -> String {
|
||||
js_minify_inner(source, true)
|
||||
}
|
||||
|
||||
/// Minify a classic script / IIFE bundle (no import/export) — returns original on failure.
|
||||
fn js_minify_script_safe(source: &str) -> String {
|
||||
js_minify_inner(source, false)
|
||||
}
|
||||
|
||||
fn js_minify_inner(source: &str, is_module: bool) -> String {
|
||||
if source.trim().is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
js_minify(source).unwrap_or_else(|e| {
|
||||
js_minify(source, is_module).unwrap_or_else(|e| {
|
||||
eprintln!("cargo:warning=JS minify failed: {e}");
|
||||
source.to_string()
|
||||
})
|
||||
}
|
||||
|
||||
fn js_minify(source: &str) -> Result<String, String> {
|
||||
fn js_minify(source: &str, is_module: bool) -> Result<String, String> {
|
||||
use oxc_allocator::Allocator;
|
||||
use oxc_codegen::{Codegen, CodegenOptions, CommentOptions};
|
||||
use oxc_minifier::{CompressOptions, CompressOptionsUnused, Minifier, MinifierOptions};
|
||||
@@ -301,7 +545,11 @@ fn js_minify(source: &str) -> Result<String, String> {
|
||||
use oxc_span::SourceType;
|
||||
|
||||
let allocator = Allocator::default();
|
||||
let source_type = SourceType::cjs(); // Non-module, script mode
|
||||
let source_type = if is_module {
|
||||
SourceType::mjs()
|
||||
} else {
|
||||
SourceType::cjs()
|
||||
};
|
||||
let ret = Parser::new(&allocator, source, source_type).parse();
|
||||
|
||||
if !ret.errors.is_empty() {
|
||||
@@ -311,8 +559,6 @@ fn js_minify(source: &str) -> Result<String, String> {
|
||||
|
||||
let mut program = ret.program;
|
||||
|
||||
// Compress (constant-fold, dead-code) — NO mangle (globals would break)
|
||||
// Keep unused top-level functions: they're called cross-file via window.*
|
||||
Minifier::new(MinifierOptions {
|
||||
mangle: None,
|
||||
compress: Some(CompressOptions {
|
||||
@@ -337,7 +583,7 @@ fn js_minify(source: &str) -> Result<String, String> {
|
||||
Ok(output.code)
|
||||
}
|
||||
|
||||
/// Walk a directory and minify every `.js` in-place (skips generated bundles).
|
||||
/// Walk a directory and minify every `.js` in-place (skips generated `app.*` bundles).
|
||||
fn minify_tree_js(dir: &Path) {
|
||||
let Ok(entries) = fs::read_dir(dir) else {
|
||||
return;
|
||||
@@ -412,11 +658,15 @@ fn json_minify(source: &str) -> String {
|
||||
// HTML rewriting
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/// Rewrite index.html: single CSS bundle, inline theme-init, single JS bundle.
|
||||
/// Rewrite index.html for release:
|
||||
/// - Collapse all `<link stylesheet href="/css/…">` into the single CSS bundle.
|
||||
/// - Inline `theme-init.js` as a `<script>` block.
|
||||
/// - Replace all `<script type="module" src="…">` with the single JS bundle.
|
||||
/// - Leave the non-module `sw-register.js` script untouched.
|
||||
fn rewrite_index_html(html: &str, css_path: &str, js_path: &str, inline_theme_js: &str) -> String {
|
||||
let mut out: Vec<String> = Vec::with_capacity(html.lines().count());
|
||||
let mut css_done = false;
|
||||
let mut defer_done = false;
|
||||
let mut js_done = false;
|
||||
|
||||
for line in html.lines() {
|
||||
let t = line.trim();
|
||||
@@ -436,22 +686,19 @@ fn rewrite_index_html(html: &str, css_path: &str, js_path: &str, inline_theme_js
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── Replace all defer <script>s with single bundle ──────────────────
|
||||
if t.starts_with("<script") && t.contains("defer") && t.contains("src=\"") {
|
||||
if !defer_done {
|
||||
out.push(format!(" <script defer src=\"{js_path}\"></script>"));
|
||||
defer_done = true;
|
||||
// ── Replace all type="module" scripts with single bundle ─────────────
|
||||
if t.starts_with("<script") && t.contains("type=\"module\"") && t.contains("src=\"") {
|
||||
if !js_done {
|
||||
out.push(format!(
|
||||
" <script defer type=\"module\" src=\"{js_path}\"></script>"
|
||||
));
|
||||
js_done = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── Drop "Service Worker Registration" comment ──────────────────────
|
||||
if t.contains("Service Worker Registration") {
|
||||
continue;
|
||||
}
|
||||
|
||||
// ── Drop "Styles" / "Scripts" section comments ──────────────────────
|
||||
if t.starts_with("<!--") && (t.contains("Styles") || t.contains("Scripts (defer")) {
|
||||
// ── Drop "Styles" / "Scripts" section comments ───────────────────────
|
||||
if t.starts_with("<!--") && (t.contains("Styles") || t.contains("Scripts")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -481,8 +728,6 @@ fn update_sw_cache(sw: &str, css_bundle: &str, js_bundle: &str) -> String {
|
||||
|
||||
format!(
|
||||
"{before}const ASSETS_TO_CACHE = [\n\
|
||||
\x20 '/',\n\
|
||||
\x20 '/index.html',\n\
|
||||
\x20 '/css/{css_bundle}',\n\
|
||||
\x20 '/js/{js_bundle}',\n\
|
||||
\x20 '/locales/en.json',\n\
|
||||
|
||||
@@ -60,9 +60,7 @@ impl AudioMetadataService {
|
||||
///
|
||||
/// All I/O is synchronous (id3 + mp3_duration crates), so this MUST
|
||||
/// only be called inside `spawn_blocking`.
|
||||
fn extract_metadata_blocking(
|
||||
file_path: &Path,
|
||||
) -> Option<AudioMetadataFields> {
|
||||
fn extract_metadata_blocking(file_path: &Path) -> Option<AudioMetadataFields> {
|
||||
if !file_path.exists() {
|
||||
warn!("File does not exist: {:?}", file_path);
|
||||
return None;
|
||||
@@ -114,12 +112,13 @@ impl AudioMetadataService {
|
||||
|
||||
// ── Sync I/O on the blocking thread pool (never stalls Tokio workers) ──
|
||||
let path = file_path.to_path_buf();
|
||||
let metadata = tokio::task::spawn_blocking(move || {
|
||||
Self::extract_metadata_blocking(&path)
|
||||
})
|
||||
let metadata = tokio::task::spawn_blocking(move || Self::extract_metadata_blocking(&path))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
DomainError::internal_error("AudioMetadataService", format!("spawn_blocking join error: {e}"))
|
||||
DomainError::internal_error(
|
||||
"AudioMetadataService",
|
||||
format!("spawn_blocking join error: {e}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let Some(m) = metadata else {
|
||||
|
||||
@@ -717,7 +717,11 @@ impl DedupService {
|
||||
// Also clean up any thumbnail files for these blob hashes
|
||||
// (thumbnails are keyed by blob_hash and live under
|
||||
// storage_root/.thumbnails/{icon,preview,large}/{hash}.jpg).
|
||||
let thumbnails_root = self.blob_root.parent().unwrap_or(&self.blob_root).join(".thumbnails");
|
||||
let thumbnails_root = self
|
||||
.blob_root
|
||||
.parent()
|
||||
.unwrap_or(&self.blob_root)
|
||||
.join(".thumbnails");
|
||||
for (hash, size) in &batch {
|
||||
let blob_path = self.blob_path(hash);
|
||||
if let Err(e) = fs::remove_file(&blob_path).await {
|
||||
|
||||
@@ -40,7 +40,12 @@ async fn generate_thumbnail_from_blob_path() {
|
||||
|
||||
// The key assertion: the service can read from a blob path (not a logical path)
|
||||
let result = svc
|
||||
.get_thumbnail("test-file-id", "ab1234567890", ThumbnailSize::Icon, &blob_path)
|
||||
.get_thumbnail(
|
||||
"test-file-id",
|
||||
"ab1234567890",
|
||||
ThumbnailSize::Icon,
|
||||
&blob_path,
|
||||
)
|
||||
.await;
|
||||
|
||||
let thumb_bytes = result.expect("thumbnail generation should succeed from blob path");
|
||||
@@ -67,7 +72,12 @@ async fn generate_thumbnail_nonexistent_path_returns_error() {
|
||||
|
||||
let bad_path = tmp.path().join("does-not-exist.png");
|
||||
let result = svc
|
||||
.get_thumbnail("missing-id", "nonexistent-hash", ThumbnailSize::Icon, &bad_path)
|
||||
.get_thumbnail(
|
||||
"missing-id",
|
||||
"nonexistent-hash",
|
||||
ThumbnailSize::Icon,
|
||||
&bad_path,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(result.is_err(), "should fail for nonexistent file");
|
||||
|
||||
@@ -746,7 +746,11 @@ impl FileHandler {
|
||||
|
||||
tokio::spawn(async move {
|
||||
tracing::info!("🖼️ Generating thumbnails for: {}", file_id);
|
||||
thumbnail_service.generate_all_sizes_background(file_id, blob_hash_owned, file_path);
|
||||
thumbnail_service.generate_all_sizes_background(
|
||||
file_id,
|
||||
blob_hash_owned,
|
||||
file_path,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,10 @@ use crate::application::services::share_service::ShareService;
|
||||
use crate::{
|
||||
application::{
|
||||
dtos::share_dto::{CreateShareDto, UpdateShareDto},
|
||||
ports::{file_ports::{FileRetrievalUseCase, OptimizedFileContent}, share_ports::ShareUseCase},
|
||||
ports::{
|
||||
file_ports::{FileRetrievalUseCase, OptimizedFileContent},
|
||||
share_ports::ShareUseCase,
|
||||
},
|
||||
},
|
||||
common::{di::AppState, errors::ErrorKind},
|
||||
domain::entities::share::ShareItemType,
|
||||
@@ -290,7 +293,7 @@ pub async fn download_shared_file(
|
||||
"Sharing is disabled",
|
||||
"Disabled",
|
||||
)
|
||||
.into_response()
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -243,10 +243,7 @@ pub async fn auth_middleware(
|
||||
if request.uri().path().starts_with("/webdav") {
|
||||
return Ok(Response::builder()
|
||||
.status(StatusCode::UNAUTHORIZED)
|
||||
.header(
|
||||
header::WWW_AUTHENTICATE,
|
||||
r#"Basic realm="OxiCloud""#,
|
||||
)
|
||||
.header(header::WWW_AUTHENTICATE, r#"Basic realm="OxiCloud""#)
|
||||
.header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
|
||||
.body(axum::body::Body::from(
|
||||
"Invalid username or app password",
|
||||
|
||||
+1
-5
@@ -5,10 +5,6 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>OxiCloud — Admin Panel</title>
|
||||
<script src="/js/core/theme-init.js"></script>
|
||||
<script src="/js/core/i18n.js" defer></script>
|
||||
<script src="/js/core/icons.js" defer></script>
|
||||
<script src="/js/core/formatters.js" defer></script>
|
||||
<script src="/js/core/csrf.js" defer></script>
|
||||
<link rel="stylesheet" href="/css/main.css" />
|
||||
<link rel="stylesheet" href="/css/views/admin.css" />
|
||||
</head>
|
||||
@@ -608,6 +604,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/js/views/admin/admin.js" defer></script>
|
||||
<script type="module" src="/js/views/admin/admin.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -48,7 +48,6 @@
|
||||
<div id="status-error" class="status error hidden"></div>
|
||||
</div>
|
||||
|
||||
<script src="/js/core/csrf.js"></script>
|
||||
<script src="/js/views/device-verify/device-verify.js"></script>
|
||||
<script type="module" src="/js/views/device-verify/device-verify.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+31
-32
@@ -19,38 +19,37 @@
|
||||
<link rel="stylesheet" href="/css/views/music.css">
|
||||
|
||||
<!-- Scripts (defer: download in parallel, execute in order, after HTML parsed) -->
|
||||
<script defer src="/js/core/i18n.js"></script>
|
||||
<script defer src="/js/core/csrf.js"></script>
|
||||
<script defer src="/js/core/languageSelector.js"></script>
|
||||
<script defer src="/js/core/notifications.js"></script>
|
||||
<script defer src="/js/core/modal.js"></script>
|
||||
<script defer src="/js/core/formatters.js"></script>
|
||||
<script defer src="/js/app/state.js"></script>
|
||||
<script defer src="/js/app/uiFileTypes.js"></script>
|
||||
<script defer src="/js/app/uiNotifications.js"></script>
|
||||
<script defer src="/js/app/ui.js"></script>
|
||||
<script defer src="/js/features/files/contextMenus.js"></script>
|
||||
<script defer src="/js/features/files/fileOperations.js"></script>
|
||||
<script defer src="/js/features/files/multiSelect.js"></script>
|
||||
<script defer src="/js/features/files/search.js"></script>
|
||||
<script defer src="/js/features/library/favorites.js"></script>
|
||||
<script defer src="/js/features/library/recent.js"></script>
|
||||
<script defer src="/js/features/library/photos.js"></script>
|
||||
<script defer src="/js/features/library/photosLightbox.js"></script>
|
||||
<script defer src="/js/features/library/music.js"></script>
|
||||
<script defer src="/js/features/sharing/fileSharing.js"></script>
|
||||
<script defer src="/js/views/shared/sharedView.js"></script>
|
||||
<script defer src="/js/features/files/inlineViewer.js"></script>
|
||||
<script defer src="/js/features/files/wopiEditor.js"></script>
|
||||
<script defer src="/js/core/icons.js"></script>
|
||||
<script defer src="/js/app/navigation.js"></script>
|
||||
<script defer src="/js/app/authSession.js"></script>
|
||||
<script defer src="/js/app/userMenu.js"></script>
|
||||
<script defer src="/js/app/filesView.js"></script>
|
||||
<script defer src="/js/app/trashView.js"></script>
|
||||
<script defer src="/js/app/searchView.js"></script>
|
||||
<script defer src="/js/app/main.js"></script>
|
||||
<script defer src="/js/app/bootstrap.js"></script>
|
||||
<script defer type="module" src="/js/core/i18n.js"></script>
|
||||
<script defer type="module" src="/js/core/csrf.js"></script>
|
||||
<script defer type="module" src="/js/core/languageSelector.js"></script>
|
||||
<script defer type="module" src="/js/core/notifications.js"></script>
|
||||
<script defer type="module" src="/js/core/modal.js"></script>
|
||||
<script defer type="module" src="/js/core/formatters.js"></script>
|
||||
<script defer type="module" src="/js/app/state.js"></script>
|
||||
<script defer type="module" src="/js/app/uiFileTypes.js"></script>
|
||||
<script defer type="module" src="/js/app/uiNotifications.js"></script>
|
||||
<script defer type="module" src="/js/app/ui.js"></script>
|
||||
<script defer type="module" src="/js/features/files/contextMenus.js"></script>
|
||||
<script defer type="module" src="/js/features/files/fileOperations.js"></script>
|
||||
<script defer type="module" src="/js/features/files/multiSelect.js"></script>
|
||||
<script defer type="module" src="/js/features/files/search.js"></script>
|
||||
<script defer type="module" src="/js/features/library/favorites.js"></script>
|
||||
<script defer type="module" src="/js/features/library/recent.js"></script>
|
||||
<script defer type="module" src="/js/features/library/photos.js"></script>
|
||||
<script defer type="module" src="/js/features/library/music.js"></script>
|
||||
<script defer type="module" src="/js/features/sharing/fileSharing.js"></script>
|
||||
<script defer type="module" src="/js/views/shared/sharedView.js"></script>
|
||||
<script defer type="module" src="/js/features/files/inlineViewer.js"></script>
|
||||
<script defer type="module" src="/js/features/files/wopiEditor.js"></script>
|
||||
<script defer type="module" src="/js/core/icons.js"></script>
|
||||
<script defer type="module" src="/js/app/navigation.js"></script>
|
||||
<script defer type="module" src="/js/app/authSession.js"></script>
|
||||
<script defer type="module" src="/js/app/userMenu.js"></script>
|
||||
<script defer type="module" src="/js/app/filesView.js"></script>
|
||||
<script defer type="module" src="/js/app/trashView.js"></script>
|
||||
<script defer type="module" src="/js/app/searchView.js"></script>
|
||||
<script defer type="module" src="/js/app/main.js"></script>
|
||||
<script defer type="module" src="/js/app/bootstrap.js"></script>
|
||||
|
||||
<!-- Service Worker Registration -->
|
||||
<script defer src="/js/core/sw-register.js"></script>
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
* Authentication/session bootstrap and home-folder resolution
|
||||
*/
|
||||
|
||||
import { getCsrfHeaders } from '../core/csrf.js';
|
||||
import { loadFiles } from './filesView.js';
|
||||
import { updateStorageUsageDisplay } from './main.js';
|
||||
import { app } from './state.js';
|
||||
import { ui } from './ui.js';
|
||||
|
||||
async function refreshUserData() {
|
||||
const USER_DATA_KEY = 'oxicloud_user';
|
||||
|
||||
@@ -24,7 +30,7 @@ async function refreshUserData() {
|
||||
console.log('Storage from server: used=', userData.storage_used_bytes, 'quota=', userData.storage_quota_bytes);
|
||||
|
||||
localStorage.setItem(USER_DATA_KEY, JSON.stringify(userData));
|
||||
window.updateStorageUsageDisplay(userData);
|
||||
updateStorageUsageDisplay(userData);
|
||||
return userData;
|
||||
} catch (error) {
|
||||
console.error('Error refreshing user data:', error);
|
||||
@@ -89,7 +95,7 @@ async function checkAuthentication() {
|
||||
if (menuName) menuName.textContent = userData.username;
|
||||
if (menuEmail) menuEmail.textContent = userData.email || '';
|
||||
|
||||
window.updateStorageUsageDisplay(userData);
|
||||
updateStorageUsageDisplay(userData);
|
||||
|
||||
// Validate session BEFORE loading files to avoid 401 race condition
|
||||
const freshData = await refreshUserData();
|
||||
@@ -133,8 +139,8 @@ async function checkAuthentication() {
|
||||
document.querySelectorAll('.user-avatar, .user-menu-avatar').forEach((el) => {
|
||||
el.textContent = userInitials;
|
||||
});
|
||||
window.updateStorageUsageDisplay(freshData);
|
||||
resolveHomeFolder().then(() => window.loadFiles());
|
||||
updateStorageUsageDisplay(freshData);
|
||||
resolveHomeFolder().then(() => loadFiles());
|
||||
} else {
|
||||
console.warn('Could not retrieve user data, redirecting to login');
|
||||
localStorage.removeItem(USER_DATA_KEY);
|
||||
@@ -154,8 +160,6 @@ async function checkAuthentication() {
|
||||
}
|
||||
|
||||
async function resolveHomeFolder() {
|
||||
const app = window.app;
|
||||
|
||||
if (app.userHomeFolderId) return;
|
||||
try {
|
||||
const response = await fetch('/api/folders', {
|
||||
@@ -173,22 +177,20 @@ async function resolveHomeFolder() {
|
||||
app.userHomeFolderName = home.name;
|
||||
app.currentPath = home.id;
|
||||
app.breadcrumbPath = [];
|
||||
window.ui.updateBreadcrumb();
|
||||
ui.updateBreadcrumb();
|
||||
console.log(`Home folder resolved: ${home.name} (${home.id})`);
|
||||
} else {
|
||||
console.warn('No root folders found for user');
|
||||
app.currentPath = '';
|
||||
app.breadcrumbPath = [];
|
||||
window.ui.updateBreadcrumb();
|
||||
ui.updateBreadcrumb();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error resolving home folder:', error);
|
||||
app.currentPath = '';
|
||||
app.breadcrumbPath = [];
|
||||
window.ui.updateBreadcrumb();
|
||||
ui.updateBreadcrumb();
|
||||
}
|
||||
}
|
||||
|
||||
window.refreshUserData = refreshUserData;
|
||||
window.checkAuthentication = checkAuthentication;
|
||||
window.resolveHomeFolder = resolveHomeFolder;
|
||||
export { checkAuthentication, refreshUserData, resolveHomeFolder };
|
||||
|
||||
Vendored
+4
-7
@@ -2,13 +2,10 @@
|
||||
* OxiCloud - App bootstrap
|
||||
* Isolated startup trigger for the main application initializer.
|
||||
*/
|
||||
import { initApp } from './main.js';
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (typeof window.initApp === 'function') {
|
||||
window.initApp();
|
||||
}
|
||||
});
|
||||
} else if (typeof window.initApp === 'function') {
|
||||
window.initApp();
|
||||
document.addEventListener('DOMContentLoaded', initApp);
|
||||
} else {
|
||||
initApp();
|
||||
}
|
||||
|
||||
+39
-35
@@ -1,5 +1,16 @@
|
||||
// @ts-check
|
||||
|
||||
import { i18n } from '../core/i18n.js';
|
||||
import { inlineViewer } from '../features/files/inlineViewer.js';
|
||||
import { multiSelect } from '../features/files/multiSelect.js';
|
||||
import { resolveHomeFolder } from './authSession.js';
|
||||
import { updateHistory } from './main.js';
|
||||
import { app } from './state.js';
|
||||
import { ui } from './ui.js';
|
||||
import { uiNotifications } from './uiNotifications.js';
|
||||
|
||||
let isLoadingFiles = false;
|
||||
|
||||
// TODO move to features/files/fileOperations.js ?
|
||||
/**
|
||||
* @typedef {Object} FolderInfo
|
||||
@@ -48,8 +59,6 @@ async function getFolder(id) {
|
||||
* rebuild breadcrumb from selected folder (iterate up to root)
|
||||
*/
|
||||
async function rebuildBreadCrumb() {
|
||||
const app = window.app;
|
||||
|
||||
/**
|
||||
* Store the leaf (this is the current displayed folder)
|
||||
* @type {FolderInfo | null}
|
||||
@@ -87,10 +96,7 @@ async function rebuildBreadCrumb() {
|
||||
} catch (_e) {
|
||||
console.log(`Error loading information from folder ${app.currentPath}, falling back to ${app.userHomeFolderId}`);
|
||||
// fallback of root
|
||||
window.uiNotifications.show(
|
||||
'error: folder not found or permission denied',
|
||||
'the given folder is not available or you do not have sufficient rights'
|
||||
);
|
||||
uiNotifications.show('error: folder not found or permission denied', 'the given folder is not available or you do not have sufficient rights');
|
||||
app.breadcrumbPath = [];
|
||||
id = app.userHomeFolderId;
|
||||
app.currentPath = id;
|
||||
@@ -109,33 +115,31 @@ async function rebuildBreadCrumb() {
|
||||
* @param {boolean} [options.forceRefresh] force refresh of content
|
||||
*/
|
||||
async function loadFiles(options = { insertHistory: true }) {
|
||||
const app = window.app;
|
||||
|
||||
try {
|
||||
console.log('Starting loadFiles() - loading files...', options);
|
||||
|
||||
const forceRefresh = options.forceRefresh || false;
|
||||
|
||||
if (window.isLoadingFiles) {
|
||||
if (isLoadingFiles) {
|
||||
console.log('A file load is already in progress, ignoring request');
|
||||
return;
|
||||
}
|
||||
|
||||
window.isLoadingFiles = true;
|
||||
isLoadingFiles = true;
|
||||
|
||||
// This to avoid blinking page, a better solution would be to put loading on an overlay and remove timeout
|
||||
const loadingFiles = setTimeout(() => {
|
||||
// display loader after few delay (will be canceled if result take less time)
|
||||
window.ui.showError(`
|
||||
ui.showError(`
|
||||
<div class="files-loading-spinner">
|
||||
<div class="spinner"></div>
|
||||
<span>${window.i18n ? window.i18n.t('files.loading') : 'Loading files…'}</span>
|
||||
<span>${i18n ? i18n.t('files.loading') : 'Loading files…'}</span>
|
||||
</div>
|
||||
`);
|
||||
}, 100);
|
||||
|
||||
if (!app.userHomeFolderId) {
|
||||
await window.resolveHomeFolder();
|
||||
await resolveHomeFolder();
|
||||
}
|
||||
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
@@ -143,9 +147,9 @@ async function loadFiles(options = { insertHistory: true }) {
|
||||
await rebuildBreadCrumb();
|
||||
|
||||
// request a breadcrumb paint
|
||||
window.ui.updateBreadcrumb();
|
||||
ui.updateBreadcrumb();
|
||||
|
||||
window.updateHistory(options.insertHistory || false);
|
||||
updateHistory(options.insertHistory || false);
|
||||
|
||||
let url;
|
||||
|
||||
@@ -154,7 +158,7 @@ async function loadFiles(options = { insertHistory: true }) {
|
||||
url = `/api/folders/${app.userHomeFolderId}/listing?t=${timestamp}`;
|
||||
app.currentPath = app.userHomeFolderId;
|
||||
app.breadcrumbPath = [];
|
||||
window.ui.updateBreadcrumb();
|
||||
ui.updateBreadcrumb();
|
||||
console.log(`Loading user folder: ${app.userHomeFolderName} (${app.userHomeFolderId})`);
|
||||
} else {
|
||||
url = `/api/folders?t=${timestamp}`;
|
||||
@@ -193,7 +197,7 @@ async function loadFiles(options = { insertHistory: true }) {
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
console.warn('Auth error when loading files, showing empty list');
|
||||
// FIXME: i18n
|
||||
window.ui.showError(`<p>Could not load files</p>`);
|
||||
ui.showError(`<p>Could not load files</p>`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -203,44 +207,44 @@ async function loadFiles(options = { insertHistory: true }) {
|
||||
|
||||
const listing = await response.json();
|
||||
|
||||
window.ui._items.clear();
|
||||
window.ui.resetFilesList();
|
||||
if (window.multiSelect) {
|
||||
window.multiSelect.clear();
|
||||
window.multiSelect.init(); // this will wire buttons & select-all-checkbox
|
||||
ui._items.clear();
|
||||
ui.resetFilesList();
|
||||
if (multiSelect) {
|
||||
multiSelect.clear();
|
||||
multiSelect.init(); // this will wire buttons & select-all-checkbox
|
||||
}
|
||||
|
||||
const folderList = Array.isArray(listing.folders) ? listing.folders : [];
|
||||
const fileList = Array.isArray(listing.files) ? listing.files : [];
|
||||
|
||||
if (folderList.length === 0 && fileList.length === 0) {
|
||||
window.ui.showEmptyList();
|
||||
ui.showEmptyList();
|
||||
} else {
|
||||
window.ui.renderFolders(folderList);
|
||||
window.ui.renderFiles(fileList);
|
||||
ui.renderFolders(folderList);
|
||||
ui.renderFiles(fileList);
|
||||
|
||||
// check if a file was provided
|
||||
if (window.app.viewFile) {
|
||||
if (app.viewFile) {
|
||||
let fileFound = null;
|
||||
|
||||
// lookup for the given fle
|
||||
for (const file of fileList) {
|
||||
if (file.id === window.app.viewFile) {
|
||||
if (file.id === app.viewFile) {
|
||||
fileFound = file;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (fileFound) {
|
||||
console.log(`file ${window.app.viewFile} found, calling viewer`);
|
||||
await window.inlineViewer.openFile(fileFound);
|
||||
console.log(`file ${app.viewFile} found, calling viewer`);
|
||||
await inlineViewer.openFile(fileFound);
|
||||
} else {
|
||||
// remove file
|
||||
console.log(`file ${window.app.viewFile} not found`);
|
||||
window.app.viewFile = null;
|
||||
console.log(`file ${app.viewFile} not found`);
|
||||
app.viewFile = null;
|
||||
|
||||
// correct url/history as file is not found
|
||||
window.updateHistory(false);
|
||||
updateHistory(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -248,10 +252,10 @@ async function loadFiles(options = { insertHistory: true }) {
|
||||
console.log(`Loaded ${folderList.length} folders and ${fileList.length} files`);
|
||||
} catch (error) {
|
||||
console.error('Error loading folders:', error);
|
||||
window.ui.showNotification('Error', 'Could not load files and folders');
|
||||
ui.showNotification('Error', 'Could not load files and folders');
|
||||
} finally {
|
||||
window.isLoadingFiles = false;
|
||||
isLoadingFiles = false;
|
||||
}
|
||||
}
|
||||
|
||||
window.loadFiles = loadFiles;
|
||||
export { loadFiles };
|
||||
|
||||
+78
-70
@@ -3,8 +3,31 @@
|
||||
* This file contains the core functionality, initialization and state management
|
||||
*/
|
||||
|
||||
const app = window.app;
|
||||
const elements = window.appElements;
|
||||
import { formatFileSize, formatQuotaSize } from '../core/formatters.js';
|
||||
import { i18n } from '../core/i18n.js';
|
||||
import { Modal } from '../core/modal.js';
|
||||
import { fileOps } from '../features/files/fileOperations.js';
|
||||
import { multiSelect } from '../features/files/multiSelect.js';
|
||||
import { favorites } from '../features/library/favorites.js';
|
||||
import { recent } from '../features/library/recent.js';
|
||||
import { fileSharing } from '../features/sharing/fileSharing.js';
|
||||
import { sharedView } from '../views/shared/sharedView.js';
|
||||
import { checkAuthentication } from './authSession.js';
|
||||
import { loadFiles } from './filesView.js';
|
||||
import {
|
||||
switchToFavoritesSection,
|
||||
switchToFilesSection,
|
||||
switchToMusicSection,
|
||||
switchToPhotosSection,
|
||||
switchToRecentFilesSection,
|
||||
switchToSharedSection,
|
||||
switchToTrashSection
|
||||
} from './navigation.js';
|
||||
import { performSearch } from './searchView.js';
|
||||
import { app, appElements as elements } from './state.js';
|
||||
import { loadTrashItems } from './trashView.js';
|
||||
import { ui } from './ui.js';
|
||||
import { setupUserMenu } from './userMenu.js';
|
||||
|
||||
// Upload dropdown listener state (prevents accumulated listeners)
|
||||
/** @type { function | null } */
|
||||
@@ -125,8 +148,8 @@ function setActionsBarMode(mode, force = false) {
|
||||
elements.gridViewBtn = document.getElementById('grid-view-btn');
|
||||
elements.listViewBtn = document.getElementById('list-view-btn');
|
||||
|
||||
if (window.i18n?.translateElement) {
|
||||
window.i18n.translateElement(elements.actionsBar);
|
||||
if (i18n?.translateElement) {
|
||||
i18n.translateElement(elements.actionsBar);
|
||||
}
|
||||
|
||||
if (mode === 'files') {
|
||||
@@ -159,7 +182,7 @@ function setupActionsBarDelegation() {
|
||||
break;
|
||||
}
|
||||
case 'new-folder-btn': {
|
||||
const folderName = await window.Modal.promptNewFolder();
|
||||
const folderName = await Modal.promptNewFolder();
|
||||
if (folderName) {
|
||||
fileOps.createFolder(folderName);
|
||||
}
|
||||
@@ -173,14 +196,14 @@ function setupActionsBarDelegation() {
|
||||
break;
|
||||
case 'empty-trash-btn':
|
||||
if (await fileOps.emptyTrash()) {
|
||||
window.loadTrashItems();
|
||||
loadTrashItems();
|
||||
}
|
||||
break;
|
||||
case 'clear-recent-btn':
|
||||
if (window.recent) {
|
||||
window.recent.clearRecentFiles();
|
||||
window.recent.displayRecentFiles();
|
||||
window.ui.showNotification('Cleanup completed', 'Recent files history has been cleared');
|
||||
if (recent) {
|
||||
recent.clearRecentFiles();
|
||||
recent.displayRecentFiles();
|
||||
ui.showNotification('Cleanup completed', 'Recent files history has been cleared');
|
||||
}
|
||||
break;
|
||||
default:
|
||||
@@ -245,8 +268,6 @@ function deserializeHash() {
|
||||
* @param {boolean} insertHistory true to change url and browser's history, false to change url only
|
||||
*/
|
||||
function updateHistory(insertHistory) {
|
||||
const app = window.app;
|
||||
|
||||
const historyData = {
|
||||
section: app.currentSection,
|
||||
id: app.currentFolder,
|
||||
@@ -259,8 +280,8 @@ function updateHistory(insertHistory) {
|
||||
historyData.id = app.currentFolder;
|
||||
historyUrl = historyUrl.concat('/folder/', app.currentFolderInfo.id);
|
||||
|
||||
if (window.app.viewFile) {
|
||||
historyUrl = historyUrl.concat('/file/', window.app.viewFile);
|
||||
if (app.viewFile) {
|
||||
historyUrl = historyUrl.concat('/file/', app.viewFile);
|
||||
}
|
||||
// update title
|
||||
document.title = `OxiCloud: ${app.currentFolderInfo.path}`;
|
||||
@@ -281,7 +302,7 @@ function updateHistory(insertHistory) {
|
||||
* @returns
|
||||
*/
|
||||
function switchSectionTo(section) {
|
||||
if (window.app.currentSection === section)
|
||||
if (app.currentSection === section)
|
||||
// no change ...
|
||||
return;
|
||||
|
||||
@@ -324,8 +345,8 @@ function initApp() {
|
||||
cacheElements();
|
||||
|
||||
// Initialize file sharing module first
|
||||
if (window.fileSharing?.init) {
|
||||
window.fileSharing.init();
|
||||
if (fileSharing?.init) {
|
||||
fileSharing.init();
|
||||
} else {
|
||||
console.warn('fileSharing module not fully initialized');
|
||||
}
|
||||
@@ -338,35 +359,26 @@ function initApp() {
|
||||
// Setup event listeners
|
||||
setupEventListeners();
|
||||
|
||||
// Ensure inline viewer is initialized
|
||||
if (!window.inlineViewer && typeof InlineViewer !== 'undefined') {
|
||||
try {
|
||||
window.inlineViewer = new InlineViewer();
|
||||
} catch (e) {
|
||||
console.error('Error initializing inline viewer:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize favorites module if available
|
||||
if (window.favorites?.init) {
|
||||
if (favorites?.init) {
|
||||
console.log('Initializing favorites module');
|
||||
window.favorites.init();
|
||||
favorites.init();
|
||||
} else {
|
||||
console.warn('Favorites module not available or not initializable');
|
||||
}
|
||||
|
||||
// Initialize recent files module if available
|
||||
if (window.recent?.init) {
|
||||
if (recent?.init) {
|
||||
console.log('Initializing recent files module');
|
||||
window.recent.init();
|
||||
recent.init();
|
||||
} else {
|
||||
console.warn('Recent files module not available or not initializable');
|
||||
}
|
||||
|
||||
// Initialize multi-select / batch actions
|
||||
if (window.multiSelect?.init) {
|
||||
if (multiSelect?.init) {
|
||||
console.log('Initializing multi-select module');
|
||||
window.multiSelect.init();
|
||||
multiSelect.init();
|
||||
}
|
||||
|
||||
window.addEventListener('authenticationDone', () => {
|
||||
@@ -376,33 +388,33 @@ function initApp() {
|
||||
if (hashContext.section === 'files') {
|
||||
if (hashContext.path) {
|
||||
console.log(`init: reusing folder from hash URL: ${hashContext.path}`);
|
||||
window.app.currentPath = hashContext.path;
|
||||
app.currentPath = hashContext.path;
|
||||
}
|
||||
|
||||
if (hashContext.file !== null) {
|
||||
window.app.viewFile = hashContext.file;
|
||||
app.viewFile = hashContext.file;
|
||||
}
|
||||
window.loadFiles();
|
||||
loadFiles();
|
||||
}
|
||||
});
|
||||
|
||||
// Wait for translations to load before checking authentication
|
||||
if (window.i18n?.isLoaded?.()) {
|
||||
if (i18n?.isLoaded?.()) {
|
||||
// Translations already loaded, proceed with authentication
|
||||
window.checkAuthentication();
|
||||
checkAuthentication();
|
||||
} else {
|
||||
// Wait for translations to be loaded before proceeding
|
||||
console.log('Waiting for translations to load...');
|
||||
window.addEventListener('translationsLoaded', () => {
|
||||
console.log('Translations loaded, proceeding with authentication');
|
||||
window.checkAuthentication();
|
||||
checkAuthentication();
|
||||
});
|
||||
|
||||
// Set a timeout as a fallback in case translations take too long
|
||||
setTimeout(() => {
|
||||
if (!window.i18n?.isLoaded?.()) {
|
||||
if (!i18n?.isLoaded?.()) {
|
||||
console.warn('Translations loading timeout, proceeding with authentication anyway');
|
||||
window.checkAuthentication();
|
||||
checkAuthentication();
|
||||
}
|
||||
}, 3000); // 3 second timeout
|
||||
}
|
||||
@@ -493,14 +505,14 @@ function setupEventListeners() {
|
||||
const hashContext = deserializeHash();
|
||||
switchSectionTo(hashContext.section);
|
||||
if (hashContext.path) {
|
||||
window.app.currentPath = hashContext.path;
|
||||
window.loadFiles({ insertHistory: false });
|
||||
app.currentPath = hashContext.path;
|
||||
loadFiles({ insertHistory: false });
|
||||
}
|
||||
} else {
|
||||
// change is from history, data provided in event
|
||||
switchSectionTo(e.state.section);
|
||||
window.app.currentPath = e.state.id;
|
||||
window.loadFiles({ insertHistory: false });
|
||||
app.currentPath = e.state.id;
|
||||
loadFiles({ insertHistory: false });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -512,19 +524,19 @@ function setupEventListeners() {
|
||||
const query = elements.searchInput.value.trim();
|
||||
|
||||
// In shared view, filter locally
|
||||
if (app.isSharedView && window.sharedView) {
|
||||
window.sharedView.filterAndSortItems();
|
||||
if (app.isSharedView && sharedView) {
|
||||
sharedView.filterAndSortItems();
|
||||
return;
|
||||
}
|
||||
|
||||
if (query) {
|
||||
window.performSearch(query);
|
||||
performSearch(query);
|
||||
} else if (app.isSearchMode) {
|
||||
// If search is empty and we're in search mode, return to normal view
|
||||
app.isSearchMode = false;
|
||||
app.currentPath = '';
|
||||
ui.updateBreadcrumb('');
|
||||
window.loadFiles();
|
||||
loadFiles();
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -536,7 +548,7 @@ function setupEventListeners() {
|
||||
|
||||
if (query.length >= SEARCH_MIN_CHARS) {
|
||||
searchDebounceTimer = setTimeout(() => {
|
||||
window.performSearch(query);
|
||||
performSearch(query);
|
||||
}, SEARCH_DEBOUNCE_MS);
|
||||
} else if (query.length === 0 && app.isSearchMode) {
|
||||
// User cleared the search input — return to normal view
|
||||
@@ -544,7 +556,7 @@ function setupEventListeners() {
|
||||
app.isSearchMode = false;
|
||||
app.currentPath = '';
|
||||
ui.updateBreadcrumb('');
|
||||
window.loadFiles();
|
||||
loadFiles();
|
||||
}, SEARCH_DEBOUNCE_MS);
|
||||
}
|
||||
});
|
||||
@@ -554,7 +566,7 @@ function setupEventListeners() {
|
||||
if (searchDebounceTimer) clearTimeout(searchDebounceTimer);
|
||||
const query = elements.searchInput.value.trim();
|
||||
if (query) {
|
||||
window.performSearch(query);
|
||||
performSearch(query);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -627,12 +639,12 @@ function setupEventListeners() {
|
||||
|
||||
default:
|
||||
// Use the proper switchToFilesView function which handles all UI restoration
|
||||
window.switchToFilesSection();
|
||||
switchToFilesSection();
|
||||
// FIXME: because fileview handles it: need to converge code
|
||||
_updateHistory = false;
|
||||
}
|
||||
|
||||
document.title = `OxiCloud: ${window.i18n.t(itemI18nKey)}`;
|
||||
document.title = `OxiCloud: ${i18n.t(itemI18nKey)}`;
|
||||
|
||||
if (_updateHistory) {
|
||||
updateHistory(true);
|
||||
@@ -649,7 +661,7 @@ function setupEventListeners() {
|
||||
}
|
||||
|
||||
// User menu
|
||||
window.setupUserMenu();
|
||||
setupUserMenu();
|
||||
|
||||
// Global events to close context menus and deselect cards
|
||||
document.addEventListener('click', (e) => {
|
||||
@@ -666,18 +678,19 @@ function setupEventListeners() {
|
||||
});
|
||||
}
|
||||
|
||||
// Expose needed functions to global scope
|
||||
window.setActionsBarMode = setActionsBarMode;
|
||||
// View-switching actions moved to app/navigation.js
|
||||
|
||||
// Set up global selectFolder function for navigation
|
||||
window.selectFolder = (id, name) => {
|
||||
/**
|
||||
* Navigate into a folder and refresh the file list.
|
||||
* @param {string} id
|
||||
* @param {string} name
|
||||
*/
|
||||
export function selectFolder(id, name) {
|
||||
app.breadcrumbPath.push({ id, name });
|
||||
app.currentPath = id;
|
||||
ui.updateBreadcrumb();
|
||||
window.loadFiles();
|
||||
};
|
||||
|
||||
// View-switching actions moved to app/navigation.js
|
||||
loadFiles();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the storage usage display with the user's actual storage usage
|
||||
@@ -719,8 +732,8 @@ function updateStorageUsageDisplay(userData) {
|
||||
storageInfo.removeAttribute('data-i18n');
|
||||
|
||||
// Use i18n if available
|
||||
if (window.i18n?.t) {
|
||||
storageInfo.textContent = window.i18n.t('storage.used', {
|
||||
if (i18n?.t) {
|
||||
storageInfo.textContent = i18n.t('storage.used', {
|
||||
percentage: usagePercentage,
|
||||
used: usedFormatted,
|
||||
total: quotaFormatted
|
||||
@@ -733,9 +746,4 @@ function updateStorageUsageDisplay(userData) {
|
||||
console.log(`Updated storage display: ${usagePercentage}% (${usedFormatted} / ${quotaFormatted})`);
|
||||
}
|
||||
|
||||
window.updateStorageUsageDisplay = updateStorageUsageDisplay;
|
||||
|
||||
// Initialize app when DOM is ready
|
||||
window.initApp = initApp;
|
||||
window.updateHistory = updateHistory;
|
||||
window.deserializeHash = deserializeHash;
|
||||
export { deserializeHash, initApp, setActionsBarMode, updateHistory, updateStorageUsageDisplay };
|
||||
|
||||
+74
-66
@@ -3,6 +3,19 @@
|
||||
* Extracted from main.js to keep navigation concerns isolated.
|
||||
*/
|
||||
|
||||
import { i18n } from '../core/i18n.js';
|
||||
import { multiSelect } from '../features/files/multiSelect.js';
|
||||
import { favorites } from '../features/library/favorites.js';
|
||||
import { musicView } from '../features/library/music.js';
|
||||
import { photosView } from '../features/library/photos.js';
|
||||
import { recent } from '../features/library/recent.js';
|
||||
import { sharedView } from '../views/shared/sharedView.js';
|
||||
import { loadFiles } from './filesView.js';
|
||||
import { setActionsBarMode } from './main.js';
|
||||
import { app, appElements } from './state.js';
|
||||
import { loadTrashItems } from './trashView.js';
|
||||
import { ui } from './ui.js';
|
||||
|
||||
/**
|
||||
* Sync the hidden class and inline display for the grid/list containers
|
||||
* based on the current view preference.
|
||||
@@ -12,7 +25,7 @@ function syncViewContainers() {
|
||||
const gridViewBtn = document.getElementById('grid-view-btn');
|
||||
const listViewBtn = document.getElementById('list-view-btn');
|
||||
|
||||
const isGrid = window.app.currentView === 'grid';
|
||||
const isGrid = app.currentView === 'grid';
|
||||
if (isGrid) {
|
||||
filesList.classList.remove('files-list-view');
|
||||
filesList.classList.add('files-grid-view');
|
||||
@@ -89,13 +102,6 @@ function initSidebarToggle() {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Expose functions globally
|
||||
window.sidebarToggle = {
|
||||
open: openSidebar,
|
||||
close: closeSidebar,
|
||||
toggle: toggleSidebar
|
||||
};
|
||||
}
|
||||
|
||||
// Initialize sidebar toggle when DOM is ready
|
||||
@@ -128,17 +134,17 @@ function getSectionFromNavItem(navItem) {
|
||||
* @returns {boolean} true if the section changed
|
||||
*/
|
||||
function setCurrentSection(section) {
|
||||
if (window.app.currentSection === section) return false;
|
||||
if (app.currentSection === section) return false;
|
||||
|
||||
// Set all view flags - true for active section, false for others
|
||||
Object.entries(VIEW_FLAGS).forEach(([key, flag]) => {
|
||||
window.app[flag] = key === section;
|
||||
app[flag] = key === section;
|
||||
});
|
||||
|
||||
window.app.currentSection = section;
|
||||
app.currentSection = section;
|
||||
|
||||
// Update nav item active classes by finding matching item from DOM
|
||||
window.appElements.navItems.forEach((item) => {
|
||||
appElements.navItems.forEach((item) => {
|
||||
const itemSection = getSectionFromNavItem(item);
|
||||
item.classList.toggle('active', itemSection === section);
|
||||
});
|
||||
@@ -146,22 +152,22 @@ function setCurrentSection(section) {
|
||||
// Update page title
|
||||
const titleKey = `nav.${section}`;
|
||||
const defaultTitle = section.charAt(0).toUpperCase() + section.slice(1);
|
||||
window.appElements.pageTitle.textContent = window.i18n ? window.i18n.t(titleKey) : defaultTitle;
|
||||
window.appElements.pageTitle.setAttribute('data-i18n', titleKey);
|
||||
appElements.pageTitle.textContent = i18n ? i18n.t(titleKey) : defaultTitle;
|
||||
appElements.pageTitle.setAttribute('data-i18n', titleKey);
|
||||
|
||||
// Hide sharedView when switching to any other section
|
||||
if (section !== 'shared' && window.sharedView) {
|
||||
window.sharedView.hide();
|
||||
if (section !== 'shared' && sharedView) {
|
||||
sharedView.hide();
|
||||
}
|
||||
|
||||
// Hide photosView when switching to any other section
|
||||
if (section !== 'photos' && window.photosView) {
|
||||
window.photosView.hide();
|
||||
if (section !== 'photos' && photosView) {
|
||||
photosView.hide();
|
||||
}
|
||||
|
||||
// Hide musicView when switching to any other section
|
||||
if (section !== 'music' && window.musicView) {
|
||||
window.musicView.hide();
|
||||
if (section !== 'music' && musicView) {
|
||||
musicView.hide();
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -175,27 +181,27 @@ function switchToSharedSection() {
|
||||
breadcrumb?.classList.add('hidden');
|
||||
|
||||
// Hide actions-bar for shared view
|
||||
window.setActionsBarMode('hidden');
|
||||
setActionsBarMode('hidden');
|
||||
|
||||
//reset files view + remove any error
|
||||
window.ui.resetFilesList();
|
||||
ui.resetFilesList();
|
||||
|
||||
// Hide file containers
|
||||
toggleFileContainer(false);
|
||||
|
||||
// Show shared view
|
||||
if (window.sharedView) {
|
||||
window.sharedView.init();
|
||||
window.sharedView.show();
|
||||
if (sharedView) {
|
||||
sharedView.init();
|
||||
sharedView.show();
|
||||
}
|
||||
if (window.multiSelect) window.multiSelect.clear();
|
||||
if (multiSelect) multiSelect.clear();
|
||||
}
|
||||
|
||||
function switchToFilesSection() {
|
||||
if (!setCurrentSection('files')) return;
|
||||
|
||||
// Set actions bar mode
|
||||
window.setActionsBarMode('files', true);
|
||||
setActionsBarMode('files', true);
|
||||
|
||||
// Show breadcrumb (only in Files view)
|
||||
const breadcrumb = document.querySelector('.breadcrumb');
|
||||
@@ -208,22 +214,22 @@ function switchToFilesSection() {
|
||||
syncViewContainers();
|
||||
|
||||
//reset files view + remove any error
|
||||
window.ui.resetFilesList();
|
||||
ui.resetFilesList();
|
||||
|
||||
// Reset to home folder and update breadcrumb
|
||||
window.app.currentPath = window.app.userHomeFolderId || '';
|
||||
window.app.breadcrumbPath = [];
|
||||
window.ui.updateBreadcrumb();
|
||||
if (window.multiSelect) window.multiSelect.clear();
|
||||
app.currentPath = app.userHomeFolderId || '';
|
||||
app.breadcrumbPath = [];
|
||||
ui.updateBreadcrumb();
|
||||
if (multiSelect) multiSelect.clear();
|
||||
|
||||
window.loadFiles();
|
||||
loadFiles();
|
||||
}
|
||||
|
||||
function switchToFavoritesSection() {
|
||||
if (!setCurrentSection('favorites')) return;
|
||||
|
||||
// Set actions bar mode
|
||||
window.setActionsBarMode('favorites');
|
||||
setActionsBarMode('favorites');
|
||||
|
||||
// Hide breadcrumb (only shown in Files view)
|
||||
const breadcrumb = document.querySelector('.breadcrumb');
|
||||
@@ -236,26 +242,26 @@ function switchToFavoritesSection() {
|
||||
syncViewContainers();
|
||||
|
||||
//reset files view + remove any error
|
||||
window.ui.resetFilesList();
|
||||
ui.resetFilesList();
|
||||
|
||||
if (window.favorites) {
|
||||
window.favorites.displayFavorites();
|
||||
if (favorites) {
|
||||
favorites.displayFavorites();
|
||||
} else {
|
||||
console.error('Favorites module not loaded or initialized');
|
||||
window.ui.showError(`
|
||||
ui.showError(`
|
||||
<i class="fas fa-exclamation-circle empty-state-icon error"></i>
|
||||
<p>Error loading the favorites module</p>
|
||||
`);
|
||||
}
|
||||
|
||||
if (window.multiSelect) window.multiSelect.clear();
|
||||
if (multiSelect) multiSelect.clear();
|
||||
}
|
||||
|
||||
function switchToRecentFilesSection() {
|
||||
if (!setCurrentSection('recent')) return;
|
||||
|
||||
// Set actions bar mode
|
||||
window.setActionsBarMode('recent');
|
||||
setActionsBarMode('recent');
|
||||
|
||||
// Hide breadcrumb (only shown in Files view)
|
||||
const breadcrumb = document.querySelector('.breadcrumb');
|
||||
@@ -268,18 +274,18 @@ function switchToRecentFilesSection() {
|
||||
syncViewContainers();
|
||||
|
||||
//reset files view + remove any error
|
||||
window.ui.resetFilesList();
|
||||
ui.resetFilesList();
|
||||
|
||||
if (window.recent) {
|
||||
window.recent.displayRecentFiles();
|
||||
if (recent) {
|
||||
recent.displayRecentFiles();
|
||||
} else {
|
||||
console.error('Recent files module not loaded or initialized');
|
||||
window.ui.showError(`
|
||||
ui.showError(`
|
||||
<i class="fas fa-exclamation-circle empty-state-icon error"></i>
|
||||
<p>Error loading the recent module</p>
|
||||
`);
|
||||
}
|
||||
if (window.multiSelect) window.multiSelect.clear();
|
||||
if (multiSelect) multiSelect.clear();
|
||||
}
|
||||
|
||||
function switchToPhotosSection() {
|
||||
@@ -290,19 +296,19 @@ function switchToPhotosSection() {
|
||||
breadcrumb?.classList.add('hidden');
|
||||
|
||||
// Hide actions-bar (photos has its own upload via selection bar)
|
||||
window.setActionsBarMode('hidden');
|
||||
setActionsBarMode('hidden');
|
||||
|
||||
//reset files view + remove any error
|
||||
window.ui.resetFilesList();
|
||||
ui.resetFilesList();
|
||||
|
||||
// Hide file containers
|
||||
toggleFileContainer(false);
|
||||
|
||||
// Show photos view
|
||||
if (window.photosView) {
|
||||
window.photosView.show();
|
||||
if (photosView) {
|
||||
photosView.show();
|
||||
}
|
||||
if (window.multiSelect) window.multiSelect.clear();
|
||||
if (multiSelect) multiSelect.clear();
|
||||
}
|
||||
|
||||
function switchToTrashSection() {
|
||||
@@ -319,15 +325,15 @@ function switchToTrashSection() {
|
||||
setActionsBarMode('trash');
|
||||
|
||||
//reset files view + remove any error
|
||||
window.ui.resetFilesList();
|
||||
ui.resetFilesList();
|
||||
|
||||
//ensure buttons match the current view
|
||||
syncViewContainers();
|
||||
|
||||
// Load trash items
|
||||
window.loadTrashItems();
|
||||
loadTrashItems();
|
||||
|
||||
if (window.multiSelect) window.multiSelect.clear();
|
||||
if (multiSelect) multiSelect.clear();
|
||||
}
|
||||
|
||||
function switchToMusicSection() {
|
||||
@@ -341,27 +347,29 @@ function switchToMusicSection() {
|
||||
toggleFileContainer(false);
|
||||
|
||||
// Hide actions-bar
|
||||
window.setActionsBarMode('hidden');
|
||||
setActionsBarMode('hidden');
|
||||
|
||||
// Reset files view + remove any error
|
||||
window.ui.resetFilesList();
|
||||
ui.resetFilesList();
|
||||
|
||||
// Hide list header (created by resetFilesList)
|
||||
const listHeader = document.querySelector('.list-header');
|
||||
listHeader?.classList.add('hidden');
|
||||
|
||||
// Show music view
|
||||
if (window.musicView) {
|
||||
window.musicView.show();
|
||||
if (musicView) {
|
||||
musicView.show();
|
||||
}
|
||||
if (window.multiSelect) window.multiSelect.clear();
|
||||
if (multiSelect) multiSelect.clear();
|
||||
}
|
||||
|
||||
window.switchToFilesSection = switchToFilesSection;
|
||||
window.switchToSharedSection = switchToSharedSection;
|
||||
window.switchToFavoritesSection = switchToFavoritesSection;
|
||||
window.switchToRecentFilesSection = switchToRecentFilesSection;
|
||||
window.switchToPhotosSection = switchToPhotosSection;
|
||||
window.switchToTrashSection = switchToTrashSection;
|
||||
window.switchToMusicSection = switchToMusicSection;
|
||||
window.syncViewContainers = syncViewContainers;
|
||||
export {
|
||||
switchToFavoritesSection,
|
||||
switchToFilesSection,
|
||||
switchToMusicSection,
|
||||
switchToPhotosSection,
|
||||
switchToRecentFilesSection,
|
||||
switchToSharedSection,
|
||||
switchToTrashSection,
|
||||
syncViewContainers
|
||||
};
|
||||
|
||||
@@ -2,16 +2,23 @@
|
||||
* Search view orchestration logic
|
||||
*/
|
||||
|
||||
async function performSearch(query, sortBy) {
|
||||
const app = window.app;
|
||||
import { search } from '../features/files/search.js';
|
||||
import { resolveHomeFolder } from './authSession.js';
|
||||
import { app } from './state.js';
|
||||
import { ui } from './ui.js';
|
||||
|
||||
/**
|
||||
* @param {string} query
|
||||
* @param {string} [sortBy]
|
||||
*/
|
||||
async function performSearch(query, sortBy) {
|
||||
console.log(`Performing search for: "${query}" (sort: ${sortBy || 'relevance'})`);
|
||||
|
||||
try {
|
||||
app.isSearchMode = true;
|
||||
window.ui.updateBreadcrumb(`Search: "${query}"`);
|
||||
ui.updateBreadcrumb(`Search: "${query}"`);
|
||||
|
||||
window.ui.showError(`<h3><i class="fas fa-spinner fa-spin search-spinner"></i> Searching for "${query}"...</h3>`);
|
||||
ui.showError(`<h3><i class="fas fa-spinner fa-spin search-spinner"></i> Searching for "${query}"...</h3>`);
|
||||
|
||||
const options = {
|
||||
recursive: true,
|
||||
@@ -22,7 +29,7 @@ async function performSearch(query, sortBy) {
|
||||
if (!app.isTrashView) {
|
||||
// Ensure we have a valid folder_id before searching
|
||||
if (!app.currentPath || app.currentPath === '') {
|
||||
await window.resolveHomeFolder();
|
||||
await resolveHomeFolder();
|
||||
}
|
||||
|
||||
// Only set folder_id if we have a valid value
|
||||
@@ -32,11 +39,11 @@ async function performSearch(query, sortBy) {
|
||||
// If still no valid folder_id, search will be global (without folder_id)
|
||||
}
|
||||
|
||||
const searchResults = await window.search.searchFiles(query, options);
|
||||
window.search.displaySearchResults(searchResults);
|
||||
const searchResults = await search.searchFiles(query, options);
|
||||
search.displaySearchResults(searchResults);
|
||||
} catch (error) {
|
||||
console.error('Search error:', error);
|
||||
window.ui.showNotification('Error', 'Error performing search');
|
||||
ui.showNotification('Error', 'Error performing search');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,4 +54,4 @@ document.addEventListener('search-resort', (e) => {
|
||||
}
|
||||
});
|
||||
|
||||
window.performSearch = performSearch;
|
||||
export { performSearch };
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* Centralized mutable state for app and cached DOM references.
|
||||
*/
|
||||
|
||||
window.app = {
|
||||
export const app = {
|
||||
currentView: 'grid',
|
||||
currentPath: '',
|
||||
currentFolder: null,
|
||||
@@ -29,4 +29,4 @@ window.app = {
|
||||
viewFile: null // current file in inline view
|
||||
};
|
||||
|
||||
window.appElements = {};
|
||||
export const appElements = {};
|
||||
|
||||
+29
-28
@@ -2,13 +2,20 @@
|
||||
* Trash view loading and rendering logic
|
||||
*/
|
||||
|
||||
import { escapeHtml, formatDateTime } from '../core/formatters.js';
|
||||
import { i18n } from '../core/i18n.js';
|
||||
import { fileOps } from '../features/files/fileOperations.js';
|
||||
import { multiSelect } from '../features/files/multiSelect.js';
|
||||
import { appElements } from './state.js';
|
||||
import { ui } from './ui.js';
|
||||
|
||||
async function loadTrashItems() {
|
||||
const elements = window.appElements;
|
||||
const elements = appElements;
|
||||
|
||||
try {
|
||||
if (window.multiSelect) window.multiSelect.clear();
|
||||
window.ui.resetFilesList(); // ensure also list visible & error hidden
|
||||
const _tt = window.i18n?.t ? window.i18n.t : (k) => k.split('.').pop();
|
||||
if (multiSelect) multiSelect.clear();
|
||||
ui.resetFilesList(); // ensure also list visible & error hidden
|
||||
const _tt = i18n?.t ? i18n.t : (k) => k.split('.').pop();
|
||||
elements.filesList.innerHTML = `
|
||||
<div class="list-header trash-header">
|
||||
<div data-i18n="files.name">${_tt('files.name')}</div>
|
||||
@@ -19,14 +26,14 @@ async function loadTrashItems() {
|
||||
</div>
|
||||
`;
|
||||
|
||||
window.ui.updateBreadcrumb('');
|
||||
ui.updateBreadcrumb('');
|
||||
|
||||
const trashItems = await window.fileOps.getTrashItems();
|
||||
const trashItems = await fileOps.getTrashItems();
|
||||
|
||||
if (trashItems.length === 0) {
|
||||
window.ui.showError(`
|
||||
ui.showError(`
|
||||
<i class="fas fa-trash empty-state-icon"></i>
|
||||
<p>${window.i18n ? window.i18n.t('trash.empty_state') : 'The trash is empty'}</p>
|
||||
<p>${i18n ? i18n.t('trash.empty_state') : 'The trash is empty'}</p>
|
||||
`);
|
||||
return;
|
||||
}
|
||||
@@ -36,33 +43,27 @@ async function loadTrashItems() {
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error loading trash items:', error);
|
||||
window.ui.showNotification('Error', 'Error loading trash items');
|
||||
ui.showNotification('Error', 'Error loading trash items');
|
||||
}
|
||||
}
|
||||
|
||||
function addTrashItemToView(item) {
|
||||
const elements = window.appElements;
|
||||
const elements = appElements;
|
||||
const isFile = item.item_type === 'file';
|
||||
|
||||
const formattedDate = window.formatDateTime(item.trashed_at);
|
||||
const formattedDate = formatDateTime(item.trashed_at);
|
||||
|
||||
let iconClass;
|
||||
let typeLabel;
|
||||
let iconSpecialClass = '';
|
||||
if (!isFile) {
|
||||
iconClass = item.icon_class || 'fas fa-folder';
|
||||
typeLabel = window.i18n ? window.i18n.t('files.file_types.folder') : 'Folder';
|
||||
typeLabel = i18n ? i18n.t('files.file_types.folder') : 'Folder';
|
||||
} else {
|
||||
iconClass = item.icon_class || (window.ui?.getIconClass ? window.ui.getIconClass(item.name) : 'fas fa-file');
|
||||
iconSpecialClass = window.ui?.getIconSpecialClass ? window.ui.getIconSpecialClass(item.name) : '';
|
||||
iconClass = item.icon_class || (ui?.getIconClass ? ui.getIconClass(item.name) : 'fas fa-file');
|
||||
iconSpecialClass = ui?.getIconSpecialClass ? ui.getIconSpecialClass(item.name) : '';
|
||||
const cat = item.category || '';
|
||||
typeLabel = cat
|
||||
? window.i18n
|
||||
? window.i18n.t(`files.file_types.${cat.toLowerCase()}`) || cat
|
||||
: cat
|
||||
: window.i18n
|
||||
? window.i18n.t('files.file_types.document')
|
||||
: 'Document';
|
||||
typeLabel = cat ? (i18n ? i18n.t(`files.file_types.${cat.toLowerCase()}`) || cat : cat) : i18n ? i18n.t('files.file_types.document') : 'Document';
|
||||
}
|
||||
|
||||
const isFolder = !isFile;
|
||||
@@ -85,10 +86,10 @@ function addTrashItemToView(item) {
|
||||
<div class="path-cell">${escapeHtml(item.original_path || '--')}</div>
|
||||
<div class="date-cell">${escapeHtml(formattedDate)}</div>
|
||||
<div class="actions-cell">
|
||||
<button class="btn-restore" title="${window.i18n ? window.i18n.t('trash.restore') : 'Restore'}">
|
||||
<button class="btn-restore" title="${i18n ? i18n.t('trash.restore') : 'Restore'}">
|
||||
<i class="fas fa-undo"></i>
|
||||
</button>
|
||||
<button class="btn-delete" title="${window.i18n ? window.i18n.t('trash.delete_permanently') : 'Delete permanently'}">
|
||||
<button class="btn-delete" title="${i18n ? i18n.t('trash.delete_permanently') : 'Delete permanently'}">
|
||||
<i class="fas fa-trash"></i>
|
||||
</button>
|
||||
</div>
|
||||
@@ -96,19 +97,19 @@ function addTrashItemToView(item) {
|
||||
|
||||
listElement.querySelector('.btn-restore').addEventListener('click', async (e) => {
|
||||
e.stopPropagation();
|
||||
if (await window.fileOps.restoreFromTrash(item.id)) {
|
||||
window.loadTrashItems();
|
||||
if (await fileOps.restoreFromTrash(item.id)) {
|
||||
loadTrashItems();
|
||||
}
|
||||
});
|
||||
|
||||
listElement.querySelector('.btn-delete').addEventListener('click', async (e) => {
|
||||
e.stopPropagation();
|
||||
if (await window.fileOps.deletePermanently(item.id)) {
|
||||
window.loadTrashItems();
|
||||
if (await fileOps.deletePermanently(item.id)) {
|
||||
loadTrashItems();
|
||||
}
|
||||
});
|
||||
|
||||
elements.filesList.appendChild(listElement);
|
||||
}
|
||||
|
||||
window.loadTrashItems = loadTrashItems;
|
||||
export { loadTrashItems };
|
||||
|
||||
+116
-111
@@ -5,6 +5,26 @@
|
||||
|
||||
// @ts-check
|
||||
|
||||
import { escapeHtml, formatDateTime, formatFileSize } from '../core/formatters.js';
|
||||
import { i18n } from '../core/i18n.js';
|
||||
import { OxiIcons, replaceIconsInElement } from '../core/icons.js';
|
||||
import { contextMenus } from '../features/files/contextMenus.js';
|
||||
import { fileOps } from '../features/files/fileOperations.js';
|
||||
import { inlineViewer } from '../features/files/inlineViewer.js';
|
||||
import { multiSelect } from '../features/files/multiSelect.js';
|
||||
import { wopiEditor } from '../features/files/wopiEditor.js';
|
||||
import { favorites } from '../features/library/favorites.js';
|
||||
import { recent } from '../features/library/recent.js';
|
||||
import { fileSharing } from '../features/sharing/fileSharing.js';
|
||||
import { loadFiles } from './filesView.js';
|
||||
import { updateHistory } from './main.js';
|
||||
import { syncViewContainers } from './navigation.js';
|
||||
import { app } from './state.js';
|
||||
import { uiFileTypes } from './uiFileTypes.js';
|
||||
import { uiNotifications } from './uiNotifications.js';
|
||||
|
||||
let __rubberBandJustFinished = false;
|
||||
|
||||
// UI Module
|
||||
const ui = {
|
||||
/** @type {HTMLDListElement | null} */
|
||||
@@ -297,13 +317,13 @@ const ui = {
|
||||
document.body.appendChild(playlistDialog);
|
||||
|
||||
document.getElementById('playlist-cancel-btn').addEventListener('click', () => {
|
||||
if (window.contextMenus) window.contextMenus.closePlaylistDialog();
|
||||
if (contextMenus) contextMenus.closePlaylistDialog();
|
||||
});
|
||||
}
|
||||
|
||||
// Assign events to menu items
|
||||
if (window.contextMenus) {
|
||||
window.contextMenus.assignMenuEvents();
|
||||
if (contextMenus) {
|
||||
contextMenus.assignMenuEvents();
|
||||
} else {
|
||||
console.warn('contextMenus module not loaded');
|
||||
}
|
||||
@@ -478,10 +498,10 @@ const ui = {
|
||||
switchToGridView() {
|
||||
this._hydrateViewIfNeeded();
|
||||
|
||||
window.app.currentView = 'grid';
|
||||
app.currentView = 'grid';
|
||||
localStorage.setItem('oxicloud-view', 'grid');
|
||||
|
||||
window.syncViewContainers();
|
||||
syncViewContainers();
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -490,10 +510,10 @@ const ui = {
|
||||
switchToListView() {
|
||||
this._hydrateViewIfNeeded();
|
||||
|
||||
window.app.currentView = 'list';
|
||||
app.currentView = 'list';
|
||||
localStorage.setItem('oxicloud-view', 'list');
|
||||
|
||||
window.syncViewContainers();
|
||||
syncViewContainers();
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -504,12 +524,12 @@ const ui = {
|
||||
updateBreadcrumb() {
|
||||
const breadcrumb = document.querySelector('.breadcrumb');
|
||||
breadcrumb.innerHTML = '';
|
||||
const path = window.app.breadcrumbPath; // [{id, name}, ...]
|
||||
const path = app.breadcrumbPath; // [{id, name}, ...]
|
||||
|
||||
// Helper function to safely get translation text
|
||||
const getTranslatedText = (key, defaultValue) => {
|
||||
if (!window.i18n?.t) return defaultValue;
|
||||
return window.i18n.t(key);
|
||||
if (!i18n?.t) return defaultValue;
|
||||
return i18n.t(key);
|
||||
};
|
||||
|
||||
// -- Home icon (always present, clickable to go to root) --
|
||||
@@ -519,24 +539,24 @@ const ui = {
|
||||
homeIcon.title = getTranslatedText('breadcrumb.home', 'Home');
|
||||
|
||||
// Home is always clickable if we have a home folder
|
||||
if (window.app.userHomeFolderId) {
|
||||
if (app.userHomeFolderId) {
|
||||
homeIcon.classList.add('breadcrumb-link');
|
||||
homeIcon.addEventListener('click', () => {
|
||||
window.app.breadcrumbPath = [];
|
||||
window.app.currentPath = window.app.userHomeFolderId;
|
||||
app.breadcrumbPath = [];
|
||||
app.currentPath = app.userHomeFolderId;
|
||||
this.updateBreadcrumb();
|
||||
window.loadFiles();
|
||||
loadFiles();
|
||||
});
|
||||
}
|
||||
breadcrumb.appendChild(homeIcon);
|
||||
|
||||
// -- Root/Home folder name (if available) is always the first element of the breadcrumb --
|
||||
// TODO clarify the difference between homeIcon & this first element
|
||||
if (window.app.userHomeFolderName) {
|
||||
if (path.length === 0 || path[0].id !== window.app.userHomeFolderId) {
|
||||
if (app.userHomeFolderName) {
|
||||
if (path.length === 0 || path[0].id !== app.userHomeFolderId) {
|
||||
path.unshift({
|
||||
name: window.app.userHomeFolderName,
|
||||
id: window.app.userHomeFolderId
|
||||
name: app.userHomeFolderName,
|
||||
id: app.userHomeFolderId
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -561,10 +581,10 @@ const ui = {
|
||||
// Intermediate segment: clickable – truncate path to this level
|
||||
item.classList.add('breadcrumb-link');
|
||||
item.addEventListener('click', () => {
|
||||
window.app.breadcrumbPath = path.slice(0, index + 1);
|
||||
window.app.currentPath = segment.id;
|
||||
app.breadcrumbPath = path.slice(0, index + 1);
|
||||
app.currentPath = segment.id;
|
||||
this.updateBreadcrumb();
|
||||
window.loadFiles();
|
||||
loadFiles();
|
||||
});
|
||||
|
||||
// can drag files on this folder
|
||||
@@ -611,7 +631,7 @@ const ui = {
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isViewableFile(file) {
|
||||
return window.uiFileTypes.isViewableFile(file);
|
||||
return uiFileTypes.isViewableFile(file);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -620,7 +640,7 @@ const ui = {
|
||||
* (e.g. trash items).
|
||||
*/
|
||||
getIconClass(fileName) {
|
||||
return window.uiFileTypes.getIconClass(fileName);
|
||||
return uiFileTypes.getIconClass(fileName);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -628,7 +648,7 @@ const ui = {
|
||||
* Used as fallback when the backend DTO doesn't include icon_special_class.
|
||||
*/
|
||||
getIconSpecialClass(fileName) {
|
||||
return window.uiFileTypes.getIconSpecialClass(fileName);
|
||||
return uiFileTypes.getIconSpecialClass(fileName);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -637,7 +657,7 @@ const ui = {
|
||||
* @param {string} message - Notification message
|
||||
*/
|
||||
showNotification(title, message) {
|
||||
window.uiNotifications.show(title, message);
|
||||
uiNotifications.show(title, message);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -647,7 +667,7 @@ const ui = {
|
||||
const menu = document.getElementById('folder-context-menu');
|
||||
if (menu) {
|
||||
menu.style.display = 'none';
|
||||
window.app.contextMenuTargetFolder = null;
|
||||
app.contextMenuTargetFolder = null;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -658,7 +678,7 @@ const ui = {
|
||||
const menu = document.getElementById('file-context-menu');
|
||||
if (menu) {
|
||||
menu.style.display = 'none';
|
||||
window.app.contextMenuTargetFile = null;
|
||||
app.contextMenuTargetFile = null;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -679,8 +699,8 @@ const ui = {
|
||||
_delegationReady: false,
|
||||
|
||||
_getActiveView() {
|
||||
if (window.app && window.app.currentView === 'list') return 'list';
|
||||
if (window.app && window.app.currentView === 'grid') return 'grid';
|
||||
if (app && app.currentView === 'list') return 'list';
|
||||
if (app && app.currentView === 'grid') return 'grid';
|
||||
|
||||
const stored = localStorage.getItem('oxicloud-view');
|
||||
return stored === 'list' ? 'list' : 'grid';
|
||||
@@ -737,9 +757,9 @@ const ui = {
|
||||
* @param {any} dataTransfer fallback if nothing is selected
|
||||
*/
|
||||
async _dropToFolder(action, targetFolderId, dataTransfer) {
|
||||
const selection = window.multiSelect.getSelection(targetFolderId);
|
||||
const selection = multiSelect.getSelection(targetFolderId);
|
||||
|
||||
window.multiSelect.clear();
|
||||
multiSelect.clear();
|
||||
|
||||
if (selection.fileIds.length === 0 && selection.folderIds.length === 0) {
|
||||
// try to use dataTransfer (direct move without selection)
|
||||
@@ -770,20 +790,20 @@ const ui = {
|
||||
let result;
|
||||
switch (action) {
|
||||
case 'copy':
|
||||
result = await window.fileOps.batchCopy(selection.fileIds, selection.folderIds, targetFolderId);
|
||||
result = await fileOps.batchCopy(selection.fileIds, selection.folderIds, targetFolderId);
|
||||
break;
|
||||
|
||||
case 'move':
|
||||
result = await window.fileOps.batchMove(selection.fileIds, selection.folderIds, targetFolderId);
|
||||
result = await fileOps.batchMove(selection.fileIds, selection.folderIds, targetFolderId);
|
||||
// redraw directory
|
||||
if (result.success > 0) window.loadFiles();
|
||||
if (result.success > 0) loadFiles();
|
||||
break;
|
||||
|
||||
default:
|
||||
console.error(`drag and drop: action ${action} unknown`);
|
||||
return;
|
||||
}
|
||||
window.multiSelect.showBatchResult(action, result);
|
||||
multiSelect.showBatchResult(action, result);
|
||||
console.log(result);
|
||||
},
|
||||
|
||||
@@ -837,7 +857,7 @@ const ui = {
|
||||
|
||||
const openFile = async (file) => {
|
||||
if (!file) return;
|
||||
if (window.recent) {
|
||||
if (recent) {
|
||||
document.dispatchEvent(new CustomEvent('file-accessed', { detail: { file } }));
|
||||
}
|
||||
// WOPI editor intercept: open Office documents in the WOPI editor
|
||||
@@ -846,8 +866,8 @@ const ui = {
|
||||
const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'webp', 'bmp', 'ico', 'heic', 'heif', 'avif', 'tiff'];
|
||||
const isImage = file.mime_type?.startsWith('image/') || imageExts.includes(ext);
|
||||
try {
|
||||
if (!isImage && window.wopiEditor && (await window.wopiEditor.canEdit(file.name))) {
|
||||
await window.wopiEditor.openInModal(file.id, file.name, 'edit');
|
||||
if (!isImage && wopiEditor && (await wopiEditor.canEdit(file.name))) {
|
||||
await wopiEditor.openInModal(file.id, file.name, 'edit');
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -855,38 +875,38 @@ const ui = {
|
||||
}
|
||||
|
||||
if (this.isViewableFile(file) || isImage) {
|
||||
if (window.inlineViewer) {
|
||||
window.inlineViewer.openFile(file);
|
||||
if (inlineViewer) {
|
||||
inlineViewer.openFile(file);
|
||||
// update history
|
||||
window.app.viewFile = file.id;
|
||||
window.updateHistory(false);
|
||||
app.viewFile = file.id;
|
||||
updateHistory(false);
|
||||
} else {
|
||||
window.fileOps.downloadFile(file.id, file.name);
|
||||
fileOps.downloadFile(file.id, file.name);
|
||||
}
|
||||
} else {
|
||||
window.fileOps.downloadFile(file.id, file.name);
|
||||
fileOps.downloadFile(file.id, file.name);
|
||||
}
|
||||
};
|
||||
|
||||
const navigateFolder = (card) => {
|
||||
const folderId = card.dataset.folderId;
|
||||
const folderName = card.dataset.folderName;
|
||||
window.app.breadcrumbPath.push({ id: folderId, name: folderName });
|
||||
window.app.currentPath = folderId;
|
||||
app.breadcrumbPath.push({ id: folderId, name: folderName });
|
||||
app.currentPath = folderId;
|
||||
this.updateBreadcrumb();
|
||||
window.loadFiles();
|
||||
loadFiles();
|
||||
};
|
||||
|
||||
const setContextTarget = (card, info) => {
|
||||
if (info.type === 'folder') {
|
||||
window.app.contextMenuTargetFolder = {
|
||||
app.contextMenuTargetFolder = {
|
||||
id: info.id,
|
||||
name: card.dataset.folderName,
|
||||
parent_id: card.dataset.parentId || ''
|
||||
};
|
||||
} else {
|
||||
const fileData = info.data || self._items.get(info.id);
|
||||
window.app.contextMenuTargetFile = {
|
||||
app.contextMenuTargetFile = {
|
||||
id: info.id,
|
||||
name: card.dataset.fileName,
|
||||
folder_id: card.dataset.folderId || '',
|
||||
@@ -932,8 +952,8 @@ const ui = {
|
||||
}
|
||||
|
||||
// shiftkey is used to complete selection
|
||||
if (e.shiftKey && window.multiSelect) {
|
||||
window.multiSelect.handleToggleItem(card, e);
|
||||
if (e.shiftKey && multiSelect) {
|
||||
multiSelect.handleToggleItem(card, e);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -962,14 +982,14 @@ const ui = {
|
||||
setContextTarget(card, info);
|
||||
const menuId = info.type === 'folder' ? 'folder-context-menu' : 'file-context-menu';
|
||||
const menu = document.getElementById(menuId);
|
||||
if (window.contextMenus && typeof window.contextMenus.syncFavoriteOptionLabels === 'function') {
|
||||
window.contextMenus.syncFavoriteOptionLabels();
|
||||
if (contextMenus && typeof contextMenus.syncFavoriteOptionLabels === 'function') {
|
||||
contextMenus.syncFavoriteOptionLabels();
|
||||
}
|
||||
if (window.contextMenus && typeof window.contextMenus.syncWopiOptionVisibility === 'function') {
|
||||
window.contextMenus.syncWopiOptionVisibility().catch(() => {});
|
||||
if (contextMenus && typeof contextMenus.syncWopiOptionVisibility === 'function') {
|
||||
contextMenus.syncWopiOptionVisibility().catch(() => {});
|
||||
}
|
||||
if (window.contextMenus && typeof window.contextMenus.syncAddToPlaylistOption === 'function') {
|
||||
window.contextMenus.syncAddToPlaylistOption();
|
||||
if (contextMenus && typeof contextMenus.syncAddToPlaylistOption === 'function') {
|
||||
contextMenus.syncAddToPlaylistOption();
|
||||
}
|
||||
menu.style.left = `${e.pageX}px`;
|
||||
menu.style.top = `${e.pageY}px`;
|
||||
@@ -1105,7 +1125,7 @@ const ui = {
|
||||
e.stopImmediatePropagation();
|
||||
e.preventDefault();
|
||||
|
||||
if (!window.favorites) return;
|
||||
if (!favorites) return;
|
||||
|
||||
const itemId = star.dataset.itemId;
|
||||
const itemType = star.dataset.itemType;
|
||||
@@ -1115,15 +1135,15 @@ const ui = {
|
||||
|
||||
if (isActive) {
|
||||
this.setFavoriteVisualState(itemId, itemType, false);
|
||||
window.favorites.removeFromFavorites(itemId, itemType);
|
||||
favorites.removeFromFavorites(itemId, itemType);
|
||||
} else {
|
||||
this.setFavoriteVisualState(itemId, itemType, true);
|
||||
window.favorites.addToFavorites(itemId, itemName, itemType);
|
||||
favorites.addToFavorites(itemId, itemName, itemType);
|
||||
}
|
||||
|
||||
// Keep context-menu label in sync if available
|
||||
if (window.contextMenus && typeof window.contextMenus.syncFavoriteOptionLabels === 'function') {
|
||||
window.contextMenus.syncFavoriteOptionLabels();
|
||||
if (contextMenus && typeof contextMenus.syncFavoriteOptionLabels === 'function') {
|
||||
contextMenus.syncFavoriteOptionLabels();
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -1142,8 +1162,8 @@ const ui = {
|
||||
|
||||
// SVG icon path (after icons.js replacement)
|
||||
const svg = starBtn.querySelector('svg');
|
||||
const filledPath = window.OxiIcons?.star;
|
||||
const outlinePath = window.OxiIcons?.['star-outline'];
|
||||
const filledPath = OxiIcons?.star;
|
||||
const outlinePath = OxiIcons?.['star-outline'];
|
||||
const targetPath = isFavorite ? filledPath : outlinePath;
|
||||
if (svg && targetPath) {
|
||||
const p = svg.querySelector('path');
|
||||
@@ -1168,9 +1188,7 @@ const ui = {
|
||||
inlineStar = document.createElement('i');
|
||||
inlineStar.className = 'fas fa-star favorite-star-inline';
|
||||
nameCell.appendChild(inlineStar);
|
||||
if (window.OxiIcons && typeof window.OxiIcons.replaceIconsInElement === 'function') {
|
||||
window.OxiIcons.replaceIconsInElement(nameCell);
|
||||
}
|
||||
replaceIconsInElement(nameCell);
|
||||
} else if (!isFavorite && inlineStar) {
|
||||
inlineStar.remove();
|
||||
}
|
||||
@@ -1190,8 +1208,8 @@ const ui = {
|
||||
el.dataset.folderName = folder.name;
|
||||
el.dataset.parentId = folder.parent_id || '';
|
||||
|
||||
const isFav = window.favorites?.isFavorite(folder.id, 'folder');
|
||||
const formattedDate = window.formatDateTime(folder.modified_at);
|
||||
const isFav = favorites?.isFavorite(folder.id, 'folder');
|
||||
const formattedDate = formatDateTime(folder.modified_at);
|
||||
|
||||
el.innerHTML = `
|
||||
<div class="checkbox-cell"><input type="checkbox" class="item-checkbox"></div>
|
||||
@@ -1202,7 +1220,7 @@ const ui = {
|
||||
<span>${escapeHtml(folder.name)}</span>
|
||||
${isFav ? '<i class="fas fa-star favorite-star-inline"></i>' : ''}
|
||||
</div>
|
||||
<div class="type-cell">${window.i18n ? window.i18n.t('files.file_types.folder') : 'Folder'}</div>
|
||||
<div class="type-cell">${i18n ? i18n.t('files.file_types.folder') : 'Folder'}</div>
|
||||
<div class="size-cell">--</div>
|
||||
<div class="date-cell">${formattedDate}</div>
|
||||
<div class="action-cell">
|
||||
@@ -1213,7 +1231,7 @@ const ui = {
|
||||
</div>
|
||||
`;
|
||||
|
||||
if (window.app.currentPath !== '') {
|
||||
if (app.currentPath !== '') {
|
||||
el.setAttribute('draggable', 'true');
|
||||
}
|
||||
this._bindStarClick(el);
|
||||
@@ -1225,16 +1243,10 @@ const ui = {
|
||||
const iconClass = file.icon_class || this.getIconClass(file.name);
|
||||
const iconSpecialClass = file.icon_special_class || this.getIconSpecialClass(file.name);
|
||||
const cat = file.category || '';
|
||||
const typeLabel = cat
|
||||
? window.i18n
|
||||
? window.i18n.t(`files.file_types.${cat.toLowerCase()}`) || cat
|
||||
: cat
|
||||
: window.i18n
|
||||
? window.i18n.t('files.file_types.document')
|
||||
: 'Document';
|
||||
const fileSize = file.size_formatted || window.formatFileSize(file.size);
|
||||
const formattedDate = window.formatDateTime(file.modified_at);
|
||||
const isFav = window.favorites?.isFavorite(file.id, 'file');
|
||||
const typeLabel = cat ? (i18n ? i18n.t(`files.file_types.${cat.toLowerCase()}`) || cat : cat) : i18n ? i18n.t('files.file_types.document') : 'Document';
|
||||
const fileSize = file.size_formatted || formatFileSize(file.size);
|
||||
const formattedDate = formatDateTime(file.modified_at);
|
||||
const isFav = favorites?.isFavorite(file.id, 'file');
|
||||
|
||||
const el = document.createElement('div');
|
||||
el.className = 'file-item';
|
||||
@@ -1293,7 +1305,7 @@ const ui = {
|
||||
<div></div><!-- actions -->
|
||||
</div>`;
|
||||
|
||||
if (window.i18n?.translateElement) window.i18n.translateElement(filesList);
|
||||
if (i18n?.translateElement) i18n.translateElement(filesList);
|
||||
|
||||
filesList.classList.remove('hidden');
|
||||
filesContainerError?.classList.add('hidden');
|
||||
@@ -1317,7 +1329,7 @@ const ui = {
|
||||
const filesList = document.getElementById('files-list');
|
||||
if (filesContainerError) filesContainerError.innerHTML = content;
|
||||
|
||||
if (window.i18n?.translateElement) window.i18n.translateElement(filesContainerError);
|
||||
if (i18n?.translateElement) i18n.translateElement(filesContainerError);
|
||||
|
||||
filesContainerError?.classList.remove('hidden');
|
||||
filesList?.classList.add('hidden');
|
||||
@@ -1403,8 +1415,8 @@ const ui = {
|
||||
* Routes through the multiSelect module so batch actions know about selected items.
|
||||
*/
|
||||
function toggleCardSelection(card, event) {
|
||||
if (window.multiSelect) {
|
||||
window.multiSelect.handleToggleItem(card, event);
|
||||
if (multiSelect) {
|
||||
multiSelect.handleToggleItem(card, event);
|
||||
} else {
|
||||
card.classList.toggle('selected');
|
||||
}
|
||||
@@ -1435,14 +1447,14 @@ function showContextMenuAtElement(triggerElement, menuId) {
|
||||
top = rect.top - 4 + window.scrollY; // flip above if no room
|
||||
}
|
||||
|
||||
if (window.contextMenus && typeof window.contextMenus.syncFavoriteOptionLabels === 'function') {
|
||||
window.contextMenus.syncFavoriteOptionLabels();
|
||||
if (contextMenus && typeof contextMenus.syncFavoriteOptionLabels === 'function') {
|
||||
contextMenus.syncFavoriteOptionLabels();
|
||||
}
|
||||
if (window.contextMenus && typeof window.contextMenus.syncWopiOptionVisibility === 'function') {
|
||||
window.contextMenus.syncWopiOptionVisibility().catch(() => {});
|
||||
if (contextMenus && typeof contextMenus.syncWopiOptionVisibility === 'function') {
|
||||
contextMenus.syncWopiOptionVisibility().catch(() => {});
|
||||
}
|
||||
if (window.contextMenus && typeof window.contextMenus.syncAddToPlaylistOption === 'function') {
|
||||
window.contextMenus.syncAddToPlaylistOption();
|
||||
if (contextMenus && typeof contextMenus.syncAddToPlaylistOption === 'function') {
|
||||
contextMenus.syncAddToPlaylistOption();
|
||||
}
|
||||
|
||||
menu.style.left = `${left}px`;
|
||||
@@ -1532,16 +1544,16 @@ function initRubberBandSelection() {
|
||||
card.classList.add('selected');
|
||||
|
||||
// Sync with multiSelect module
|
||||
if (window.multiSelect) {
|
||||
const info = window.multiSelect._extractInfo(card);
|
||||
if (info) window.multiSelect.select(info.id, info.name, info.type, info.parentId);
|
||||
if (multiSelect) {
|
||||
const info = multiSelect._extractInfo(card);
|
||||
if (info) multiSelect.select(info.id, info.name, info.type, info.parentId);
|
||||
}
|
||||
} else {
|
||||
card.classList.remove('selected');
|
||||
// Deselect from multiSelect module
|
||||
if (window.multiSelect) {
|
||||
const info = window.multiSelect._extractInfo(card);
|
||||
if (info) window.multiSelect.deselect(info.id);
|
||||
if (multiSelect) {
|
||||
const info = multiSelect._extractInfo(card);
|
||||
if (info) multiSelect.deselect(info.id);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1553,13 +1565,13 @@ function initRubberBandSelection() {
|
||||
const hadSelection = selRect.style.display === 'block';
|
||||
selRect.style.display = 'none';
|
||||
// Update the batch bar after rubber band selection completes
|
||||
if (window.multiSelect) window.multiSelect._syncUI();
|
||||
if (multiSelect) multiSelect._syncUI();
|
||||
// Suppress the click event that follows mouseup so the global
|
||||
// deselect handler doesn't immediately clear the selection.
|
||||
if (hadSelection) {
|
||||
window.__rubberBandJustFinished = true;
|
||||
__rubberBandJustFinished = true;
|
||||
requestAnimationFrame(() => {
|
||||
window.__rubberBandJustFinished = false;
|
||||
__rubberBandJustFinished = false;
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1572,11 +1584,6 @@ if (document.readyState === 'loading') {
|
||||
initRubberBandSelection();
|
||||
}
|
||||
|
||||
// Expose helpers globally
|
||||
window.toggleCardSelection = toggleCardSelection;
|
||||
window.showContextMenuAtElement = showContextMenuAtElement;
|
||||
window.initRubberBandSelection = initRubberBandSelection;
|
||||
|
||||
/**
|
||||
* Show a modern confirm dialog (replaces native confirm())
|
||||
* @param {Object} options
|
||||
@@ -1588,9 +1595,9 @@ window.initRubberBandSelection = initRubberBandSelection;
|
||||
* @returns {Promise<boolean>} true if confirmed, false if cancelled
|
||||
*/
|
||||
function showConfirmDialog({ title, message, confirmText, cancelText, danger = true } = {}) {
|
||||
const ct = confirmText || (window.i18n ? window.i18n.t('actions.delete') : 'Delete');
|
||||
const cc = cancelText || (window.i18n ? window.i18n.t('actions.cancel') : 'Cancel');
|
||||
const t = title || (window.i18n ? window.i18n.t('dialogs.confirm_title') : 'Confirm action');
|
||||
const ct = confirmText || (i18n ? i18n.t('actions.delete') : 'Delete');
|
||||
const cc = cancelText || (i18n ? i18n.t('actions.cancel') : 'Cancel');
|
||||
const t = title || (i18n ? i18n.t('dialogs.confirm_title') : 'Confirm action');
|
||||
|
||||
return new Promise((resolve) => {
|
||||
// Remove any previous confirm dialog
|
||||
@@ -1633,7 +1640,5 @@ function showConfirmDialog({ title, message, confirmText, cancelText, danger = t
|
||||
});
|
||||
});
|
||||
}
|
||||
window.showConfirmDialog = showConfirmDialog;
|
||||
|
||||
// Expose UI module globally
|
||||
window.ui = ui;
|
||||
export { initRubberBandSelection, showConfirmDialog, showContextMenuAtElement, toggleCardSelection, ui };
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
* Isolated icon and preview classification helpers used by ui.js.
|
||||
*/
|
||||
|
||||
import { isTextViewable } from '../core/formatters.js';
|
||||
|
||||
const uiFileTypes = {
|
||||
// TODO: 'd better to use a canViw() method in inlineViewer
|
||||
isViewableFile(file) {
|
||||
@@ -11,7 +13,7 @@ const uiFileTypes = {
|
||||
if (file.mime_type === 'application/pdf') return true;
|
||||
if (file.mime_type.startsWith('audio/')) return true;
|
||||
if (file.mime_type.startsWith('video/')) return true;
|
||||
return window.isTextViewable ? window.isTextViewable(file.mime_type) : false;
|
||||
return isTextViewable(file.mime_type);
|
||||
},
|
||||
|
||||
getIconClass(fileName) {
|
||||
@@ -170,4 +172,4 @@ const uiFileTypes = {
|
||||
}
|
||||
};
|
||||
|
||||
window.uiFileTypes = uiFileTypes;
|
||||
export { uiFileTypes };
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
* Isolates notification rendering policy from ui.js.
|
||||
*/
|
||||
|
||||
import { notifications } from '../core/notifications.js';
|
||||
|
||||
const uiNotifications = {
|
||||
show(title, message) {
|
||||
if (window.notifications && typeof window.notifications.addNotification === 'function') {
|
||||
if (notifications && typeof notifications.addNotification === 'function') {
|
||||
const normalizedTitle = String(title || '').toLowerCase();
|
||||
let icon = 'fa-info-circle';
|
||||
let iconClass = 'upload';
|
||||
@@ -27,7 +29,7 @@ const uiNotifications = {
|
||||
iconClass = 'success';
|
||||
}
|
||||
|
||||
window.notifications.addNotification({
|
||||
notifications.addNotification({
|
||||
icon,
|
||||
iconClass,
|
||||
title: title || '',
|
||||
@@ -58,4 +60,4 @@ const uiNotifications = {
|
||||
}
|
||||
};
|
||||
|
||||
window.uiNotifications = uiNotifications;
|
||||
export { uiNotifications };
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
* User menu, profile modal and logout logic
|
||||
*/
|
||||
|
||||
import { getCsrfHeaders } from '../core/csrf.js';
|
||||
import { formatFileSize, formatQuotaSize } from '../core/formatters.js';
|
||||
import { i18n } from '../core/i18n.js';
|
||||
import { ui } from './ui.js';
|
||||
|
||||
function setupUserMenu() {
|
||||
const wrapper = document.getElementById('user-menu-wrapper');
|
||||
const avatarBtn = document.getElementById('user-avatar-btn');
|
||||
@@ -102,7 +107,7 @@ function setupUserMenu() {
|
||||
}
|
||||
}
|
||||
|
||||
window.ui.showNotification(newIsDark ? '🌙' : '☀️', newIsDark ? 'Dark mode enabled' : 'Light mode enabled');
|
||||
ui.showNotification(newIsDark ? '🌙' : '☀️', newIsDark ? 'Dark mode enabled' : 'Light mode enabled');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -173,8 +178,8 @@ function updateUserMenuData() {
|
||||
|
||||
if (storageFill) storageFill.style.width = `${percentage}%`;
|
||||
if (storageText) {
|
||||
const used = window.formatFileSize(usedBytes);
|
||||
const total = window.formatQuotaSize(quotaBytes);
|
||||
const used = formatFileSize(usedBytes);
|
||||
const total = formatQuotaSize(quotaBytes);
|
||||
storageText.textContent = `${quotaBytes > 0 ? `${percentage}% · ` : ''}${used} / ${total}`;
|
||||
}
|
||||
}
|
||||
@@ -206,7 +211,7 @@ function showUserProfileModal() {
|
||||
const percentage = quotaBytes > 0 ? Math.min(Math.round((usedBytes / quotaBytes) * 100), 100) : 0;
|
||||
const barColor = percentage > 90 ? '#ef4444' : percentage > 70 ? '#f59e0b' : '#22c55e';
|
||||
|
||||
const t = (key, fallback) => (window.i18n?.t ? window.i18n.t(key) || fallback : fallback);
|
||||
const t = (key, fallback) => (i18n?.t ? i18n.t(key) || fallback : fallback);
|
||||
|
||||
const existing = document.getElementById('profile-modal-overlay');
|
||||
if (existing) existing.remove();
|
||||
@@ -229,7 +234,7 @@ function showUserProfileModal() {
|
||||
<div class="about-modal-bar-bg">
|
||||
<div class="about-modal-bar-fill" id="about-bar-fill"></div>
|
||||
</div>
|
||||
<div class="about-modal-bar-text">${percentage}% · ${window.formatFileSize(usedBytes)} / ${window.formatQuotaSize(quotaBytes)}</div>
|
||||
<div class="about-modal-bar-text">${percentage}% · ${formatFileSize(usedBytes)} / ${formatQuotaSize(quotaBytes)}</div>
|
||||
</div>
|
||||
<div class="about-modal-footer">
|
||||
<button id="profile-modal-close" class="about-modal-close-btn">${t('actions.close', 'Close')}</button>
|
||||
@@ -283,6 +288,4 @@ async function logout() {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
|
||||
window.setupUserMenu = setupUserMenu;
|
||||
window.showUserProfileModal = showUserProfileModal;
|
||||
window.logout = logout;
|
||||
export { logout, setupUserMenu, showUserProfileModal };
|
||||
|
||||
@@ -13,14 +13,14 @@
|
||||
* HttpOnly cookies.
|
||||
*/
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
function getCsrfToken() {
|
||||
const match = document.cookie.split('; ').find((row) => row.startsWith('oxicloud_csrf='));
|
||||
return match ? match.split('=')[1] : '';
|
||||
}
|
||||
|
||||
// biome-ignore lint/correctness/noUnusedVariables: global function
|
||||
function getCsrfHeaders() {
|
||||
const token = getCsrfToken();
|
||||
return token ? { 'X-CSRF-Token': token } : {};
|
||||
}
|
||||
|
||||
export { getCsrfHeaders, getCsrfToken };
|
||||
|
||||
@@ -65,9 +65,4 @@ function isTextViewable(mimeType) {
|
||||
return textTypes.includes(mimeType);
|
||||
}
|
||||
|
||||
window.escapeHtml = escapeHtml;
|
||||
window.formatFileSize = formatFileSize;
|
||||
window.formatQuotaSize = formatQuotaSize;
|
||||
window.formatDateTime = formatDateTime;
|
||||
window.formatDateShort = formatDateShort;
|
||||
window.isTextViewable = isTextViewable;
|
||||
export { escapeHtml, formatDateShort, formatDateTime, formatFileSize, formatQuotaSize, isTextViewable };
|
||||
|
||||
@@ -314,8 +314,7 @@ function safeT(key, params = {}) {
|
||||
return interpolate(value, params);
|
||||
}
|
||||
|
||||
// Export functions for use in other modules
|
||||
window.i18n = {
|
||||
export const i18n = {
|
||||
t: safeT,
|
||||
setLocale,
|
||||
getCurrentLocale,
|
||||
|
||||
@@ -483,9 +483,8 @@ function replaceIconsInElement(container) {
|
||||
}
|
||||
|
||||
// ── Expose globally ────────────────────────────────────────────
|
||||
window.oxiIcon = oxiIcon;
|
||||
window.replaceIconsInElement = replaceIconsInElement;
|
||||
window.OxiIcons = _ICONS;
|
||||
export { oxiIcon, replaceIconsInElement };
|
||||
export const OxiIcons = _ICONS;
|
||||
|
||||
// ── Auto-replace: MutationObserver bridge ──────────────────────
|
||||
// Watches the DOM for new <i class="fa-..."> elements and converts them
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { ALL_LANGUAGES } from '../features/auth/auth.js';
|
||||
import { i18n } from './i18n.js';
|
||||
|
||||
/**
|
||||
* Language Selector Component for OxiCloud
|
||||
* Custom styled dropdown with flags
|
||||
@@ -63,7 +66,7 @@ function createLanguageSelector(containerId = 'language-selector') {
|
||||
|
||||
// Get current language
|
||||
const languages = getAvailableLanguages();
|
||||
const currentLocale = window.i18n ? window.i18n.getCurrentLocale() : 'en';
|
||||
const currentLocale = i18n ? i18n.getCurrentLocale() : 'en';
|
||||
const currentLang = languages.find((l) => l.code === currentLocale) || languages[0];
|
||||
|
||||
// Set initial HTML attributes
|
||||
@@ -183,8 +186,8 @@ function closeDropdown(container) {
|
||||
*/
|
||||
async function selectLanguage(langCode, container) {
|
||||
// Update i18n if available
|
||||
if (window.i18n) {
|
||||
await window.i18n.setLocale(langCode);
|
||||
if (i18n) {
|
||||
await i18n.setLocale(langCode);
|
||||
}
|
||||
|
||||
// Update HTML lang attribute and dir for RTL languages
|
||||
|
||||
+12
-9
@@ -1,3 +1,6 @@
|
||||
import { i18n } from './i18n.js';
|
||||
import { replaceIconsInElement } from './icons.js';
|
||||
|
||||
/**
|
||||
* Modal System for OxiCloud
|
||||
* Provides modern, styled modals to replace browser prompts/alerts
|
||||
@@ -86,8 +89,8 @@ const Modal = {
|
||||
iconContainer.innerHTML = `<i id="modal-icon" class="fas ${icon}"></i>`;
|
||||
this.icon = document.getElementById('modal-icon');
|
||||
// Let icons.js convert it to SVG
|
||||
if (window.replaceIconsInElement) {
|
||||
window.replaceIconsInElement(iconContainer);
|
||||
if (replaceIconsInElement) {
|
||||
replaceIconsInElement(iconContainer);
|
||||
this.icon = document.getElementById('modal-icon');
|
||||
}
|
||||
}
|
||||
@@ -99,14 +102,14 @@ const Modal = {
|
||||
// Set button text (use i18n if available)
|
||||
if (confirmText) {
|
||||
this.confirmBtn.textContent = confirmText;
|
||||
} else if (window.i18n) {
|
||||
this.confirmBtn.textContent = window.i18n.t('actions.confirm');
|
||||
} else if (i18n) {
|
||||
this.confirmBtn.textContent = i18n.t('actions.confirm');
|
||||
}
|
||||
|
||||
if (cancelText) {
|
||||
this.cancelBtn.textContent = cancelText;
|
||||
} else if (window.i18n) {
|
||||
this.cancelBtn.textContent = window.i18n.t('actions.cancel');
|
||||
} else if (i18n) {
|
||||
this.cancelBtn.textContent = i18n.t('actions.cancel');
|
||||
}
|
||||
|
||||
// Set callbacks
|
||||
@@ -126,7 +129,7 @@ const Modal = {
|
||||
* @returns {Promise<string|null>}
|
||||
*/
|
||||
promptNewFolder() {
|
||||
const t = window.i18n ? window.i18n.t.bind(window.i18n) : (k) => k;
|
||||
const t = i18n ? i18n.t.bind(i18n) : (k) => k;
|
||||
|
||||
return this.prompt({
|
||||
title: t('dialogs.new_folder_title') || 'New folder',
|
||||
@@ -144,7 +147,7 @@ const Modal = {
|
||||
* @returns {Promise<string|null>}
|
||||
*/
|
||||
promptRename(currentName, isFolder = false) {
|
||||
const t = window.i18n ? window.i18n.t.bind(window.i18n) : (k) => k;
|
||||
const t = i18n ? i18n.t.bind(i18n) : (k) => k;
|
||||
|
||||
// For files, we want to select only the name part (without extension)
|
||||
this._selectNameOnly = !isFolder;
|
||||
@@ -232,4 +235,4 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
});
|
||||
|
||||
// Export for use in other modules
|
||||
window.Modal = Modal;
|
||||
export { Modal };
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { i18n } from './i18n.js';
|
||||
|
||||
/**
|
||||
* OxiCloud – Notification Bell Module
|
||||
*
|
||||
@@ -5,7 +7,7 @@
|
||||
* in the top-bar. Upload progress, quota errors, and general messages all
|
||||
* go through this module.
|
||||
*
|
||||
* Public API (on window.notifications):
|
||||
* Public API (exported as `notifications`):
|
||||
* addUploadBatch(totalFiles) → batchId
|
||||
* updateFile(batchId, fileName, pct, status)
|
||||
* finishBatch(batchId, successCount, totalFiles)
|
||||
@@ -147,7 +149,7 @@ const notifications = (() => {
|
||||
item.className = 'notif-item';
|
||||
item.id = batchId;
|
||||
|
||||
const t = window.i18n?.t || ((k) => k);
|
||||
const t = i18n?.t || ((k) => k);
|
||||
const uploadingText = folderName ? `📁 ${t('upload.uploading')} ${_esc(folderName)}…` : t('upload.uploading');
|
||||
const filesLabel = t('upload.files');
|
||||
|
||||
@@ -252,7 +254,7 @@ const notifications = (() => {
|
||||
const pctEl = $(`${batchId}-pct`);
|
||||
const statsEl = $(`${batchId}-stats`);
|
||||
|
||||
const t = window.i18n?.t || ((k) => k);
|
||||
const t = i18n?.t || ((k) => k);
|
||||
const filesLabel = t('upload.files');
|
||||
|
||||
if (fillEl) fillEl.style.width = `${pctVal}%`;
|
||||
@@ -280,7 +282,7 @@ const notifications = (() => {
|
||||
const curEl = $(`${batchId}-current`);
|
||||
if (curEl) curEl.textContent = '';
|
||||
|
||||
const t = window.i18n?.t || ((k) => k);
|
||||
const t = i18n?.t || ((k) => k);
|
||||
const completeText = t('upload.complete', {
|
||||
count: successCount,
|
||||
total: totalFiles
|
||||
@@ -351,4 +353,4 @@ const notifications = (() => {
|
||||
};
|
||||
})();
|
||||
|
||||
window.notifications = notifications;
|
||||
export { notifications };
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
* Handles login, registration, and admin setup
|
||||
*/
|
||||
|
||||
import { getCsrfHeaders } from '../../core/csrf.js';
|
||||
import { i18n } from '../../core/i18n.js';
|
||||
|
||||
// API endpoints
|
||||
const API_URL = '/api/auth';
|
||||
const LOGIN_ENDPOINT = `${API_URL}/login`;
|
||||
@@ -112,7 +115,7 @@ const LANGUAGE_TEXTS = {
|
||||
|
||||
// Complete language registry — add new languages here, they'll appear automatically
|
||||
// `popular: true` languages show as cards on the main screen, the rest in the modal
|
||||
const ALL_LANGUAGES = [
|
||||
export const ALL_LANGUAGES = [
|
||||
{
|
||||
code: 'en',
|
||||
name: 'English',
|
||||
@@ -509,8 +512,8 @@ function initLanguageSelector() {
|
||||
localStorage.setItem(FIRST_RUN_KEY, 'true');
|
||||
|
||||
// Update i18n if available
|
||||
if (window.i18n?.setLocale) {
|
||||
await window.i18n.setLocale(selectedLanguage);
|
||||
if (i18n?.setLocale) {
|
||||
await i18n.setLocale(selectedLanguage);
|
||||
}
|
||||
|
||||
// Hide language panel
|
||||
@@ -632,7 +635,7 @@ async function configureOidcLoginUI() {
|
||||
// Update button text with provider name
|
||||
const btnTextEl = oidcBtn.querySelector('span');
|
||||
if (btnTextEl && oidcInfo.provider_name) {
|
||||
const template = window.i18n?.t ? window.i18n.t('auth.sso_login_provider') : 'Sign in with {{provider}}';
|
||||
const template = i18n?.t ? i18n.t('auth.sso_login_provider') : 'Sign in with {{provider}}';
|
||||
btnTextEl.textContent = template.replace('{{provider}}', oidcInfo.provider_name);
|
||||
}
|
||||
|
||||
@@ -669,7 +672,6 @@ function initLoginElements() {
|
||||
return false;
|
||||
}
|
||||
|
||||
languagePanel = document.getElementById('language-panel');
|
||||
loginPanel = document.getElementById('login-panel');
|
||||
registerPanel = document.getElementById('register-panel');
|
||||
adminSetupPanel = document.getElementById('admin-setup-panel');
|
||||
@@ -940,7 +942,7 @@ if (isLoginPage && registerForm) {
|
||||
|
||||
// Validate passwords match
|
||||
if (password !== confirmPassword) {
|
||||
const errorMsg = window.i18n ? window.i18n.t('auth.passwords_mismatch') : 'Passwords do not match';
|
||||
const errorMsg = i18n ? i18n.t('auth.passwords_mismatch') : 'Passwords do not match';
|
||||
registerError.textContent = errorMsg;
|
||||
registerError.style.display = 'block';
|
||||
return;
|
||||
@@ -950,7 +952,7 @@ if (isLoginPage && registerForm) {
|
||||
await register(username, email, password);
|
||||
|
||||
// Show success message
|
||||
const successMsg = window.i18n ? window.i18n.t('auth.account_success') : 'Account created successfully! You can now log in.';
|
||||
const successMsg = i18n ? i18n.t('auth.account_success') : 'Account created successfully! You can now log in.';
|
||||
registerSuccess.textContent = successMsg;
|
||||
registerSuccess.style.display = 'block';
|
||||
|
||||
@@ -963,7 +965,7 @@ if (isLoginPage && registerForm) {
|
||||
hidePanel(registerPanel);
|
||||
}, 2000);
|
||||
} catch (error) {
|
||||
const errorMsg = window.i18n ? window.i18n.t('auth.admin_create_error') : 'Error registering account';
|
||||
const errorMsg = i18n ? i18n.t('auth.admin_create_error') : 'Error registering account';
|
||||
registerError.textContent = error.message || errorMsg;
|
||||
registerError.style.display = 'block';
|
||||
}
|
||||
@@ -986,7 +988,7 @@ if (isLoginPage && adminSetupForm) {
|
||||
|
||||
// Validate passwords match
|
||||
if (password !== confirmPassword) {
|
||||
const errorMsg = window.i18n ? window.i18n.t('auth.passwords_mismatch') : 'Passwords do not match';
|
||||
const errorMsg = i18n ? i18n.t('auth.passwords_mismatch') : 'Passwords do not match';
|
||||
adminSetupError.textContent = errorMsg;
|
||||
adminSetupError.style.display = 'block';
|
||||
return;
|
||||
@@ -1011,7 +1013,7 @@ if (isLoginPage && adminSetupForm) {
|
||||
await response.json();
|
||||
|
||||
// Show success message in the GUI instead of alert
|
||||
const successMsg = window.i18n ? window.i18n.t('auth.admin_success') : 'Admin account created successfully! You can now log in.';
|
||||
const successMsg = i18n ? i18n.t('auth.admin_success') : 'Admin account created successfully! You can now log in.';
|
||||
|
||||
if (adminSetupSuccess) {
|
||||
adminSetupSuccess.textContent = successMsg;
|
||||
@@ -1025,7 +1027,7 @@ if (isLoginPage && adminSetupForm) {
|
||||
if (adminSetupSuccess) adminSetupSuccess.style.display = 'none';
|
||||
}, 2000);
|
||||
} catch (error) {
|
||||
const errorMsg = window.i18n ? window.i18n.t('auth.admin_create_error') : 'Error creating admin account';
|
||||
const errorMsg = i18n ? i18n.t('auth.admin_create_error') : 'Error creating admin account';
|
||||
adminSetupError.textContent = error.message || errorMsg;
|
||||
adminSetupError.style.display = 'block';
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,6 +3,14 @@
|
||||
* This file handles file and folder operations (create, move, delete, rename, upload)
|
||||
*/
|
||||
|
||||
import { refreshUserData } from '../../app/authSession.js';
|
||||
import { loadFiles } from '../../app/filesView.js';
|
||||
import { app } from '../../app/state.js';
|
||||
import { showConfirmDialog, ui } from '../../app/ui.js';
|
||||
import { getCsrfHeaders, getCsrfToken } from '../../core/csrf.js';
|
||||
import { i18n } from '../../core/i18n.js';
|
||||
import { notifications } from '../../core/notifications.js';
|
||||
|
||||
/**
|
||||
* Get authorization headers for API requests.
|
||||
* Tokens are now in HttpOnly cookies — no explicit Authorization header needed.
|
||||
@@ -22,13 +30,13 @@ const fileOps = {
|
||||
|
||||
/** Start a new upload batch in the notification bell */
|
||||
_initUploadToast(totalFiles, folderName) {
|
||||
this._currentBatchId = window.notifications ? window.notifications.addUploadBatch(totalFiles, folderName) : null;
|
||||
this._currentBatchId = notifications ? notifications.addUploadBatch(totalFiles, folderName) : null;
|
||||
},
|
||||
|
||||
/** Finalise the batch in the notification bell */
|
||||
_finishUploadToast(successCount, totalFiles) {
|
||||
if (window.notifications && this._currentBatchId) {
|
||||
window.notifications.finishBatch(this._currentBatchId, successCount, totalFiles);
|
||||
if (notifications && this._currentBatchId) {
|
||||
notifications.finishBatch(this._currentBatchId, successCount, totalFiles);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -58,7 +66,7 @@ const fileOps = {
|
||||
_uploadFileXHR(formData, batchId, fileName, timeoutMs = 120000) {
|
||||
return new Promise((resolve) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
const notif = window.notifications;
|
||||
const notif = notifications;
|
||||
// Do NOT set xhr.timeout — it is a TOTAL deadline from send() to
|
||||
// response and would kill large uploads even while data is flowing.
|
||||
// Instead we rely on the stall timer (no progress for N seconds)
|
||||
@@ -299,13 +307,13 @@ const fileOps = {
|
||||
|
||||
const totalFiles = readableFiles.length;
|
||||
|
||||
if (skippedEntries.length > 0 && window.notifications) {
|
||||
const locale = window.i18n?.getCurrentLocale?.() || 'en';
|
||||
if (skippedEntries.length > 0 && notifications) {
|
||||
const locale = i18n?.getCurrentLocale?.() || 'en';
|
||||
const title = locale.startsWith('es') ? 'Entradas omitidas' : 'Entries skipped';
|
||||
const text = locale.startsWith('es')
|
||||
? `Se omitieron ${skippedEntries.length} carpeta(s)/entrada(s) no legibles. Usa "Subir carpeta".`
|
||||
: `${skippedEntries.length} unreadable folder/entry items were skipped. Use "Upload folder".`;
|
||||
window.notifications.addNotification({
|
||||
notifications.addNotification({
|
||||
icon: 'fa-folder-open',
|
||||
iconClass: 'upload',
|
||||
title,
|
||||
@@ -331,7 +339,7 @@ const fileOps = {
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
const targetFolderId = window.app.currentPath || window.app.userHomeFolderId;
|
||||
const targetFolderId = app.currentPath || app.userHomeFolderId;
|
||||
if (targetFolderId) formData.append('folder_id', targetFolderId);
|
||||
formData.append('file', file);
|
||||
|
||||
@@ -353,9 +361,9 @@ const fileOps = {
|
||||
progressBar.style.width = `${(uploadedCount / totalFiles) * 100}%`;
|
||||
}
|
||||
// Notify bell of per-file completion
|
||||
if (window.notifications && batchId) {
|
||||
if (notifications && batchId) {
|
||||
try {
|
||||
window.notifications.fileCompleted(batchId, result.ok);
|
||||
notifications.fileCompleted(batchId, result.ok);
|
||||
} catch (e) {
|
||||
console.warn('Batch progress update failed:', e);
|
||||
}
|
||||
@@ -366,8 +374,8 @@ const fileOps = {
|
||||
console.log(`Successfully uploaded ${file.name}`, result.data);
|
||||
} else {
|
||||
console.error(`Upload error for ${file.name}`);
|
||||
if (result.isTimeout && window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (result.isTimeout && notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-clock',
|
||||
iconClass: 'error',
|
||||
title: file.name,
|
||||
@@ -375,9 +383,9 @@ const fileOps = {
|
||||
});
|
||||
}
|
||||
if (result.isQuotaError) {
|
||||
const msg = result.errorMsg || window.i18n?.t('storage_quota_exceeded') || 'Storage quota exceeded';
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
const msg = result.errorMsg || i18n?.t('storage_quota_exceeded') || 'Storage quota exceeded';
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-exclamation-triangle',
|
||||
iconClass: 'error',
|
||||
title: file.name,
|
||||
@@ -393,14 +401,12 @@ const fileOps = {
|
||||
this._finishUploadToast(successCount, totalFiles);
|
||||
|
||||
// Refresh storage usage display
|
||||
if (typeof window.refreshUserData === 'function') {
|
||||
try {
|
||||
await window.refreshUserData();
|
||||
await refreshUserData();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
try {
|
||||
await window.loadFiles({ forceRefresh: true });
|
||||
await loadFiles({ forceRefresh: true });
|
||||
} catch (reloadError) {
|
||||
console.error('Error reloading files:', reloadError);
|
||||
}
|
||||
@@ -466,7 +472,7 @@ const fileOps = {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentFolderId = window.app.currentPath || window.app.userHomeFolderId;
|
||||
const currentFolderId = app.currentPath || app.userHomeFolderId;
|
||||
|
||||
// Build folder structure from relative paths
|
||||
const folderMap = new Map();
|
||||
@@ -528,7 +534,7 @@ const fileOps = {
|
||||
.filter(Boolean)
|
||||
)
|
||||
];
|
||||
const locale = window.i18n?.getCurrentLocale?.() || 'en';
|
||||
const locale = i18n?.getCurrentLocale?.() || 'en';
|
||||
const rootFolderLabel =
|
||||
rootFolderNames.length <= 1
|
||||
? rootFolderNames[0] || ''
|
||||
@@ -585,9 +591,9 @@ const fileOps = {
|
||||
console.warn(`[SKIP] #${idx} ${rel} — cannot read 0-byte file (FIFO/pipe?), skipping`);
|
||||
uploadedCount++;
|
||||
successCount++;
|
||||
if (window.notifications && batchId) {
|
||||
if (notifications && batchId) {
|
||||
try {
|
||||
window.notifications.fileCompleted(batchId, true);
|
||||
notifications.fileCompleted(batchId, true);
|
||||
} catch (_) {}
|
||||
}
|
||||
return;
|
||||
@@ -617,9 +623,9 @@ const fileOps = {
|
||||
|
||||
uploadedCount++;
|
||||
|
||||
if (window.notifications && batchId) {
|
||||
if (notifications && batchId) {
|
||||
try {
|
||||
window.notifications.fileCompleted(batchId, result.ok);
|
||||
notifications.fileCompleted(batchId, result.ok);
|
||||
} catch (_) {}
|
||||
}
|
||||
if (progressBar && uploadedCount % 10 === 0) {
|
||||
@@ -633,8 +639,8 @@ const fileOps = {
|
||||
successCount++;
|
||||
} else if (result.isQuotaError) {
|
||||
quotaStop = true;
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-exclamation-triangle',
|
||||
iconClass: 'error',
|
||||
title: file.name,
|
||||
@@ -661,14 +667,12 @@ const fileOps = {
|
||||
|
||||
this._finishUploadToast(successCount, totalFiles);
|
||||
|
||||
if (typeof window.refreshUserData === 'function') {
|
||||
try {
|
||||
await window.refreshUserData();
|
||||
await refreshUserData();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
try {
|
||||
await window.loadFiles({ forceRefresh: true });
|
||||
await loadFiles({ forceRefresh: true });
|
||||
} catch (reloadError) {
|
||||
console.error('Error reloading files:', reloadError);
|
||||
}
|
||||
@@ -699,7 +703,7 @@ const fileOps = {
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: name,
|
||||
parent_id: window.app.currentPath || window.app.userHomeFolderId || null
|
||||
parent_id: app.currentPath || app.userHomeFolderId || null
|
||||
})
|
||||
});
|
||||
|
||||
@@ -710,17 +714,17 @@ const fileOps = {
|
||||
|
||||
// Optimistic UI: add folder card directly from server response
|
||||
// — no reload needed since the backend already confirmed creation.
|
||||
window.ui.addFolderToView(folder);
|
||||
ui.addFolderToView(folder);
|
||||
|
||||
window.ui.showNotification('Folder created', `"${name}" created successfully`);
|
||||
ui.showNotification('Folder created', `"${name}" created successfully`);
|
||||
} else {
|
||||
const errorData = await response.text();
|
||||
console.error('Create folder error:', errorData);
|
||||
window.ui.showNotification('Error', 'Error creating the folder');
|
||||
ui.showNotification('Error', 'Error creating the folder');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error creating folder:', error);
|
||||
window.ui.showNotification('Error', 'Error creating the folder');
|
||||
ui.showNotification('Error', 'Error creating the folder');
|
||||
}
|
||||
},
|
||||
|
||||
@@ -745,8 +749,8 @@ const fileOps = {
|
||||
|
||||
if (response.ok) {
|
||||
// Reload files after moving
|
||||
await window.loadFiles();
|
||||
window.ui.showNotification('File moved', 'File moved successfully');
|
||||
await loadFiles();
|
||||
ui.showNotification('File moved', 'File moved successfully');
|
||||
return true;
|
||||
} else {
|
||||
let errorMessage = 'Unknown error';
|
||||
@@ -756,12 +760,12 @@ const fileOps = {
|
||||
} catch (_e) {
|
||||
errorMessage = 'Error processing server response';
|
||||
}
|
||||
window.ui.showNotification('Error', `Error moving the file: ${errorMessage}`);
|
||||
ui.showNotification('Error', `Error moving the file: ${errorMessage}`);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error moving file:', error);
|
||||
window.ui.showNotification('Error', 'Error moving the file');
|
||||
ui.showNotification('Error', 'Error moving the file');
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -787,8 +791,8 @@ const fileOps = {
|
||||
|
||||
if (response.ok) {
|
||||
// Reload files after moving
|
||||
await window.loadFiles();
|
||||
window.ui.showNotification('Folder moved', 'Folder moved successfully');
|
||||
await loadFiles();
|
||||
ui.showNotification('Folder moved', 'Folder moved successfully');
|
||||
return true;
|
||||
} else {
|
||||
let errorMessage = 'Unknown error';
|
||||
@@ -798,12 +802,12 @@ const fileOps = {
|
||||
} catch (_e) {
|
||||
errorMessage = 'Error processing server response';
|
||||
}
|
||||
window.ui.showNotification('Error', `Error moving the folder: ${errorMessage}`);
|
||||
ui.showNotification('Error', `Error moving the folder: ${errorMessage}`);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error moving folder:', error);
|
||||
window.ui.showNotification('Error', 'Error moving the folder');
|
||||
ui.showNotification('Error', 'Error moving the folder');
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -890,8 +894,8 @@ const fileOps = {
|
||||
if (response.ok) {
|
||||
await response.json();
|
||||
// Reload files after copying
|
||||
await window.loadFiles();
|
||||
window.ui.showNotification('File copied', 'File copied successfully');
|
||||
await loadFiles();
|
||||
ui.showNotification('File copied', 'File copied successfully');
|
||||
return true;
|
||||
} else {
|
||||
let errorMessage = 'Unknown error';
|
||||
@@ -901,12 +905,12 @@ const fileOps = {
|
||||
} catch (_e) {
|
||||
errorMessage = 'Error processing server response';
|
||||
}
|
||||
window.ui.showNotification('Error', `Error copying the file: ${errorMessage}`);
|
||||
ui.showNotification('Error', `Error copying the file: ${errorMessage}`);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error copying file:', error);
|
||||
window.ui.showNotification('Error', 'Error copying the file');
|
||||
ui.showNotification('Error', 'Error copying the file');
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -920,7 +924,7 @@ const fileOps = {
|
||||
*/
|
||||
async copyFolder(_folderId, _targetFolderId) {
|
||||
// Folder copy is not yet implemented in the backend
|
||||
window.ui.showNotification('Not implemented', 'Folder copy is not yet supported');
|
||||
ui.showNotification('Not implemented', 'Folder copy is not yet supported');
|
||||
return false;
|
||||
},
|
||||
|
||||
@@ -954,7 +958,7 @@ const fileOps = {
|
||||
|
||||
// Note: Folder copy is not yet implemented in batch API
|
||||
if (folderIds.length > 0) {
|
||||
window.ui.showNotification('Info', 'Folder copy is not yet supported in batch mode');
|
||||
ui.showNotification('Info', 'Folder copy is not yet supported in batch mode');
|
||||
errors += folderIds.lenngth;
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -990,9 +994,9 @@ const fileOps = {
|
||||
console.log('Response status:', response.status);
|
||||
|
||||
if (response.ok) {
|
||||
window.ui.showNotification(
|
||||
window.i18n ? window.i18n.t('notifications.file_renamed') : 'File renamed',
|
||||
window.i18n ? window.i18n.t('notifications.file_renamed_to', { name: newName }) : `File renamed to "${newName}"`
|
||||
ui.showNotification(
|
||||
i18n ? i18n.t('notifications.file_renamed') : 'File renamed',
|
||||
i18n ? i18n.t('notifications.file_renamed_to', { name: newName }) : `File renamed to "${newName}"`
|
||||
);
|
||||
return true;
|
||||
} else {
|
||||
@@ -1005,12 +1009,12 @@ const fileOps = {
|
||||
} catch (_e) {
|
||||
errorMessage = errorText || response.statusText;
|
||||
}
|
||||
window.ui.showNotification('Error', `Error renaming the file: ${errorMessage}`);
|
||||
ui.showNotification('Error', `Error renaming the file: ${errorMessage}`);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error renaming file:', error);
|
||||
window.ui.showNotification('Error', 'Error renaming the file');
|
||||
ui.showNotification('Error', 'Error renaming the file');
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -1037,7 +1041,7 @@ const fileOps = {
|
||||
console.log('Response status:', response.status);
|
||||
|
||||
if (response.ok) {
|
||||
window.ui.showNotification('Folder renamed', `Folder renamed to "${newName}"`);
|
||||
ui.showNotification('Folder renamed', `Folder renamed to "${newName}"`);
|
||||
return true;
|
||||
} else {
|
||||
const errorText = await response.text();
|
||||
@@ -1053,12 +1057,12 @@ const fileOps = {
|
||||
errorMessage = errorText || response.statusText;
|
||||
}
|
||||
|
||||
window.ui.showNotification('Error', `Error renaming the folder: ${errorMessage}`);
|
||||
ui.showNotification('Error', `Error renaming the folder: ${errorMessage}`);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error renaming folder:', error);
|
||||
window.ui.showNotification('Error', 'Error renaming the folder');
|
||||
ui.showNotification('Error', 'Error renaming the folder');
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -1071,11 +1075,9 @@ const fileOps = {
|
||||
*/
|
||||
async deleteFile(fileId, fileName) {
|
||||
const confirmed = await showConfirmDialog({
|
||||
title: window.i18n ? window.i18n.t('dialogs.confirm_delete') : 'Move to trash',
|
||||
message: window.i18n
|
||||
? window.i18n.t('dialogs.confirm_delete_file', { name: fileName })
|
||||
: `Are you sure you want to move the file "${fileName}" to trash?`,
|
||||
confirmText: window.i18n ? window.i18n.t('actions.delete') : 'Delete'
|
||||
title: i18n ? i18n.t('dialogs.confirm_delete') : 'Move to trash',
|
||||
message: i18n ? i18n.t('dialogs.confirm_delete_file', { name: fileName }) : `Are you sure you want to move the file "${fileName}" to trash?`,
|
||||
confirmText: i18n ? i18n.t('actions.delete') : 'Delete'
|
||||
});
|
||||
if (!confirmed) return false;
|
||||
|
||||
@@ -1087,8 +1089,8 @@ const fileOps = {
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
window.loadFiles();
|
||||
window.ui.showNotification('File moved to trash', `"${fileName}" moved to trash`);
|
||||
loadFiles();
|
||||
ui.showNotification('File moved to trash', `"${fileName}" moved to trash`);
|
||||
return true;
|
||||
} else {
|
||||
// Fallback to direct deletion if trash fails
|
||||
@@ -1098,17 +1100,17 @@ const fileOps = {
|
||||
});
|
||||
|
||||
if (fallbackResponse.ok) {
|
||||
window.loadFiles();
|
||||
window.ui.showNotification('File deleted', `"${fileName}" deleted successfully`);
|
||||
loadFiles();
|
||||
ui.showNotification('File deleted', `"${fileName}" deleted successfully`);
|
||||
return true;
|
||||
} else {
|
||||
window.ui.showNotification('Error', 'Error deleting the file');
|
||||
ui.showNotification('Error', 'Error deleting the file');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting file:', error);
|
||||
window.ui.showNotification('Error', 'Error deleting the file');
|
||||
ui.showNotification('Error', 'Error deleting the file');
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -1121,11 +1123,11 @@ const fileOps = {
|
||||
*/
|
||||
async deleteFolder(folderId, folderName) {
|
||||
const confirmed = await showConfirmDialog({
|
||||
title: window.i18n ? window.i18n.t('dialogs.confirm_delete') : 'Move to trash',
|
||||
message: window.i18n
|
||||
? window.i18n.t('dialogs.confirm_delete_folder', { name: folderName })
|
||||
title: i18n ? i18n.t('dialogs.confirm_delete') : 'Move to trash',
|
||||
message: i18n
|
||||
? i18n.t('dialogs.confirm_delete_folder', { name: folderName })
|
||||
: `Are you sure you want to move the folder "${folderName}" and all its contents to trash?`,
|
||||
confirmText: window.i18n ? window.i18n.t('actions.delete') : 'Delete'
|
||||
confirmText: i18n ? i18n.t('actions.delete') : 'Delete'
|
||||
});
|
||||
if (!confirmed) return false;
|
||||
|
||||
@@ -1138,12 +1140,12 @@ const fileOps = {
|
||||
|
||||
if (response.ok) {
|
||||
// If we're inside the folder we just deleted, go back up
|
||||
if (window.app.currentPath === folderId) {
|
||||
window.app.currentPath = '';
|
||||
window.ui.updateBreadcrumb('');
|
||||
if (app.currentPath === folderId) {
|
||||
app.currentPath = '';
|
||||
ui.updateBreadcrumb('');
|
||||
}
|
||||
window.loadFiles();
|
||||
window.ui.showNotification('Folder moved to trash', `"${folderName}" moved to trash`);
|
||||
loadFiles();
|
||||
ui.showNotification('Folder moved to trash', `"${folderName}" moved to trash`);
|
||||
return true;
|
||||
} else {
|
||||
// Fallback to direct deletion if trash fails
|
||||
@@ -1154,21 +1156,21 @@ const fileOps = {
|
||||
|
||||
if (fallbackResponse.ok) {
|
||||
// If we're inside the folder we just deleted, go back up
|
||||
if (window.app.currentPath === folderId) {
|
||||
window.app.currentPath = '';
|
||||
window.ui.updateBreadcrumb('');
|
||||
if (app.currentPath === folderId) {
|
||||
app.currentPath = '';
|
||||
ui.updateBreadcrumb('');
|
||||
}
|
||||
window.loadFiles();
|
||||
window.ui.showNotification('Folder deleted', `"${folderName}" deleted successfully`);
|
||||
loadFiles();
|
||||
ui.showNotification('Folder deleted', `"${folderName}" deleted successfully`);
|
||||
return true;
|
||||
} else {
|
||||
window.ui.showNotification('Error', 'Error deleting the folder');
|
||||
ui.showNotification('Error', 'Error deleting the folder');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting folder:', error);
|
||||
window.ui.showNotification('Error', 'Error deleting the folder');
|
||||
ui.showNotification('Error', 'Error deleting the folder');
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -1212,15 +1214,15 @@ const fileOps = {
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
window.ui.showNotification('Item restored', 'Item restored successfully');
|
||||
ui.showNotification('Item restored', 'Item restored successfully');
|
||||
return true;
|
||||
} else {
|
||||
window.ui.showNotification('Error', 'Error restoring the item');
|
||||
ui.showNotification('Error', 'Error restoring the item');
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error restoring item from trash:', error);
|
||||
window.ui.showNotification('Error', 'Error restoring the item');
|
||||
ui.showNotification('Error', 'Error restoring the item');
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -1232,11 +1234,11 @@ const fileOps = {
|
||||
*/
|
||||
async deletePermanently(trashId) {
|
||||
const confirmed = await showConfirmDialog({
|
||||
title: window.i18n ? window.i18n.t('dialogs.confirm_permanent_delete') : 'Delete permanently',
|
||||
message: window.i18n
|
||||
? window.i18n.t('dialogs.confirm_permanent_delete_msg')
|
||||
title: i18n ? i18n.t('dialogs.confirm_permanent_delete') : 'Delete permanently',
|
||||
message: i18n
|
||||
? i18n.t('dialogs.confirm_permanent_delete_msg')
|
||||
: 'Are you sure you want to permanently delete this item? This action cannot be undone.',
|
||||
confirmText: window.i18n ? window.i18n.t('actions.delete_permanently') : 'Delete permanently'
|
||||
confirmText: i18n ? i18n.t('actions.delete_permanently') : 'Delete permanently'
|
||||
});
|
||||
if (!confirmed) return false;
|
||||
|
||||
@@ -1247,15 +1249,15 @@ const fileOps = {
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
window.ui.showNotification('Item deleted', 'Item permanently deleted');
|
||||
ui.showNotification('Item deleted', 'Item permanently deleted');
|
||||
return true;
|
||||
} else {
|
||||
window.ui.showNotification('Error', 'Error deleting the item');
|
||||
ui.showNotification('Error', 'Error deleting the item');
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting item permanently:', error);
|
||||
window.ui.showNotification('Error', 'Error deleting the item');
|
||||
ui.showNotification('Error', 'Error deleting the item');
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -1266,11 +1268,9 @@ const fileOps = {
|
||||
*/
|
||||
async emptyTrash() {
|
||||
const confirmed = await showConfirmDialog({
|
||||
title: window.i18n ? window.i18n.t('dialogs.confirm_empty_trash') : 'Empty trash',
|
||||
message: window.i18n
|
||||
? window.i18n.t('trash.empty_confirm')
|
||||
: 'Are you sure you want to empty the trash? This action will permanently delete all items.',
|
||||
confirmText: window.i18n ? window.i18n.t('actions.empty_trash') : 'Empty trash'
|
||||
title: i18n ? i18n.t('dialogs.confirm_empty_trash') : 'Empty trash',
|
||||
message: i18n ? i18n.t('trash.empty_confirm') : 'Are you sure you want to empty the trash? This action will permanently delete all items.',
|
||||
confirmText: i18n ? i18n.t('actions.empty_trash') : 'Empty trash'
|
||||
});
|
||||
if (!confirmed) return false;
|
||||
|
||||
@@ -1281,15 +1281,15 @@ const fileOps = {
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
window.ui.showNotification('Trash emptied', 'The trash has been emptied successfully');
|
||||
ui.showNotification('Trash emptied', 'The trash has been emptied successfully');
|
||||
return true;
|
||||
} else {
|
||||
window.ui.showNotification('Error', 'Error emptying the trash');
|
||||
ui.showNotification('Error', 'Error emptying the trash');
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error emptying trash:', error);
|
||||
window.ui.showNotification('Error', 'Error emptying the trash');
|
||||
ui.showNotification('Error', 'Error emptying the trash');
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -1315,11 +1315,11 @@ const fileOps = {
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
} else {
|
||||
window.ui.showNotification('Error', 'Error downloading the file');
|
||||
ui.showNotification('Error', 'Error downloading the file');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error downloading file:', error);
|
||||
window.ui.showNotification('Error', 'Error downloading the file');
|
||||
ui.showNotification('Error', 'Error downloading the file');
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1331,7 +1331,7 @@ const fileOps = {
|
||||
async downloadFolder(folderId, folderName) {
|
||||
try {
|
||||
// Show notification to user
|
||||
window.ui.showNotification('Preparing download', 'Preparing the folder for download...');
|
||||
ui.showNotification('Preparing download', 'Preparing the folder for download...');
|
||||
|
||||
const response = await fetch(`/api/folders/${folderId}/download?format=zip`, {
|
||||
headers: getAuthHeaders()
|
||||
@@ -1347,14 +1347,13 @@ const fileOps = {
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
} else {
|
||||
window.ui.showNotification('Error', 'Error downloading the folder');
|
||||
ui.showNotification('Error', 'Error downloading the folder');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error downloading folder:', error);
|
||||
window.ui.showNotification('Error', 'Error downloading the folder');
|
||||
ui.showNotification('Error', 'Error downloading the folder');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Expose file operations module globally
|
||||
window.fileOps = fileOps;
|
||||
export { fileOps, getAuthHeaders };
|
||||
|
||||
@@ -3,6 +3,11 @@
|
||||
* A simpler approach to viewing files that doesn't rely on complex DOM manipulation
|
||||
*/
|
||||
|
||||
import { updateHistory } from '../../app/main.js';
|
||||
import { app } from '../../app/state.js';
|
||||
import { isTextViewable } from '../../core/formatters.js';
|
||||
import { wopiEditor } from './wopiEditor.js';
|
||||
|
||||
class InlineViewer {
|
||||
constructor() {
|
||||
this.setupViewer();
|
||||
@@ -97,9 +102,9 @@ class InlineViewer {
|
||||
const ext = (file.name || '').split('.').pop().toLowerCase();
|
||||
const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'webp', 'bmp', 'ico', 'heic', 'heif', 'avif', 'tiff'];
|
||||
const isImage = file.mime_type?.startsWith('image/') || imageExts.includes(ext);
|
||||
if (!isImage && window.wopiEditor && (await window.wopiEditor.canEdit(file.name))) {
|
||||
if (!isImage && wopiEditor && (await wopiEditor.canEdit(file.name))) {
|
||||
try {
|
||||
window.wopiEditor.openInModal(file.id, file.name, 'edit');
|
||||
wopiEditor.openInModal(file.id, file.name, 'edit');
|
||||
return;
|
||||
} catch (e) {
|
||||
console.warn('WOPI editor failed, falling back to inline viewer:', e);
|
||||
@@ -204,9 +209,9 @@ class InlineViewer {
|
||||
modal.classList.add('active');
|
||||
}
|
||||
|
||||
// Check if a MIME type is text-viewable — delegates to window.isTextViewable
|
||||
// Check if a MIME type is text-viewable
|
||||
isTextViewable(mimeType) {
|
||||
return window.isTextViewable ? window.isTextViewable(mimeType) : false;
|
||||
return isTextViewable(mimeType);
|
||||
}
|
||||
|
||||
// Creates a text viewer using authenticated fetch
|
||||
@@ -513,8 +518,8 @@ class InlineViewer {
|
||||
}
|
||||
|
||||
// clear
|
||||
window.app.viewFile = null;
|
||||
window.updateHistory(false);
|
||||
app.viewFile = null;
|
||||
updateHistory(false);
|
||||
|
||||
// Clear references
|
||||
this.currentFile = null;
|
||||
@@ -573,21 +578,4 @@ class InlineViewer {
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize viewer when document is ready
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Check if it's already initialized
|
||||
if (!window.inlineViewer) {
|
||||
console.log('Initializing inline viewer on DOMContentLoaded');
|
||||
window.inlineViewer = new InlineViewer();
|
||||
}
|
||||
});
|
||||
|
||||
// Fallback initialization for cases where DOMContentLoaded already fired
|
||||
if (document.readyState === 'complete' || document.readyState === 'interactive') {
|
||||
if (!window.inlineViewer) {
|
||||
console.log('Fallback initialization for inline viewer');
|
||||
setTimeout(() => {
|
||||
window.inlineViewer = new InlineViewer();
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
export const inlineViewer = new InlineViewer();
|
||||
|
||||
@@ -11,6 +11,14 @@
|
||||
|
||||
// @ts-check
|
||||
|
||||
import { loadFiles } from '../../app/filesView.js';
|
||||
import { app } from '../../app/state.js';
|
||||
import { showConfirmDialog, ui } from '../../app/ui.js';
|
||||
import { i18n } from '../../core/i18n.js';
|
||||
import { favorites } from '../library/favorites.js';
|
||||
import { contextMenus } from './contextMenus.js';
|
||||
import { getAuthHeaders } from './fileOperations.js';
|
||||
|
||||
const multiSelect = {
|
||||
/** Currently selected items: Map<id, { id, name, type, parentId }> */
|
||||
_selected: new Map(),
|
||||
@@ -42,8 +50,8 @@ const multiSelect = {
|
||||
// ── Helpers for i18n ────────────────────────────────────
|
||||
|
||||
_t(key, vars) {
|
||||
if (window.i18n && typeof window.i18n.t === 'function') {
|
||||
const val = window.i18n.t(key, vars);
|
||||
if (i18n && typeof i18n.t === 'function') {
|
||||
const val = i18n.t(key, vars);
|
||||
// If i18n returned the key itself, it's missing → fall back
|
||||
if (val && val !== key) return val;
|
||||
}
|
||||
@@ -133,15 +141,15 @@ const multiSelect = {
|
||||
showBatchResult(action, result) {
|
||||
if (action === 'copy') {
|
||||
if (result.errors > 0) {
|
||||
window.ui.showNotification('Batch copy', `${result.success} copied, ${result.errors} failed`);
|
||||
ui.showNotification('Batch copy', `${result.success} copied, ${result.errors} failed`);
|
||||
} else {
|
||||
window.ui.showNotification('Items copied', `${result.success} item${result.success !== 1 ? 's' : ''} copied successfully`);
|
||||
ui.showNotification('Items copied', `${result.success} item${result.success !== 1 ? 's' : ''} copied successfully`);
|
||||
}
|
||||
} else {
|
||||
if (result.errors > 0) {
|
||||
window.ui.showNotification('Batch move', `${result.success} moved, ${result.errors} failed`);
|
||||
ui.showNotification('Batch move', `${result.success} moved, ${result.errors} failed`);
|
||||
} else {
|
||||
window.ui.showNotification('Items moved', `${result.success} item${result.success !== 1 ? 's' : ''} moved successfully`);
|
||||
ui.showNotification('Items moved', `${result.success} item${result.success !== 1 ? 's' : ''} moved successfully`);
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -366,18 +374,18 @@ const multiSelect = {
|
||||
const errors = data.stats?.failed || 0;
|
||||
|
||||
this.clear();
|
||||
window.loadFiles();
|
||||
loadFiles();
|
||||
|
||||
if (errors > 0) {
|
||||
window.ui.showNotification('Batch delete', `${success} moved to trash, ${errors} failed`);
|
||||
ui.showNotification('Batch delete', `${success} moved to trash, ${errors} failed`);
|
||||
} else {
|
||||
window.ui.showNotification('Moved to trash', `${success} item${success !== 1 ? 's' : ''} moved to trash`);
|
||||
ui.showNotification('Moved to trash', `${success} item${success !== 1 ? 's' : ''} moved to trash`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Batch trash error:', e);
|
||||
window.ui.showNotification('Error', 'Could not move items to trash');
|
||||
ui.showNotification('Error', 'Could not move items to trash');
|
||||
this.clear();
|
||||
window.loadFiles();
|
||||
loadFiles();
|
||||
}
|
||||
},
|
||||
|
||||
@@ -386,9 +394,9 @@ const multiSelect = {
|
||||
const items = this.items;
|
||||
if (items.length === 0) return;
|
||||
|
||||
window.app.moveDialogMode = 'batch';
|
||||
window.app.batchMoveItems = items;
|
||||
window.app.selectedTargetFolderId = '';
|
||||
app.moveDialogMode = 'batch';
|
||||
app.batchMoveItems = items;
|
||||
app.selectedTargetFolderId = '';
|
||||
|
||||
const dialog = document.getElementById('move-file-dialog');
|
||||
const dialogHeader = dialog.querySelector('.rename-dialog-header');
|
||||
@@ -406,7 +414,7 @@ const multiSelect = {
|
||||
const items = this.items;
|
||||
if (items.length === 0) return;
|
||||
|
||||
window.ui.showNotification('Preparing download', 'Creating ZIP archive...');
|
||||
ui.showNotification('Preparing download', 'Creating ZIP archive...');
|
||||
|
||||
try {
|
||||
const fileIds = items.filter((i) => i.type === 'file').map((i) => i.id);
|
||||
@@ -431,20 +439,20 @@ const multiSelect = {
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (e) {
|
||||
console.error('Batch download error:', e);
|
||||
window.ui.showNotification('Error', 'Could not download selected items');
|
||||
ui.showNotification('Error', 'Could not download selected items');
|
||||
}
|
||||
},
|
||||
|
||||
/** Batch add to favorites — single API call */
|
||||
async batchFavorites() {
|
||||
const items = this.items;
|
||||
if (items.length === 0 || !window.favorites) return;
|
||||
if (items.length === 0 || !favorites) return;
|
||||
|
||||
// Filter out items already in favourites
|
||||
const toAdd = items.filter((i) => !window.favorites.isFavorite(i.id, i.type));
|
||||
const toAdd = items.filter((i) => !favorites.isFavorite(i.id, i.type));
|
||||
if (toAdd.length === 0) {
|
||||
this.clear();
|
||||
window.ui.showNotification(this._t('favorites.add') || 'Favorites', 'All selected items are already favorites');
|
||||
ui.showNotification(this._t('favorites.add') || 'Favorites', 'All selected items are already favorites');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -463,23 +471,23 @@ const multiSelect = {
|
||||
const inserted = data.stats?.inserted || 0;
|
||||
|
||||
// Replace cache directly from response (no extra GET)
|
||||
if (data.favorites && window.favorites._replaceCacheFromResponse) {
|
||||
window.favorites._replaceCacheFromResponse(data.favorites);
|
||||
if (data.favorites && favorites._replaceCacheFromResponse) {
|
||||
favorites._replaceCacheFromResponse(data.favorites);
|
||||
} else {
|
||||
await window.favorites._fetchFromServer();
|
||||
await favorites._fetchFromServer();
|
||||
}
|
||||
|
||||
this.clear();
|
||||
if (typeof window.loadFiles === 'function') window.loadFiles();
|
||||
loadFiles();
|
||||
|
||||
if (inserted > 0) {
|
||||
window.ui.showNotification(this._t('favorites.add') || 'Added to favorites', `${inserted} item${inserted !== 1 ? 's' : ''} added to favorites`);
|
||||
ui.showNotification(this._t('favorites.add') || 'Added to favorites', `${inserted} item${inserted !== 1 ? 's' : ''} added to favorites`);
|
||||
} else {
|
||||
window.ui.showNotification(this._t('favorites.add') || 'Favorites', 'All selected items are already favorites');
|
||||
ui.showNotification(this._t('favorites.add') || 'Favorites', 'All selected items are already favorites');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Batch favorites error:', e);
|
||||
window.ui.showNotification('Error', 'Could not add items to favorites');
|
||||
ui.showNotification('Error', 'Could not add items to favorites');
|
||||
}
|
||||
},
|
||||
|
||||
@@ -510,8 +518,8 @@ const multiSelect = {
|
||||
const batchSelectionBar = document.getElementById('batch-selection-bar');
|
||||
batchSelectionBar.innerHTML = this._buildSelectionBarHTML();
|
||||
|
||||
if (window.i18n?.translateElement) {
|
||||
window.i18n.translateElement(batchSelectionBar);
|
||||
if (i18n?.translateElement) {
|
||||
i18n.translateElement(batchSelectionBar);
|
||||
}
|
||||
this._wireBarButtons();
|
||||
},
|
||||
@@ -524,5 +532,4 @@ const multiSelect = {
|
||||
}
|
||||
};
|
||||
|
||||
// Expose globally
|
||||
window.multiSelect = multiSelect;
|
||||
export { multiSelect };
|
||||
|
||||
@@ -7,6 +7,11 @@
|
||||
* displays the enriched results returned by the server.
|
||||
*/
|
||||
|
||||
import { loadFiles } from '../../app/filesView.js';
|
||||
import { app } from '../../app/state.js';
|
||||
import { ui } from '../../app/ui.js';
|
||||
import { getAuthHeaders } from './fileOperations.js';
|
||||
|
||||
const search = {
|
||||
/**
|
||||
* Perform a search using query parameters.
|
||||
@@ -55,7 +60,7 @@ const search = {
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error performing search:', error);
|
||||
window.ui.showNotification('Error', 'Error performing search');
|
||||
ui.showNotification('Error', 'Error performing search');
|
||||
return {
|
||||
files: [],
|
||||
folders: [],
|
||||
@@ -109,7 +114,7 @@ const search = {
|
||||
* @param {Object} results - Enriched search results from backend
|
||||
*/
|
||||
displaySearchResults(results) {
|
||||
window.ui.resetFilesList(); // ensure also list visible & error hidden
|
||||
ui.resetFilesList(); // ensure also list visible & error hidden
|
||||
//FIXME: move into action rather bage sticky header + hide bread crumb ? + note also that search result does not consider section
|
||||
const pageStickyHeader = document.getElementById('page-sticky-header');
|
||||
|
||||
@@ -163,17 +168,17 @@ const search = {
|
||||
if (clearSearchBtn) {
|
||||
clearSearchBtn.addEventListener('click', () => {
|
||||
document.querySelector('.search-container input').value = '';
|
||||
window.app.currentPath = '';
|
||||
window.app.isSearchMode = false;
|
||||
app.currentPath = '';
|
||||
app.isSearchMode = false;
|
||||
document.querySelector('.search-results-header')?.remove();
|
||||
window.ui.updateBreadcrumb('');
|
||||
window.loadFiles();
|
||||
ui.updateBreadcrumb('');
|
||||
loadFiles();
|
||||
});
|
||||
}
|
||||
|
||||
// Empty state
|
||||
if (results.files.length === 0 && results.folders.length === 0) {
|
||||
window.ui.showError(`
|
||||
ui.showError(`
|
||||
<i class="fas fa-search empty-state-icon"></i>
|
||||
<p class="search-empty-text">No results found for this search</p>
|
||||
`);
|
||||
@@ -182,12 +187,12 @@ const search = {
|
||||
|
||||
// Render folders (server-provided enriched data)
|
||||
results.folders.forEach((folder) => {
|
||||
window.ui.addFolderToView(folder);
|
||||
ui.addFolderToView(folder);
|
||||
});
|
||||
|
||||
// Render files (server-provided enriched data)
|
||||
results.files.forEach((file) => {
|
||||
window.ui.addFileToView(file);
|
||||
ui.addFileToView(file);
|
||||
});
|
||||
},
|
||||
|
||||
@@ -203,19 +208,18 @@ const search = {
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
window.ui.showNotification('Cache cleared', 'Search cache cleared successfully');
|
||||
ui.showNotification('Cache cleared', 'Search cache cleared successfully');
|
||||
return true;
|
||||
} else {
|
||||
window.ui.showNotification('Error', 'Error clearing search cache');
|
||||
ui.showNotification('Error', 'Error clearing search cache');
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error clearing search cache:', error);
|
||||
window.ui.showNotification('Error', 'Error clearing search cache');
|
||||
ui.showNotification('Error', 'Error clearing search cache');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Expose the search module globally
|
||||
window.search = search;
|
||||
export { search };
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
* Opens document files in Collabora Online / OnlyOffice via WOPI protocol.
|
||||
* Supports two modes: in-app modal (default) and new browser tab.
|
||||
*/
|
||||
|
||||
import { loadFiles } from '../../app/filesView.js';
|
||||
|
||||
class WopiEditor {
|
||||
constructor() {
|
||||
this.editorModal = null;
|
||||
@@ -203,11 +206,10 @@ class WopiEditor {
|
||||
this._messageHandler = null;
|
||||
}
|
||||
this.editorModal = null;
|
||||
|
||||
// Refresh file list to pick up any saves
|
||||
if (typeof loadFiles === 'function') {
|
||||
loadFiles();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch supported extensions from the server (cached).
|
||||
@@ -243,7 +245,7 @@ class WopiEditor {
|
||||
}
|
||||
|
||||
// Global instance
|
||||
window.wopiEditor = new WopiEditor();
|
||||
export const wopiEditor = new WopiEditor();
|
||||
|
||||
// Prefetch supported extensions so canEdit() is fast on first use
|
||||
window.wopiEditor._fetchSupportedExtensions();
|
||||
wopiEditor._fetchSupportedExtensions();
|
||||
|
||||
@@ -6,6 +6,10 @@
|
||||
* rendering path so star icons can be painted without a round-trip.
|
||||
*/
|
||||
|
||||
import { ui } from '../../app/ui.js';
|
||||
import { getCsrfHeaders } from '../../core/csrf.js';
|
||||
import { i18n } from '../../core/i18n.js';
|
||||
|
||||
const favorites = {
|
||||
/** @type {Map<string, object>} key = "file:<id>" | "folder:<id>" */
|
||||
_cache: new Map(),
|
||||
@@ -104,10 +108,10 @@ const favorites = {
|
||||
await this._fetchFromServer();
|
||||
|
||||
// Notify user
|
||||
if (window.ui?.showNotification) {
|
||||
window.ui.showNotification(
|
||||
window.i18n ? window.i18n.t('favorites.added_title') : 'Added to favorites',
|
||||
`"${name}" ${window.i18n ? window.i18n.t('favorites.added_msg') : 'added to favorites'}`
|
||||
if (ui?.showNotification) {
|
||||
ui.showNotification(
|
||||
i18n ? i18n.t('favorites.added_title') : 'Added to favorites',
|
||||
`"${name}" ${i18n ? i18n.t('favorites.added_msg') : 'added to favorites'}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -139,10 +143,10 @@ const favorites = {
|
||||
// Remove from local cache
|
||||
this._cache.delete(this._cacheKey(id, type));
|
||||
|
||||
if (window.ui?.showNotification) {
|
||||
window.ui.showNotification(
|
||||
window.i18n ? window.i18n.t('favorites.removed_title') : 'Removed from favorites',
|
||||
`"${itemName}" ${window.i18n ? window.i18n.t('favorites.removed_msg') : 'removed from favorites'}`
|
||||
if (ui?.showNotification) {
|
||||
ui.showNotification(
|
||||
i18n ? i18n.t('favorites.removed_title') : 'Removed from favorites',
|
||||
`"${itemName}" ${i18n ? i18n.t('favorites.removed_msg') : 'removed from favorites'}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -167,14 +171,14 @@ const favorites = {
|
||||
await this._fetchFromServer();
|
||||
}
|
||||
|
||||
window.ui.resetFilesList(); // ensure also list visible & error hidden
|
||||
window.ui.updateBreadcrumb('');
|
||||
ui.resetFilesList(); // ensure also list visible & error hidden
|
||||
ui.updateBreadcrumb('');
|
||||
|
||||
if (this._cache.size === 0) {
|
||||
window.ui.showError(`
|
||||
ui.showError(`
|
||||
<i class="fas fa-star empty-state-icon"></i>
|
||||
<p>${window.i18n ? window.i18n.t('favorites.empty_state') : 'No favorite items'}</p>
|
||||
<p>${window.i18n ? window.i18n.t('favorites.empty_hint') : 'To mark as favorite, right-click on any file or folder'}</p>
|
||||
<p>${i18n ? i18n.t('favorites.empty_state') : 'No favorite items'}</p>
|
||||
<p>${i18n ? i18n.t('favorites.empty_hint') : 'To mark as favorite, right-click on any file or folder'}</p>
|
||||
`);
|
||||
return;
|
||||
}
|
||||
@@ -204,16 +208,15 @@ const favorites = {
|
||||
});
|
||||
}
|
||||
}
|
||||
if (folders.length) window.ui.renderFolders(folders);
|
||||
if (files.length) window.ui.renderFiles(files);
|
||||
if (folders.length) ui.renderFolders(folders);
|
||||
if (files.length) ui.renderFiles(files);
|
||||
} catch (error) {
|
||||
console.error('Error displaying favorites:', error);
|
||||
if (window.ui?.showNotification) {
|
||||
window.ui.showNotification('Error', 'Error loading favorite items');
|
||||
if (ui?.showNotification) {
|
||||
ui.showNotification('Error', 'Error loading favorite items');
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Expose globally
|
||||
window.favorites = favorites;
|
||||
export { favorites };
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
import { app } from '../../app/state.js';
|
||||
import { getCsrfHeaders } from '../../core/csrf.js';
|
||||
import { formatFileSize } from '../../core/formatters.js';
|
||||
import { i18n } from '../../core/i18n.js';
|
||||
import { oxiIcon } from '../../core/icons.js';
|
||||
import { Modal } from '../../core/modal.js';
|
||||
import { notifications } from '../../core/notifications.js';
|
||||
|
||||
/**
|
||||
* OxiCloud - Music Library View
|
||||
* Playlist management with track listings and audio player
|
||||
@@ -13,7 +21,7 @@ const musicView = {
|
||||
selected: new Set(),
|
||||
|
||||
_headers(json = false) {
|
||||
const h = typeof getCsrfHeaders === 'function' ? { ...getCsrfHeaders() } : {};
|
||||
const h = { ...getCsrfHeaders() };
|
||||
if (json) h['Content-Type'] = 'application/json';
|
||||
return h;
|
||||
},
|
||||
@@ -78,8 +86,9 @@ const musicView = {
|
||||
_renderPlaylists() {
|
||||
if (!this._container) return;
|
||||
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
// FIXME should call directly
|
||||
const t = (key, _fallback = '') => {
|
||||
return i18n.t(key);
|
||||
};
|
||||
|
||||
// Empty state: no playlists at all — show full-width centered onboarding
|
||||
@@ -178,7 +187,7 @@ const musicView = {
|
||||
if (!listEl) return;
|
||||
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
return i18n?.t ? i18n.t(key) : fallback || key;
|
||||
};
|
||||
|
||||
if (this.playlists.length === 0) {
|
||||
@@ -283,7 +292,7 @@ const musicView = {
|
||||
if (nameEl) nameEl.textContent = playlist.name;
|
||||
if (metaEl) {
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
return i18n?.t ? i18n.t(key) : fallback || key;
|
||||
};
|
||||
metaEl.textContent = `${playlist.track_count || 0} ${t('music.tracks', 'tracks')}`;
|
||||
}
|
||||
@@ -305,7 +314,7 @@ const musicView = {
|
||||
}
|
||||
const togglePublicBtn = document.getElementById('music-toggle-public-btn');
|
||||
if (togglePublicBtn) {
|
||||
const t2 = (key, fallback = '') => (typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key);
|
||||
const t2 = (key, fallback = '') => (i18n?.t ? i18n.t(key) : fallback || key);
|
||||
togglePublicBtn.title = playlist.is_public ? t2('music.make_private', 'Make private') : t2('music.make_public', 'Make public');
|
||||
togglePublicBtn.classList.toggle('active', playlist.is_public);
|
||||
}
|
||||
@@ -344,7 +353,7 @@ const musicView = {
|
||||
if (!trackListEl) return;
|
||||
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
return i18n?.t ? i18n.t(key) : fallback || key;
|
||||
};
|
||||
|
||||
if (this.currentTracks.length === 0) {
|
||||
@@ -459,7 +468,7 @@ const musicView = {
|
||||
if (!this.currentTracks[idx]) return;
|
||||
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
return i18n?.t ? i18n.t(key) : fallback || key;
|
||||
};
|
||||
musicPlayer.setQueue(this.currentTracks, this.currentPlaylist?.name || t('music.playlists', 'Playlist'));
|
||||
musicPlayer.playTrack(idx);
|
||||
@@ -479,7 +488,7 @@ const musicView = {
|
||||
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
|
||||
}
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
return i18n?.t ? i18n.t(key) : fallback || key;
|
||||
};
|
||||
musicPlayer.setQueue(shuffled, this.currentPlaylist?.name || t('music.shuffle', 'Shuffle'));
|
||||
musicPlayer.playTrack(0);
|
||||
@@ -488,11 +497,10 @@ const musicView = {
|
||||
|
||||
async _showCreatePlaylistDialog() {
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
return i18n?.t ? i18n.t(key) : fallback || key;
|
||||
};
|
||||
|
||||
if (!window.Modal) return;
|
||||
const name = await window.Modal.prompt({
|
||||
const name = await Modal.prompt({
|
||||
title: t('music.create_playlist', 'Create Playlist'),
|
||||
label: t('music.playlist_name', 'Playlist name'),
|
||||
placeholder: t('music.playlist_name', 'Playlist name'),
|
||||
@@ -506,7 +514,7 @@ const musicView = {
|
||||
|
||||
async _createPlaylist(name) {
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
return i18n?.t ? i18n.t(key) : fallback || key;
|
||||
};
|
||||
const createBtn = document.getElementById('music-create-playlist-btn');
|
||||
if (createBtn) createBtn.disabled = true;
|
||||
@@ -524,8 +532,8 @@ const musicView = {
|
||||
this.playlists.unshift(playlist);
|
||||
this._renderPlaylists();
|
||||
this._selectPlaylist(playlist.id);
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-check-circle',
|
||||
iconClass: 'upload',
|
||||
title: t('music.create_playlist', 'Create Playlist'),
|
||||
@@ -534,8 +542,8 @@ const musicView = {
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Create playlist error:', err);
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-exclamation-circle',
|
||||
iconClass: 'error',
|
||||
title: t('music.error', 'Error'),
|
||||
@@ -549,17 +557,13 @@ const musicView = {
|
||||
|
||||
async _deletePlaylist() {
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
return i18n?.t ? i18n.t(key) : fallback || key;
|
||||
};
|
||||
|
||||
if (!this.currentPlaylist) return;
|
||||
|
||||
const confirmed = await new Promise((resolve) => {
|
||||
if (!window.Modal) {
|
||||
resolve(confirm(t('music.confirm_delete', 'Delete this playlist?')));
|
||||
return;
|
||||
}
|
||||
window.Modal.prompt({
|
||||
Modal.prompt({
|
||||
title: t('music.delete', 'Delete'),
|
||||
label: t('music.confirm_delete', 'Delete this playlist?'),
|
||||
placeholder: '',
|
||||
@@ -586,13 +590,13 @@ const musicView = {
|
||||
this.currentPlaylist = null;
|
||||
this.currentTracks = [];
|
||||
this._renderPlaylists();
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({ icon: 'fa-check-circle', iconClass: 'upload', title: t('music.delete', 'Delete'), text: deletedName });
|
||||
if (notifications) {
|
||||
notifications.addNotification({ icon: 'fa-check-circle', iconClass: 'upload', title: t('music.delete', 'Delete'), text: deletedName });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Delete playlist error:', err);
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-exclamation-circle',
|
||||
iconClass: 'error',
|
||||
title: t('music.error', 'Error'),
|
||||
@@ -641,11 +645,10 @@ const musicView = {
|
||||
async _showEditPlaylistDialog() {
|
||||
if (!this.currentPlaylist) return;
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
return i18n?.t ? i18n.t(key) : fallback || key;
|
||||
};
|
||||
|
||||
if (!window.Modal) return;
|
||||
const newName = await window.Modal.prompt({
|
||||
const newName = await Modal.prompt({
|
||||
title: t('music.edit', 'Edit'),
|
||||
label: t('music.playlist_name', 'Playlist name'),
|
||||
placeholder: t('music.playlist_name', 'Playlist name'),
|
||||
@@ -674,8 +677,8 @@ const musicView = {
|
||||
this._renderPlaylistList();
|
||||
} catch (err) {
|
||||
console.error('Edit playlist error:', err);
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-exclamation-circle',
|
||||
iconClass: 'error',
|
||||
title: t('music.error', 'Error'),
|
||||
@@ -688,11 +691,10 @@ const musicView = {
|
||||
async _showSharePlaylistDialog() {
|
||||
if (!this.currentPlaylist) return;
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
return i18n?.t ? i18n.t(key) : fallback || key;
|
||||
};
|
||||
|
||||
if (!window.Modal) return;
|
||||
const userId = await window.Modal.prompt({
|
||||
const userId = await Modal.prompt({
|
||||
title: t('music.share', 'Share'),
|
||||
label: t('music.share_with_user', 'User ID or email'),
|
||||
placeholder: t('music.share_with_user', 'User ID or email'),
|
||||
@@ -711,8 +713,8 @@ const musicView = {
|
||||
|
||||
if (!resp.ok) throw new Error('Failed to share playlist');
|
||||
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-check-circle',
|
||||
iconClass: 'upload',
|
||||
title: t('music.share', 'Share'),
|
||||
@@ -721,8 +723,8 @@ const musicView = {
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Share playlist error:', err);
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-exclamation-circle',
|
||||
iconClass: 'error',
|
||||
title: t('music.error', 'Error'),
|
||||
@@ -735,7 +737,7 @@ const musicView = {
|
||||
async _showAddTracksDialog() {
|
||||
if (!this.currentPlaylist) return;
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
return i18n?.t ? i18n.t(key) : fallback || key;
|
||||
};
|
||||
|
||||
// ── Build modal overlay ──
|
||||
@@ -813,7 +815,7 @@ const musicView = {
|
||||
for (const file of files) {
|
||||
const row = document.createElement('label');
|
||||
row.className = `music-picker-item${selectedIds.has(file.id) ? ' selected' : ''}`;
|
||||
const sizeStr = file.size != null && window.formatFileSize ? window.formatFileSize(file.size) : '';
|
||||
const sizeStr = file.size != null && formatFileSize ? formatFileSize(file.size) : '';
|
||||
row.innerHTML = `
|
||||
<input type="checkbox" value="${file.id}" ${selectedIds.has(file.id) ? 'checked' : ''}>
|
||||
<i class="fas fa-file-audio"></i>
|
||||
@@ -858,8 +860,8 @@ const musicView = {
|
||||
});
|
||||
if (!resp.ok) throw new Error('Failed to add tracks');
|
||||
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-check-circle',
|
||||
iconClass: 'upload',
|
||||
title: t('music.add_tracks', 'Add Tracks'),
|
||||
@@ -878,8 +880,8 @@ const musicView = {
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Add tracks error:', err);
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-exclamation-circle',
|
||||
iconClass: 'error',
|
||||
title: t('music.error', 'Error'),
|
||||
@@ -898,7 +900,7 @@ const musicView = {
|
||||
|
||||
async _removeTrackFromPlaylist(_trackId, fileId) {
|
||||
if (!this.currentPlaylist) return;
|
||||
const t = (key, fallback = '') => (typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key);
|
||||
const t = (key, fallback = '') => (i18n?.t ? i18n.t(key) : fallback || key);
|
||||
|
||||
try {
|
||||
const resp = await fetch(`/api/playlists/${this.currentPlaylist.id}/tracks/${encodeURIComponent(fileId)}`, {
|
||||
@@ -908,8 +910,8 @@ const musicView = {
|
||||
});
|
||||
if (!resp.ok) throw new Error('Failed to remove track');
|
||||
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-check-circle',
|
||||
iconClass: 'upload',
|
||||
title: t('music.remove', 'Remove'),
|
||||
@@ -927,8 +929,8 @@ const musicView = {
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Remove track error:', err);
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-exclamation-circle',
|
||||
iconClass: 'error',
|
||||
title: t('music.error', 'Error'),
|
||||
@@ -940,7 +942,7 @@ const musicView = {
|
||||
|
||||
async _reorderTrack(fromIdx, toIdx) {
|
||||
if (!this.currentPlaylist) return;
|
||||
const t = (key, fallback = '') => (typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key);
|
||||
const t = (key, fallback = '') => (i18n?.t ? i18n.t(key) : fallback || key);
|
||||
|
||||
const tracks = [...this.currentTracks];
|
||||
const [moved] = tracks.splice(fromIdx, 1);
|
||||
@@ -959,8 +961,8 @@ const musicView = {
|
||||
if (!resp.ok) throw new Error('Failed to reorder tracks');
|
||||
} catch (err) {
|
||||
console.error('Reorder error:', err);
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-exclamation-circle',
|
||||
iconClass: 'error',
|
||||
title: t('music.error', 'Error'),
|
||||
@@ -973,7 +975,7 @@ const musicView = {
|
||||
|
||||
async _showManageSharesDialog() {
|
||||
if (!this.currentPlaylist) return;
|
||||
const t = (key, fallback = '') => (typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key);
|
||||
const t = (key, fallback = '') => (i18n?.t ? i18n.t(key) : fallback || key);
|
||||
|
||||
const existing = document.getElementById('music-shares-dialog');
|
||||
if (existing) existing.remove();
|
||||
@@ -1025,8 +1027,8 @@ const musicView = {
|
||||
userInput.value = '';
|
||||
writeInput.checked = false;
|
||||
this._loadSharesList(dialog);
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-check-circle',
|
||||
iconClass: 'upload',
|
||||
title: t('music.share', 'Share'),
|
||||
@@ -1034,8 +1036,8 @@ const musicView = {
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-exclamation-circle',
|
||||
iconClass: 'error',
|
||||
title: t('music.error', 'Error'),
|
||||
@@ -1050,7 +1052,7 @@ const musicView = {
|
||||
|
||||
async _loadSharesList(dialog) {
|
||||
if (!this.currentPlaylist) return;
|
||||
const t = (key, fallback = '') => (typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key);
|
||||
const t = (key, fallback = '') => (i18n?.t ? i18n.t(key) : fallback || key);
|
||||
const body = dialog.querySelector('.music-shares-body');
|
||||
if (!body) return;
|
||||
|
||||
@@ -1095,7 +1097,7 @@ const musicView = {
|
||||
|
||||
async _removeShare(userId, dialog) {
|
||||
if (!this.currentPlaylist) return;
|
||||
const t = (key, fallback = '') => (typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key);
|
||||
const t = (key, fallback = '') => (i18n?.t ? i18n.t(key) : fallback || key);
|
||||
|
||||
try {
|
||||
const resp = await fetch(`/api/playlists/${this.currentPlaylist.id}/share/${encodeURIComponent(userId)}`, {
|
||||
@@ -1106,8 +1108,8 @@ const musicView = {
|
||||
if (!resp.ok) throw new Error('Failed to remove share');
|
||||
this._loadSharesList(dialog);
|
||||
} catch (err) {
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-exclamation-circle',
|
||||
iconClass: 'error',
|
||||
title: t('music.error', 'Error'),
|
||||
@@ -1119,7 +1121,7 @@ const musicView = {
|
||||
|
||||
async _togglePublic() {
|
||||
if (!this.currentPlaylist) return;
|
||||
const t = (key, fallback = '') => (typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key);
|
||||
const t = (key, fallback = '') => (i18n?.t ? i18n.t(key) : fallback || key);
|
||||
const newValue = !this.currentPlaylist.is_public;
|
||||
|
||||
try {
|
||||
@@ -1144,9 +1146,9 @@ const musicView = {
|
||||
btn.classList.toggle('active', newValue);
|
||||
}
|
||||
|
||||
if (window.notifications) {
|
||||
if (notifications) {
|
||||
const status = newValue ? t('music.public', 'Public') : t('music.private', 'Private');
|
||||
window.notifications.addNotification({
|
||||
notifications.addNotification({
|
||||
icon: 'fa-check-circle',
|
||||
iconClass: 'upload',
|
||||
title: t('music.toggle_public', 'Visibility'),
|
||||
@@ -1155,8 +1157,8 @@ const musicView = {
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Toggle public error:', err);
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-exclamation-circle',
|
||||
iconClass: 'error',
|
||||
title: t('music.error', 'Error'),
|
||||
@@ -1168,7 +1170,7 @@ const musicView = {
|
||||
|
||||
async _showCoverPicker() {
|
||||
if (!this.currentPlaylist) return;
|
||||
const t = (key, fallback = '') => (typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key);
|
||||
const t = (key, fallback = '') => (i18n?.t ? i18n.t(key) : fallback || key);
|
||||
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
@@ -1184,13 +1186,13 @@ const musicView = {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
const folderId = window.app?.currentPath || window.app?.userHomeFolderId || '';
|
||||
const folderId = app?.currentPath || app?.userHomeFolderId || '';
|
||||
formData.append('folder_id', folderId);
|
||||
|
||||
const uploadResp = await fetch('/api/files/upload', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: typeof getCsrfHeaders === 'function' ? getCsrfHeaders() : {},
|
||||
headers: getCsrfHeaders(),
|
||||
body: formData
|
||||
});
|
||||
if (!uploadResp.ok) throw new Error('Upload failed');
|
||||
@@ -1214,8 +1216,8 @@ const musicView = {
|
||||
coverEl.innerHTML = `<img src="/api/files/${encodeURIComponent(uploaded.id)}" alt="" class="music-cover-img"><div class="music-cover-overlay"><i class="fas fa-camera"></i></div>`;
|
||||
}
|
||||
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-check-circle',
|
||||
iconClass: 'upload',
|
||||
title: t('music.set_cover', 'Set cover'),
|
||||
@@ -1224,8 +1226,8 @@ const musicView = {
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Cover upload error:', err);
|
||||
if (window.notifications) {
|
||||
window.notifications.addNotification({
|
||||
if (notifications) {
|
||||
notifications.addNotification({
|
||||
icon: 'fa-exclamation-circle',
|
||||
iconClass: 'error',
|
||||
title: t('music.error', 'Error'),
|
||||
@@ -1647,11 +1649,11 @@ const musicPlayer = {
|
||||
this.isPlaying = false;
|
||||
this._updateUI();
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
return i18n?.t ? i18n.t(key) : fallback || key;
|
||||
};
|
||||
if (window.notifications) {
|
||||
if (notifications) {
|
||||
const trackName = this.currentTrack?.title || this.currentTrack?.file_name || t('music.unknown_title', 'Unknown');
|
||||
window.notifications.addNotification({
|
||||
notifications.addNotification({
|
||||
icon: 'fa-exclamation-circle',
|
||||
iconClass: 'error',
|
||||
title: t('music.error', 'Error'),
|
||||
@@ -1670,8 +1672,8 @@ const musicPlayer = {
|
||||
if (icon) {
|
||||
const iconName = this.isPlaying ? 'pause' : 'play';
|
||||
const extraClass = 'player-btn-main';
|
||||
if (window.oxiIcon) {
|
||||
icon.outerHTML = window.oxiIcon(iconName, extraClass);
|
||||
if (oxiIcon) {
|
||||
icon.outerHTML = oxiIcon(iconName, extraClass);
|
||||
} else {
|
||||
icon.className = `fas fa-${iconName} ${extraClass}`;
|
||||
}
|
||||
@@ -1680,7 +1682,7 @@ const musicPlayer = {
|
||||
|
||||
if (trackName) {
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
return i18n?.t ? i18n.t(key) : fallback || key;
|
||||
};
|
||||
trackName.textContent = this.currentTrack
|
||||
? this.currentTrack.title || this.currentTrack.file_name || t('music.unknown_title', 'Unknown')
|
||||
@@ -1704,8 +1706,8 @@ const musicPlayer = {
|
||||
if (playIcon) playIcon.classList.remove('hidden');
|
||||
if (playIcon) {
|
||||
const iconName = this.isPlaying ? 'pause' : 'play';
|
||||
if (window.oxiIcon) {
|
||||
playIcon.outerHTML = window.oxiIcon(iconName, 'track-play-icon');
|
||||
if (oxiIcon) {
|
||||
playIcon.outerHTML = oxiIcon(iconName, 'track-play-icon');
|
||||
} else {
|
||||
playIcon.className = `fas fa-${iconName} track-play-icon`;
|
||||
}
|
||||
@@ -1735,7 +1737,7 @@ const musicPlayer = {
|
||||
if (!queueList) return;
|
||||
|
||||
const t = (key, fallback = '') => {
|
||||
return typeof i18n !== 'undefined' && i18n.t ? i18n.t(key) : fallback || key;
|
||||
return i18n?.t ? i18n.t(key) : fallback || key;
|
||||
};
|
||||
|
||||
if (this.queue.length === 0) {
|
||||
@@ -1838,4 +1840,4 @@ const musicPlayer = {
|
||||
}
|
||||
};
|
||||
|
||||
window.musicView = musicView;
|
||||
export { musicView };
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
* Photo grid grouped by day/month/year, with infinite scroll and multi-select.
|
||||
*/
|
||||
|
||||
import { getCsrfHeaders } from '../../core/csrf.js';
|
||||
import { i18n } from '../../core/i18n.js';
|
||||
import { photosLightbox } from './photosLightbox.js';
|
||||
|
||||
const photosView = {
|
||||
/** @type {Array} All loaded photo items */
|
||||
items: [],
|
||||
@@ -37,7 +41,7 @@ const photosView = {
|
||||
|
||||
/** Auth headers (HttpOnly cookies) */
|
||||
_headers(json = false) {
|
||||
const h = typeof getCsrfHeaders === 'function' ? { ...getCsrfHeaders() } : {};
|
||||
const h = getCsrfHeaders();
|
||||
if (json) h['Content-Type'] = 'application/json';
|
||||
return h;
|
||||
},
|
||||
@@ -406,7 +410,7 @@ const photosView = {
|
||||
|
||||
/** Render the group mode toolbar */
|
||||
_renderToolbar() {
|
||||
const t = (k, d) => (window.i18n ? window.i18n.t(k) : d);
|
||||
const t = (k, d) => (i18n ? i18n.t(k) : d);
|
||||
const modes = [
|
||||
['daily', t('photos.view_daily', 'Day')],
|
||||
['monthly', t('photos.view_monthly', 'Month')],
|
||||
@@ -423,7 +427,7 @@ const photosView = {
|
||||
|
||||
/** Render empty state */
|
||||
_renderEmpty() {
|
||||
const t = (k, d) => (window.i18n ? window.i18n.t(k) : d);
|
||||
const t = (k, d) => (i18n ? i18n.t(k) : d);
|
||||
this._container.innerHTML = `
|
||||
<div class="photos-empty">
|
||||
<i class="fas fa-images"></i>
|
||||
@@ -483,8 +487,8 @@ const photosView = {
|
||||
|
||||
// Otherwise open lightbox
|
||||
const idx = this.items.findIndex((f) => f.id === id);
|
||||
if (idx >= 0 && window.photosLightbox) {
|
||||
window.photosLightbox.open(this.items, idx);
|
||||
if (idx >= 0) {
|
||||
photosLightbox.open(this.items, idx);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -516,7 +520,7 @@ const photosView = {
|
||||
document.body.appendChild(bar);
|
||||
}
|
||||
|
||||
const t = (k, d) => (window.i18n ? window.i18n.t(k) : d);
|
||||
const t = (k, d) => (i18n ? i18n.t(k) : d);
|
||||
const count = this.selected.size;
|
||||
bar.innerHTML = `
|
||||
<span class="selection-count">${count} ${t('photos.items_selected', 'selected')}</span>
|
||||
@@ -605,4 +609,6 @@ const photosView = {
|
||||
}
|
||||
};
|
||||
|
||||
window.photosView = photosView;
|
||||
photosLightbox.setPhotosView(photosView);
|
||||
|
||||
export { photosView };
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
* Full-screen image/video viewer with prev/next navigation.
|
||||
*/
|
||||
|
||||
const photosLightbox = {
|
||||
import { getCsrfHeaders } from '../../core/csrf.js';
|
||||
import { favorites } from '../library/favorites.js';
|
||||
|
||||
export const photosLightbox = {
|
||||
/** @type {Array} Items array reference */
|
||||
items: [],
|
||||
/** @type {number} Current index */
|
||||
@@ -14,10 +17,20 @@ const photosLightbox = {
|
||||
_blobUrl: null,
|
||||
/** @type {Function|null} */
|
||||
_keyHandler: null,
|
||||
/** @type {Object|null} Reference to photosView, set after both modules load */
|
||||
_photosView: null,
|
||||
|
||||
/**
|
||||
* Register the photosView reference (called from photos.js to avoid circular imports).
|
||||
* @param {Object} pv
|
||||
*/
|
||||
setPhotosView(pv) {
|
||||
this._photosView = pv;
|
||||
},
|
||||
|
||||
/** Auth headers */
|
||||
_headers() {
|
||||
return typeof getCsrfHeaders === 'function' ? { ...getCsrfHeaders() } : {};
|
||||
return getCsrfHeaders();
|
||||
},
|
||||
|
||||
/** Open lightbox at given index */
|
||||
@@ -202,7 +215,7 @@ const photosLightbox = {
|
||||
/** Toggle favorite on current item */
|
||||
async _toggleFavorite() {
|
||||
const item = this.items[this.index];
|
||||
if (!item || !window.favorites) return;
|
||||
if (!item || !favorites) return;
|
||||
try {
|
||||
await fetch(`/api/favorites/file/${item.id}`, {
|
||||
method: 'POST',
|
||||
@@ -235,17 +248,17 @@ const photosLightbox = {
|
||||
headers: this._headers()
|
||||
});
|
||||
// Remove from photosView items too
|
||||
if (window.photosView) {
|
||||
window.photosView.items = window.photosView.items.filter((f) => f.id !== item.id);
|
||||
if (this._photosView) {
|
||||
this._photosView.items = this._photosView.items.filter((f) => f.id !== item.id);
|
||||
}
|
||||
this.items.splice(this.index, 1);
|
||||
if (this.items.length === 0) {
|
||||
this.close();
|
||||
if (window.photosView) window.photosView._render();
|
||||
if (this._photosView) this._photosView._render();
|
||||
} else {
|
||||
if (this.index >= this.items.length) this.index = this.items.length - 1;
|
||||
this._show();
|
||||
if (window.photosView) window.photosView._render();
|
||||
if (this._photosView) this._photosView._render();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Delete failed:', err);
|
||||
@@ -282,5 +295,3 @@ const photosLightbox = {
|
||||
.replace(/</g, '<');
|
||||
}
|
||||
};
|
||||
|
||||
window.photosLightbox = photosLightbox;
|
||||
|
||||
@@ -6,6 +6,11 @@
|
||||
* No localStorage usage — the server persists and prunes recent items.
|
||||
*/
|
||||
|
||||
import { ui } from '../../app/ui.js';
|
||||
import { getCsrfHeaders } from '../../core/csrf.js';
|
||||
import { i18n } from '../../core/i18n.js';
|
||||
import { multiSelect } from '../files/multiSelect.js';
|
||||
|
||||
const recent = {
|
||||
/** Maximum items to request from the server */
|
||||
MAX_RECENT_FILES: 20,
|
||||
@@ -86,7 +91,7 @@ const recent = {
|
||||
|
||||
const recentItems = await response.json();
|
||||
|
||||
window.ui.resetFilesList(); // ensure also list visible & error hidden
|
||||
ui.resetFilesList(); // ensure also list visible & error hidden
|
||||
const filesList = document.getElementById('files-list');
|
||||
|
||||
filesList.innerHTML = `
|
||||
@@ -100,17 +105,17 @@ const recent = {
|
||||
</div>
|
||||
`;
|
||||
|
||||
if (window.multiSelect) {
|
||||
window.multiSelect.clear();
|
||||
window.multiSelect.init(); // this will wire buttons & select-all-checkbox
|
||||
if (multiSelect) {
|
||||
multiSelect.clear();
|
||||
multiSelect.init(); // this will wire buttons & select-all-checkbox
|
||||
}
|
||||
window.ui.updateBreadcrumb('');
|
||||
ui.updateBreadcrumb('');
|
||||
|
||||
if (recentItems.length === 0) {
|
||||
window.ui.showError(`
|
||||
ui.showError(`
|
||||
<i class="fas fa-clock empty-state-icon"></i>
|
||||
<p>${window.i18n ? window.i18n.t('recent.empty_state') : 'No recent files'}</p>
|
||||
<p>${window.i18n ? window.i18n.t('recent.empty_hint') : 'Files you open will appear here'}</p>
|
||||
<p>${i18n ? i18n.t('recent.empty_state') : 'No recent files'}</p>
|
||||
<p>${i18n ? i18n.t('recent.empty_hint') : 'Files you open will appear here'}</p>
|
||||
`);
|
||||
}
|
||||
|
||||
@@ -140,16 +145,15 @@ const recent = {
|
||||
});
|
||||
}
|
||||
}
|
||||
if (folders.length) window.ui.renderFolders(folders);
|
||||
if (files.length) window.ui.renderFiles(files);
|
||||
if (folders.length) ui.renderFolders(folders);
|
||||
if (files.length) ui.renderFiles(files);
|
||||
} catch (error) {
|
||||
console.error('Error displaying recent files:', error);
|
||||
if (window.ui?.showNotification) {
|
||||
window.ui.showNotification('Error', 'Error loading recent files');
|
||||
if (ui?.showNotification) {
|
||||
ui.showNotification('Error', 'Error loading recent files');
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Expose globally
|
||||
window.recent = recent;
|
||||
export { recent };
|
||||
|
||||
@@ -4,6 +4,11 @@
|
||||
* No localStorage is used for share data.
|
||||
*/
|
||||
|
||||
import { switchToSharedSection } from '../../app/navigation.js';
|
||||
import { ui } from '../../app/ui.js';
|
||||
import { getCsrfHeaders } from '../../core/csrf.js';
|
||||
import { formatDateTime } from '../../core/formatters.js';
|
||||
|
||||
const fileSharing = {
|
||||
/** Auth header helper — tokens are in HttpOnly cookies now */
|
||||
_headers(json = true) {
|
||||
@@ -149,11 +154,11 @@ const fileSharing = {
|
||||
async copyLinkToClipboard(url) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
window.ui.showNotification('Link copied', 'Link copied to clipboard');
|
||||
ui.showNotification('Link copied', 'Link copied to clipboard');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error copying to clipboard:', error);
|
||||
window.ui.showNotification('Error', 'Could not copy link');
|
||||
ui.showNotification('Error', 'Could not copy link');
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -165,7 +170,7 @@ const fileSharing = {
|
||||
*/
|
||||
formatExpirationDate(value) {
|
||||
if (!value) return 'No expiration';
|
||||
return window.formatDateTime(value);
|
||||
return formatDateTime(value);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -178,9 +183,7 @@ const fileSharing = {
|
||||
async sendShareNotification(shareUrl, recipientEmail, _message = '') {
|
||||
// TODO: implement backend endpoint for email notifications
|
||||
console.log(`Share notification for ${shareUrl} sent to ${recipientEmail}`);
|
||||
if (window.ui) {
|
||||
window.ui.showNotification('Notification sent', `Notification sent to ${recipientEmail}`);
|
||||
}
|
||||
ui.showNotification('Notification sent', `Notification sent to ${recipientEmail}`);
|
||||
return true;
|
||||
},
|
||||
|
||||
@@ -193,20 +196,11 @@ const fileSharing = {
|
||||
const span = item.querySelector('span');
|
||||
if (span && span.getAttribute('data-i18n') === 'nav.shared') {
|
||||
item.addEventListener('click', () => {
|
||||
if (window.switchToSharedSection) {
|
||||
window.switchToSharedSection();
|
||||
}
|
||||
switchToSharedSection();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Expose module globally
|
||||
window.fileSharing = fileSharing;
|
||||
|
||||
// Global convenience functions that delegate to the module
|
||||
window.getSharedLinks = () => fileSharing.getSharedLinks();
|
||||
window.updateSharedLink = (id, data) => fileSharing.updateSharedLink(id, data);
|
||||
window.removeSharedLink = (id) => fileSharing.removeSharedLink(id);
|
||||
window.sendShareNotification = (url, email, msg) => fileSharing.sendShareNotification(url, email, msg);
|
||||
export { fileSharing };
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import { getCsrfHeaders } from '../../core/csrf.js';
|
||||
import { escapeHtml } from '../../core/formatters.js';
|
||||
import { i18n } from '../../core/i18n.js';
|
||||
|
||||
const API = '/api';
|
||||
let currentAdminId = '';
|
||||
let usersPage = 0;
|
||||
@@ -6,7 +10,7 @@ let totalUsers = 0;
|
||||
|
||||
/* ── i18n helper — falls back to key if i18n not ready ── */
|
||||
function t(key, params) {
|
||||
if (window.i18n && typeof window.i18n.t === 'function') return window.i18n.t(key, params);
|
||||
if (i18n && typeof i18n.t === 'function') return i18n.t(key, params);
|
||||
// fallback: strip prefix and humanise
|
||||
return key.split('.').pop().replace(/_/g, ' ');
|
||||
}
|
||||
@@ -748,13 +752,13 @@ function showAccessDenied() {
|
||||
|
||||
/* ── Apply i18n when translations load / change ── */
|
||||
document.addEventListener('translationsLoaded', () => {
|
||||
if (window.i18n?.translatePage) window.i18n.translatePage();
|
||||
if (i18n?.translatePage) i18n.translatePage();
|
||||
// Re-render dynamic content that uses t()
|
||||
loadDashboard();
|
||||
if (activeTabName === 'users') loadUsers();
|
||||
});
|
||||
document.addEventListener('localeChanged', () => {
|
||||
if (window.i18n?.translatePage) window.i18n.translatePage();
|
||||
if (i18n?.translatePage) i18n.translatePage();
|
||||
loadDashboard();
|
||||
if (activeTabName === 'users') loadUsers();
|
||||
});
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
// device-verify.js — Extracted from inline <script> in device-verify.html
|
||||
import { getCsrfHeaders } from '../../core/csrf.js';
|
||||
|
||||
(() => {
|
||||
var API_BASE = window.location.origin;
|
||||
var codeInput = document.getElementById('user-code');
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { getCsrfHeaders } from '../../core/csrf.js';
|
||||
import { i18n } from '../../core/i18n.js';
|
||||
|
||||
const API = '/api';
|
||||
|
||||
/* ── i18n helper — falls back to key if i18n not ready ── */
|
||||
function t(key, params) {
|
||||
if (window.i18n && typeof window.i18n.t === 'function') return window.i18n.t(key, params);
|
||||
if (i18n && typeof i18n.t === 'function') return i18n.t(key, params);
|
||||
return key.split('.').pop().replace(/_/g, ' ');
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,13 @@
|
||||
* In-app shared files view. All operations go through the backend API.
|
||||
*/
|
||||
|
||||
import { switchToFilesSection } from '../../app/navigation.js';
|
||||
import { ui } from '../../app/ui.js';
|
||||
import { getCsrfHeaders } from '../../core/csrf.js';
|
||||
import { formatDateShort } from '../../core/formatters.js';
|
||||
import { i18n } from '../../core/i18n.js';
|
||||
import { fileSharing } from '../../features/sharing/fileSharing.js';
|
||||
|
||||
const sharedView = {
|
||||
// State
|
||||
items: [],
|
||||
@@ -181,8 +188,8 @@ const sharedView = {
|
||||
</div>
|
||||
`;
|
||||
|
||||
if (window.i18n?.translateElement) {
|
||||
window.i18n.translateElement(container);
|
||||
if (i18n?.translateElement) {
|
||||
i18n.translateElement(container);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -246,7 +253,7 @@ const sharedView = {
|
||||
const goToFilesBtn = document.getElementById('go-to-files-btn');
|
||||
if (goToFilesBtn) {
|
||||
goToFilesBtn.addEventListener('click', () => {
|
||||
if (window.switchToFilesSection) window.switchToFilesSection();
|
||||
if (switchToFilesSection) switchToFilesSection();
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -590,8 +597,8 @@ const sharedView = {
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.fileSharing?.sendShareNotification) {
|
||||
window.fileSharing
|
||||
if (fileSharing?.sendShareNotification) {
|
||||
fileSharing
|
||||
.sendShareNotification(this.currentItem.url, email, message)
|
||||
.then(() => {
|
||||
this.closeNotificationDialog();
|
||||
@@ -602,8 +609,8 @@ const sharedView = {
|
||||
},
|
||||
|
||||
showNotification(message, type = 'success') {
|
||||
if (window.ui?.showNotification) {
|
||||
window.ui.showNotification(message, type);
|
||||
if (ui?.showNotification) {
|
||||
ui.showNotification(message, type);
|
||||
} else {
|
||||
alert(message);
|
||||
}
|
||||
@@ -614,13 +621,13 @@ const sharedView = {
|
||||
},
|
||||
|
||||
formatDate(value) {
|
||||
return window.formatDateShort ? window.formatDateShort(value) : String(value);
|
||||
return formatDateShort(value);
|
||||
},
|
||||
|
||||
translate(key, defaultText) {
|
||||
if (window.i18n?.t) return window.i18n.t(key, defaultText);
|
||||
if (i18n?.t) return i18n.t(key, defaultText);
|
||||
return defaultText;
|
||||
}
|
||||
};
|
||||
|
||||
window.sharedView = sharedView;
|
||||
export { sharedView };
|
||||
|
||||
+1
-4
@@ -12,10 +12,7 @@
|
||||
<link rel="stylesheet" href="/css/views/auth.css">
|
||||
|
||||
<!-- Scripts -->
|
||||
<script src="/js/core/i18n.js"></script>
|
||||
<script src="/js/core/csrf.js"></script>
|
||||
<script src="/js/core/icons.js" defer></script>
|
||||
<script src="/js/features/auth/auth.js" defer></script>
|
||||
<script type="module" src="/js/features/auth/auth.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="auth-container">
|
||||
|
||||
+1
-4
@@ -5,9 +5,6 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>OxiCloud — My Profile</title>
|
||||
<script src="/js/core/theme-init.js"></script>
|
||||
<script src="/js/core/i18n.js" defer></script>
|
||||
<script src="/js/core/icons.js" defer></script>
|
||||
<script src="/js/core/csrf.js" defer></script>
|
||||
<link rel="stylesheet" href="/css/main.css">
|
||||
<link rel="stylesheet" href="/css/views/profile.css">
|
||||
</head>
|
||||
@@ -164,6 +161,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/js/views/profile/profile.js" defer></script>
|
||||
<script type="module" src="/js/views/profile/profile.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+20
-7
@@ -1,12 +1,14 @@
|
||||
// OxiCloud Service Worker
|
||||
const CACHE_NAME = 'oxicloud-cache-v16';
|
||||
const CACHE_NAME = 'oxicloud-cache-v17';
|
||||
|
||||
// Only cache static assets — NOT HTML files.
|
||||
// HTML files are served network-first so browsers always get the latest
|
||||
// script/link references. Caching HTML causes stale entry points.
|
||||
const ASSETS_TO_CACHE = [
|
||||
'/',
|
||||
'/index.html',
|
||||
'/js/icons.js',
|
||||
'/js/i18n.js',
|
||||
'/js/languageSelector.js',
|
||||
'/js/notifications.js',
|
||||
'/js/core/icons.js',
|
||||
'/js/core/i18n.js',
|
||||
'/js/core/languageSelector.js',
|
||||
'/js/core/notifications.js',
|
||||
'/locales/en.json',
|
||||
'/locales/es.json',
|
||||
'/locales/fa.json',
|
||||
@@ -15,6 +17,9 @@ const ASSETS_TO_CACHE = [
|
||||
'/favicon.ico'
|
||||
];
|
||||
|
||||
// HTML paths that should always be fetched from the network
|
||||
const HTML_PATHS = ['/', '/index.html', '/login', '/login.html', '/admin', '/admin.html', '/profile', '/profile.html'];
|
||||
|
||||
// Install event - cache assets
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(
|
||||
@@ -55,6 +60,14 @@ self.addEventListener('fetch', (event) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// HTML pages: always network-first so entry points are never stale
|
||||
const pathname = new URL(event.request.url).pathname;
|
||||
const isHtml = HTML_PATHS.includes(pathname) || pathname.endsWith('.html') || event.request.headers.get('accept')?.includes('text/html');
|
||||
if (isHtml) {
|
||||
event.respondWith(fetch(event.request).catch(() => caches.match(event.request)));
|
||||
return;
|
||||
}
|
||||
|
||||
event.respondWith(
|
||||
caches.match(event.request).then((response) => {
|
||||
// Cache hit - return the response from the cached version
|
||||
|
||||
Reference in New Issue
Block a user