Merge pull request #2017 from maxberger/master

Implement Share by map, improve share by token, added test action for javascript errors.
This commit is contained in:
Peter Bieringer
2026-03-08 07:15:46 +01:00
committed by GitHub
16 changed files with 1335 additions and 792 deletions

View File

@@ -186,6 +186,29 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: coveralls --service=github --finish run: coveralls --service=github --finish
js-test:
name: JS Type Check
runs-on: ubuntu-latest
needs: test-ubuntu-python-newest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
- name: JS Type Check
run: |
set -o pipefail
npx -p typescript tsc -p radicale/web/jsconfig.json | npx typescript-xunit-xml > tsc-results.xml
- uses: mikepenz/action-junit-report@v6
if: ${{ failure() && (github.event.pull_request.head.repo.full_name != github.repository) }}
with:
report_paths: 'tsc-results.xml'
annotate_only: true # forked repo cannot write to checks so just do annotations
- uses: mikepenz/action-junit-report@v6
if: ${{ always() && github.event.pull_request.head.repo.full_name == github.repository }}
with:
report_paths: 'tsc-results.xml'
lint: lint:
name: Lint name: Lint
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -220,6 +243,6 @@ jobs:
report_paths: 'pytest-results.xml' report_paths: 'pytest-results.xml'
annotate_only: true # forked repo cannot write to checks so just do annotations annotate_only: true # forked repo cannot write to checks so just do annotations
- uses: mikepenz/action-junit-report@v6 - uses: mikepenz/action-junit-report@v6
if: ${{ github.event.pull_request.head.repo.full_name == github.repository }} if: ${{ always() && github.event.pull_request.head.repo.full_name == github.repository }}
with: with:
report_paths: 'pytest-results.xml' report_paths: 'pytest-results.xml'

View File

@@ -45,6 +45,8 @@ permit_create_map = true
with open(user_path, "w") as f: with open(user_path, "w") as f:
f.write( f.write(
"""admin:adminpassword """admin:adminpassword
max:maxpassword
""" """
) )

View File

@@ -22,7 +22,8 @@ def test_create_and_delete_share_by_key(page: Page, radicale_server: str) -> Non
page.locator("tr[data-name='sharetokenrowtemplate']:not(.hidden)") page.locator("tr[data-name='sharetokenrowtemplate']:not(.hidden)")
).to_have_count(0) ).to_have_count(0)
page.click('button[data-name="sharebytoken_ro"]') page.click('button[data-name="sharebytoken"]')
page.click('#newshare button[data-name="submit"]')
expect( expect(
page.locator("tr[data-name='sharetokenrowtemplate']:not(.hidden)") page.locator("tr[data-name='sharetokenrowtemplate']:not(.hidden)")
).to_have_count(1) ).to_have_count(1)
@@ -34,7 +35,9 @@ def test_create_and_delete_share_by_key(page: Page, radicale_server: str) -> Non
expect( expect(
page.locator("tr[data-name='sharetokenrowtemplate']:not(.hidden)") page.locator("tr[data-name='sharetokenrowtemplate']:not(.hidden)")
).to_have_count(0) ).to_have_count(0)
page.click('button[data-name="sharebytoken_rw"]') page.click('button[data-name="sharebytoken"]')
page.click('label[for="newshare_attr_permissions_rw"]')
page.click('#newshare button[data-name="submit"]')
expect( expect(
page.locator("tr[data-name='sharetokenrowtemplate']:not(.hidden)") page.locator("tr[data-name='sharetokenrowtemplate']:not(.hidden)")
).to_have_count(1) ).to_have_count(1)
@@ -46,3 +49,46 @@ def test_create_and_delete_share_by_key(page: Page, radicale_server: str) -> Non
expect( expect(
page.locator("tr[data-name='sharetokenrowtemplate']:not(.hidden)") page.locator("tr[data-name='sharetokenrowtemplate']:not(.hidden)")
).to_have_count(0) ).to_have_count(0)
def test_create_and_delete_share_by_map(page: Page, radicale_server: str) -> None:
login(page, radicale_server)
create_collection(page, radicale_server)
page.hover("article:not(.hidden)")
page.click('article:not(.hidden) a[data-name="share"]', force=True, strict=True)
expect(
page.locator("tr[data-name='sharemaprowtemplate']:not(.hidden)")
).to_have_count(0)
page.click('button[data-name="sharebymap"]')
page.locator('input[data-name="shareuser"]').fill("max")
page.locator('input[data-name="sharehref"]').fill("1234")
page.click('#newshare button[data-name="submit"]')
expect(
page.locator("tr[data-name='sharemaprowtemplate']:not(.hidden)")
).to_have_count(1)
expect(
page.locator("tr[data-name='sharemaprowtemplate']:not(.hidden) img[alt='RO']")
).to_be_visible()
page.once("dialog", lambda dialog: dialog.accept())
page.click('tr:not(.hidden) button[data-name="delete"]', strict=True)
expect(
page.locator("tr[data-name='sharemaprowtemplate']:not(.hidden)")
).to_have_count(0)
page.click('button[data-name="sharebymap"]')
page.click('label[for="newshare_attr_permissions_rw"]')
page.locator('input[data-name="shareuser"]').fill("max")
page.locator('input[data-name="sharehref"]').fill("1234")
page.click('#newshare button[data-name="submit"]')
expect(
page.locator("tr[data-name='sharemaprowtemplate']:not(.hidden)")
).to_have_count(1)
expect(
page.locator("tr[data-name='sharemaprowtemplate']:not(.hidden) img[alt='RW']")
).to_be_visible()
page.once("dialog", lambda dialog: dialog.accept())
page.click('tr:not(.hidden) button[data-name="delete"]', strict=True)
expect(
page.locator("tr[data-name='sharemaprowtemplate']:not(.hidden)")
).to_have_count(0)

8
radicale/web/README.md Normal file
View File

@@ -0,0 +1,8 @@
# Built-in web UI
If you have tsc installed, you can type-check all JavaScript using
``` lang=shell
tsc -p radicale/web/jsconfig.json --noEmit --pretty
```

View File

@@ -21,7 +21,7 @@
import { CreateEditCollectionScene } from "./CreateEditCollectionScene.js"; import { CreateEditCollectionScene } from "./CreateEditCollectionScene.js";
import { DeleteCollectionScene } from "./DeleteCollectionScene.js"; import { DeleteCollectionScene } from "./DeleteCollectionScene.js";
import { LoadingScene } from "./LoadingScene.js"; import { LoadingScene } from "./LoadingScene.js";
import { CreateShareCollectionScene, maybe_enable_sharing_options } from "./ShareCollectionScene.js"; import { ShareCollectionScene, maybe_enable_sharing_options } from "./ShareCollectionScene.js";
import { UploadCollectionScene } from "./UploadCollectionScene.js"; import { UploadCollectionScene } from "./UploadCollectionScene.js";
import { discover_server_features, get_collections } from "./api.js"; import { discover_server_features, get_collections } from "./api.js";
import { SERVER } from "./constants.js"; import { SERVER } from "./constants.js";
@@ -30,15 +30,16 @@ import { Scene, pop_scene, push_scene, scene_stack } from "./scene_manager.js";
import { bytesToHumanReadable } from "./utils.js"; import { bytesToHumanReadable } from "./utils.js";
/** /**
* @constructor
* @implements {Scene} * @implements {Scene}
*/
export class CollectionsScene {
/**
* @param {string} user * @param {string} user
* @param {string} password * @param {string} password
* @param {Collection} collection The principal collection. * @param {Collection} collection The collection to show sharing options for.
* @param {function(string):void} onerror Called when an error occurs, before the * @param {function(string):void} onerror Called when an error occurs, before the
* scene is popped. * scene is popped.
*/ */
export class CollectionsScene {
constructor(user, password, collection, onerror) { constructor(user, password, collection, onerror) {
/** @type {HTMLElement} */ let html_scene = document.getElementById("collectionsscene"); /** @type {HTMLElement} */ let html_scene = document.getElementById("collectionsscene");
/** @type {HTMLElement} */ let template = html_scene.querySelector("[data-name=collectiontemplate]"); /** @type {HTMLElement} */ let template = html_scene.querySelector("[data-name=collectiontemplate]");
@@ -82,7 +83,7 @@ export class CollectionsScene {
function onshare(collection) { function onshare(collection) {
try { try {
let share_collection_scene = new CreateShareCollectionScene(user, password, collection); let share_collection_scene = new ShareCollectionScene(user, password, collection);
push_scene(share_collection_scene, false); push_scene(share_collection_scene, false);
} catch (err) { } catch (err) {
console.error(err); console.error(err);

View File

@@ -23,35 +23,31 @@ import { create_collection, edit_collection } from "./api.js";
import { COLOR_RE } from "./constants.js"; import { COLOR_RE } from "./constants.js";
import { Collection, CollectionType } from "./models.js"; import { Collection, CollectionType } from "./models.js";
import { Scene, pop_scene, push_scene, scene_stack } from "./scene_manager.js"; import { Scene, pop_scene, push_scene, scene_stack } from "./scene_manager.js";
import { cleanHREFinput, isValidHREF, random_hex, random_uuid } from "./utils.js"; import { cleanHREFinput, isValidHREF, onCleanHREFinput, random_hex, random_uuid } from "./utils.js";
/** /**
* @constructor
* @implements {Scene} * @implements {Scene}
*/
export class CreateEditCollectionScene {
/**
* @param {string} user * @param {string} user
* @param {string} password * @param {string} password
* @param {Collection} collection if it's a principal collection, a new * @param {Collection} collection if it's a principal collection, a new
* collection will be created inside of it. * collection will be created inside of it.
* Otherwise the collection will be edited. * Otherwise the collection will be edited.
*/ */
export class CreateEditCollectionScene {
constructor(user, password, collection) { constructor(user, password, collection) {
let edit = collection.type !== CollectionType.PRINCIPAL; let edit = collection.type !== CollectionType.PRINCIPAL;
let html_scene = document.getElementById(edit ? "editcollectionscene" : "createcollectionscene"); let html_scene = document.getElementById(edit ? "editcollectionscene" : "createcollectionscene");
/** @type {HTMLElement} */ let title_form = edit ? html_scene.querySelector("[data-name=title]") : null; /** @type {HTMLElement} */ let title_form = edit ? html_scene.querySelector("[data-name=title]") : null;
/** @type {HTMLElement} */ let error_form = html_scene.querySelector("[data-name=error]"); /** @type {HTMLElement} */ let error_form = html_scene.querySelector("[data-name=error]");
/** @type {HTMLInputElement} */ let href_form = html_scene.querySelector("[data-name=href]"); /** @type {HTMLInputElement} */ let href_form = html_scene.querySelector("[data-name=href]");
/** @type {HTMLElement} */ let href_label = html_scene.querySelector("label[for=href]");
/** @type {HTMLInputElement} */ let displayname_form = html_scene.querySelector("[data-name=displayname]"); /** @type {HTMLInputElement} */ let displayname_form = html_scene.querySelector("[data-name=displayname]");
/** @type {HTMLElement} */ let displayname_label = html_scene.querySelector("label[for=displayname]");
/** @type {HTMLInputElement} */ let description_form = html_scene.querySelector("[data-name=description]"); /** @type {HTMLInputElement} */ let description_form = html_scene.querySelector("[data-name=description]");
/** @type {HTMLElement} */ let description_label = html_scene.querySelector("label[for=description]");
/** @type {HTMLInputElement} */ let source_form = html_scene.querySelector("[data-name=source]"); /** @type {HTMLInputElement} */ let source_form = html_scene.querySelector("[data-name=source]");
/** @type {HTMLElement} */ let source_label = html_scene.querySelector("label[for=source]"); /** @type {HTMLElement} */ let source_label = html_scene.querySelector("label[for=source]");
/** @type {HTMLSelectElement} */ let type_form = html_scene.querySelector("[data-name=type]"); /** @type {HTMLSelectElement} */ let type_form = html_scene.querySelector("[data-name=type]");
/** @type {HTMLElement} */ let type_label = html_scene.querySelector("label[for=type]");
/** @type {HTMLInputElement} */ let color_form = html_scene.querySelector("[data-name=color]"); /** @type {HTMLInputElement} */ let color_form = html_scene.querySelector("[data-name=color]");
/** @type {HTMLElement} */ let color_label = html_scene.querySelector("label[for=color]");
/** @type {HTMLElement} */ let submit_btn = html_scene.querySelector("[data-name=submit]"); /** @type {HTMLElement} */ let submit_btn = html_scene.querySelector("[data-name=submit]");
/** @type {HTMLElement} */ let cancel_btn = html_scene.querySelector("[data-name=cancel]"); /** @type {HTMLElement} */ let cancel_btn = html_scene.querySelector("[data-name=cancel]");
@@ -69,7 +65,7 @@ export class CreateEditCollectionScene {
let color = edit && collection.color ? collection.color : "#" + random_hex(6); let color = edit && collection.color ? collection.color : "#" + random_hex(6);
if (!edit) { if (!edit) {
href_form.addEventListener("keydown", cleanHREFinput); href_form.addEventListener("input", onCleanHREFinput);
} }
function remove_invalid_types() { function remove_invalid_types() {
@@ -118,7 +114,7 @@ export class CreateEditCollectionScene {
error_form.classList.remove("hidden"); error_form.classList.remove("hidden");
} }
error_form.classList.add("hidden"); error_form.classList.add("hidden");
onTypeChange(); onTypeChange(null);
type_form.addEventListener("change", onTypeChange); type_form.addEventListener("change", onTypeChange);
} }
@@ -172,8 +168,10 @@ export class CreateEditCollectionScene {
return false; return false;
} }
/**
function onTypeChange(e) { * @param {Event} _e
*/
function onTypeChange(_e) {
if (type_form.value == CollectionType.WEBCAL) { if (type_form.value == CollectionType.WEBCAL) {
source_label.classList.remove("hidden"); source_label.classList.remove("hidden");
source_form.classList.remove("hidden"); source_form.classList.remove("hidden");

View File

@@ -21,10 +21,10 @@
import { Scene } from "./scene_manager.js"; import { Scene } from "./scene_manager.js";
/** /**
* @constructor
* @implements {Scene} * @implements {Scene}
*/ */
export function LoadingScene() { export class LoadingScene {
constructor() {
let html_scene = document.getElementById("loadingscene"); let html_scene = document.getElementById("loadingscene");
this.show = function () { this.show = function () {
html_scene.classList.remove("hidden"); html_scene.classList.remove("hidden");
@@ -34,3 +34,4 @@ export function LoadingScene() {
}; };
this.release = function () { }; this.release = function () { };
} }
}

View File

@@ -0,0 +1,124 @@
/**
* This file is part of Radicale Server - Calendar Server
* Copyright © 2017-2024 Unrud <unrud@outlook.com>
* Copyright © 2023-2024 Matthew Hana <matthew.hana@gmail.com>
* Copyright © 2024-2025 Peter Bieringer <pb@bieringer.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { add_share_by_map, add_share_by_token } from "./api.js";
import { Scene, pop_scene, scene_stack } from "./scene_manager.js";
import { onCleanHREFinput } from "./utils.js";
/**
* @implements {Scene}
*/
export class NewShareScene {
/**
* @param {string} user
* @param {string} password
* @param {string} pathMapped
* @param {string} shareType
* @param {function():void} onclose
*/
constructor(user, password, pathMapped, shareType, onclose) {
/** @type {HTMLElement} */ let html_scene = document.getElementById("newshare");
/** @type {HTMLFormElement} */ let form = html_scene.querySelector("form");
/** @type {HTMLElement} */ let sharemapfields = html_scene.querySelector("[data-name=sharemapfields]");
/** @type {HTMLInputElement} */ let shareuser_input = html_scene.querySelector("[data-name=shareuser]");
/** @type {HTMLInputElement} */ let sharehref_input = html_scene.querySelector("[data-name=sharehref]");
/** @type {HTMLInputElement} */ let enabled_checkbox = html_scene.querySelector("[data-name=enabled]");
/** @type {HTMLInputElement} */ let hidden_checkbox = html_scene.querySelector("[data-name=hidden]");
let permissions_ro_radio = /** @type {HTMLInputElement} */ (document.getElementById("newshare_attr_permissions_ro"));
let permissions_rw_radio = /** @type {HTMLInputElement} */ (document.getElementById("newshare_attr_permissions_rw"));
/** @type {HTMLInputElement} */ let properties_input = html_scene.querySelector("[data-name=properties]");
/** @type {HTMLElement} */ let cancel_btn = html_scene.querySelector("[data-name=cancel]");
sharehref_input.addEventListener("input", onCleanHREFinput);
/** @type {?number} */ let scene_index = null;
function oncancel() {
try {
if (scene_index !== null) {
pop_scene(scene_index - 1);
}
if (onclose) onclose();
} catch (err) {
console.error(err);
}
return false;
}
function onsubmit() {
try {
let enabled = enabled_checkbox.checked;
let hidden = hidden_checkbox.checked;
let permissions = permissions_rw_radio.checked ? "rw" : "r";
let properties = properties_input.value;
let callback = function () {
if (scene_index !== null) {
pop_scene(scene_index - 1);
}
if (onclose) onclose();
};
if (shareType === "map") {
let share_user = shareuser_input.value;
let href = sharehref_input.value;
add_share_by_map(user, password, pathMapped, permissions, enabled, hidden, properties, share_user, href, callback);
} else {
add_share_by_token(user, password, pathMapped, permissions, enabled, hidden, properties, callback);
}
} catch (err) {
console.error(err);
}
return false;
}
this.show = function () {
this.release();
scene_index = scene_stack.length - 1;
html_scene.classList.remove("hidden");
cancel_btn.onclick = oncancel;
form.onsubmit = onsubmit;
if (shareType === "map") {
sharemapfields.classList.remove("hidden");
} else {
sharemapfields.classList.add("hidden");
}
shareuser_input.value = "";
sharehref_input.value = "";
enabled_checkbox.checked = true;
hidden_checkbox.checked = false;
permissions_ro_radio.checked = true;
permissions_rw_radio.checked = false;
properties_input.value = "";
};
this.hide = function () {
html_scene.classList.add("hidden");
cancel_btn.onclick = null;
form.onsubmit = null;
};
this.release = function () {
scene_index = null;
};
}
}

View File

@@ -19,32 +19,41 @@
*/ */
import { import {
add_share_by_token, delete_share_by_map,
delete_share_by_token, delete_share_by_token,
reload_sharing_list, reload_sharing_list,
server_features, server_features,
} from "./api.js"; } from "./api.js";
import { Collection } from "./models.js"; import { Collection } from "./models.js";
import { Scene, pop_scene, scene_stack } from "./scene_manager.js"; import { NewShareScene } from "./NewShareScene.js";
import { Scene, pop_scene, push_scene, scene_stack } from "./scene_manager.js";
/** /**
* @implements {Scene} * @implements {Scene}
*/
export class ShareCollectionScene {
/**
* @param {string} user * @param {string} user
* @param {string} password * @param {string} password
* @param {Collection} collection The collection on which to edit sharing setting. Must exist. * @param {Collection} collection The collection on which to edit sharing setting. Must exist.
*/ */
export class CreateShareCollectionScene {
constructor(user, password, collection) { constructor(user, password, collection) {
/** @type {?number} */ let scene_index = null; /** @type {?number} */ let scene_index = null;
let html_scene = document.getElementById("sharecollectionscene"); let html_scene = document.getElementById("sharecollectionscene");
/** @type {HTMLElement} */ let cancel_btn = html_scene.querySelector("[data-name=cancel]"); /** @type {HTMLElement} */ let cancel_btn = html_scene.querySelector("[data-name=cancel]");
/** @type {HTMLElement} */ let share_by_token_btn_ro = html_scene.querySelector( /** @type {HTMLElement} */ let share_by_token_btn = html_scene.querySelector(
"[data-name=sharebytoken_ro]" "button[data-name=sharebytoken]"
); );
/** @type {HTMLElement} */ let share_by_token_btn_rw = html_scene.querySelector( /** @type {HTMLElement} */ let share_by_map_btn = html_scene.querySelector(
"[data-name=sharebytoken_rw]" "button[data-name=sharebymap]"
);
/** @type {HTMLElement} */ let share_by_token_div = html_scene.querySelector(
"div[data-name=sharebytoken]"
);
/** @type {HTMLElement} */ let share_by_map_div = html_scene.querySelector(
"div[data-name=sharebymap]"
); );
/** @type {HTMLElement} */ let title = html_scene.querySelector("[data-name=title]"); /** @type {HTMLElement} */ let title = html_scene.querySelector("[data-name=title]");
@@ -58,16 +67,18 @@ export class CreateShareCollectionScene {
return false; return false;
} }
function onsharebytoken_rw() { function onsharebytoken() {
add_share_by_token(user, password, collection, "rw", function () { let new_share_scene = new NewShareScene(user, password, collection.href, "token", function () {
update_share_list(user, password, collection); update_share_list(user, password, collection);
}); });
push_scene(new_share_scene, false);
} }
function onsharebytoken_ro() { function onsharebymap() {
add_share_by_token(user, password, collection, "r", function () { let new_share_scene = new NewShareScene(user, password, collection.href, "map", function () {
update_share_list(user, password, collection); update_share_list(user, password, collection);
}); });
push_scene(new_share_scene, false);
} }
this.show = function () { this.show = function () {
@@ -75,15 +86,36 @@ export class CreateShareCollectionScene {
scene_index = scene_stack.length - 1; scene_index = scene_stack.length - 1;
html_scene.classList.remove("hidden"); html_scene.classList.remove("hidden");
cancel_btn.onclick = oncancel; cancel_btn.onclick = oncancel;
if (server_features["sharing"]["PermittedCreateCollectionByToken"]) { if (server_features.sharing && server_features.sharing.PermittedCreateCollectionByToken) {
share_by_token_btn_ro.classList.remove("hidden"); if (share_by_token_btn) {
share_by_token_btn_rw.classList.remove("hidden"); share_by_token_btn.classList.remove("hidden");
share_by_token_btn_ro.onclick = onsharebytoken_ro; share_by_token_btn.onclick = onsharebytoken;
share_by_token_btn_rw.onclick = onsharebytoken_rw;
} else {
share_by_token_btn_ro.classList.add("hidden");
share_by_token_btn_rw.classList.add("hidden");
} }
} else {
if (share_by_token_btn) share_by_token_btn.classList.add("hidden");
}
if (server_features.sharing && server_features.sharing.FeatureEnabledCollectionByToken) {
if (share_by_token_div) share_by_token_div.classList.remove("hidden");
} else {
if (share_by_token_div) share_by_token_div.classList.add("hidden");
}
if (server_features.sharing && server_features.sharing.PermittedCreateCollectionByMap) {
if (share_by_map_btn) {
share_by_map_btn.classList.remove("hidden");
share_by_map_btn.onclick = onsharebymap;
}
} else {
if (share_by_map_btn) share_by_map_btn.classList.add("hidden");
}
if (server_features.sharing && server_features.sharing.FeatureEnabledCollectionByMap) {
if (share_by_map_div) share_by_map_div.classList.remove("hidden");
} else {
if (share_by_map_div) share_by_map_div.classList.add("hidden");
}
title.textContent = collection.displayname || collection.href; title.textContent = collection.displayname || collection.href;
update_share_list(user, password, collection); update_share_list(user, password, collection);
}; };
@@ -97,9 +129,14 @@ export class CreateShareCollectionScene {
} }
} }
/**
* @param {string} user
* @param {string} password
* @param {Collection} collection
*/
function update_share_list(user, password, collection) { function update_share_list(user, password, collection) {
let share_rows = document.querySelectorAll( let share_rows = document.querySelectorAll(
"[data-name=sharetokenrowtemplate]", "[data-name=sharetokenrowtemplate], [data-name=sharemaprowtemplate]",
); );
share_rows.forEach(function (row) { share_rows.forEach(function (row) {
if (!row.classList.contains("hidden")) { if (!row.classList.contains("hidden")) {
@@ -107,24 +144,31 @@ function update_share_list(user, password, collection) {
} }
}); });
reload_sharing_list(user, password, collection, function (response) { reload_sharing_list(user, password, collection, function (shares) {
add_share_rows(user, password, collection, response["Content"] || []); add_share_rows(user, password, collection, shares);
}); });
} }
function add_share_rows(user, password, collection, shares) { /**
/** @type {HTMLElement} */ let template = document.querySelector("[data-name=sharetokenrowtemplate]"); *
shares.forEach(function (share) { * @param {string} user
* @param {string} password
* @param {Collection} collection
* @param {import('./api.js').Share} share
* @param {HTMLElement} template
* @param {string} delete_label
* @param {function(string, string, string, function():void):void} delete_action
*/
function add_share_row_node(user, password, collection, share, template, delete_label, delete_action) {
let pathortoken = share["PathOrToken"] || ""; let pathortoken = share["PathOrToken"] || "";
let pathmapped = share["PathMapped"] || "";
if ((
collection.href.includes(pathmapped) ||
collection.href.includes(pathortoken)
) && (share["ShareType"] === "token")) {
let node = /** @type {HTMLElement} */ (template.cloneNode(true)); let node = /** @type {HTMLElement} */ (template.cloneNode(true));
node.classList.remove("hidden"); node.classList.remove("hidden");
/** @type {HTMLInputElement} */ let pathortoken_form = node.querySelector("[data-name=pathortoken]"); /** @type {HTMLInputElement} */ let pathortoken_form = node.querySelector("[data-name=pathortoken]");
if (pathortoken_form) {
pathortoken_form.value = pathortoken; pathortoken_form.value = pathortoken;
}
let permissions = (share["Permissions"] || "").toLowerCase(); let permissions = (share["Permissions"] || "").toLowerCase();
if (permissions === "rw") { if (permissions === "rw") {
node node
@@ -137,12 +181,13 @@ function add_share_rows(user, password, collection, shares) {
} else { } else {
console.warn("Unknown permissions", permissions); console.warn("Unknown permissions", permissions);
} }
/** @type {HTMLElement} */ let delete_btn = node.querySelector("[data-name=delete]"); /** @type {HTMLElement} */ let delete_btn = node.querySelector("[data-name=delete]");
delete_btn.onclick = function () { delete_btn.onclick = function () {
if (!confirm("Are you sure you want to delete share " + pathortoken + "?")) { if (!confirm("Are you sure you want to delete " + delete_label + " " + pathortoken + "?")) {
return; return;
} }
delete_share_by_token( delete_action(
user, user,
password, password,
pathortoken, pathortoken,
@@ -154,15 +199,36 @@ function add_share_rows(user, password, collection, shares) {
template.parentNode.insertBefore(node, template); template.parentNode.insertBefore(node, template);
} }
/**
* @param {string} user
* @param {string} password
* @param {Collection} collection
* @param {Array<import('./api.js').Share>} shares
*/
function add_share_rows(user, password, collection, shares) {
/** @type {HTMLElement} */ let token_template = document.querySelector("[data-name=sharetokenrowtemplate]");
/** @type {HTMLElement} */ let map_template = document.querySelector("[data-name=sharemaprowtemplate]");
shares.forEach(function (share) {
let pathortoken = share["PathOrToken"] || "";
let pathmapped = share["PathMapped"] || "";
if (
collection.href.includes(pathmapped) ||
collection.href.includes(pathortoken)
) {
if (share["ShareType"] === "token") {
add_share_row_node(user, password, collection, share, token_template, "share", delete_share_by_token);
} else if (share["ShareType"] === "map") {
add_share_row_node(user, password, collection, share, map_template, "map", delete_share_by_map);
}
}
}); });
} }
export function maybe_enable_sharing_options() { export function maybe_enable_sharing_options() {
if (!server_features["sharing"]) return; if (!server_features.sharing) return;
let map_is_enabled = let map_is_enabled = server_features.sharing.FeatureEnabledCollectionByMap || false;
server_features["sharing"]["FeatureEnabledCollectionByMap"] || false; let token_is_enabled = server_features.sharing.FeatureEnabledCollectionByToken || false;
let token_is_enabled =
server_features["sharing"]["FeatureEnabledCollectionByToken"] || false;
if (map_is_enabled || token_is_enabled) { if (map_is_enabled || token_is_enabled) {
let share_options = document.querySelectorAll("[data-name=shareoption]"); let share_options = document.querySelectorAll("[data-name=shareoption]");
for (let i = 0; i < share_options.length; i++) { for (let i = 0; i < share_options.length; i++) {

View File

@@ -20,17 +20,19 @@
import { Scene, pop_scene, scene_stack } from "./scene_manager.js"; import { Scene, pop_scene, scene_stack } from "./scene_manager.js";
import { Collection } from "./models.js"; import { Collection } from "./models.js";
import { cleanHREFinput, isValidHREF, random_uuid } from "./utils.js"; import { cleanHREFinput, isValidHREF, onCleanHREFinput, random_uuid } from "./utils.js";
import { upload_collection } from "./api.js"; import { upload_collection } from "./api.js";
/** /**
* @constructor
* @implements {Scene} * @implements {Scene}
*/
export class UploadCollectionScene {
/**
* @param {string} user * @param {string} user
* @param {string} password * @param {string} password
* @param {Collection} collection parent collection * @param {Collection} collection parent collection
*/ */
export function UploadCollectionScene(user, password, collection) { constructor(user, password, collection) {
/** @type {HTMLElement} */ let html_scene = document.getElementById("uploadcollectionscene"); /** @type {HTMLElement} */ let html_scene = document.getElementById("uploadcollectionscene");
/** @type {HTMLElement} */ let template = html_scene.querySelector("[data-name=filetemplate]"); /** @type {HTMLElement} */ let template = html_scene.querySelector("[data-name=filetemplate]");
/** @type {HTMLElement} */ let upload_btn = html_scene.querySelector("[data-name=submit]"); /** @type {HTMLElement} */ let upload_btn = html_scene.querySelector("[data-name=submit]");
@@ -43,7 +45,7 @@ export function UploadCollectionScene(user, password, collection) {
/** @type {HTMLElement} */ let pending_html = html_scene.querySelector("[data-name=pending]"); /** @type {HTMLElement} */ let pending_html = html_scene.querySelector("[data-name=pending]");
let files = uploadfile_form.files; let files = uploadfile_form.files;
href_form.addEventListener("keydown", cleanHREFinput); href_form.addEventListener("input", onCleanHREFinput);
upload_btn.onclick = upload_start; upload_btn.onclick = upload_start;
uploadfile_form.onchange = onfileschange; uploadfile_form.onchange = onfileschange;
@@ -73,7 +75,7 @@ export function UploadCollectionScene(user, password, collection) {
nodes = []; nodes = [];
for (let i = 0; i < files.length; i++) { for (let i = 0; i < files.length; i++) {
let file = files[i]; let file = files[i];
/** @type {HTMLElement} */ let node = template.cloneNode(true); let node = /** @type {HTMLElement} */ (template.cloneNode(true));
node.classList.remove("hidden"); node.classList.remove("hidden");
let name_form = node.querySelector("[data-name=name]"); let name_form = node.querySelector("[data-name=name]");
name_form.textContent = file.name; name_form.textContent = file.name;
@@ -212,3 +214,4 @@ export function UploadCollectionScene(user, password, collection) {
} }
}; };
} }
}

View File

@@ -18,10 +18,25 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
import { COLOR_RE, ROOT_PATH, SERVER } from "./constants.js";
import { Collection, CollectionType } from "./models.js"; import { Collection, CollectionType } from "./models.js";
import { SERVER, ROOT_PATH, COLOR_RE } from "./constants.js";
import { escape_xml } from "./utils.js"; import { escape_xml } from "./utils.js";
/**
* @typedef {Object} SharingFeatures
* @property {number} [ApiVersion]
* @property {string} [Status]
* @property {boolean} [FeatureEnabledCollectionByMap]
* @property {boolean} [PermittedCreateCollectionByMap]
* @property {boolean} [FeatureEnabledCollectionByToken]
* @property {boolean} [PermittedCreateCollectionByToken]
*/
/**
* @typedef {Object} ServerFeatures
* @property {SharingFeatures} [sharing]
*/
/** @type {ServerFeatures} */
export let server_features = {}; export let server_features = {};
/** /**
@@ -50,6 +65,7 @@ export function get_principal(user, password, callback) {
"", "",
"", "",
0, 0,
0,
""), null); ""), null);
} else { } else {
callback(null, "Internal error"); callback(null, "Internal error");
@@ -345,6 +361,16 @@ export function edit_collection(user, password, collection, callback) {
} }
/* Sharing API */ /* Sharing API */
/**
* @param {string} user
* @param {string} password
* @param {string} path
* @param {object} body
* @param {function(string):void} on_success
* @param {function():void} on_not_found
* @param {function(string):void} on_error
* @returns {XMLHttpRequest}
*/
function call_sharing_api( function call_sharing_api(
user, user,
password, password,
@@ -390,6 +416,11 @@ function call_sharing_api(
return request; return request;
} }
/**
* @param {string} user
* @param {string} password
* @param {function():void} callback
*/
export function discover_server_features(user, password, callback) { export function discover_server_features(user, password, callback) {
call_sharing_api( call_sharing_api(
user, user,
@@ -411,6 +442,29 @@ export function discover_server_features(user, password, callback) {
); );
} }
/**
* @typedef {Object} Share
* @property {string} ShareType
* @property {string} PathOrToken
* @property {string} PathMapped
* @property {string} Owner
* @property {string} User
* @property {string} Permissions
* @property {boolean} EnabledByOwner
* @property {boolean} EnabledByUser
* @property {boolean} HiddenByOwner
* @property {boolean} HiddenByUser
* @property {number} TimestampCreated
* @property {number} TimestampUpdated
* @property {string} Properties
*/
/**
* @param {string} user
* @param {string} password
* @param {Collection} collection
* @param {function(Array<Share>):void} callback
*/
export function reload_sharing_list(user, password, collection, callback) { export function reload_sharing_list(user, password, collection, callback) {
call_sharing_api( call_sharing_api(
user, user,
@@ -418,16 +472,30 @@ export function reload_sharing_list(user, password, collection, callback) {
"all/list", "all/list",
{ PathMapped: collection.href }, { PathMapped: collection.href },
function (response) { function (response) {
callback(JSON.parse(response)); let parsed = JSON.parse(response);
callback(parsed["Content"] || []);
}, },
); );
} }
/**
* @param {string} user
* @param {string} password
* @param {string} pathMapped
* @param {string} permissions
* @param {boolean} enabled
* @param {boolean} hidden
* @param {string} properties
* @param {function():void} callback
*/
export function add_share_by_token( export function add_share_by_token(
user, user,
password, password,
collection, pathMapped,
permissions, permissions,
enabled,
hidden,
properties,
callback, callback,
) { ) {
call_sharing_api( call_sharing_api(
@@ -435,8 +503,11 @@ export function add_share_by_token(
password, password,
"token/create", "token/create",
{ {
PathMapped: collection.href, PathMapped: pathMapped,
Permissions: permissions, Permissions: permissions,
Enabled: enabled,
Hidden: hidden,
Properties: properties,
}, },
function (response) { function (response) {
let json_response = JSON.parse(response); let json_response = JSON.parse(response);
@@ -449,6 +520,60 @@ export function add_share_by_token(
); );
} }
/**
* @param {string} user
* @param {string} password
* @param {string} pathMapped
* @param {string} permissions
* @param {boolean} enabled
* @param {boolean} hidden
* @param {string} properties
* @param {string} share_user
* @param {string} href
* @param {function():void} callback
*/
export function add_share_by_map(
user,
password,
pathMapped,
permissions,
enabled,
hidden,
properties,
share_user,
href,
callback,
) {
call_sharing_api(
user,
password,
"map/create",
{
PathMapped: pathMapped,
Permissions: permissions,
Enabled: enabled,
Hidden: hidden,
Properties: properties,
User: share_user,
PathOrToken: "/" + share_user + "/" + href,
},
function (response) {
let json_response = JSON.parse(response);
if (json_response["Status"] !== "success") {
console.error("Failed to create share map: " + (json_response["Status"] || "Unknown error"));
} else {
callback();
}
},
);
}
/**
* @param {string} user
* @param {string} password
* @param {string} token
* @param {function():void} callback
*/
export function delete_share_by_token( export function delete_share_by_token(
user, user,
password, password,
@@ -470,3 +595,31 @@ export function delete_share_by_token(
}, },
); );
} }
/**
* @param {string} user
* @param {string} password
* @param {string} pathortoken
* @param {function():void} callback
*/
export function delete_share_by_map(
user,
password,
pathortoken,
callback,
) {
call_sharing_api(
user,
password,
"map/delete",
{ PathOrToken: pathortoken },
function (response) {
let json_response = JSON.parse(response);
if (json_response["Status"] !== "success") {
console.error("Failed to delete map " + pathortoken + ": " + (json_response["Status"] || "Unknown error"));
} else {
callback();
}
},
);
}

View File

@@ -44,7 +44,7 @@ main{
width: 100%; width: 100%;
text-align: left; text-align: left;
color: #484848; color: #484848;
font-size: 1.5em; font-size: 14pt;
} }
#loginscene .infcloudlink { #loginscene .infcloudlink {
@@ -58,10 +58,6 @@ main{
visibility: hidden; visibility: hidden;
} }
#loginscene input{
}
#loginscene .logocontainer { #loginscene .logocontainer {
width: 100%; width: 100%;
text-align: center; text-align: center;
@@ -267,6 +263,11 @@ main{
margin-top: 15px; margin-top: 15px;
} }
#newshare input[type=text] {
margin-bottom: 0 !important;
}
.deleteconfirmationtxt { .deleteconfirmationtxt {
text-align: center; text-align: center;
font-size: 1em; font-size: 1em;
@@ -379,7 +380,8 @@ button{
position: relative; position: relative;
} }
input, select{ input,
select {
width: 100%; width: 100%;
height: 3em; height: 3em;
border-style: solid; border-style: solid;
@@ -396,56 +398,77 @@ input.inline {
margin-bottom: 0 !important; margin-bottom: 0 !important;
} }
input[type=text], input[type=password]{ input[type=text],
input[type=password] {
width: calc(100% - 30px); width: calc(100% - 30px);
} }
input:active, input:focus, input:focus-visible{ input:active,
input:focus,
input:focus-visible {
border-color: #2494fe !important; border-color: #2494fe !important;
border-width: 1px !important; border-width: 1px !important;
} }
p.red, span.red{ input[type=radio],
input[type=checkbox] {
width: auto;
height: 1.5em;
padding: 0;
margin: 2px;
}
p.red,
span.red {
color: #b50202; color: #b50202;
} }
button.red, a.red{ button.red,
a.red {
background: #b50202; background: #b50202;
border: 1px solid #a40000; border: 1px solid #a40000;
} }
button.red:hover, a.red:hover{ button.red:hover,
a.red:hover {
background: #a40000; background: #a40000;
} }
button.red:active, a.red:active{ button.red:active,
a.red:active {
background: #8f0000; background: #8f0000;
} }
button.green, a.green{ button.green,
a.green {
background: #4e9a06; background: #4e9a06;
border: 1px solid #377200; border: 1px solid #377200;
} }
button.green:hover, a.green:hover{ button.green:hover,
a.green:hover {
background: #377200; background: #377200;
} }
button.green:active, a.green:active{ button.green:active,
a.green:active {
background: #285200; background: #285200;
} }
button.blue, a.blue{ button.blue,
a.blue {
background: #2494fe; background: #2494fe;
border: 1px solid #055fb5; border: 1px solid #055fb5;
} }
button.blue:hover, a.blue:hover{ button.blue:hover,
a.blue:hover {
background: #1578d6; background: #1578d6;
cursor: pointer !important; cursor: pointer !important;
} }
button.blue:active, a.blue:active{ button.blue:active,
a.blue:active {
background: #055fb5; background: #055fb5;
cursor: pointer !important; cursor: pointer !important;
} }

View File

@@ -6,6 +6,7 @@
* Copyright © 2024-2025 Peter Bieringer <pb@bieringer.de> * Copyright © 2024-2025 Peter Bieringer <pb@bieringer.de>
--> -->
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
@@ -13,7 +14,11 @@
<title>Radicale Web Interface</title> <title>Radicale Web Interface</title>
<link href="css/main.css" type="text/css" media="screen" rel="stylesheet"> <link href="css/main.css" type="text/css" media="screen" rel="stylesheet">
<link href="css/icon.png" type="image/png" rel="icon"> <link href="css/icon.png" type="image/png" rel="icon">
<style>.hidden {display: none !important;}</style> <style>
.hidden {
display: none !important;
}
</style>
<script type="module" src="main.js"></script> <script type="module" src="main.js"></script>
</head> </head>
@@ -142,35 +147,94 @@
<h1>Sharing</h1> <h1>Sharing</h1>
<p>Manage sharing for collection <span class="title" data-name="title">title</span> <p>Manage sharing for collection <span class="title" data-name="title">title</span>
</p> </p>
<div data-name="sharebytoken">
<h2>By Token</h2> <h2>By Token</h2>
<table> <table>
<tbody> <tbody>
<tr data-name="sharetokenrowtemplate" class="hidden"> <tr data-name="sharetokenrowtemplate" class="hidden">
<td> <td>
<button type="button" class="red inline" data-name="delete"><img src="css/icons/delete.svg" class="small_icon" alt="Share"></button> <button type="button" class="red inline" data-name="delete"><img src="css/icons/delete.svg"
class="small_icon" alt="Delete"></button>
</td> </td>
<td><img <td><img src="css/icons/edit.svg" class="med_icon" alt="RW" data-name="rw" /><img src="css/icons/eye.svg"
src="css/icons/edit.svg" class="med_icon" alt="RW" data-name="rw"/><img class="med_icon" alt="RO" data-name="ro" /></td>
src="css/icons/eye.svg" class="med_icon" alt="RO" data-name="ro"/></td> <td><input type="text" data-name="pathortoken" value="" readonly=""
<td><input type="text" data-name="pathortoken" value="" readonly="" onfocus="this.setSelectionRange(0, 99999);" class="inline"></td> onfocus="this.setSelectionRange(0, 99999);" class="inline"></td>
</tr> </tr>
<tr> <tr>
<td></td> <td></td>
<td></td> <td></td>
<td><button type="button" class="blue inline" data-name="sharebytoken_ro"><img <td><button type="button" class="blue inline" data-name="sharebytoken"><img src="css/icons/new.svg"
src="css/icons/eye.svg" class="small_icon" alt="RO"><img class="small_icon" alt="New Share by Token"></button>
src="css/icons/new.svg" class="badge_icon" alt="New"></button>&nbsp; </td>
<button type="button" class="blue inline" data-name="sharebytoken_rw"><img
src="css/icons/edit.svg" class="small_icon" alt="RW"><img
src="css/icons/new.svg" class="badge_icon" alt="New"></button></td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
</div>
<div data-name="sharebymap">
<h2>By Map</h2>
<table>
<tbody>
<tr data-name="sharemaprowtemplate" class="hidden">
<td>
<button type="button" class="red inline" data-name="delete"><img src="css/icons/delete.svg"
class="small_icon" alt="Delete"></button>
</td>
<td><img src="css/icons/edit.svg" class="med_icon" alt="RW" data-name="rw" /><img src="css/icons/eye.svg"
class="med_icon" alt="RO" data-name="ro" /></td>
<td><input type="text" data-name="pathortoken" value="" readonly=""
onfocus="this.setSelectionRange(0, 99999);" class="inline"></td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<button type="button" class="blue inline" data-name="sharebymap">
<img src="css/icons/new.svg" class="small_icon" alt="New Share by Map">
</button>
</td>
</tr>
</tbody>
</table>
</div>
<form> <form>
<button type="button" class="green" data-name="cancel">Close</button> <button type="button" class="green" data-name="cancel">Close</button>
</form> </form>
</section> </section>
<section id="newshare" class="container hidden">
<h1>New Share</h1>
<form>
<fieldset data-name="sharemapfields" class="hidden">
<legend>Map Target</legend>
<label for="newshare_attr_shareuser">Share User</label>
<input type="text" data-name="shareuser" id="newshare_attr_shareuser" />
<label for="newshare_attr_sharehref">Share Href</label>
<input type="text" data-name="sharehref" id="newshare_attr_sharehref" />
</fieldset>
<fieldset>
<legend>Attributes</legend>
<input type="checkbox" data-name="enabled" checked="true" id="newshare_attr_enabled" /><label
for="newshare_attr_enabled">Enabled</label>
<input type="checkbox" data-name="hidden" checked="false" id="newshare_attr_hidden" /><label
for="newshare_attr_hidden">Hidden</label>
</fieldset>
<fieldset>
<legend>Permissions</legend>
<input type="radio" data-name="permissions" checked="true" id="newshare_attr_permissions_ro"
name="newshare_permissions"><label for="newshare_attr_permissions_ro">Readonly</label>
<input type="radio" data-name="permissions" checked="false" id="newshare_attr_permissions_rw"
name="newshare_permissions" /><label for="newshare_attr_permissions_rw">Read/Write</label>
</fieldset>
<fieldset>
<legend>Properties override</legend>
<input type="text" data-name="properties" />
</fieldset>
<button type="submit" class="green" data-name="submit">Create</button>
<button type="button" class="red" data-name="cancel">Cancel</button>
</form>
</section>
<section id="createcollectionscene" class="container hidden"> <section id="createcollectionscene" class="container hidden">
<h1>Create a new Collection</h1> <h1>Create a new Collection</h1>
<p>Enter the details of your new collection.</p> <p>Enter the details of your new collection.</p>
@@ -233,7 +297,8 @@
<section id="deletecollectionscene" class="container hidden"> <section id="deletecollectionscene" class="container hidden">
<h1>Delete Collection</h1> <h1>Delete Collection</h1>
<p>To delete the collection <span class="title" data-name="title">title</span> please enter the phrase <strong data-name="deleteconfirmationtext"></strong> in the box below:</p> <p>To delete the collection <span class="title" data-name="title">title</span> please enter the phrase <strong
data-name="deleteconfirmationtext"></strong> in the box below:</p>
<input type="text" class="deleteconfirmationtxt" data-name="confirmationtxt" /> <input type="text" class="deleteconfirmationtxt" data-name="confirmationtxt" />
<p class="red">WARNING: This action cannot be reversed.</p> <p class="red">WARNING: This action cannot be reversed.</p>
<form> <form>
@@ -246,4 +311,5 @@
</main> </main>
</body> </body>
</html> </html>

View File

@@ -18,21 +18,32 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** export class CollectionType {
* @enum {string} // Private Fields
*/ static #_PRINCIPAL = "PRINCIPAL";
export const CollectionType = { static #_ADDRESSBOOK = "ADDRESSBOOK";
PRINCIPAL: "PRINCIPAL", static #_CALENDAR_JOURNAL_TASKS = "CALENDAR_JOURNAL_TASKS";
ADDRESSBOOK: "ADDRESSBOOK", static #_CALENDAR_JOURNAL = "CALENDAR_JOURNAL";
CALENDAR_JOURNAL_TASKS: "CALENDAR_JOURNAL_TASKS", static #_CALENDAR_TASKS = "CALENDAR_TASKS";
CALENDAR_JOURNAL: "CALENDAR_JOURNAL", static #_JOURNAL_TASKS = "JOURNAL_TASKS";
CALENDAR_TASKS: "CALENDAR_TASKS", static #_CALENDAR = "CALENDAR";
JOURNAL_TASKS: "JOURNAL_TASKS", static #_JOURNAL = "JOURNAL";
CALENDAR: "CALENDAR", static #_TASKS = "TASKS";
JOURNAL: "JOURNAL", static #_WEBCAL = "WEBCAL";
TASKS: "TASKS",
WEBCAL: "WEBCAL", // Accessors for "get" functions only (no "set" functions)
is_subset: function(a, b) { static get PRINCIPAL() { return this.#_PRINCIPAL; }
static get ADDRESSBOOK() { return this.#_ADDRESSBOOK; }
static get CALENDAR_JOURNAL_TASKS() { return this.#_CALENDAR_JOURNAL_TASKS; }
static get CALENDAR_JOURNAL() { return this.#_CALENDAR_JOURNAL; }
static get CALENDAR_TASKS() { return this.#_CALENDAR_TASKS; }
static get JOURNAL_TASKS() { return this.#_JOURNAL_TASKS; }
static get CALENDAR() { return this.#_CALENDAR; }
static get JOURNAL() { return this.#_JOURNAL; }
static get TASKS() { return this.#_TASKS; }
static get WEBCAL() { return this.#_WEBCAL; }
static is_subset(/** @type {string} */ a, /** @type {string} */ b) {
let components = a.split("_"); let components = a.split("_");
for (let i = 0; i < components.length; i++) { for (let i = 0; i < components.length; i++) {
if (b.search(components[i]) === -1) { if (b.search(components[i]) === -1) {
@@ -40,8 +51,9 @@ export const CollectionType = {
} }
} }
return true; return true;
}, }
union: function(a, b) {
static union(/** @type {string} */ a, /** @type {string} */ b) {
if (a.search(this.ADDRESSBOOK) !== -1 || b.search(this.ADDRESSBOOK) !== -1) { if (a.search(this.ADDRESSBOOK) !== -1 || b.search(this.ADDRESSBOOK) !== -1) {
if (a && a !== this.ADDRESSBOOK || b && b !== this.ADDRESSBOOK) { if (a && a !== this.ADDRESSBOOK || b && b !== this.ADDRESSBOOK) {
throw "Invalid union: " + a + " " + b; throw "Invalid union: " + a + " " + b;
@@ -62,8 +74,12 @@ export const CollectionType = {
union.push(this.WEBCAL); union.push(this.WEBCAL);
} }
return union.join("_"); return union.join("_");
}, }
valid_options_for_type: function(a){
/**
* @param {string} a
*/
static valid_options_for_type(a) {
a = a.trim().toUpperCase(); a = a.trim().toUpperCase();
switch (a) { switch (a) {
case CollectionType.CALENDAR_JOURNAL_TASKS: case CollectionType.CALENDAR_JOURNAL_TASKS:
@@ -80,18 +96,21 @@ export const CollectionType = {
return [a]; return [a];
} }
} }
}; }
export class Collection {
/** /**
* @constructor
* @struct
* @param {string} href Must always start and end with /. * @param {string} href Must always start and end with /.
* @param {CollectionType} type * @param {string} type
* @param {string} displayname * @param {string} displayname
* @param {string} description * @param {string} description
* @param {string} color * @param {string} color
* @param {number} contentcount
* @param {number} size
* @param {string} source
*/ */
export function Collection(href, type, displayname, description, color, contentcount, size, source) { constructor(href, type, displayname, description, color, contentcount, size, source) {
this.href = href; this.href = href;
this.type = type; this.type = type;
this.displayname = displayname; this.displayname = displayname;
@@ -101,3 +120,4 @@ export function Collection(href, type, displayname, description, color, contentc
this.contentcount = contentcount; this.contentcount = contentcount;
this.size = size; this.size = size;
} }
}

View File

@@ -47,19 +47,18 @@ export function random_uuid() {
export function random_hex(length) { export function random_hex(length) {
let bytes = new Uint8Array(Math.ceil(length / 2)); let bytes = new Uint8Array(Math.ceil(length / 2));
window.crypto.getRandomValues(bytes); window.crypto.getRandomValues(bytes);
return bytes.reduce((s, b) => s + b.toString(16).padStart(2, "0"), "").substring(0, length); // Fallback for compatibility with older browsers which may not have padStart
return bytes.reduce((s, b) => {
let hex = b.toString(16);
return s + (String.prototype["padStart"] ? hex["padStart"](2, "0") : ("0" + hex).slice(-2));
}, "").substring(0, length);
} }
/** /**
* Removed invalid HREF characters for a collection HREF. * Removed invalid HREF characters for a collection HREF.
* * @param {HTMLInputElement} href_form A valid Input element or an onchange Event of an Input element.
* @param a A valid Input element or an onchange Event of an Input element.
*/ */
export function cleanHREFinput(a) { export function cleanHREFinput(href_form) {
let href_form = a;
if (a.target) {
href_form = a.target;
}
let currentTxtVal = href_form.value.trim().toLowerCase(); let currentTxtVal = href_form.value.trim().toLowerCase();
//Clean the HREF to remove not permitted chars //Clean the HREF to remove not permitted chars
currentTxtVal = currentTxtVal.replace(/(?![0-9a-z\-\_\.])./g, ''); currentTxtVal = currentTxtVal.replace(/(?![0-9a-z\-\_\.])./g, '');
@@ -68,11 +67,19 @@ export function cleanHREFinput(a) {
href_form.value = currentTxtVal; href_form.value = currentTxtVal;
} }
/**
* Event listener for cleaning HREF input.
* @param {Event} event
*/
export function onCleanHREFinput(event) {
if (event.target instanceof HTMLInputElement) {
cleanHREFinput(event.target);
}
}
/** /**
* Checks if a proposed HREF for a collection has a valid format and syntax. * Checks if a proposed HREF for a collection has a valid format and syntax.
* * @param {string} href String of the proposed HREF.
* @param href String of the porposed HREF.
*
* @return Boolean results if the HREF is valid. * @return Boolean results if the HREF is valid.
*/ */
export function isValidHREF(href) { export function isValidHREF(href) {
@@ -88,16 +95,15 @@ export function isValidHREF(href) {
/** /**
* Format bytes to human-readable text. * Format bytes to human-readable text.
* * @param {number} bytes Number of bytes.
* @param bytes Number of bytes.
*
* @return Formatted string. * @return Formatted string.
*/ */
export function bytesToHumanReadable(bytes, dp=1) { export function bytesToHumanReadable(bytes) {
let isNumber = !isNaN(parseFloat(bytes)) && !isNaN(bytes - 0); if (isNaN(bytes - 0)) {
if(!isNumber){
return ""; return "";
} }
var i = bytes == 0 ? 0 : Math.floor(Math.log(bytes) / Math.log(1024)); const units = ['b', 'kb', 'mb', 'gb', 'tb'];
return (bytes / Math.pow(1024, i)).toFixed(dp) * 1 + ' ' + ['b', 'kb', 'mb', 'gb', 'tb'][i]; let i = bytes == 0 ? 0 : Math.floor(Math.log(bytes) / Math.log(1024));
i = Math.min(i, units.length - 1);
return (bytes / Math.pow(1024, i)) + ' ' + units[i];
} }

View File

@@ -2,7 +2,10 @@
"compilerOptions": { "compilerOptions": {
"module": "CommonJS", "module": "CommonJS",
"target": "ES6", "target": "ES6",
"checkJs": true "checkJs": true,
"noEmit": true,
"noUnusedLocals": true,
"noUnusedParameters": true
}, },
"include": [ "include": [
"internal_data/**/*.js" "internal_data/**/*.js"