Apply prettier rules

This commit is contained in:
2024-11-14 18:47:38 +01:00
parent 610227815a
commit aa0785fc71
291 changed files with 23646 additions and 22071 deletions

View File

@@ -1,35 +1,61 @@
import {Address, GeographicalUnitLayer, SimpleGeographicalUnit} from "../../types";
import {fetchResults, makeFetch} from "./apiMethods";
import {
Address,
GeographicalUnitLayer,
SimpleGeographicalUnit,
} from "../../types";
import { fetchResults, makeFetch } from "./apiMethods";
export const getAddressById = async (address_id: number): Promise<Address> =>
{
const url = `/api/1.0/main/address/${address_id}.json`;
export const getAddressById = async (address_id: number): Promise<Address> => {
const url = `/api/1.0/main/address/${address_id}.json`;
const response = await fetch(url);
const response = await fetch(url);
if (response.ok) {
return response.json();
}
if (response.ok) {
return response.json();
}
throw Error('Error with request resource response');
throw Error("Error with request resource response");
};
export const getGeographicalUnitsByAddress = async (address: Address): Promise<SimpleGeographicalUnit[]> => {
return fetchResults<SimpleGeographicalUnit>(`/api/1.0/main/geographical-unit/by-address/${address.address_id}.json`);
}
export const getGeographicalUnitsByAddress = async (
address: Address,
): Promise<SimpleGeographicalUnit[]> => {
return fetchResults<SimpleGeographicalUnit>(
`/api/1.0/main/geographical-unit/by-address/${address.address_id}.json`,
);
};
export const getAllGeographicalUnitLayers = async (): Promise<GeographicalUnitLayer[]> => {
return fetchResults<GeographicalUnitLayer>(`/api/1.0/main/geographical-unit-layer.json`);
}
export const getAllGeographicalUnitLayers = async (): Promise<
GeographicalUnitLayer[]
> => {
return fetchResults<GeographicalUnitLayer>(
`/api/1.0/main/geographical-unit-layer.json`,
);
};
export const syncAddressWithReference = async (address: Address): Promise<Address> => {
return makeFetch<null, Address>("POST", `/api/1.0/main/address/reference-match/${address.address_id}/sync-with-reference`);
}
export const syncAddressWithReference = async (
address: Address,
): Promise<Address> => {
return makeFetch<null, Address>(
"POST",
`/api/1.0/main/address/reference-match/${address.address_id}/sync-with-reference`,
);
};
export const markAddressReviewed = async (address: Address): Promise<Address> => {
return makeFetch<null, Address>("POST", `/api/1.0/main/address/reference-match/${address.address_id}/set/reviewed`);
}
export const markAddressReviewed = async (
address: Address,
): Promise<Address> => {
return makeFetch<null, Address>(
"POST",
`/api/1.0/main/address/reference-match/${address.address_id}/set/reviewed`,
);
};
export const markAddressToReview = async (address: Address): Promise<Address> => {
return makeFetch<null, Address>("POST", `/api/1.0/main/address/reference-match/${address.address_id}/set/to_review`);
}
export const markAddressToReview = async (
address: Address,
): Promise<Address> => {
return makeFetch<null, Address>(
"POST",
`/api/1.0/main/address/reference-match/${address.address_id}/set/to_review`,
);
};

View File

@@ -1,58 +1,61 @@
import {Scope} from '../../types';
import { Scope } from "../../types";
export type body = Record<string, boolean|string|number|null>;
export type fetchOption = Record<string, boolean|string|number|null>;
export type body = Record<string, boolean | string | number | null>;
export type fetchOption = Record<string, boolean | string | number | null>;
export type Params = Record<string, number|string>;
export type Params = Record<string, number | string>;
export interface PaginationResponse<T> {
pagination: {
more: boolean;
items_per_page: number;
};
results: T[];
count: number;
pagination: {
more: boolean;
items_per_page: number;
};
results: T[];
count: number;
}
export type FetchParams = Record<string, string|number|null>;;
export type FetchParams = Record<string, string | number | null>;
export interface TransportExceptionInterface {
name: string;
name: string;
}
export interface ValidationExceptionInterface extends TransportExceptionInterface {
name: 'ValidationException';
error: object;
violations: string[];
titles: string[];
propertyPaths: string[];
export interface ValidationExceptionInterface
extends TransportExceptionInterface {
name: "ValidationException";
error: object;
violations: string[];
titles: string[];
propertyPaths: string[];
}
export interface ValidationErrorResponse extends TransportExceptionInterface {
violations: {
title: string;
propertyPath: string;
}[];
violations: {
title: string;
propertyPath: string;
}[];
}
export interface AccessExceptionInterface extends TransportExceptionInterface {
name: 'AccessException';
violations: string[];
name: "AccessException";
violations: string[];
}
export interface NotFoundExceptionInterface extends TransportExceptionInterface {
name: 'NotFoundException';
export interface NotFoundExceptionInterface
extends TransportExceptionInterface {
name: "NotFoundException";
}
export interface ServerExceptionInterface extends TransportExceptionInterface {
name: 'ServerException';
message: string;
code: number;
body: string;
name: "ServerException";
message: string;
code: number;
body: string;
}
export interface ConflictHttpExceptionInterface extends TransportExceptionInterface {
name: 'ConflictHttpException';
export interface ConflictHttpExceptionInterface
extends TransportExceptionInterface {
name: "ConflictHttpException";
violations: string[];
}
@@ -60,35 +63,33 @@ export interface ConflictHttpExceptionInterface extends TransportExceptionInterf
* Generic api method that can be adapted to any fetch request
*/
export const makeFetch = <Input, Output>(
method: 'POST'|'GET'|'PUT'|'PATCH'|'DELETE',
url: string, body?: body | Input | null,
options?: FetchParams
method: "POST" | "GET" | "PUT" | "PATCH" | "DELETE",
url: string,
body?: body | Input | null,
options?: FetchParams,
): Promise<Output> => {
let opts = {
method: method,
headers: {
'Content-Type': 'application/json;charset=utf-8'
"Content-Type": "application/json;charset=utf-8",
},
};
if (body !== null && typeof body !== 'undefined') {
Object.assign(opts, {body: JSON.stringify(body)})
if (body !== null && typeof body !== "undefined") {
Object.assign(opts, { body: JSON.stringify(body) });
}
if (typeof options !== 'undefined') {
if (typeof options !== "undefined") {
opts = Object.assign(opts, options);
}
return fetch(url, opts)
.then(response => {
return fetch(url, opts).then((response) => {
if (response.ok) {
return response.json();
}
if (response.status === 422) {
return response.json().then(response => {
throw ValidationException(response)
return response.json().then((response) => {
throw ValidationException(response);
});
}
@@ -101,79 +102,94 @@ export const makeFetch = <Input, Output>(
}
throw {
name: 'Exception',
name: "Exception",
sta: response.status,
txt: response.statusText,
err: new Error(),
violations: response.body
violations: response.body,
};
});
}
};
/**
* Fetch results with certain parameters
*/
function _fetchAction<T>(page: number, uri: string, params?: FetchParams): Promise<PaginationResponse<T>> {
function _fetchAction<T>(
page: number,
uri: string,
params?: FetchParams,
): Promise<PaginationResponse<T>> {
const item_per_page = 50;
const searchParams = new URLSearchParams();
searchParams.append('item_per_page', item_per_page.toString());
searchParams.append('page', page.toString());
searchParams.append("item_per_page", item_per_page.toString());
searchParams.append("page", page.toString());
if (params !== undefined) {
Object.keys(params).forEach(key => {
const v = params[key];
if (typeof v === 'string') {
searchParams.append(key, v);
} else if (typeof v === 'number') {
searchParams.append(key, v.toString());
} else if (v === null) {
searchParams.append(key, '');
}
});
Object.keys(params).forEach((key) => {
const v = params[key];
if (typeof v === "string") {
searchParams.append(key, v);
} else if (typeof v === "number") {
searchParams.append(key, v.toString());
} else if (v === null) {
searchParams.append(key, "");
}
});
}
const url = uri + '?' + searchParams.toString();
const url = uri + "?" + searchParams.toString();
return fetch(url, {
method: 'GET',
method: "GET",
headers: {
'Content-Type': 'application/json;charset=utf-8'
"Content-Type": "application/json;charset=utf-8",
},
}).then((response) => {
if (response.ok) { return response.json(); }
})
.then((response) => {
if (response.ok) {
return response.json();
}
if (response.status === 404) {
throw NotFoundException(response);
}
if (response.status === 404) {
throw NotFoundException(response);
}
if (response.status === 422) {
return response.json().then(response => {
throw ValidationException(response)
});
}
if (response.status === 422) {
return response.json().then((response) => {
throw ValidationException(response);
});
}
if (response.status === 403) {
throw AccessException(response);
}
if (response.status === 403) {
throw AccessException(response);
}
if (response.status >= 500) {
return response.text().then(body => {
throw ServerException(response.status, body);
});
}
if (response.status >= 500) {
return response.text().then((body) => {
throw ServerException(response.status, body);
});
}
throw new Error("other network error");
}).catch((reason: any) => {
console.error(reason);
throw new Error(reason);
});
};
throw new Error("other network error");
})
.catch((reason: any) => {
console.error(reason);
throw new Error(reason);
});
}
export const fetchResults = async<T> (uri: string, params?: FetchParams): Promise<T[]> => {
export const fetchResults = async <T>(
uri: string,
params?: FetchParams,
): Promise<T[]> => {
let promises: Promise<T[]>[] = [],
page = 1;
const firstData: PaginationResponse<T> = await _fetchAction(page, uri, params) as PaginationResponse<T>;
const firstData: PaginationResponse<T> = (await _fetchAction(
page,
uri,
params,
)) as PaginationResponse<T>;
promises.push(Promise.resolve(firstData.results));
@@ -181,61 +197,74 @@ export const fetchResults = async<T> (uri: string, params?: FetchParams): Promis
do {
page = ++page;
promises.push(
_fetchAction<T>(page, uri, params)
.then(r => Promise.resolve(r.results))
_fetchAction<T>(page, uri, params).then((r) =>
Promise.resolve(r.results),
),
);
} while (page * firstData.pagination.items_per_page < firstData.count)
} while (page * firstData.pagination.items_per_page < firstData.count);
}
return Promise.all(promises).then((values) => values.flat());
};
export const fetchScopes = (): Promise<Scope[]> => {
return fetchResults('/api/1.0/main/scope.json');
return fetchResults("/api/1.0/main/scope.json");
};
/**
* Error objects to be thrown
*/
const ValidationException = (response: ValidationErrorResponse): ValidationExceptionInterface => {
const ValidationException = (
response: ValidationErrorResponse,
): ValidationExceptionInterface => {
const error = {} as ValidationExceptionInterface;
error.name = 'ValidationException';
error.violations = response.violations.map((violation) => `${violation.title}: ${violation.propertyPath}`);
error.name = "ValidationException";
error.violations = response.violations.map(
(violation) => `${violation.title}: ${violation.propertyPath}`,
);
error.titles = response.violations.map((violation) => violation.title);
error.propertyPaths = response.violations.map((violation) => violation.propertyPath);
error.propertyPaths = response.violations.map(
(violation) => violation.propertyPath,
);
return error;
}
};
const AccessException = (response: Response): AccessExceptionInterface => {
const error = {} as AccessExceptionInterface;
error.name = 'AccessException';
error.violations = ['You are not allowed to perform this action'];
error.name = "AccessException";
error.violations = ["You are not allowed to perform this action"];
return error;
}
};
const NotFoundException = (response: Response): NotFoundExceptionInterface => {
const error = {} as NotFoundExceptionInterface;
error.name = 'NotFoundException';
return error;
}
const ServerException = (code: number, body: string): ServerExceptionInterface => {
const error = {} as ServerExceptionInterface;
error.name = 'ServerException';
error.code = code;
error.body = body;
return error;
}
const ConflictHttpException = (response: Response): ConflictHttpExceptionInterface => {
const error = {} as ConflictHttpExceptionInterface;
error.name = 'ConflictHttpException';
error.violations = ['Sorry, but someone else has already changed this entity. Please refresh the page and apply the changes again']
const error = {} as NotFoundExceptionInterface;
error.name = "NotFoundException";
return error;
}
};
const ServerException = (
code: number,
body: string,
): ServerExceptionInterface => {
const error = {} as ServerExceptionInterface;
error.name = "ServerException";
error.code = code;
error.body = body;
return error;
};
const ConflictHttpException = (
response: Response,
): ConflictHttpExceptionInterface => {
const error = {} as ConflictHttpExceptionInterface;
error.name = "ConflictHttpException";
error.violations = [
"Sorry, but someone else has already changed this entity. Please refresh the page and apply the changes again",
];
return error;
};

View File

@@ -1,4 +1,3 @@
// const _fetchAction = (page, uri, params) => {
// const item_per_page = 50;
// if (params === undefined) {

View File

@@ -1,6 +1,8 @@
import {fetchResults} from "./apiMethods";
import {Location, LocationType} from "../../types";
import { fetchResults } from "./apiMethods";
import { Location, LocationType } from "../../types";
export const getLocations = (): Promise<Location[]> => fetchResults('/api/1.0/main/location.json');
export const getLocations = (): Promise<Location[]> =>
fetchResults("/api/1.0/main/location.json");
export const getLocationTypes = (): Promise<LocationType[]> => fetchResults('/api/1.0/main/location-type.json');
export const getLocationTypes = (): Promise<LocationType[]> =>
fetchResults("/api/1.0/main/location-type.json");

View File

@@ -1,25 +1,24 @@
import {User} from "../../types";
import {makeFetch} from "./apiMethods";
import { User } from "../../types";
import { makeFetch } from "./apiMethods";
export const whoami = (): Promise<User> => {
const url = `/api/1.0/main/whoami.json`;
return fetch(url)
.then(response => {
if (response.ok) {
return response.json();
}
throw {
msg: 'Error while getting whoami.',
sta: response.status,
txt: response.statusText,
err: new Error(),
body: response.body
};
const url = `/api/1.0/main/whoami.json`;
return fetch(url).then((response) => {
if (response.ok) {
return response.json();
}
throw {
msg: "Error while getting whoami.",
sta: response.status,
txt: response.statusText,
err: new Error(),
body: response.body,
};
});
};
export const whereami = (): Promise<Location | null> => {
const url = `/api/1.0/main/user-current-location.json`;
const url = `/api/1.0/main/user-current-location.json`;
return makeFetch<null, Location|null>("GET", url);
}
return makeFetch<null, Location | null>("GET", url);
};

View File

@@ -1,3 +1 @@
require("./layout.scss");

View File

@@ -15,58 +15,61 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import mime from 'mime';
import mime from "mime";
export const download_report = (url, container) => {
var download_text = container.dataset.downloadText,
alias = container.dataset.alias;
var download_text = container.dataset.downloadText,
alias = container.dataset.alias;
window.fetch(url, { credentials: 'same-origin' })
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
window
.fetch(url, { credentials: "same-origin" })
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response.blob();
}).then(blob => {
return response.blob();
})
.then((blob) => {
var content = URL.createObjectURL(blob),
link = document.createElement("a"),
type = blob.type,
hasForcedType = "mimeType" in container.dataset,
extension;
var content = URL.createObjectURL(blob),
link = document.createElement("a"),
type = blob.type,
hasForcedType = 'mimeType' in container.dataset,
extension;
if (hasForcedType) {
// force a type
type = container.dataset.mimeType;
blob = new Blob([blob], { type: type });
content = URL.createObjectURL(blob);
}
if (hasForcedType) {
// force a type
type = container.dataset.mimeType;
blob = new Blob([ blob ], { 'type': type });
content = URL.createObjectURL(blob);
}
const extensions = new Map();
extensions.set(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"xlsx",
);
extensions.set("application/vnd.oasis.opendocument.spreadsheet", "ods");
extensions.set("application/vnd.ms-excel", "xlsx");
extensions.set("text/csv", "csv");
extensions.set("text/csv; charset=utf-8", "csv");
const extensions = new Map();
extensions.set('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xlsx');
extensions.set('application/vnd.oasis.opendocument.spreadsheet', 'ods');
extensions.set('application/vnd.ms-excel', 'xlsx');
extensions.set('text/csv', 'csv');
extensions.set('text/csv; charset=utf-8', 'csv');
extension = extensions.get(type);
extension = extensions.get(type);
link.appendChild(document.createTextNode(download_text));
link.classList.add("btn", "btn-action");
link.href = content;
link.download = alias;
if (extension !== false) {
link.download = link.download + "." + extension;
}
container.innerHTML = "";
container.appendChild(link);
})
.catch(function (error) {
console.error(error);
var problem_text = document.createTextNode("Problem during download");
link.appendChild(document.createTextNode(download_text));
link.classList.add("btn", "btn-action");
link.href = content;
link.download = alias;
if (extension !== false) {
link.download = link.download + '.' + extension;
}
container.innerHTML = "";
container.appendChild(link);
}).catch(function(error) {
console.error(error);
var problem_text =
document.createTextNode("Problem during download");
container
.replaceChild(problem_text, container.firstChild);
});
container.replaceChild(problem_text, container.firstChild);
});
};

View File

@@ -1,4 +1,4 @@
/*
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify

View File

@@ -1,20 +1,22 @@
const buildLinkCreate = function (relatedEntityClass: string, relatedEntityId: number, to: number | null, returnPath: string | null): string
{
const buildLinkCreate = function (
relatedEntityClass: string,
relatedEntityId: number,
to: number | null,
returnPath: string | null,
): string {
const params = new URLSearchParams();
params.append('entityClass', relatedEntityClass);
params.append('entityId', relatedEntityId.toString());
params.append("entityClass", relatedEntityClass);
params.append("entityId", relatedEntityId.toString());
if (null !== to) {
params.append('tos[0]', to.toString());
params.append("tos[0]", to.toString());
}
if (null !== returnPath) {
params.append('returnPath', returnPath);
params.append("returnPath", returnPath);
}
return `/fr/notification/create?${params.toString()}`;
}
};
export {
buildLinkCreate,
}
export { buildLinkCreate };

View File

@@ -1,12 +1,14 @@
const buildLinkCreate = function(workflowName, relatedEntityClass, relatedEntityId) {
let params = new URLSearchParams();
params.set('entityClass', relatedEntityClass);
params.set('entityId', relatedEntityId);
params.set('workflow', workflowName);
const buildLinkCreate = function (
workflowName,
relatedEntityClass,
relatedEntityId,
) {
let params = new URLSearchParams();
params.set("entityClass", relatedEntityClass);
params.set("entityId", relatedEntityId);
params.set("workflow", workflowName);
return `/fr/main/workflow/create?`+params.toString();
return `/fr/main/workflow/create?` + params.toString();
};
export {
buildLinkCreate,
};
export { buildLinkCreate };

View File

@@ -1,36 +1,30 @@
window.addEventListener('load', function (e) {
var
postalCodes = document.querySelectorAll('[data-select-interactive-loading]')
;
for (let i = 0; i < postalCodes.length; i++) {
let
searchUrl = postalCodes[i].dataset.searchUrl,
noResultsLabel = postalCodes[i].dataset.noResultsLabel,
errorLoadLabel = postalCodes[i].dataset.errorLoadLabel,
searchingLabel = postalCodes[i].dataset.searchingLabel
;
$(postalCodes[i]).select2({
allowClear: true,
language: {
errorLoading: function () {
return errorLoadLabel;
},
noResults: function () {
return noResultsLabel;
},
searching: function () {
return searchingLabel;
}
},
ajax: {
url: searchUrl,
dataType: 'json',
delay: 250
}
});
}
window.addEventListener("load", function (e) {
var postalCodes = document.querySelectorAll(
"[data-select-interactive-loading]",
);
for (let i = 0; i < postalCodes.length; i++) {
let searchUrl = postalCodes[i].dataset.searchUrl,
noResultsLabel = postalCodes[i].dataset.noResultsLabel,
errorLoadLabel = postalCodes[i].dataset.errorLoadLabel,
searchingLabel = postalCodes[i].dataset.searchingLabel;
$(postalCodes[i]).select2({
allowClear: true,
language: {
errorLoading: function () {
return errorLoadLabel;
},
noResults: function () {
return noResultsLabel;
},
searching: function () {
return searchingLabel;
},
},
ajax: {
url: searchUrl,
dataType: "json",
delay: 250,
},
});
}
});

View File

@@ -1,5 +1,5 @@
//require("./show_hide.js");
import { ShowHide } from './show_hide.js'
import { ShowHide } from "./show_hide.js";
export { ShowHide }
export { ShowHide };

View File

@@ -16,132 +16,137 @@
*
* @param object options
*/
var ShowHide = function(options) {
var
froms = typeof options.froms[Symbol.iterator] === "function" ? options.froms : [ options.froms ], //options.froms;
test = options.test,
container = typeof options.container[Symbol.iterator] === "function" ? options.container : [ options.container ],
is_shown = true,
event_name = 'event_name' in options ? options.event_name : 'change',
container_content = [],
debug = 'debug' in options ? options.debug : false,
load_event = 'load_event' in options ? options.load_event : 'load',
id = 'uid' in options ? options.id : Math.random(),
toggle_callback = 'toggle_callback' in options ? options.toggle_callback : null
;
var bootstrap = function(event) {
if (debug) {
console.log('debug is activated on this show-hide', this);
}
// keep the content in memory
for (let c of container.values()) {
let contents = [];
for (let el of c.childNodes.values()) {
contents.push(el);
}
container_content.push(contents);
}
// attach the listener on each input
for (let f of froms.values()) {
let
inputs = f.querySelectorAll('input'),
selects = f.querySelectorAll('select');
for (let input of inputs.values()) {
if (debug) {
console.log('attaching event to input', input);
}
input.addEventListener(event_name, function(e) {
onChange(e);
});
}
for (let input of selects.values()) {
if (debug) {
console.log('attaching event to selects', input);
}
input.addEventListener(event_name, function(e) {
onChange(e);
});
}
}
// first launch of the show/hide
onChange(event);
};
var onChange = function (event) {
var result = test(froms, event), me;
if (result === true) {
if (is_shown === false) {
forceShow();
me = new CustomEvent('show-hide-show', { detail: { id: id, container: container, froms: froms } });
window.dispatchEvent(me);
}
} else if (result === false) {
if (is_shown) {
forceHide();
me = new CustomEvent('show-hide-hide', { detail: { id: id, container: container, froms: froms } });
window.dispatchEvent(me);
}
} else {
throw "the result of test is not a boolean";
}
};
var forceHide = function() {
if (debug) {
console.log('force hide');
}
if (toggle_callback !== null) {
toggle_callback(container, 'hide');
} else {
for (let contents of container_content.values()) {
for (let el of contents.values()) {
el.remove();
}
}
}
is_shown = false;
};
var forceShow = function() {
if (debug) {
console.log('show');
}
if (toggle_callback !== null) {
toggle_callback(container, 'show');
} else {
for (let i of container_content.keys()) {
var contents = container_content[i];
for (let el of contents.values()) {
container[i].appendChild(el);
}
}
}
is_shown = true;
};
var forceCompute = function(event) {
onChange(event);
};
if (load_event !== null) {
window.addEventListener('load', bootstrap);
} else {
bootstrap(null);
var ShowHide = function (options) {
var froms =
typeof options.froms[Symbol.iterator] === "function"
? options.froms
: [options.froms], //options.froms;
test = options.test,
container =
typeof options.container[Symbol.iterator] === "function"
? options.container
: [options.container],
is_shown = true,
event_name = "event_name" in options ? options.event_name : "change",
container_content = [],
debug = "debug" in options ? options.debug : false,
load_event = "load_event" in options ? options.load_event : "load",
id = "uid" in options ? options.id : Math.random(),
toggle_callback =
"toggle_callback" in options ? options.toggle_callback : null;
var bootstrap = function (event) {
if (debug) {
console.log("debug is activated on this show-hide", this);
}
// keep the content in memory
for (let c of container.values()) {
let contents = [];
for (let el of c.childNodes.values()) {
contents.push(el);
}
container_content.push(contents);
}
return {
forceHide: forceHide,
forceShow: forceShow,
forceCompute: forceCompute,
};
// attach the listener on each input
for (let f of froms.values()) {
let inputs = f.querySelectorAll("input"),
selects = f.querySelectorAll("select");
for (let input of inputs.values()) {
if (debug) {
console.log("attaching event to input", input);
}
input.addEventListener(event_name, function (e) {
onChange(e);
});
}
for (let input of selects.values()) {
if (debug) {
console.log("attaching event to selects", input);
}
input.addEventListener(event_name, function (e) {
onChange(e);
});
}
}
// first launch of the show/hide
onChange(event);
};
var onChange = function (event) {
var result = test(froms, event),
me;
if (result === true) {
if (is_shown === false) {
forceShow();
me = new CustomEvent("show-hide-show", {
detail: { id: id, container: container, froms: froms },
});
window.dispatchEvent(me);
}
} else if (result === false) {
if (is_shown) {
forceHide();
me = new CustomEvent("show-hide-hide", {
detail: { id: id, container: container, froms: froms },
});
window.dispatchEvent(me);
}
} else {
throw "the result of test is not a boolean";
}
};
var forceHide = function () {
if (debug) {
console.log("force hide");
}
if (toggle_callback !== null) {
toggle_callback(container, "hide");
} else {
for (let contents of container_content.values()) {
for (let el of contents.values()) {
el.remove();
}
}
}
is_shown = false;
};
var forceShow = function () {
if (debug) {
console.log("show");
}
if (toggle_callback !== null) {
toggle_callback(container, "show");
} else {
for (let i of container_content.keys()) {
var contents = container_content[i];
for (let el of contents.values()) {
container[i].appendChild(el);
}
}
}
is_shown = true;
};
var forceCompute = function (event) {
onChange(event);
};
if (load_event !== null) {
window.addEventListener("load", bootstrap);
} else {
bootstrap(null);
}
return {
forceHide: forceHide,
forceShow: forceShow,
forceCompute: forceCompute,
};
};
export { ShowHide };

View File

@@ -1,118 +1,104 @@
/*
* Remove active class on both elements: link and content
*/
let resetActive = function(links, contents)
{
for (items of [links, contents]) {
items.forEach(function(item) {
if (item.classList.contains('active')) {
item.classList.remove('active');
}
});
}
}
let resetActive = function (links, contents) {
for (items of [links, contents]) {
items.forEach(function (item) {
if (item.classList.contains("active")) {
item.classList.remove("active");
}
});
}
};
/*
* Count links array and return rank of given link
*/
let countNewActive = function(links, link)
{
let rank = 0;
for (let i = 0; i < links.length; ++i) {
rank++;
if(links[i] == link) {
return rank;
}
let countNewActive = function (links, link) {
let rank = 0;
for (let i = 0; i < links.length; ++i) {
rank++;
if (links[i] == link) {
return rank;
}
}
}
};
/*
* Set class active on both new elements: link and content
*/
let setNewActive = function(links, contents, rank)
{
if (! links[rank-1]) { rank = 1; }
link = links[rank-1];
let setNewActive = function (links, contents, rank) {
if (!links[rank - 1]) {
rank = 1;
}
link = links[rank - 1];
link.classList.add('active');
link.classList.add("active");
count = 0;
contents.forEach(function(pane) {
count++;
if (rank == count) {
pane.classList.add('active');
}
});
}
count = 0;
contents.forEach(function (pane) {
count++;
if (rank == count) {
pane.classList.add("active");
}
});
};
/*
* Set height of content pane
*/
let setPaneHeight = function(contents)
{
contents.forEach(function(pane) {
// let computedStyle = getComputedStyle(pane);
// console.log(computedStyle.height);
// comment prendre la hauteur d'une div masquée avec display:none
});
}
let setPaneHeight = function (contents) {
contents.forEach(function (pane) {
// let computedStyle = getComputedStyle(pane);
// console.log(computedStyle.height);
// comment prendre la hauteur d'une div masquée avec display:none
});
};
/*
* Check if links are defined in controller
* If true, disable javascript listener
*/
let isLinkRef = function(link) {
if (link.getAttribute('href') == "#") {
return false;
}
return true;
}
let isLinkRef = function (link) {
if (link.getAttribute("href") == "#") {
return false;
}
return true;
};
/*
* Main function
*/
window.addEventListener('load', function()
{
tabParams.forEach(function(unit) {
let tabPanel = document.querySelector('#'+ unit.id );
if (tabPanel) {
window.addEventListener("load", function () {
tabParams.forEach(function (unit) {
let tabPanel = document.querySelector("#" + unit.id);
if (tabPanel) {
let nav = tabPanel.querySelector("nav"),
tabs = nav.querySelectorAll("ul.nav-tabs li.nav-item"),
links = nav.querySelectorAll("ul.nav-tabs li.nav-item a.nav-link"),
contents = tabPanel.querySelectorAll("div.tab-content div.tab-pane");
if (unit.type == "pill") {
tabPanel.classList.add("pills");
}
let
nav = tabPanel.querySelector('nav'),
tabs = nav.querySelectorAll('ul.nav-tabs li.nav-item'),
links = nav.querySelectorAll('ul.nav-tabs li.nav-item a.nav-link'),
contents = tabPanel.querySelectorAll('div.tab-content div.tab-pane')
;
if (!unit.initPane) {
unit.initPane = 1;
}
if (unit.type == 'pill') {
tabPanel.classList.add('pills');
}
setPaneHeight(contents);
if (! unit.initPane) {
unit.initPane = 1;
}
setPaneHeight(contents);
// initial position
setNewActive(links, contents, unit.initPane);
// listen
links.forEach(function(link) {
if (isLinkRef(link) == false) {
link.addEventListener('click', function()
{
resetActive(links, contents);
setNewActive(links, contents, countNewActive(links, link));
});
}
});
// initial position
setNewActive(links, contents, unit.initPane);
// listen
links.forEach(function (link) {
if (isLinkRef(link) == false) {
link.addEventListener("click", function () {
resetActive(links, contents);
setNewActive(links, contents, countNewActive(links, link));
});
}
});
});
});
}
});
});