Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • geocontrib/geocontrib-frontend
  • ext_matthieu/geocontrib-frontend
  • fnecas/geocontrib-frontend
  • MatthieuE/geocontrib-frontend
4 results
Show changes
Showing
with 3570 additions and 682 deletions
<template>
<div class="ui grey segment">
<h3 class="ui header">
Paramètres du projet
</h3>
<div class="ui three stackable cards">
<div class="card">
<div class="content">
<h4 class="ui center aligned icon header">
<i
class="disabled grey eye icon"
aria-hidden="true"
/>
<div class="content">
Visibilité des signalements publiés
</div>
</h4>
</div>
<div class="center aligned extra content">
{{ project.access_level_pub_feature }}
</div>
</div>
<div class="card">
<div class="content">
<h4 class="ui center aligned icon header">
<i
class="disabled grey eye icon"
aria-hidden="true"
/>
<div class="content">
Visibilité des signalements archivés
</div>
</h4>
</div>
<div class="center aligned extra content">
{{ project.access_level_arch_feature }}
</div>
</div>
<div class="card">
<div class="content">
<h4 class="ui center aligned icon header">
<i
class="disabled grey cogs icon"
aria-hidden="true"
/>
<div class="content">
Modération
</div>
</h4>
</div>
<div class="center aligned extra content">
{{ project.moderation ? "Oui" : "Non" }}
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'ProjectParameters',
props: {
project: {
type: Object,
default: () => {
return {};
}
}
}
};
</script>
<template>
<div class="field">
<label for="attribute-value">
{{ attribute.label }}
</label>
<div>
<ExtraForm
:id="`attribute-value-for-${attribute.name}`"
ref="extraForm"
name="attribute-value"
:field="{ ...attribute, value }"
:use-value-only="true"
@update:value="updateValue($event.toString(), attribute.id)"
/>
</div>
</div>
</template>
<script>
import ExtraForm from '@/components/ExtraForm';
export default {
name: 'ProjectAttributeForm',
components: {
ExtraForm,
},
props: {
attribute: {
type: Object,
default: () => {
return {};
}
},
formProjectAttributes: {
type: Array,
default: () => {
return [];
}
}
},
computed: {
/**
* Retrieves the current value of a specific project attribute.
* This computed property checks the array of project attributes to find the one that matches
* the current attribute's ID. If the attribute is found, its value is returned.
* Otherwise, null is returned to indicate that the attribute is not set for the current project.
*
* @returns {String|null} The value of the attribute if it exists in the project's attributes; otherwise, null.
*/
value() {
// Searches for the attribute within the array of attributes associated with the project.
const projectAttribute = this.formProjectAttributes.find(el => el.attribute_id === this.attribute.id);
// Returns the value of the attribute if it exists, or null if the attribute is not found.
return projectAttribute ? projectAttribute.value : null;
},
},
created() {
// Checks if the component is being used in the context of creating a new project and attribute's default value is set
if (this.$route.name === 'project_create' && this.attribute.default_value !== null) {
// If so, initializes the attribute's value with its default value as defined in the attribute's settings.
this.updateValue(this.attribute.default_value, this.attribute.id);
}
},
methods: {
/**
* Updates or adds a value for a specific attribute in the project.
* This method emits an event to update the project's attributes with a new value for a given attribute ID.
* It is typically called when the user changes the value of an attribute in the UI.
*
* @param {String} value - The new value for the attribute.
* @param {Number} attributeId - The unique ID of the attribute being updated or added to the project.
*/
updateValue(value, attributeId) {
// Emits an event to the parent component, requesting an update to the project's attributes.
this.$emit('update:project_attributes', { value, attributeId });
}
}
};
</script>
<template>
<div>
<div class="ui form">
<div
v-if="(permissions.can_update_feature || permissions.can_delete_feature) && isOnline"
class="inline fields"
>
<label
data-tooltip="Choisir un type de sélection de signalements pour effectuer une action"
data-position="bottom left"
>Mode de sélection :</label>
<div class="field">
<div class="ui radio checkbox">
<input
id="edit-status"
v-model="mode"
type="radio"
name="mode"
value="edit-status"
>
<label for="edit-status">Édition de statut</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input
id="edit-attributes"
v-model="mode"
type="radio"
name="mode"
value="edit-attributes"
>
<label for="edit-attributes">Édition d'attribut</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input
id="delete-features"
v-model="mode"
type="radio"
name="mode"
value="delete-features"
>
<label for="delete-features">Suppression de signalement</label>
</div>
</div>
</div>
</div>
<div
data-tab="list"
class="dataTables_wrapper no-footer"
>
<table
id="table-features"
class="ui compact table unstackable dataTable"
aria-describedby="Liste des signalements du projet"
>
<thead>
<tr>
<th
v-if="(permissions.can_update_feature || permissions.can_delete_feature) && isOnline"
scope="col"
class="dt-center"
>
<div
v-if="massMode === 'edit-status' || massMode === 'delete-features'"
class="ui checkbox"
>
<input
id="select-all"
v-model="isAllSelected"
type="checkbox"
name="select-all"
>
<label for="select-all">
<span v-if="!isAllSelected">
Tout sélectionner
</span>
<span v-else>
Tout désélectionner
</span>
</label>
</div>
<span v-else>Sélection</span>
</th>
<th
scope="col"
class="dt-center"
>
<div
:class="isOnline ? 'pointer' : 'disabled'"
@click="changeSort('status')"
>
Statut
<i
:class="{
down: isSortedAsc('status'),
up: isSortedDesc('status'),
}"
class="icon sort"
aria-hidden="true"
/>
</div>
</th>
<th
scope="col"
class="dt-center"
>
<div
:class="isOnline ? 'pointer' : 'disabled'"
@click="changeSort('feature_type')"
>
Type
<i
:class="{
down: isSortedAsc('feature_type'),
up: isSortedDesc('feature_type'),
}"
class="icon sort"
aria-hidden="true"
/>
</div>
</th>
<th
scope="col"
class="dt-center"
>
<div
:class="isOnline ? 'pointer' : 'disabled'"
@click="changeSort('title')"
>
Nom
<i
:class="{
down: isSortedAsc('title'),
up: isSortedDesc('title'),
}"
class="icon sort"
aria-hidden="true"
/>
</div>
</th>
<th
scope="col"
class="dt-center"
>
<div
:class="isOnline ? 'pointer' : 'disabled'"
@click="changeSort('created_on')"
>
Date de création
<i
:class="{
down: isSortedAsc('created_on'),
up: isSortedDesc('created_on'),
}"
class="icon sort"
aria-hidden="true"
/>
</div>
</th>
<th
scope="col"
class="dt-center"
>
<div
:class="isOnline ? 'pointer' : 'disabled'"
@click="changeSort('updated_on')"
>
Dernière modification
<i
:class="{
down: isSortedAsc('updated_on'),
up: isSortedDesc('updated_on'),
}"
class="icon sort"
aria-hidden="true"
/>
</div>
</th>
<th
v-if="user"
scope="col"
class="dt-center"
>
<div
:class="isOnline ? 'pointer' : 'disabled'"
@click="changeSort('display_creator')"
>
Auteur
<i
:class="{
down: isSortedAsc('display_creator'),
up: isSortedDesc('display_creator'),
}"
class="icon sort"
aria-hidden="true"
/>
</div>
</th>
<th
v-if="user"
scope="col"
class="dt-center"
>
<div
:class="isOnline ? 'pointer' : 'disabled'"
@click="changeSort('display_last_editor')"
>
Dernier éditeur
<i
:class="{
down: isSortedAsc('display_last_editor'),
up: isSortedDesc('display_last_editor'),
}"
class="icon sort"
aria-hidden="true"
/>
</div>
</th>
</tr>
</thead>
<tbody>
<tr
v-for="(feature, index) in paginatedFeatures"
:key="index"
>
<td
v-if="(permissions.can_update_feature || permissions.can_delete_feature) && isOnline"
id="select"
class="dt-center"
>
<div
:class="['ui checkbox', { disabled: isAllSelected || !checkRights(feature) }]"
>
<input
:id="feature.feature_id"
type="checkbox"
:value="feature.feature_id"
:checked="isFeatureSelected(feature)"
:disabled="isAllSelected || !checkRights(feature)"
name="select"
@input="handleFeatureSelection($event, feature)"
>
<label :for="feature.feature_id" />
</div>
</td>
<td
id="status"
class="dt-center"
>
<div
v-if="feature.status === 'archived'"
data-tooltip="Archivé"
>
<i
class="grey archive icon"
aria-hidden="true"
/>
</div>
<div
v-else-if="feature.status === 'pending'"
data-tooltip="En attente de publication"
>
<i
class="teal hourglass outline icon"
aria-hidden="true"
/>
</div>
<div
v-else-if="feature.status === 'published'"
data-tooltip="Publié"
>
<i
class="olive check icon"
aria-hidden="true"
/>
</div>
<div
v-else-if="feature.status === 'draft'"
data-tooltip="Brouillon"
>
<i
class="orange pencil alternate icon"
aria-hidden="true"
/>
</div>
</td>
<td
id="type"
class="dt-center"
>
<router-link
:to="{
name: 'details-type-signalement',
params: {
feature_type_slug: feature.feature_type.slug,
},
}"
class="ellipsis space-left"
>
{{ feature.feature_type.title }}
</router-link>
</td>
<td
id="name"
class="dt-center"
>
<router-link
:to="{
name: 'details-signalement-filtre',
query: { ...queryparams, offset: queryparams.offset + index }
}"
class="ellipsis space-left"
>
{{ feature.title || feature.feature_id }}
</router-link>
</td>
<td
id="create"
class="dt-center"
>
{{ feature.created_on | formatDate }}
</td>
<td
id="update"
class="dt-center"
>
{{ feature.updated_on | formatDate }}
</td>
<td
v-if="user"
id="author"
class="dt-center"
>
{{ feature.display_creator || ' ---- ' }}
</td>
<td
v-if="user"
id="last_editor"
class="dt-center"
>
{{ feature.display_last_editor || ' ---- ' }}
</td>
</tr>
<tr
v-if="featuresCount === 0"
class="odd"
>
<td
colspan="5"
class="dataTables_empty"
valign="top"
>
Aucune donnée disponible
</td>
</tr>
</tbody>
</table>
<div
v-if="pageNumbers.length > 1"
id="table-features_info"
class="dataTables_info"
role="status"
aria-live="polite"
>
Affichage de l'élément {{ pagination.start + 1 }} à
{{ displayedPageEnd }}
sur {{ featuresCount }} éléments
</div>
<div
v-if="pageNumbers.length > 1 && isOnline"
id="table-features_paginate"
class="dataTables_paginate paging_simple_numbers"
>
<a
id="table-features_previous"
:class="[
'paginate_button previous',
{ disabled: pagination.currentPage === 1 },
]"
aria-controls="table-features"
data-dt-idx="0"
tabindex="0"
@click="$emit('update:page', 'previous')"
>Précédent</a>
<span>
<span v-if="pagination.currentPage > 5">
<a
key="page1"
class="paginate_button"
aria-controls="table-features"
data-dt-idx="1"
tabindex="0"
@click="$emit('update:page', 1)"
>1</a>
<span class="ellipsis"></span>
</span>
<a
v-for="pageNumber in displayedPageNumbers"
:key="'page' + pageNumber"
:class="[
'paginate_button',
{ current: pageNumber === pagination.currentPage },
]"
aria-controls="table-features"
data-dt-idx="1"
tabindex="0"
@click="$emit('update:page', pageNumber)"
>{{ pageNumber }}</a>
<span v-if="(lastPageNumber - pagination.currentPage) > 4">
<span class="ellipsis"></span>
<a
:key="'page' + lastPageNumber"
class="paginate_button"
aria-controls="table-features"
data-dt-idx="1"
tabindex="0"
@click="$emit('update:page', lastPageNumber)"
>{{ lastPageNumber }}</a>
</span>
</span>
<a
id="table-features_next"
:class="[
'paginate_button next',
{ disabled: pagination.currentPage === pageNumbers.length },
]"
aria-controls="table-features"
data-dt-idx="7"
tabindex="0"
@click="$emit('update:page', 'next')"
>Suivant</a>
</div>
</div>
</div>
</template>
<script>
import { mapState, mapGetters, mapMutations } from 'vuex';
import { formatStringDate } from '@/utils';
export default {
name: 'FeatureListTable',
filters: {
formatDate(value) {
return formatStringDate(value);
},
},
beforeRouteLeave (to, from, next) {
if (to.name !== 'editer-attribut-signalement') {
this.UPDATE_CHECKED_FEATURES([]); // empty if not needed anymore
}
next(); // continue navigation
},
props: {
paginatedFeatures: {
type: Array,
default: null,
},
pageNumbers: {
type: Array,
default: null,
},
allSelected: {
type: Boolean,
default: false,
},
checkedFeatures: {
type: Array,
default: null,
},
featuresCount: {
type: Number,
default: 0,
},
pagination: {
type: Object,
default: null,
},
sort: {
type: Object,
default: null,
},
queryparams: {
type: Object,
default: null,
},
editAttributesFeatureType: {
type: String,
default: null,
},
},
computed: {
...mapGetters(['permissions']),
...mapState([
'user',
'USER_LEVEL_PROJECTS',
'isOnline'
]),
...mapState('projects', ['project']),
...mapState('feature', ['clickedFeatures', 'massMode']),
mode: {
get() {
return this.massMode;
},
set(newMode) {
this.TOGGLE_MASS_MODE(newMode);
// Reset all selections
this.isAllSelected = false;
this.UPDATE_CLICKED_FEATURES([]);
this.UPDATE_CHECKED_FEATURES([]);
},
},
userStatus() {
return this.USER_LEVEL_PROJECTS ? this.USER_LEVEL_PROJECTS[this.$route.params.slug] : '';
},
checkedFeaturesSet() {
return new Set(this.checkedFeatures); // Set améliore la performance sur la recherche
},
isAllSelected: {
get() {
return this.allSelected;
},
set(isChecked) {
this.$emit('update:allSelected', isChecked);
},
},
displayedPageEnd() {
return this.featuresCount <= this.pagination.end
? this.featuresCount
: this.pagination.end;
},
lastPageNumber() {
return this.pageNumbers.slice(-1)[0];
},
displayedPageNumbers() {
//* s'il y a moins de 5 pages, renvoyer toutes les pages
if (this.lastPageNumber < 5) {
return this.pageNumbers;
}
//* si la page courante est inférieur à 5, la liste commence à l'index 0 et on retourne 5 pages
let firstPageInList = 0;
let pagesQuantity = 5;
//* à partir de la 5ième page et jusqu'à la 4ième page avant la fin : n'afficher que 3 page entre les ellipses et la page courante doit être au milieu
if (this.pagination.currentPage >= 5 && !((this.lastPageNumber - this.pagination.currentPage) < 4)) {
firstPageInList = this.pagination.currentPage - 2;
pagesQuantity = 3;
}
//* à partir de 4 résultat avant la fin afficher seulement les 5 derniers résultats
if ((this.lastPageNumber - this.pagination.currentPage) < 4) {
firstPageInList = this.lastPageNumber - 5;
}
return this.pageNumbers.slice(firstPageInList, firstPageInList + pagesQuantity);
},
},
methods: {
...mapMutations('feature', [
'UPDATE_CLICKED_FEATURES',
'UPDATE_CHECKED_FEATURES',
'TOGGLE_MASS_MODE',
]),
/**
* Vérifie si une feature doit être cochée en fonction de la sélection globale et des droits d'édition.
* @param {Object} feature - L'objet représentant la feature.
* @returns {Boolean} - `true` si la feature doit être cochée.
*/
isFeatureSelected(feature) {
if (this.isAllSelected) {
return this.checkRights(feature); // Si tout doit être sélectionné, on vérifie les droits
}
return this.checkedFeaturesSet.has(feature.feature_id);
},
/**
* Ajoute ou supprime une feature de la sélection en fonction de l'état de la checkbox.
* Met également à jour les features cliquées et les restrictions d'édition d'attributs.
* @param {Event} event - L'événement de changement de l'input checkbox.
* @param {Object} feature - La feature associée.
*/
handleFeatureSelection(event, feature) {
const isChecked = event.target.checked;
const updatedFeatures = isChecked
? [...this.checkedFeatures, feature.feature_id]
: this.checkedFeatures.filter(id => id !== feature.feature_id);
this.$store.commit('feature/UPDATE_CHECKED_FEATURES', updatedFeatures);
this.trackClickedFeature(feature);
this.manageAttributeEdition(feature, updatedFeatures.length);
},
/**
* Gère les restrictions sur la modification des attributs en fonction de la sélection en masse.
* @param {Object} feature - La feature actuellement sélectionnée.
* @param {Number} checkedCount - Nombre total de features actuellement cochées.
*/
manageAttributeEdition(feature, checkedCount) {
if (this.massMode !== 'edit-attributes') return;
if (checkedCount === 1) {
// Premier élément sélectionné, on stocke son type pour restreindre la sélection
this.$emit('update:editAttributesFeatureType', feature.feature_type.slug);
} else if (checkedCount === 0) {
// Dernière feature désélectionnée -> on réinitialise la restriction
this.$emit('update:editAttributesFeatureType', null);
}
},
/**
* Ajoute une feature cliquée à la liste pour conserver son historique de sélection.
* Permet de gérer la sélection de plusieurs features sur différentes pages sans surcharger la mémoire.
* @param {Object} feature - La feature cliquée.
*/
trackClickedFeature(feature) {
this.UPDATE_CLICKED_FEATURES([
...this.clickedFeatures,
{ feature_id: feature.feature_id, feature_type: feature.feature_type.slug }
]);
},
/**
* Vérifie si l'utilisateur a le droit de supprimer une feature.
* @param {Object} feature - La feature à vérifier.
* @returns {Boolean} - `true` si l'utilisateur peut supprimer la feature.
*/
canDeleteFeature(feature) {
if (this.userStatus === 'Administrateur projet' || this.user.is_superuser) {
return true; // Un administrateur ou super utilisateur peut tout supprimer
}
// Sinon, on ne peut supprimer que ses propres features
return feature.creator === this.user.id;
},
/**
* Vérifie si l'utilisateur a le droit de modifier une feature.
* @param {Object} feature - La feature à vérifier.
* @returns {Boolean} - `true` si l'utilisateur peut modifier la feature.
*/
canEditFeature(feature) {
const permissions = {
'Administrateur projet' : ['draft', 'pending', 'published', 'archived'],
Modérateur : ['draft', 'pending', 'published'],
'Super Contributeur' : ['draft', 'pending', 'published'],
Contributeur : ['draft', 'pending', 'published'],
};
if (this.checkedFeatures.length > 0 && // check if selection should be restricted to a specific feature type, for attributes modification
feature.feature_type.slug !== this.editAttributesFeatureType &&
this.massMode === 'edit-attributes') {
return false;
} else if (this.user.is_superuser) {
return true;
} else if (this.userStatus === 'Contributeur' && feature.creator !== this.user.id) {
return false;
} else if (permissions[this.userStatus]) {
return permissions[this.userStatus].includes(feature.status);
} else {
return false;
}
},
checkRights(feature) {
if (this.massMode.includes('edit')) {
return this.canEditFeature(feature);
} else if (this.massMode === 'delete-features') {
return this.canDeleteFeature(feature);
}
},
isSortedAsc(column) {
return this.sort.column === column && this.sort.ascending;
},
isSortedDesc(column) {
return this.sort.column === column && !this.sort.ascending;
},
changeSort(column) {
if (!this.isOnline) return;
if (this.sort.column === column) {
//changer only order
this.$emit('update:sort', {
column: this.sort.column,
ascending: !this.sort.ascending,
});
} else { // change column and reset order
this.$emit('update:sort', { column, ascending: true });
}
},
},
};
</script>
<style scoped>
/* datatables */
.dataTables_wrapper {
position: relative;
clear: both;
}
.dataTables_paginate {
margin-bottom: 1rem;
}
table.dataTable th.dt-center, table.dataTable td.dt-center, table.dataTable td.dataTables_empty {
text-align: center;
}
.dataTables_wrapper .dataTables_length,
.dataTables_wrapper .dataTables_filter,
.dataTables_wrapper .dataTables_info,
.dataTables_wrapper .dataTables_processing,
.dataTables_wrapper .dataTables_paginate {
color: #333;
}
.dataTables_wrapper .dataTables_info {
clear: both;
float: left;
padding-top: 0.755em;
}
.dataTables_wrapper .dataTables_paginate {
float: right;
text-align: right;
padding-top: 0.25em;
}
.dataTables_wrapper .dataTables_paginate .paginate_button.current,
.dataTables_wrapper .dataTables_paginate .paginate_button.current:hover {
color: #333 !important;
border: 1px solid #979797;
background: -webkit-gradient(
linear,
left top,
left bottom,
color-stop(0%, #fff),
color-stop(100%, #dcdcdc)
);
background: -webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%);
background: -moz-linear-gradient(top, #fff 0%, #dcdcdc 100%);
background: -ms-linear-gradient(top, #fff 0%, #dcdcdc 100%);
background: -o-linear-gradient(top, #fff 0%, #dcdcdc 100%);
background: linear-gradient(to bottom, #fff 0%, #dcdcdc 100%);
}
.dataTables_wrapper .dataTables_paginate .paginate_button {
box-sizing: border-box;
display: inline-block;
min-width: 1.5em;
padding: 0.5em 1em;
margin-left: 2px;
text-align: center;
text-decoration: none !important;
cursor: pointer;
color: #333 !important;
border: 1px solid transparent;
border-radius: 2px;
}
.dataTables_wrapper .dataTables_paginate .paginate_button:hover {
color: white !important;
border: 1px solid #111;
background: -webkit-gradient(
linear,
left top,
left bottom,
color-stop(0%, #585858),
color-stop(100%, #111)
);
background: -webkit-linear-gradient(top, #585858 0%, #111 100%);
background: -moz-linear-gradient(top, #585858 0%, #111 100%);
background: -ms-linear-gradient(top, #585858 0%, #111 100%);
background: -o-linear-gradient(top, #585858 0%, #111 100%);
background: linear-gradient(to bottom, #585858 0%, #111 100%);
}
.dataTables_wrapper .dataTables_paginate .paginate_button.disabled,
.dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover,
.dataTables_wrapper .dataTables_paginate .paginate_button.disabled:active {
cursor: default;
color: #666 !important;
border: 1px solid transparent;
background: transparent;
box-shadow: none;
}
.dataTables_wrapper .dataTables_paginate .ellipsis {
padding: 0 1em;
}
i.icon.sort:not(.down):not(.up) {
color: rgb(220, 220, 220);
}
.grey {
color: #bbbbbb;
}
.ui.dropdown .menu .left.menu, .ui.dropdown > .left.menu .menu {
margin-right: 0 !important;
}
.table-mobile-buttons {
margin-bottom: 1em;
}
/* increase contrast between available checkboxes and disabled ones */
#table-features .ui.disabled.checkbox label::before {
background-color: #fbf5f5;;
}
#select-all + label {
text-align: left;
&:hover {
cursor: pointer;
}
}
@media only screen and (min-width: 761px) {
.table-mobile-buttons {
display: none !important;
}
}
/*
Max width before this PARTICULAR table gets nasty
This query will take effect for any screen smaller than 760px
and also iPads specifically.
*/
@media only screen and (max-width: 760px) {
.table-mobile-buttons {
display: flex !important;
}
.inline.fields label {
width: 100% !important;
}
/* hide table border */
.ui.table {
border: none !important;
margin-top: 2em;
}
/* Force table to not be like tables anymore */
table,
thead,
tbody,
th,
td,
tr {
display: block;
}
/* Hide table headers (but not display: none;, for accessibility) */
thead tr {
position: absolute;
top: -9999px;
left: -9999px;
}
tr { /* style as a card */
border: 1px solid #ccc;
border-radius: 7px;
margin-bottom: 3vh;
padding: 0 2vw .5em 2vw;
box-shadow: rgba(50, 50, 50, 0.1) 2px 5px 10px ;
}
td {
/* Behave like a "row" */
border: none;
border-bottom: 1px solid #eee;
position: relative;
padding-left: 50%;
}
.ui.table tr td {
border-top: none;
}
.ui.compact.table td {
padding: .2em;
}
td:nth-of-type(1) {
border: none !important;
padding: .25em !important;
}
td:nth-of-type(8) {
border-bottom: none !important;
}
td:before {
/* Now like a table header */
position: absolute;
/* Top/left values mimic padding */
left: 6px;
padding-right: 10px;
white-space: nowrap;
}
/*
Label the data
*/
td#select:before {
content: "";
}
td#status:before {
content: "Statut";
}
td#type:before {
content: "Type";
}
td#name:before {
content: "Nom";
}
td#create:before {
content: "Date de création";
}
td#update:before {
content: "Dernière modification";
}
td#author:before {
content: "Auteur";
}
td#last_editor:before {
content: "Dernier éditeur";
}
table.dataTable th.dt-center, table.dataTable td.dt-center, table.dataTable {
text-align: right;
}
#select .ui.checkbox {
position: absolute;
left: calc(-1vw - 20px);
top: -12px;
min-height: 24px;
font-size: 1rem;
line-height: 24px;
min-width: 24px;
}
#select .ui.checkbox .box::before, #select .ui.checkbox label::before,
#select .ui.checkbox .box::after, #select .ui.checkbox label::after {
width: 24px;
height: 24px;
}
/* cover all the card to ease selection by user */
#select .ui.checkbox {
width: 100%;
}
#select .ui.checkbox input[type="checkbox"] {
width: calc(100% + 1vw + 20px + 4vw);
height: calc(14em + 12px);
}
/* keep the links above the checkbox input to receive the click event */
table a {
z-index: 4;
position: sticky;
}
#select .ui.checkbox .box::before, #select .ui.checkbox label::before {
border-radius: 12px;
}
#select .ui.checkbox .box::after, #select .ui.checkbox label::after {
font-size: 18px;
}
.dataTables_wrapper .dataTables_info,
.dataTables_wrapper .dataTables_paginate {
width: 100%;
text-align: center;
margin: .5em 0;
}
/* preserve space to not overlap column label */
.space-left {
margin-left: 2.5em;
}
}
@media only screen and (max-width: 410px) {
.ui.table tr td {
border: none;
}
}
</style>
<template>
<div>
<div
id="feature-list-container"
class="ui mobile-column"
>
<div class="mobile-fullwidth">
<h1>Signalements</h1>
</div>
<div class="no-padding-mobile mobile-fullwidth">
<div class="ui large text loader">
Chargement
</div>
<div class="ui secondary menu no-margin">
<a
id="show-map"
:class="['item no-margin', { active: showMap }]"
data-tab="map"
data-tooltip="Carte"
data-position="bottom left"
@click="$emit('show-map', true)"
>
<i
class="map fitted icon"
aria-hidden="true"
/>
</a>
<a
id="show-list"
:class="['item no-margin', { active: !showMap }]"
data-tab="list"
data-tooltip="Liste"
data-position="bottom left"
@click="$emit('show-map', false)"
>
<i
class="list fitted icon"
aria-hidden="true"
/>
</a>
<div class="item">
<h4>
{{ featuresCount }} signalement{{ featuresCount > 1 ? "s" : "" }}
</h4>
</div>
<div
v-if="
project &&
filteredFeatureTypeChoices.length > 0 &&
permissions.can_create_feature
"
id="button-dropdown"
class="item right"
>
<div
class="ui dropdown button compact button-hover-green"
data-tooltip="Ajouter un signalement"
data-position="bottom right"
@click="toggleAddFeature"
>
<i
class="plus fitted icon"
aria-hidden="true"
/>
<div
v-if="showAddFeature"
class="menu left transition visible"
style="z-index: 9999"
>
<div class="header">
Ajouter un signalement du type
</div>
<div class="scrolling menu text-wrap">
<router-link
v-for="(type, index) in filteredFeatureTypeChoices"
:key="type.slug + index"
:to="{
name: 'ajouter-signalement',
params: { slug_type_signal: type.slug },
}"
class="item"
>
{{ type.title }}
</router-link>
</div>
</div>
</div>
<div
v-if="(allSelected || checkedFeatures.length > 0) && massMode.includes('edit') && isOnline"
id="edit-button"
class="ui dropdown button compact button-hover-green tiny-margin-left"
:data-tooltip="`Modifier le${massMode.includes('status') ? ' statut' : 's attributs'} des signalements`"
data-position="bottom right"
@click="editFeatures"
>
<i
class="pencil fitted icon"
aria-hidden="true"
/>
<div
v-if="showModifyStatus"
class="menu left transition visible"
style="z-index: 9999"
>
<div class="header">
Modifier le statut des Signalements
</div>
<div class="scrolling menu text-wrap">
<span
v-for="status in availableStatus"
:key="status.value"
class="item"
@click="$emit('edit-status', status.value)"
>
{{ status.name }}
</span>
</div>
</div>
</div>
<div
v-if="(allSelected || checkedFeatures.length > 0) && massMode === 'delete-features' && isOnline"
class="ui button compact button-hover-red tiny-margin-left"
data-tooltip="Supprimer tous les signalements sélectionnés"
data-position="bottom right"
@click="$emit('toggle-delete-modal')"
>
<i
class="grey trash fitted icon"
aria-hidden="true"
/>
</div>
</div>
</div>
</div>
</div>
<section
id="form-filters"
class="ui form grid equal width"
>
<div
id="type"
:class="['field column', { 'disabled': !isOnline }]"
>
<label>Type</label>
<Multiselect
v-model="form.type"
:options="featureTypeOptions"
:multiple="true"
:searchable="false"
:close-on-select="false"
:show-labels="false"
placeholder="Sélectionner un type"
track-by="value"
label="name"
/>
</div>
<div
id="statut"
:class="['field column', { 'disabled': !isOnline }]"
>
<label>Statut</label>
<Multiselect
v-model="form.status"
:options="statusOptions"
:multiple="true"
:searchable="false"
:close-on-select="false"
:show-labels="false"
placeholder="Sélectionner un statut"
track-by="value"
label="name"
/>
</div>
<div
id="name"
:class="['field column', { 'disabled': !isOnline }]"
>
<label>Nom</label>
<div class="ui icon input">
<i
class="search icon"
aria-hidden="true"
/>
<div class="ui action input">
<input
v-model="form.title"
type="text"
name="title"
@keyup.enter="resetPaginationNfetchFeatures"
>
<button
id="submit-search"
class="ui teal icon button"
@click="resetPaginationNfetchFeatures"
>
<i
class="search icon"
aria-hidden="true"
/>
</button>
</div>
</div>
</div>
</section>
</div>
</template>
<script>
import { mapState, mapGetters } from 'vuex';
import Multiselect from 'vue-multiselect';
import { statusChoices, allowedStatus2change } from '@/utils';
const initialPagination = {
currentPage: 1,
pagesize: 15,
start: 0,
end: 15,
};
export default {
name: 'FeaturesListAndMapFilters',
components: {
Multiselect
},
props: {
showMap: {
type: Boolean,
default: true
},
featuresCount: {
type: Number,
default: 0
},
pagination: {
type: Object,
default: () => {
return {
...initialPagination
};
}
},
allSelected: {
type: Boolean,
default: false,
},
editAttributesFeatureType: {
type: String,
default: null,
},
},
data() {
return {
form: {
type: [],
status: [],
title: null,
},
lat: null,
lng: null,
showAddFeature: false,
showModifyStatus: false,
zoom: null,
};
},
computed: {
...mapState([
'user',
'USER_LEVEL_PROJECTS',
'isOnline'
]),
...mapState('feature', [
'checkedFeatures',
'massMode',
]),
...mapState('feature-type', [
'feature_types',
]),
...mapState('projects', [
'project',
]),
...mapGetters([
'permissions',
]),
availableStatus() {
if (this.project && this.user) {
const isModerate = this.project.moderation;
const userStatus = this.USER_LEVEL_PROJECTS[this.project.slug];
const isOwnFeature = true; //* dans ce cas le contributeur est toujours l'auteur des signalements qu'il peut modifier
return allowedStatus2change(this.user, isModerate, userStatus, isOwnFeature);
}
return [];
},
featureTypeTitles() {
return this.feature_types.map((el) => el.title);
},
featureTypeOptions() {
return this.feature_types.map((el) => ({ name: el.title, value: el.slug }));
},
statusOptions() {
//* if project is not moderate, remove pending status
return statusChoices.filter((el) =>
this.project && this.project.moderation ? true : el.value !== 'pending'
);
},
filteredFeatureTypeChoices() {
return this.feature_types.filter((fType) =>
!fType.geom_type.includes('multi')
);
},
},
watch: {
'form.type'(newValue) {
this.$emit('set-filter', { type: newValue });
this.resetPaginationNfetchFeatures();
},
'form.status': {
deep: true,
handler(newValue) {
this.$emit('set-filter', { status: newValue });
this.resetPaginationNfetchFeatures();
}
},
'form.title'(newValue) {
this.$emit('set-filter', { title: newValue });
this.resetPaginationNfetchFeatures();
},
},
mounted() {
window.addEventListener('mousedown', this.clickOutsideDropdown);
},
destroyed() {
window.removeEventListener('mousedown', this.clickOutsideDropdown);
},
methods: {
resetPaginationNfetchFeatures() {
this.$emit('reset-pagination');
this.$emit('fetch-features');
},
toggleAddFeature() {
this.showAddFeature = !this.showAddFeature;
this.showModifyStatus = false;
},
editFeatures() {
switch (this.massMode) {
case 'edit-status':
this.toggleModifyStatus();
break;
case 'edit-attributes':
this.displayAttributesForm();
break;
}
},
toggleModifyStatus() {
this.showModifyStatus = !this.showModifyStatus;
this.showAddFeature = false;
},
displayAttributesForm() {
if (this.checkedFeatures.length > 1) {
this.$router.push({
name: 'editer-attribut-signalement',
params: {
slug_type_signal: this.editAttributesFeatureType,
},
});
} else {
this.$store.commit('DISPLAY_MESSAGE', {
comment: 'Veuillez sélectionner au moins 2 signalements pour l\'édition multiple d\'attributs'
});
}
},
clickOutsideDropdown(e) {
if (!e.target.closest('#button-dropdown')) {
this.showModifyStatus = false;
setTimeout(() => { //* timout necessary to give time to click on link to add feature
this.showAddFeature = false;
}, 500);
}
},
}
};
</script>
<style lang="less" scoped>
#feature-list-container {
display: flex;
justify-content: space-between;
.no-padding-mobile {
width: 100%;
margin-left: 25%;
.secondary.menu #button-dropdown {
z-index: 10;
margin-right: 0;
padding-right: 0;
}
}
}
#form-filters {
margin: 0;
label + div {
min-height: 42px;
}
}
.ui.dropdown .menu .left.menu, .ui.dropdown > .left.menu .menu {
margin-right: 0 !important;
}
@media screen and (min-width: 767px) {
#form-filters {
div.field:first-child {
padding-left: 0;
}
div.field:last-child {
padding-right: 0;
}
}
}
@media screen and (max-width: 767px) {
#feature-list-container > .mobile-fullwidth {
width: 100% !important;
}
.no-margin-mobile {
margin: 0 !important;
}
.no-padding-mobile {
padding-top: 0 !important;
padding-bottom: 0 !important;
margin-left: 0 !important;
}
.mobile-column {
flex-direction: column;
}
#form-filters > .field.column {
width: 100%;
padding: 0;
}
#form-filters > .field.column:first-child {
margin-top: 1rem;
}
#form-filters > .field.column:last-child {
margin-bottom: 1rem;
}
.map-container {
width: 100%;
}
}
</style>
<style>
#form-filters .multiselect__tags {
white-space: normal !important;
}
#form-filters .multiselect__tag {
background: var(--primary-color, #008c86) !important;
}
#form-filters .multiselect__tag-icon:focus, #form-filters .multiselect__tag-icon:hover{
background: var(--primary-highlight-color, #006f6a) !important;
}
#form-filters .multiselect__tag-icon:not(:hover)::after {
color: var(--primary-highlight-color, #006f6a);
filter: brightness(0.6);
}
#form-filters .multiselect__option--selected:not(:hover) {
background-color: #e8e8e8 !important;
}
</style>
\ No newline at end of file
<template>
<div class="field">
<Dropdown
v-if="!disabled"
:options="projectMemberOptions"
:selected="selectedMember ? selectedMember.name : ''"
:selection.sync="selectedMember"
:search="true"
:clearable="true"
/>
<div v-else-if="selectedMember && selectedMember.name && Array.isArray(selectedMember.name)">
<span> {{ selectedMember.name[0] || selectedMember.name[1] }}</span>
</div>
</div>
</template>
<script>
import Dropdown from '@/components/Dropdown.vue';
import { formatUserOption } from '@/utils';
import { mapState } from 'vuex';
export default {
name: 'ProjectMemberSelect',
components: {
Dropdown,
},
props: {
selectedUserId: {
type: Number,
default: null,
},
disabled: {
type: Boolean,
default: false,
}
},
computed: {
...mapState('projects', [
'projectUsers'
]),
projectMemberOptions: function () {
return this.projectUsers
.filter((el) => el.level.codename !== 'logged_user') // Filter out user not member of the project (with level lower than contributor)
.map((el) => formatUserOption(el.user)); // Format user data to fit dropdown option structure
},
selectedMember: {
get() {
return this.projectMemberOptions.find(el => el.value === this.selectedUserId);
},
set(newValue) {
/**
* If the user delete previous assigned_member the value is undefined
* We replace it by null in order to allow empty field to be sent with the request
* & to comply with UPDATE_FORM_FIELD mutation logic
* TODO: If refactoring the app one day -> merge together both featureEdit form and feature store form to work the same way
*/
this.$emit('update:user', newValue.value || null);
},
}
},
created() {
this.$store.dispatch('projects/GET_PROJECT_USERS', this.$route.params.slug);
},
};
</script>
\ No newline at end of file
<template>
<Multiselect
v-model="selection"
:class="{ multiple }"
:options="options"
:allow-empty="true"
track-by="label"
label="label"
:reset-after="false"
select-label=""
selected-label=""
deselect-label=""
:searchable="false"
:placeholder="placeholder"
:clear-on-select="false"
:preserve-search="true"
:multiple="multiple"
:disabled="loading"
@select="select"
@remove="remove"
@close="close"
>
<template
slot="option"
slot-scope="props"
>
<span :title="props.option.label">{{ props.option.label }}</span>
</template>
<template
v-if="multiple"
slot="selection"
slot-scope="{ values }"
>
<span
v-if="values && values.length > 1"
class="multiselect__single"
>
{{ values.length }} options sélectionnées
</span>
<span
v-else
class="multiselect__single"
>{{ currentSelectionLabel || selection.label }}</span>
</template>
</Multiselect>
</template>
<script>
import Multiselect from 'vue-multiselect';
export default {
name: 'DropdownMenuItem',
components: {
Multiselect
},
props: {
placeholder: {
type: String,
default: 'Sélectionnez une valeur'
},
options: {
type: Array,
default: () => {
return [];
}
},
loading: {
type: Boolean,
default: false
},
multiple: {
type: Boolean,
default: false
},
currentSelection: {
type: [String, Array, Boolean],
default: null,
},
defaultFilter: {
type: [String, Array, Boolean],
default: null,
}
},
data() {
return {
selection: null,
};
},
computed: {
/**
* Get the label of an option to work with project attributes options as JSON
*/
currentSelectionLabel() {
const option = this.options.find(opt => opt.value === this.currentSelection);
return option ? option.label : '';
}
},
watch: {
selection: {
deep: true,
handler(newValue) {
if (!newValue) {
this.selection = this.options[0];
this.$emit('filter', this.selection);
}
}
},
currentSelection(newValue) {
this.updateSelection(newValue);
},
},
created() {
if (this.currentSelection !== null) {
this.selection = this.options.find(opt => opt.value === this.currentSelection);
} else {
this.selection = this.options[0];
}
},
methods: {
select(e) {
this.$emit('filter', e);
},
remove(e) {
this.$emit('remove', e);
},
close() {
this.$emit('close', this.selection);
},
/**
* Normalizes the input value(s) to an array of strings.
* This handles both single string inputs and comma-separated strings, converting them into an array.
*
* @param {String|Array} value - The input value to normalize, can be a string or an array of strings.
* @return {Array} An array of strings representing the input values.
*/
normalizeValues(value) {
// If the value is a string and contains commas, split it into an array; otherwise, wrap it in an array.
return typeof value === 'string' ? (value.includes(',') ? value.split(',') : [value]) : value;
},
/**
* Updates the current selection based on new value, ensuring compatibility with multiselect.
* This method processes the new selection value, accommodating both single and multiple selections,
* and updates the internal `selection` state with the corresponding option objects from `options`.
*
* @param {String|Array} value - The new selection value(s), can be a string or an array of strings.
*/
// Check if the component is in multiple selection mode and the new value is provided.
updateSelection(value) {
if (this.multiple && value) {
// Normalize the value to an array format, accommodating both single and comma-separated values.
const normalizedValues = this.normalizeValues(value);
// Map each value to its corresponding option object based on the 'value' field.
this.selection = normalizedValues.map(value =>
this.options.find(option => option.value === value)
);
} else {
// For single selection mode or null value, find the option object that matches the value.
this.selection = this.options.find(option => option.value === value);
}
}
}
};
</script>
<style>
#filters-container .multiple .multiselect__option--selected:not(:hover) {
background-color: #e8e8e8 !important;
}
#filters-container .multiselect--disabled .multiselect__select {
background: 0, 0 !important;
}
</style>
\ No newline at end of file
<template>
<div
:id="project.title"
class="item"
data-test="project-list-item"
>
<div class="ui tiny image">
<img
:src="
!project.thumbnail
? require('@/assets/img/default.png')
: DJANGO_BASE_URL + project.thumbnail + refreshId()
"
alt="Thumbnail du projet"
>
</div>
<div class="middle aligned content">
<router-link
:to="{
name: 'project_detail',
params: { slug: project.slug },
}"
class="header"
>
{{ project.title }}
</router-link>
<div class="description">
<textarea
:id="`editor-${project.slug}`"
:value="project.description"
:data-preview="`#preview-${project.slug}`"
hidden
/>
<div
:id="`preview-${project.slug}`"
class="preview"
/>
</div>
<div class="meta top">
<span class="right floated">
<strong v-if="project.moderation">Projet modéré</strong>
<strong v-else>Projet non modéré</strong>
</span>
<span>Niveau d'autorisation requis :
{{ project.access_level_pub_feature }}</span><br>
<span v-if="user">
Mon niveau d'autorisation :
<span v-if="USER_LEVEL_PROJECTS && project">{{
USER_LEVEL_PROJECTS[project.slug]
}}</span>
<span v-if="user && user.is_administrator">{{
"+ Gestionnaire métier"
}}</span>
</span>
</div>
<div class="meta">
<span class="right floated">
<i
class="calendar icon"
aria-hidden="true"
/>&nbsp; {{ project.created_on }}
</span>
<span data-tooltip="Membres">
{{ project.nb_contributors }}&nbsp;
<i
class="user icon"
aria-hidden="true"
/>
</span>
<span data-tooltip="Signalements publiés">
{{ project.nb_published_features }}&nbsp;
<i
class="map marker icon"
aria-hidden="true"
/>
</span>
<span data-tooltip="Commentaires">
{{ project.nb_published_features_comments }}&nbsp;
<i
class="comment icon"
aria-hidden="true"
/>
</span>
</div>
</div>
</div>
</template>
<script>
import TextareaMarkdown from 'textarea-markdown';
import { mapState } from 'vuex';
export default {
name: 'ProjectsListItem',
props: {
project: {
type: Object,
default: () => {
return {};
}
}
},
computed: {
...mapState([
'user',
'USER_LEVEL_PROJECTS'
]),
DJANGO_BASE_URL() {
return this.$store.state.configuration.VUE_APP_DJANGO_BASE;
},
},
mounted() {
let textarea = document.getElementById(`editor-${this.project.slug}`);
new TextareaMarkdown(textarea);
},
methods: {
refreshId() {
const crypto = window.crypto || window.msCrypto;
var array = new Uint32Array(1);
return '?ver=' + crypto.getRandomValues(array); // Compliant for security-sensitive use cases
},
}
};
</script>
<style lang="less" scoped>
.preview {
max-height: 10em;
overflow-y: scroll;
margin-bottom: 0.8em;
}
.description {
p {
text-align: justify;
}
}
@media screen and (max-width: 767px) {
.content {
width: 90% !important;
.meta.top {
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
.right.floated {
float: none !important;
margin-left: 0 !important;
margin-bottom: 0.5em;
}
span {
margin: 0.15em 0;
}
}
}
}
</style>
<template>
<div
v-if="chunkedNsortedFilters.length > 0"
id="filters-container"
>
<div
class="ui styled accordion"
@click="displayFilters = !displayFilters"
>
<div
id="filters"
class="title collapsible-filters"
>
FILTRES
<i
:class="['ui icon customcaret', { 'collapsed': !displayFilters }]"
aria-hidden="true"
/>
</div>
</div>
<div :class="['full-width', 'filters', { 'hidden': displayFilters }]">
<div
v-for="(chunkedFilters, index) in chunkedNsortedFilters"
:key="index"
class="ui menu filter-row"
>
<div
v-for="filter in chunkedFilters"
:key="filter.name"
class="item"
>
<label>
{{ filter.label }}
</label>
<search-projects
v-if="filter.name === 'search'"
v-on="$listeners"
/>
<DropdownMenuItem
v-else-if="!filter.id"
:options="filter.options"
:loading="loading"
v-on="$listeners"
/>
<DropdownMenuItem
v-else
:options="filter.options"
:loading="loading"
:multiple="isMultiple(filter)"
:current-selection="attributesFilter[filter.id]"
:default-filter="filter.default_filter_enabled ? filter.default_filter_value : null"
@filter="updateAttributeFilter"
@remove="removeAttributeFilter"
/>
</div>
</div>
</div>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
import DropdownMenuItem from '@/components/Projects/DropdownMenuItem.vue';
import SearchProjects from '@/components/Projects/SearchProjects.vue';
export default {
name: 'ProjectsMenu',
components: {
DropdownMenuItem,
SearchProjects,
},
props: {
loading: {
type: Boolean,
default: false
},
},
data() {
return {
displayFilters: false,
classicFilters: [
{
name: 'access_level',
label: 'Niveau d\'autorisation requis',
options: [
{
label: 'Utilisateur anonyme',
value: 'anonymous'
},
{
label: 'Utilisateur connecté',
value: 'logged_user'
},
{
label: 'Contributeur',
value: 'contributor'
},
],
},
{
name: 'user_access_level',
label: 'Mon niveau d\'autorisation',
options: [
{
label: 'Utilisateur connecté',
value: '1'
},
{
label: 'Contributeur',
value: '2'
},
{
label: 'Super contributeur',
value: '3'
},
{
label: 'Modérateur',
value: '4'
},
{
label: 'Administrateur projet',
value: '5'
},
],
},
{
name: 'moderation',
label: 'Modération',
options: [
{
label: 'Projet modéré',
value: 'true'
},
{
label: 'Projet non modéré',
value: 'false'
},
]
},
{
name: 'search',
label: 'Recherche par nom',
}
],
attributesFilter: {},
};
},
computed: {
...mapState([
'user',
'configuration',
'projectAttributes'
]),
...mapState('projects', [
'filters',
]),
/**
* Processes project filters to prepare them for display.
* It also adds a global 'Tous' (All) option to each attribute's options for filtering purposes.
*
* @returns {Array} An array of filter objects with modified options for display.
*/
displayedClassicFilters() {
if (!this.configuration.VUE_APP_PROJECT_FILTERS) return [];
const projectFilters = this.configuration.VUE_APP_PROJECT_FILTERS.split(',');
// Filter filters to be displayed according to configuration and process filters
return this.classicFilters.filter(filter => projectFilters.includes(filter.name))
.map(filter => {
if (filter.options) {
// if user is not connected display its user access level corresponding to anonymous user
if (!this.user && filter.name ==='user_access_level') {
filter.options.unshift({
label: 'Utilisateur anonyme',
value: '0'
});
}
// Format the options to be displayed by dropdowns
const options = this.generateFilterOptions(filter);
// Add the global option at beginning
options.unshift({
label: 'Tous',
filter: filter.name,
value: null,
});
return { ...filter, options };
} else { // Search input field doesn't take options
return filter;
}
});
},
/**
* Processes project attributes to prepare them for display, adjusting the options based on the attribute type.
* For boolean attributes, it creates specific options for true and false values.
* It also adds a global 'Tous' (All) option to each attribute's options for filtering purposes.
* Finally, it chunks the array of attributes into multiple arrays, each containing up to 4 elements.
*
* @returns {Array} An array of arrays, where each sub-array contains up to 4 project attributes with modified options for display.
*/
displayedAttributeFilters() {
// Filter displayed filters & filter only attribute of boolean type (no need for option property) or list type with options
return this.projectAttributes.filter(attribute => attribute.display_filter && (attribute.field_type === 'boolean' || attribute.options))
// Process attributes for display
.map(attribute => {
// Format the options to be displayed by dropdowns
const options = this.generateFilterOptions(attribute);
// Add the global option at beginning
options.unshift({
label: 'Tous',
filter: attribute.id,
value: null,
});
return { ...attribute, options };
});
},
/**
* Merge all filters and place the search filters at the end of the array
* Then chunks the array into rows of 4 filters to display each chunk in a row
*/
chunkedNsortedFilters() {
const allFilters = [...this.displayedClassicFilters, ...this.displayedAttributeFilters];
const sortedFilters = [
...allFilters.filter(el => el.name !== 'search'),
...allFilters.filter(el => el.name === 'search'),
];
// Chunk the filters into arrays of up to 4 elements
return this.chunkArray(sortedFilters, 4);
},
},
created() {
// parse all project attributes to find default value and set filters in store before updating project list results
for (const attribFilter of this.displayedAttributeFilters) {
this.setDefaultFilters(attribFilter);
}
// When all the default filters are set, fetch projects list data
this.$emit('getData');
},
methods: {
...mapMutations('projects', [
'SET_PROJECTS_FILTER'
]),
/**
* Helper function to chunk an array into smaller arrays of a specified size.
*
* @param {Array} array - The original array to be chunked.
* @param {Number} size - The maximum size of each chunk.
* @returns {Array} An array of chunked arrays.
*/
chunkArray(array, size) {
const chunkedArr = [];
for (let i = 0; i < array.length; i += size) {
chunkedArr.push(array.slice(i, i + size));
}
return chunkedArr;
},
/**
* Generates options for a given filter.
* It handles boolean attributes specially by creating explicit true/false options.
* Other attribute types use their predefined options.
*
* @param {Object} attribute - The project attribute for which to generate options.
* @returns {Array} An array of options for the given attribute.
*/
generateFilterOptions(filter) {
// Handle boolean attributes specially by creating true/false options
if (filter.field_type === 'boolean') {
return [
{ filter: filter.id, label: 'Oui', value: 'true' },
{ filter: filter.id, label: 'Non', value: 'false' },
];
} else if (filter.options) {
// For other filter types, map each option to the expected format
return filter.options.map(option => ({
filter: filter.id || filter.name,
label: option.name || option.label || option,
value: option.id || option.value || option,
}));
}
return [];
},
/**
* Retrieves a project attribute by its ID.
* Returns an empty object if not found to prevent errors from undefined access.
*
* @param {Number|String} id - The ID of the attribute to find.
* @returns {Object} The found attribute or an empty object.
*/
getProjectAttribute(id) {
// Search for the attribute by ID, default to an empty object if not found
return this.projectAttributes.find(el => el.id === id) || {};
},
/**
* Emits an updated filter event with the current state of attributesFilter.
* This method serializes the attributesFilter object to a JSON string and emits it,
* allowing the parent component to update the query parameters.
*/
emitUpdatedFilter() {
// Emit an 'filter' event with the updated attributes filter as a JSON string
this.$emit('filter', { filter: 'attributes', value: JSON.stringify(this.attributesFilter) });
},
/**
* Updates or adds a new attribute value to the attributesFilter.
* Handles both single-choice and multi-choice attribute types.
* @param {Object} newFilter - The new filter to be added, containing the attribute key and value.
*/
updateAttributeFilter({ filter, value, noUpdate }) {
// Retrieve the attribute type information to determine how to handle the update
const attribute = this.getProjectAttribute(filter);
// Check if the attribute allows multiple selections
const isMultiChoice = attribute.field_type.includes('list');
if (isMultiChoice) {
// For multi-choice attributes, manage the values as an array to allow multiple selections
let arrayValue = this.attributesFilter[filter] ? this.attributesFilter[filter].split(',') : [];
if (value) {
// If a value is provided, add it to the array, ensuring no duplicates and removing null corresponding to "Tous" default option
arrayValue.push(value);
arrayValue = [...new Set(arrayValue)].filter(el => el !== null);
// Convert the array back to a comma-separated string to store in the filter object
this.attributesFilter[filter] = arrayValue.join(',');
} else {
// If null value is provided "Tous" is selected, it indicates removal of the attribute filter
delete this.attributesFilter[filter];
}
} else {
// For single-choice attributes, directly set or delete the value
value ? this.attributesFilter[filter] = value : delete this.attributesFilter[filter];
}
if (noUpdate) {
this.SET_PROJECTS_FILTER({ filter: 'attributes', value: JSON.stringify(this.attributesFilter) });
} else {
// After updating the filter object, emit the updated filter for application-wide use
this.emitUpdatedFilter();
}
},
/**
* Removes a specified value from a project attribute filter.
* Particularly useful for multi-choice attributes where individual values can be deselected.
* @param {Object} removedFilter - The filter to be removed, containing the attribute key and value.
*/
removeAttributeFilter({ filter, value }) {
// Retrieve attribute information to determine if it's a multi-choice attribute
const attribute = this.getProjectAttribute(filter);
const isMultiChoice = attribute.field_type.includes('list');
if (isMultiChoice) {
// For multi-choice attributes, convert the current filter value to an array for manipulation
let arrayValue = this.attributesFilter[filter] ? this.attributesFilter[filter].split(',') : [];
// Remove the specified value from the array
arrayValue = arrayValue.filter(val => val !== value);
// Update the attributesFilter with the new array, converted back to a string
this.attributesFilter[filter] = arrayValue.join(',');
} else {
// For single-choice attributes, directly update the filter to remove the value
delete this.attributesFilter[filter];
}
// Emit the updated filter after removal
this.emitUpdatedFilter();
},
isMultiple(filter) {
return filter.field_type.includes('list');
},
setDefaultFilters(filter) {
const defaultFilter = filter.default_filter_enabled ? filter.default_filter_value : null;
if (defaultFilter) {
// make an array from the string in case of a list
const filtersArray = defaultFilter.split(',');
// for each value update the filter
filtersArray.forEach(defaultValue => {
const defaultOption = filter.options.find(option => option.value === defaultValue);
if (defaultOption) {
this.updateAttributeFilter({ ...defaultOption, noUpdate: true });
}
});
}
},
}
};
</script>
<style lang="less" scoped>
.transition-properties(...) {
-webkit-transition: @arguments;
-moz-transition: @arguments;
-o-transition: @arguments;
transition: @arguments;
}
#filters-container {
width: 100%;
display: flex;
flex-direction: column;
justify-content: flex-end;
align-items: flex-end;
.accordion {
width: fit-content;
.collapsible-filters {
font-size: 1.25em;
padding-right: 0;
.customcaret{
transition: transform .2s ease;
&.collapsed {
transform: rotate(180deg);
}
&::before{
position: relative;
right: 0;
top: 65%;
color: #999;
margin-top: 4px;
border-color: #999 transparent transparent;
border-style: solid;
border-width: 5px 5px 0;
content: "";
}
}
}
}
.filters {
width: 100%;
height:auto;
max-height:100vh;
opacity: 1;
z-index: 1001;
.transition-properties(all 0.2s ease;);
.filter-row {
border: none;
box-shadow: none;
}
.item {
display: flex;
flex-direction: column;
align-items: flex-start !important;
padding: 0.5em;
&:first-child {
padding-left: 0;
}
&:last-child {
padding-right: 0;
}
label {
margin-bottom: 0.2em;
font-size: 0.9em;
font-weight: 600;
}
}
.item {
width: 25%;
}
.item::before {
width: 0;
}
#search-projects {
width: 100%;
}
}
.filters.hidden {
overflow: hidden;
opacity: 0;
max-height: 0;
}
}
@media screen and (min-width: 701px) {
.item {
&:first-child {
padding-left: 0;
}
&:last-child {
padding-right: 0;
}
}
}
@media screen and (max-width: 700px) {
#filters-container {
.filter-row {
display: flex;
flex-direction: column;
max-height: 275px;
.transition-properties(all 0.2s ease-out;);
.item {
width: 100%;
padding-right: 0;
padding-left: 0;
}
}
}
}
</style>
<template>
<div id="search-projects">
<input
type="text"
placeholder="Rechercher un projet ..."
@input="searchProjects"
>
</div>
</template>
<script>
import { debounce } from 'lodash';
import { mapActions, mapMutations } from 'vuex';
export default {
name: 'SearchProjects',
methods: {
...mapMutations('projects', [
'SET_CURRENT_PAGE'
]),
...mapActions('projects', [
'SEARCH_PROJECTS'
]),
searchProjects:
debounce(function(e) {
this.$emit('loading', true);
this.SET_CURRENT_PAGE(1);
this.SEARCH_PROJECTS({ text: e.target.value })
.then(() => {
this.$emit('loading', false);
})
.catch((err) => {
if (err.message) {
this.$emit('loading', false);
}
});
}, 100)
}
};
</script>
<style lang="less" scoped>
#search-projects {
height: 100%;
min-height: 40px;
display: flex;
flex-direction: column;
justify-content: flex-end;
font-size: 1rem;
input {
display: block;
width: 100%;
height: 100%;
text-align: left;
color: #35495e;
padding: 8px 40px 8px 8px;
border: 1px solid #ced4da;
font-size: 1rem;
font-family: var(--font-family, 'Roboto Condensed', 'Lato', 'Helvetica Neue', Arial, Helvetica, sans-serif);
}
input:focus {
outline: none !important;
box-shadow: 0 0 1px grey;
}
}
</style>
<template>
<div>
<Multiselect
v-model="selection"
:options="options"
:options-limit="10"
:allow-empty="true"
track-by="feature_id"
label="title"
:reset-after="false"
select-label=""
selected-label=""
deselect-label=""
:searchable="true"
:placeholder="placeholder"
:show-no-results="true"
:loading="loading"
:clear-on-select="false"
:preserve-search="true"
@search-change="search"
@select="select"
@close="close"
>
<template slot="clear">
<div
v-if="selection"
class="multiselect__clear"
@click.prevent.stop="selection = null"
>
<i
class="close icon"
aria-hidden="true"
/>
</div>
</template>
<span slot="noResult">
Aucun résultat.
</span>
<span slot="noOptions">
Saisissez les premiers caractères ...
</span>
</Multiselect>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import Multiselect from 'vue-multiselect';
export default {
name: 'SearchFeature',
components: {
Multiselect
},
props: {
currentSelection : {
type: Object,
default: null,
}
},
data() {
return {
loading: false,
selection: null,
text: null,
results: [],
placeholder: 'Rechercher un signalement ...'
};
},
computed: {
...mapState('feature', [
'features'
]),
options() {
return this.results.map((el) => {
return {
featureId: el.id,
title: el.properties.title
};
});
},
},
watch: {
text: function(newValue) {
this.loading = true;
this.GET_PROJECT_FEATURES({
project_slug: this.$route.params.slug,
feature_type__slug: this.$route.params.slug_type_signal,
search: newValue,
limit: '10'
})
.then(() => {
if (newValue) { // filter out current feature
this.results = this.features.filter((el) => el.id !== this.$route.params.slug_signal);
} else {
this.results.splice(0);
}
this.loading = false;
})
.catch((err) => {
console.error(err);
this.loading = false;
});
}
},
created() {
this.RESET_CANCELLABLE_SEARCH_REQUEST();
},
mounted() {
if (this.currentSelection && this.currentSelection.feature_to) {
this.placeholder = this.currentSelection.feature_to.title;
}
},
methods: {
...mapMutations(['RESET_CANCELLABLE_SEARCH_REQUEST']),
...mapActions('feature', [
'GET_PROJECT_FEATURES'
]),
search(text) {
this.text = text;
},
select(e) {
this.$emit('select', e.featureId);
},
close() { // close calls as well selectFeatureTo, in case user didn't select a value
this.$emit('close', this.selection && this.selection.featureId ?
this.selection.featureId : this.selection);
}
}
};
</script>
<style>
.multiselect input {
line-height: 1em !important;
padding: 0 !important;
}
.multiselect__placeholder {
margin: 0;
padding: 0;
}
.multiselect__input {
min-height: auto !important;
line-height: 1em !important;
}
</style>
<template>
<div
:class="[
'ui selection dropdown',
{ 'active visible': isOpen },
{ disabled },
]"
@click="toggleDropdown"
>
<div class="default text">{{ selected }}</div>
<i class="dropdown icon"></i>
<div :class="['menu', { 'visible transition': isOpen }]">
<div
v-for="option in options || ['No results found.']"
@click="select(option)"
:key="option"
:class="[
options ? 'item' : 'message',
{ 'active selected': option === selected },
]"
>
{{ option }}
</div>
</div>
</div>
</template>
<script>
export default {
name: "Dropdown",
props: ["options", "selected", "disabled"],
computed: {},
data() {
return {
isOpen: false,
};
},
methods: {
toggleDropdown() {
this.isOpen = !this.isOpen;
},
select(option) {
this.$emit("update:selection", option);
},
},
};
</script>
\ No newline at end of file
<template>
<div>
<!-- <span v-for="hidden in form.hidden_fields" :key="hidden">
{{ hidden }}
</span> -->
<div class="ui teal segment">
<h4>
Pièce jointe
<button
@click="remove_attachment_formset(form.dataKey)"
class="ui small compact right floated icon button remove-formset"
type="button"
>
<i class="ui times icon"></i>
</button>
</h4>
{{ form.errors }}
<div class="visible-fields">
<div class="two fields">
<div class="required field">
<label :for="form.title.id_for_label">{{ form.title.label }}</label>
<input
type="text"
required
:maxlength="form.title.field.max_length"
:name="form.title.html_name"
:id="form.title.id_for_label"
v-model="form.title.value"
@blur="updateStore"
/>
{{ form.title.errors }}
</div>
<div class="required field">
<label>Fichier (PDF, PNG, JPEG)</label>
// todo : mettre en place la sélection de fichier
<label
@click="selectFile"
class="ui icon button"
:for="form.attachment_file.id_for_label"
>
<i class="file icon"></i>
<span v-if="form.attachment_file.value" class="label">{{
form.attachment_file.value
}}</span>
<span v-else class="label">Sélectionner un fichier ...</span>
</label>
// todo: récupérer la valeur :accept="IMAGE_FORMAT"
<!-- @change="processImgData" -->
<input
type="file"
style="display: none"
:name="form.attachment_file.html_name"
class="image_file"
:id="form.attachment_file.id_for_label"
@blur="updateStore"
/>
{{ form.attachment_file.errors }}
</div>
</div>
<div class="field">
<label for="form.info.id_for_label">{{ form.info.label }}</label>
<textarea
name="form.info.html_name"
rows="5"
v-model="form.info.value"
@blur="updateStore"
></textarea>
{{ form.info.errors }}
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "FeatureAttachmentFormset",
props: ["attachmentForm"],
data() {
return {
form: {
title: {
errors: null,
id_for_label: "titre",
field: {
max_length: 30, // todo : vérifier dans django
},
html_name: "titre",
label: "Titre",
value: "",
},
attachment_file: {
errors: null,
id_for_label: "titre",
html_name: "titre",
label: "Titre",
value: "",
},
info: {
value: "",
errors: null,
label: "Info",
},
},
};
},
methods: {
remove_attachment_formset() {
console.log("send to store");
this.$store.commit(
"feature/REMOVE_ATTACHMENT_FORM",
this.attachmentForm.dataKey
);
/* this.attachment_formset = this.attachment_formset.filter(
(form) => form.dataKey !== dataKey
); */
},
selectFile() {
console.log("selectFile");
},
updateStore() {
this.$store.commit("feature/UPDATE_ATTACHMENT_FORM", {
dataKey: this.attachmentForm.dataKey,
title: this.form.title.value,
attachment_file: this.form.attachment_file.value,
info: this.form.info.value,
});
},
},
};
</script>
\ No newline at end of file
<template>
<div class="ui teal segment pers-field">
<h4>
Champ personnalisé
<button
@click="removeCustomForm()"
class="ui small compact right floated icon button remove-field"
type="button"
>
<i class="ui times icon"></i>
</button>
</h4>
<div class="visible-fields">
<div class="two fields">
<div class="required field">
<label :for="form.label.id_for_label">{{ form.label.label }}</label>
<input
type="text"
required
:maxlength="form.label.field.max_length"
:name="form.label.html_name"
:id="form.label.id_for_label"
v-model="form.label.value"
@blur="updateStore"
/>
<small>{{ form.label.help_text }}</small>
{{ form.label.errors }}
</div>
<div class="required field">
<label :for="form.name.id_for_label">{{ form.name.label }}</label>
<input
type="text"
required
:maxlength="form.name.field.max_length"
:name="form.name.html_name"
:id="form.name.id_for_label"
v-model="form.name.value"
@blur="updateStore"
/>
<small>{{ form.name.help_text }}</small>
{{ form.name.errors }}
</div>
</div>
<div class="three fields">
<div class="required field">
<label :for="form.position.id_for_label">{{
form.position.label
}}</label>
<div class="ui input">
<input
type="number"
:min="form.position.field.min_value"
:name="form.position.html_name"
:id="form.position.id_for_label"
:value="form.position.value"
@blur="updateStore"
/>
</div>
<small>{{ form.position.help_text }}</small>
{{ form.position.errors }}
</div>
<div class="required field">
<label :for="form.field_type.id_for_label">{{
form.field_type.label
}}</label>
<Dropdown
:disabled="!form.label.value || !form.name.value"
:options="form.field_type.field.choices"
:selected="selected"
:selection.sync="selected"
/>
</div>
<div v-if="selected" class="field field-list-options required field">
<label :for="form.options.id_for_label">{{
form.options.label
}}</label>
<input
type="text"
:maxlength="form.options.field.max_length"
:name="form.options.html_name"
:id="form.options.id_for_label"
v-model="form.options.value"
class="options-field"
@input="updateOptions"
/>
<small>{{ form.help_text }}</small>
{{ form.options.errors }}
</div>
</div>
</div>
<!-- <input class="delete-hidden-field" type="checkbox"
name="{{ form.DELETE.html_name }}"
id="{{ form.DELETE.id_for_label }}"> -->
</div>
</template>
<script>
import Dropdown from "@/components/Dropdown.vue";
export default {
name: "FeatureTypeCustomForm",
components: {
Dropdown,
},
props: ["customForm"],
computed: {
selected: {
// getter
get() {
return this.form.field_type.value;
},
// setter
set(newValue) {
this.form.field_type.value = newValue;
this.updateStore();
},
},
},
data() {
return {
form: {
label: {
errors: null,
id_for_label: "label",
label: "Label",
help_text: "Nom en language naturel du champ",
html_name: "label",
field: {
max_length: 128,
},
value: null,
},
name: {
errors: null,
id_for_label: "name",
label: "Nom",
html_name: "name",
help_text:
"Nom technique du champ tel qu'il apparaît dans la base de données ou dans l'export GeoJSON. Seuls les caractères alphanumériques et les traits d'union sont autorisés: a-z, A-Z, 0-9, _ et -)",
field: {
max_length: 128,
},
value: null,
},
position: {
errors: null,
id_for_label: "position",
label: "Position",
min_value: 0, // ! check if good values (not found)
html_name: "position",
help_text:
"Numéro d'ordre du champ dans le formulaire de saisie du signalement",
field: {
max_length: 128, // ! check if good values (not found)
},
value: 0,
},
field_type: {
errors: null,
id_for_label: "field_type",
label: "Type de champ",
html_name: "field_type",
help_text: "",
field: {
max_length: 50,
choices: [
"Booléen",
"Chaîne de caractères",
"Date",
"Liste de valeurs",
"Nombre entier",
"Nombre décimal",
"Texte multiligne",
],
},
value: null,
},
options: {
errors: null,
id_for_label: "options",
label: "Options",
html_name: "options",
help_text: "",
field: {
max_length: 256,
},
value: null,
},
},
};
},
methods: {
removeCustomForm() {
this.$store.commit(
"feature_type/REMOVE_CUSTOM_FORM",
this.customForm.dataKey
);
},
updateStore() {
this.$store.commit("feature_type/UPDATE_CUSTOM_FORM", {
dataKey: this.customForm.dataKey,
label: this.form.label.value,
name: this.form.name.value,
position: this.form.position.value,
field_type: this.form.field_type.value,
options: this.form.options.value,
});
},
updateOptions() {
this.updateStore();
this.$store.commit("feature_type/UPDATE_COLOR_STYLE");
},
},
};
</script>
<template>
<div :class="['sidebar-container', { expanded }]">
<!-- <div class="sidebar-layers"></div> -->
<div @click="expanded = !expanded" class="layers-icon">
<!-- // ! svg point d'interrogation pas accepté par linter -->
<!-- <?xml version="1.0" encoding="iso-8859-1"?> -->
<svg
version="1.1"
id="Capa_1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
x="0px"
y="0px"
viewBox="0 0 491.203 491.203"
style="enable-background: new 0 0 491.203 491.203"
xml:space="preserve"
>
<g>
<g>
<path
d="M487.298,326.733l-62.304-37.128l62.304-37.128c2.421-1.443,3.904-4.054,3.904-6.872s-1.483-5.429-3.904-6.872
l-62.304-37.128l62.304-37.128c3.795-2.262,5.038-7.172,2.776-10.968c-0.68-1.142-1.635-2.096-2.776-2.776l-237.6-141.6
c-2.524-1.504-5.669-1.504-8.192,0l-237.6,141.6c-3.795,2.262-5.038,7.172-2.776,10.968c0.68,1.142,1.635,2.096,2.776,2.776
l62.304,37.128L3.905,238.733c-3.795,2.262-5.038,7.172-2.776,10.968c0.68,1.142,1.635,2.096,2.776,2.776l62.304,37.128
L3.905,326.733c-3.795,2.262-5.038,7.172-2.776,10.968c0.68,1.142,1.635,2.096,2.776,2.776l237.6,141.6
c2.526,1.494,5.666,1.494,8.192,0l237.6-141.6c3.795-2.262,5.038-7.172,2.776-10.968
C489.393,328.368,488.439,327.414,487.298,326.733z M23.625,157.605L245.601,25.317l221.976,132.288L245.601,289.893
L23.625,157.605z M23.625,245.605l58.208-34.68l159.672,95.2c2.524,1.504,5.668,1.504,8.192,0l159.672-95.2l58.208,34.68
L245.601,377.893L23.625,245.605z M245.601,465.893L23.625,333.605l58.208-34.68l159.672,95.2c2.524,1.504,5.668,1.504,8.192,0
l159.672-95.2l58.208,34.68L245.601,465.893z"
/>
</g>
</g>
</svg>
</div>
<div class="basemaps-title">
<h4>
Fonds cartographiques
<!-- <span data-tooltip="Il est possible pour chaque fond cartographique de modifier l'ordre des couches"
data-position="bottom left">
<i class="question circle outline icon"></i>
</span> -->
</h4>
</div>
<div class="basemaps-items ui accordion styled">
<div class="basemap-item title active">Fond par défaut</div>
<div class="content active" id="list-0" data-basemap-index="0">
<div
v-for="basemap in $store.state.map.basemaps"
:key="`list-${basemap.id}`"
data-id="1"
class="layer-item transition visible"
>
<p v-for="layer in basemap.layers" :key="layer.id" class="layer-handle-sort">
<i class="th icon"></i>Open street map
</p>
<label>Opacité &nbsp;<span>(%)</span></label>
<div class="range-container">
<!-- // todo : rendre réactif les valeurs et connectés avec store/Map -->
<input
id="opacity"
type="range"
min="0"
max="1"
step="0.01"
/><output class="range-output-bubble">100</output>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "SidebarLayers",
data() {
return {
expanded: false,
};
},
methods: {},
};
</script>
<style>
@import "../../assets/styles/sidebar-layers.css";
.queryable-layers-dropdown {
margin-bottom: 1em;
}
.queryable-layers-dropdown > label {
font-weight: bold;
}
</style>
\ No newline at end of file
<template>
<!-- //? typo dans segment manquerait un s ou pas ? -->
<div class="ui segment" :data-segment="form.prefix + '-SEGMENT'">
<!-- {% for hidden in form.hidden_fields %}{{ hidden }}{% endfor %} -->
<div v-if="form.non_field_errors" class="ui segment">
{{ form.non_field_errors }}
</div>
<div class="field required">
<label :for="form.title.id_for_label">{{ form.title.label }}</label>
<small>{{ form.title.help_text }}</small> <!-- | safe -->
<input
type="text"
:maxlength="form.title.field.max_length"
:name="form.title.html_name"
:id="form.title.id_for_label"
:value="form.title.value"
required
/>
{{ form.title.errors }}
</div>
<div class="nested">
{% if form.nested %}
{{ form.nested.management_form }}
<div
class="ui segments layers-container"
:data-segments="form.nested.prefix + '-SEGMENTS'"
>
{% for contextlayer_form in form.nested %} {% include
'geocontrib/project/project_mapping_contextlayer.html' with
formset=form.nested form=contextlayer_form is_empty=False %} {% endfor
%}
</div>
<div
class="formset_hidden"
:data-empty-form="form.nested.prefix + '-EMPTY'"
style="display: none"
>
{% include 'geocontrib/project/project_mapping_contextlayer.html' with
formset=form.nested form=form.nested.empty_form is_empty=True %}
</div>
<div class="ui buttons">
<a
class="ui compact small icon left floated button green"
data-variation="mini"
:data-add-form="form.nested.prefix + '-ADD'"
>
<i class="ui plus icon"></i>
<span>Ajouter une couche</span>
</a>
</div>
<div
class="ui buttons"
data-variation="mini"
:data-delete-form="form.prefix + '-DELETE'"
>
<a
class="
ui
compact
red
small
icon
right
floated
button button-hover-green
"
>
<i class="ui trash alternate icon"></i>
<span>Supprimer ce fond cartographique</span>
</a>
<div style="display: none">
{% if is_empty %}
<input
type="text"
:name="form.prefix + '-DELETE'"
:id="'id_' + form.prefix + '-DELETE'"
/>
{% else %}
{{ form.DELETE }}
{% endif %}
</div>
</div>
{% endif %}
</div>
</div>
</template>
<script>
export default {
name: "Project_mapping_basemap",
props: ["form"],
};
</script>
\ No newline at end of file
const axios = require("axios")
import Vue from 'vue'
import SuiVue from 'semantic-ui-vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
Vue.config.productionTip = false
axios.all([store.dispatch("USER_INFO"),
store.dispatch("GET_ALL_PROJECTS"),
store.dispatch("GET_STATIC_PAGES"),
store.dispatch("GET_USER_LEVEL_PROJECTS") // * mock en attendant endpoint ou autre
]).then(axios.spread(function () {
// Importing necessary libraries and components
const axios = require('axios'); // Axios for HTTP requests
import Vue from 'vue'; // Vue.js framework
import App from './App.vue'; // Main Vue component
import './registerServiceWorker'; // Service worker registration
import router from '@/router'; // Application router
import store from '@/store'; // Vuex store for state management
// Importing CSS for styling
import './assets/styles/base.css'; // Base styles
import './assets/resources/semantic-ui-2.4.2/semantic.min.css'; // Semantic UI for UI components
import '@fortawesome/fontawesome-free/css/all.css'; // Font Awesome for icons
import '@fortawesome/fontawesome-free/js/all.js'; // Font Awesome JS
import 'ol/ol.css'; // OpenLayers CSS for maps
import '@/assets/styles/openlayers-custom.css'; // Custom styles for OpenLayers
import '@/assets/styles/sidebar-layers.css'; // Styles for sidebar layers
// Font Awesome library setup
import { library } from '@fortawesome/fontawesome-svg-core';
import { fas } from '@fortawesome/free-solid-svg-icons'; // Importing solid icons
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'; // Font Awesome component
// Vue Multiselect CSS
import 'vue-multiselect/dist/vue-multiselect.min.css'; // Multiselect component styles
// Adding Font Awesome icons to the library
library.add(fas);
// Registering Font Awesome as a Vue component for use in templates
Vue.component('FontAwesomeIcon', FontAwesomeIcon);
// Setting Vue's production tip configuration
Vue.config.productionTip = false;
Vue.config.ignoredElements = ['geor-header'];
// Handling service worker updates and precaching
var refreshing = false; // Flag to prevent multiple refreshes
if (navigator.serviceWorker) {
navigator.serviceWorker.addEventListener('controllerchange', () => {
// Check if the page is already refreshing to prevent duplicate refreshes
if (refreshing) {
return;
}
refreshing = true;
// Reload the page to activate the new service worker
window.location.reload();
});
}
/**
* Dynamically loads a font from Google Fonts and sets CSS variables.
* @param {string} fontNames - A comma-separated list of font names, where the first font is the one to be imported and others are fallbacks.
* @param {string} headerColor - The color to be used for headers.
* @param {string} primaryColor - The primary color for the application.
* @param {string} primaryHighlightColor - The primary color to highlight elements in the application.
*/
const setAppTheme = (fontNames, headerColor, primaryColor, primaryHighlightColor) => {
// Set CSS variables for header and primary color.
if (headerColor) {
document.documentElement.style.setProperty('--header-color', headerColor);
}
if (primaryColor) {
document.documentElement.style.setProperty('--primary-color', primaryColor);
}
if (primaryHighlightColor) {
document.documentElement.style.setProperty('--primary-highlight-color', primaryHighlightColor);
}
// Proceed to load the font if fontNames is provided.
if (fontNames) {
const fontNameToImport = fontNames.split(',')[0].trim();
const link = document.createElement('link');
link.href = `https://fonts.googleapis.com/css?family=${fontNameToImport.replace(/ /g, '+')}:400,700&display=swap`;
link.rel = 'stylesheet';
document.head.appendChild(link);
// Set the CSS variable for font family.
document.documentElement.style.setProperty('--font-family', fontNames);
}
};
/**
* Sets the favicon of the application.
* @param {string} favicoUrl - The URL of the favicon to be set.
*/
const setFavicon = (favicoUrl) => {
const link = document.createElement('link');
link.id = 'dynamic-favicon';
link.rel = 'shortcut icon';
link.href = favicoUrl;
document.head.appendChild(link);
};
/**
* Regularly updates the online status of the application.
*/
const updateOnlineStatus = () => {
setInterval(() => {
store.commit('SET_IS_ONLINE', navigator.onLine);
}, 2000);
};
/**
* Regularly updates the user status if using external auth to keep the frontend updated with backend.
*/
function handleLogout() {
if (store.state.user) {
store.commit('SET_USER', false);
store.commit('SET_USER_PERMISSIONS', null);
store.commit('SET_USER_LEVEL_PROJECTS', null);
store.commit('DISPLAY_MESSAGE', {
level: 'negative',
comment: `Vous avez été déconnecté du service d'authentification.
Reconnectez-vous ou continuez en mode anonyme.`
});
store.dispatch('projects/GET_PROJECTS');
store.dispatch('GET_USER_LEVEL_PERMISSIONS');
store.dispatch('GET_USER_LEVEL_PROJECTS');
}
}
const updateUserStatus = () => {
setInterval(() => {
if (navigator.onLine) {
axios
.get(`${store.state.configuration.VUE_APP_DJANGO_API_BASE}user_info/`)
.then((response) => {
const user = response.data?.user || null;
// Cas où l'utilisateur a changé
if (store.state.user?.username !== user.username) {
store.commit('SET_USER', user);
// Cas où l'utilisateur est bien authentifié
if (user) {
store.commit('DISPLAY_MESSAGE', {
level: 'positive',
comment: 'Bienvenue à nouveau ! Vous êtes reconnecté au service d\'authentification'
});
store.dispatch('projects/GET_PROJECTS');
store.dispatch('GET_USER_LEVEL_PERMISSIONS');
store.dispatch('GET_USER_LEVEL_PROJECTS');
} else {
// On force la suppression de l'utilisateur au cas où le serveur SSO ne permet pas à la requête API d'aboutir (ex: redirection si non authentifié SSO)
handleLogout();
}
}
})
.catch(() => {
handleLogout();
});
}
}, 10000);
};
/**
* Fetches initial data for the application and initializes the Vue instance.
*/
const fetchDataAndInitializeApp = async () => {
await Promise.all([
store.dispatch('GET_USER_INFO'),
store.dispatch('GET_STATIC_PAGES'),
store.dispatch('map/GET_AVAILABLE_LAYERS'),
store.dispatch('GET_LEVELS_PERMISSIONS'),
store.dispatch('GET_PROJECT_ATTRIBUTES'),
]);
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
}))
}).$mount('#app');
};
/**
* Initializes the application configuration.
* @param {object} config - Configuration object with application settings.
*/
const onConfigLoaded = async (config) => {
// Set application configuration in the store.
store.commit('SET_CONFIG', config);
// Update the online status at regular intervals.
updateOnlineStatus();
// Update the user status at regular intervals to check if backend session expired.
updateUserStatus();
// Set the document title and favicon from the configuration.
document.title = `${config.VUE_APP_APPLICATION_NAME} ${config.VUE_APP_APPLICATION_ABSTRACT}`;
setFavicon(config.VUE_APP_APPLICATION_FAVICO);
// Apply the application theme settings using values specified in the configuration.
setAppTheme(
config.VUE_APP_FONT_FAMILY,
config.VUE_APP_HEADER_COLOR,
config.VUE_APP_PRIMARY_COLOR,
config.VUE_APP_PRIMARY_HIGHLIGHT_COLOR
);
// Set a global proxy URL based on the configuration.
window.proxy_url = config.VUE_APP_DJANGO_API_BASE + 'proxy/';
// Fetch initial data and initialize the Vue application.
await fetchDataAndInitializeApp();
};
// Attempt to load the application configuration from an external JSON file.
axios.get('./config/config.json')
.catch((error) => {
// Log an error if the configuration file cannot be loaded.
console.error(error);
console.log('Attempting to get config from Localstorage');
// Attempt to retrieve the configuration from local storage as a fallback.
const conf = localStorage.getItem('geontrib_conf');
if (conf) {
// If a configuration is found in local storage, parse it and load the config.
onConfigLoaded(JSON.parse(conf));
}
})
.then((response) => {
// Check if the response is valid and the request was successful.
if (response && response.status === 200) {
// Store the retrieved configuration in local storage for future use.
localStorage.setItem('geontrib_conf', JSON.stringify(response.data));
Vue.use(SuiVue,
);
\ No newline at end of file
// Load the configuration into the application.
onConfigLoaded(response.data);
}
})
.catch((error) => {
// Throw an error if there are issues processing the response.
throw error;
});
/* eslint-disable no-console */
import { register } from 'register-service-worker'
import { register } from 'register-service-worker';
if (process.env.NODE_ENV === 'production') {
register(`${process.env.BASE_URL}service-worker.js`, {
......@@ -8,25 +8,43 @@ if (process.env.NODE_ENV === 'production') {
console.log(
'App is being served from cache by a service worker.\n' +
'For more details, visit https://goo.gl/AFskqB'
)
);
},
registered () {
console.log('Service worker has been registered.')
registered (registration) {
//console.log('Service worker has been registered.')
console.log(
'Service worker has been registered and now polling for updates.'
);
setInterval(() => {
registration.update();
}, 10000); // every 10 seconds
},
cached () {
console.log('Content has been cached for offline use.')
console.log('Content has been cached for offline use.');
},
updatefound () {
console.log('New content is downloading.')
console.log('New content is downloading.');
},
updated () {
console.log('New content is available; please refresh.')
updated (registration) {
if (!navigator.webdriver) {
alert('Une nouvelle version de l\'application est disponible, l\'application va se recharger');
console.log('New content is available; please refresh.');
//
if (!registration || !registration.waiting) {
return;
}
// Send message to SW to skip the waiting and activate the new SW
registration.waiting.postMessage({ type: 'SKIP_WAITING' });
//window.location.reload(true);
} else {
console.log('Execution dans un navigateur controlé par un agent automatisé, la mise à jour n\'est pas appliqué pendant le test.');
}
},
offline () {
console.log('No internet connection found. App is running in offline mode.')
console.log('No internet connection found. App is running in offline mode.');
},
error (error) {
console.error('Error during service worker registration:', error)
console.error('Error during service worker registration:', error);
}
})
});
}
import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '../views/Index.vue'
import Vue from 'vue';
import VueRouter from 'vue-router';
import ProjectsList from '../views/Projects/ProjectsList.vue';
import store from '@/store';
import featureAPI from '@/services/feature-api';
Vue.use(VueRouter)
Vue.use(VueRouter);
let projectBase = 'projet';
if (window.location.pathname.includes('projet-partage')) {
projectBase = 'projet-partage';
}
const routes = [
{
path: '/',
name: 'index',
component: Index
component: ProjectsList
},
{
path: '/connexion/',
path: `${projectBase === 'projet' ? '': `/${projectBase}/:slug`}/connexion/`,
name: 'login',
// route level code-splitting
// this generates a separate chunk (login.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "login" */'../views/registration/Login.vue')
props: true,
component: () => import('../views/Login.vue')
},
{
path: `${projectBase === 'projet' ? '': `/${projectBase}/:slug`}/inscription/`,
name: 'signup',
component: () => import('../views/Login.vue')
},
{
path: '/my_account/',
path: `${projectBase === 'projet' ? '': `/${projectBase}/:slug`}/inscription/succes`,
name: 'sso-signup-success',
props: true,
component: () => import('../views/Login.vue')
},
{
path: `${projectBase === 'projet' ? '': `/${projectBase}/:slug`}/my_account/`,
name: 'my_account',
component: () => import('../views/My_account.vue')
component: () => import('../views/Account.vue')
},
{
path: '/mentions/',
path: `${projectBase === 'projet' ? '': '/' + projectBase}/mentions/`,
name: 'mentions',
component: () => import('../views/flatpages/with_right_menu.vue')
component: () => import('../views/FlatPages/LegalMentions.vue')
},
{
path: '/aide/',
path: `${projectBase === 'projet' ? '': '/' + projectBase}/aide/`,
name: 'aide',
component: () => import('../views/flatpages/Default.vue')
component: () => import('../views/FlatPages/Help.vue')
},
// * PROJECT
{
path: '/creer-projet/',
name: 'project_create',
component: () => import('../views/project/Project_edit.vue')
component: () => import('../views/Project/ProjectEdit.vue')
},
{
path: '/projet/:slug',
path: `/${projectBase}/:slug`,
name: 'project_detail',
component: () => import('../views/project/Project_detail.vue'),
props: true,
component: () => import('../views/Project/ProjectDetail.vue'),
},
{
path: '/projet/:slug/editer',
path: `/${projectBase}/:slug/signalement/lister/`,
name: 'liste-signalements',
component: () => import('../views/Project/FeaturesListAndMap.vue')
},
{
path: `/${projectBase}/:slug/editer`,
name: 'project_edit',
component: () => import('../views/project/Project_edit.vue')
component: () => import('../views/Project/ProjectEdit.vue')
},
{
path: '/projet-type/',
name: 'project_type_list',
component: () => import('../views/project/Project_type_list.vue')
component: () => import('../views/Projects/ProjectsTypes.vue')
},
{
path: '/creer-projet/create_from/:slug/',
name: 'project_create_from',
component: () => import('../views/project/Project_edit.vue')
component: () => import('../views/Project/ProjectEdit.vue')
},
{
path: '/projet/:slug/administration-carte/',
path: `/${projectBase}/:slug/administration-carte/`,
name: 'project_mapping',
component: () => import('../views/project/Project_mapping.vue')
component: () => import('../views/Project/ProjectBasemaps.vue')
},
{
path: '/projet/:slug/membres/',
path: `/${projectBase}/:slug/membres/`,
name: 'project_members',
component: () => import('../views/project/Project_members.vue')
component: () => import('../views/Project/ProjectMembers.vue')
},
{
path: `/${projectBase}/:slug/signalement-filtre/`,
name: 'details-signalement-filtre',
component: () => import('../views/Feature/FeatureDetail.vue')
},
// * FEATURE TYPE
{
path: '/projet/:slug/type-signalement/ajouter/',
path: `/${projectBase}/:slug/type-signalement/ajouter/`,
name: 'ajouter-type-signalement',
component: () => import('../views/feature_type/Feature_type_edit.vue')
props: true,
component: () => import('../views/FeatureType/FeatureTypeEdit.vue')
},
{
path: '/projet/:slug/type-signalement/ajouter/create_from/:slug_type_signal',
path: `/${projectBase}/:slug/type-signalement/ajouter/create_from/:slug_type_signal`,
name: 'dupliquer-type-signalement',
component: () => import('../views/feature_type/Feature_type_edit.vue')
component: () => import('../views/FeatureType/FeatureTypeEdit.vue')
},
{
path: '/projet/:slug/type-signalement/:feature_type_slug/',
path: `/${projectBase}/:slug/type-signalement/:feature_type_slug/`,
name: 'details-type-signalement',
component: () => import('../views/feature_type/Feature_type_detail.vue')
component: () => import('../views/FeatureType/FeatureTypeDetail.vue')
},
{
path: '/projet/:slug/type-signalement/:slug_type_signal/editer/',
path: `/${projectBase}/:slug/type-signalement/:slug_type_signal/editer/`,
name: 'editer-type-signalement',
component: () => import('../views/feature_type/Feature_type_edit.vue')
component: () => import('../views/FeatureType/FeatureTypeEdit.vue')
},
// * FEATURE
{
path: '/projet/:slug/signalement/lister/',
name: 'liste-signalements',
component: () => import('../views/feature/Feature_list.vue')
path: `/${projectBase}/:slug/type-signalement/:slug_type_signal/affichage/`,
name: 'editer-affichage-signalement',
component: () => import('../views/FeatureType/FeatureTypeDisplay.vue')
},
// * FEATURE
{
path: '/projet/:slug/type-signalement/:slug_type_signal/signalement/ajouter/',
path: `/${projectBase}/:slug/type-signalement/:slug_type_signal/signalement/ajouter/`,
name: 'ajouter-signalement',
component: () => import('../views/feature/Feature_edit.vue')
component: () => import('../views/Feature/FeatureEdit.vue')
},
{ // todo : créer le template
path: '/projet/:slug/type-signalement/:slug_type_signal/signalement/:slug_signal',
{
path: `/${projectBase}/:slug/type-signalement/:slug_type_signal/signalement/:slug_signal`,
name: 'details-signalement',
component: () => import('../views/feature/Feature_detail.vue')
component: () => import('../views/Feature/FeatureDetail.vue'),
/**
* Handles routing logic before entering the details-signalement route.
* This function manages access and navigation based on user permissions and feature data.
*/
beforeEnter: async (to, from, next) => {
try {
const { slug, slug_type_signal, slug_signal } = to.params;
// Retrieve the project details from the store
const project = await store.dispatch('projects/GET_PROJECT', slug);
// Prepare query based on the project settings for feature browsing
const query = { ordering: project.feature_browsing_default_sort };
// Check if the default filter of the project is set to feature_type and apply it
if (project.feature_browsing_default_filter) { // when feature_type is the default filter of the project,
query['feature_type_slug'] = slug_type_signal; // set feature_type slug in query
}
// Get the feature's position based on the feature slug and query settings
const offset = await featureAPI.getFeaturePosition(slug, slug_signal, query);
// Decide next routing based on the offset result
if (offset >= 0) {
next({
name: 'details-signalement-filtre',
params: { slug },
query: { ...query, offset }
});
} else if (offset === 'No Content') {
// API return no content when user is not allowed to see the feature or isn't connected
if (store.state.user) {
// If the user is connected, display information that he's not allowed to view the feature
store.commit('DISPLAY_MESSAGE', { comment: 'Vous n\'avez pas accès à ce signalement avec cet utilisateur', level: 'negative' });
// and redirect to main page
next({ path: '/' });
} else {
// If the user is not connected, remove other messages to avoid displaying twice that the user is not connected
store.commit('CLEAR_MESSAGES');
// display information that user need to be connected
store.commit('DISPLAY_MESSAGE', { comment: 'Vous n\'avez pas accès à ce signalement hors connexion, veuillez-vous connecter au préalable', level: 'negative' });
// Then redirect to login page
if (store.state.configuration.VUE_APP_LOGIN_URL) {
// If the login is through SSO, redirect to external login page (if the instance accepts a redirect_url it would be caught before when requesting user_info with GET_USER_INFO)
setTimeout(() => { // delay switching page to allow the info message to be read by user
window.open(store.state.configuration.VUE_APP_LOGIN_URL);
}, 1500);
} else {
// In a classic installation, redirect to the login page of this application
next({ name: 'login' });
}
}
} else {
store.commit('DISPLAY_MESSAGE', { comment: 'Désolé, une erreur est survenue pendant la recherche du signalement', level: 'negative' });
next({ path: '/' });
}
} catch (error) {
console.error('error', error);
store.commit('DISPLAY_MESSAGE', { comment: `Désolé, une erreur est survenue pendant la recherche du signalement - ${error}`, level: 'negative' });
next({ path: '/' });
}
}
},
{
path: `/${projectBase}/:slug/type-signalement/:slug_type_signal/offline`,
name: 'offline-signalement',
component: () => import('../views/Feature/FeatureOffline.vue')
},
{
path: '/projet/:slug/type-signalement/:slug_type_signal/signalement/:slug_signal/editer/',
path: `/${projectBase}/:slug/type-signalement/:slug_type_signal/signalement/:slug_signal/editer/`,
name: 'editer-signalement',
component: () => import('../views/feature/Feature_edit.vue')
component: () => import('../views/Feature/FeatureEdit.vue')
},
{
path: `/${projectBase}/:slug/type-signalement/:slug_type_signal/editer-signalements-attributs/`,
name: 'editer-attribut-signalement',
component: () => import('../views/Feature/FeatureEdit.vue')
},
{
path: '/projet/:slug/catalog/:feature_type_slug',
name: 'catalog-import',
component: () => import('../views/Catalog.vue')
},
{
path: '/projet/:slug/type-signalement/:slug_type_signal/signalement/:slug_signal/attachment-preview/',
name: 'attachment-preview',
component: () => import('../views/AttachmentPreview.vue')
},
{ path: '/:pathMatch(.*)*', name: 'NotFound', component: () => import('../views/NotFound.vue') },
]
//let routerHistory = [];
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
base: '/geocontrib/',
routes,
routerHistory: [],
scrollBehavior(to, from, savedPosition) { //* record each route change to turn back to origin after redirect
scrollBehavior(to, from, savedPosition) { //* record each route change to keep scroll position
const fromHistory = Boolean(savedPosition);
if (fromHistory && this.options.routerHistory.length > 0) {
......@@ -131,6 +239,6 @@ const router = new VueRouter({
}
return savedPosition || { x: 0, y: 0 };
},
})
});
export default router
export default router;
/* global workbox */ //* allow undefined variable for 'workbox' in this file (because global variable) to avoid eslint error
// custom service-worker.js
if (workbox) {
// adjust log level for displaying workbox logs
//workbox.core.setLogLevel(workbox.core.LOG_LEVELS.debug)
// apply precaching. In the built version, the precacheManifest will
// be imported using importScripts (as is workbox itself) and we can
// precache this. This is all we need for precaching
workbox.precaching.precacheAndRoute(self.__precacheManifest);
//workbox.core.skipWaiting();
// Make sure to return a specific response for all navigation requests.
// Since we have a SPA here, this should be index.html always.
// https://stackoverflow.com/questions/49963982/vue-router-history-mode-with-pwa-in-offline-mode
workbox.routing.registerNavigationRoute('/geocontrib/index.html', {
blacklist: [/\/api/,/\/admin/,/\/media/,/\/cas/],
});
workbox.routing.registerRoute(
new RegExp('.*/config/config.json'),
new workbox.strategies.StaleWhileRevalidate({
cacheName: 'config',
})
);
workbox.routing.registerRoute(
new RegExp('.*/api/.*'),
new workbox.strategies.NetworkFirst({
cacheName: 'api',
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
}),
],
})
);
workbox.routing.registerRoute(
/^https:\/\/[a-zA-Z]\.tile\.openstreetmap\.fr/,
new workbox.strategies.CacheFirst({
cacheName: 'osm',
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
}),
new workbox.expiration.Plugin({
maxAgeSeconds: 60 * 60 * 24 * 365,
// maxEntries: 30, pour limiter le nombre d'entrée dans le cache
}),
],
})
);
workbox.routing.registerRoute(
new RegExp('.*/service=WMS&request=GetMap/.*'),
new workbox.strategies.CacheFirst({
cacheName: 'wms',
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
}),
new workbox.expiration.Plugin({
maxAgeSeconds: 60 * 60 * 24 * 365,
// maxEntries: 30, pour limiter le nombre d'entrée dans le cache
}),
],
})
);
}
// This code listens for the user's confirmation to update the app.
self.addEventListener('message', (e) => {
if (!e.data) {
return;
}
switch (e.data.type) {
case 'SKIP_WAITING':
self.skipWaiting();
break;
default:
// NOOP
break;
}
});
import { Draw, Snap } from 'ol/interaction';
import Modify from 'ol/interaction/Modify';
import { Collection } from 'ol';
import MultiPoint from 'ol/geom/MultiPoint';
import {
Fill, Stroke, Style, Circle, Text //RegularShape, Circle as CircleStyle, Text,Icon
} from 'ol/style';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import mapService from '@/services/map-service';
import { buffer } from 'ol/extent';
const editionService = {
drawnFeature: null,
featureToEdit: null,
editing_feature: {},
geom_type: 'linestring',
// Création d'une collection filtrée
filteredFeatures: new Collection(),
// Méthode pour créer un style basé sur la couleur actuelle
createDrawStyle(isEditing) {
return [
new Style({
// Style principal pour le polygone
fill: new Fill({
color: isEditing ? 'rgba(255, 145, 0, .2)' : 'rgba(255, 255, 255, .2)',
}),
// Style principal pour la ligne et le tour du polygone
stroke: new Stroke({
color: isEditing ? 'rgba(255, 145, 0, .9)' : 'rgba(255, 45, 0, 0.5)',
lineDash: [],
width: 2,
}),
// Style principal pour le point
image: new Circle({
radius: 7,
stroke: new Stroke({
color: 'rgba(255, 0, 0, 0.5)',
lineDash: [],
width: 2
}),
fill: new Fill({
color: isEditing ? 'rgba(255, 145, 0, 0.9)' : 'rgba(255, 255, 255, 0.5)'
})
}),
// Style pour le texte, pas utilisé mais peut être conservé au cas où
text: new Text({
font: '12px Calibri,sans-serif',
fill: new Fill({ color: '#000' }),
stroke: new Stroke({
color: '#fff',
width: 1
}),
text: ''
}),
zIndex: 50
}),
// Style pour afficher des points sur les sommets de ligne ou polygone (seulement en mode édition)
...(isEditing
? [
// Définition du style de point
new Style({
image: new Circle({
radius: 5,
stroke: new Stroke({
color: 'rgba(255, 145, 0, .9)',
width: 2,
}),
fill: new Fill({
color: 'rgba(255, 145, 0, .5)',
}),
}),
// Récupération des sommets où afficher les points uniquement pour ligne et polygone
geometry: function (feature) {
const geometry = feature.getGeometry();
if (geometry.getType() === 'LineString') {
return new MultiPoint(geometry.getCoordinates()); // Sommets de la ligne
} else if (geometry.getType() === 'Polygon') {
return new MultiPoint(geometry.getCoordinates()[0]); // Sommets du premier anneau
}
return null;
},
}),
]
: []),
];
},
// Méthode pour changer la couleur de la géométrie existante en passant en mode édition
toggleEditionColor(isEditing) {
const drawStyle = this.createDrawStyle(isEditing); // Re-crée le style
this.drawnItems.setStyle(drawStyle); // Applique le style à la couche
},
setEditingFeature(feature) {
this.editing_feature = feature;
},
initFeatureToEdit(feature) {
this.editing_feature = feature;
this.draw.setActive(false);
this.drawSource.addFeature(feature);
this.drawnItems.setZIndex(50);
mapService.fitExtent(buffer(this.drawSource.getExtent(),200));
},
addEditionControls(geomType) {
this.geom_type = geomType;
this.drawSource = new VectorSource();
this.drawnItems = new VectorLayer({
source: this.drawSource,
style: this.createDrawStyle(),
zIndex: 4000
});
mapService.getMap().addLayer(this.drawnItems);
if (this.draw) {
mapService.getMap().removeInteraction(this.draw);
}
let gType = 'Point';
if (geomType.toUpperCase().indexOf('POLYGON') >= 0) {
gType = 'Polygon';
}
else if (geomType.toUpperCase().indexOf('LINE') >= 0) {
gType = 'LineString';
}
this.draw = new Draw({
source: this.drawSource,
type: gType,
style: this.createDrawStyle()
});
mapService.getMap().addInteraction(this.draw);
this.setEditingFeature(undefined);
this.draw.on('drawend', (evt) => {
var feature = evt.feature;
this.drawnFeature = feature;
this.setEditingFeature(feature);
this.draw.setActive(false);
});
this.modify = new Modify({
style: this.createDrawStyle(),
features: this.filteredFeatures, // Limite la modification aux entités filtrées
});
// This workaround allows to avoid the ol freeze
// referenced bug : https://github.com/openlayers/openlayers/issues/6310
// May be corrected in a future version
this.modify.handleUpEvent_old = this.modify.handleUpEvent;
this.modify.handleUpEvent = function (evt) {
try {
this.handleUpEvent_old(evt);
} catch (ex) {
console.log(ex);
}
};
mapService.getMap().addInteraction(this.modify);
// Supprime dynamiquement la feature des entités modifiables
this.drawSource.on('removefeature', (event) => {
const feature = event.feature;
this.filteredFeatures.remove(feature);
});
},
resetAllTools() {
if (this.draw) {
this.draw.setActive(false);
}
if (this.modify) {
this.modify.setActive(false);
}
},
removeSelectInteraction(interaction) {
interaction.getFeatures().clear();
interaction.setActive(false);
},
activeUpdateFeature(isEditing) {
this.resetAllTools();
if (isEditing) {
// Mise à jour des entités modifiables
this.drawSource.forEachFeature((feature) => {
if (
(this.featureToEdit && feature.id_ === this.featureToEdit.id) ||
(this.drawnFeature && feature.ol_uid === this.drawnFeature.ol_uid) ||
(!this.drawnFeature && !this.featureToEdit)
) {
this.filteredFeatures.push(feature);
}
});
this.modify.setActive(true);
}
this.toggleEditionColor(isEditing);
},
/**
* Deletes the currently displayed feature from the map.
* This method removes the feature directly from the source without additional selection steps.
* It assumes that there is only one feature present in the source.
* Resets the color for future drawings to the default to ensure that the editing color
* is not displayed if the edit mode was active prior to deletion.
*/
removeFeatureFromMap() {
// Access the source where the features are stored
const source = this.drawSource; // Replace with the correct reference to your OpenLayers source
// Get all features from the source
const features = source.getFeatures();
// Check if there is a feature to delete
if (features.length > 0 && confirm('Etes-vous sur de vouloir supprimer cet objet ?')) {
try {
// Reset all other tools to ensure only the delete feature functionality is active
this.resetAllTools();
// Remove the feature from the source
const featureToRemove = features[0];
source.removeFeature(featureToRemove);
// Reinitialize the feature edited on the map
this.editing_feature = undefined;
// Toggle draw mode to create a new feature
this.draw.setActive(true);
// Reset color to default
this.toggleEditionColor(false);
// Return operation result after user confirmed to remove the feature
return true;
} catch (error) {
// Log an error if the feature cannot be removed
console.error('Error while deleting the feature: ', error);
}
}
return false;
},
setFeatureToEdit(feature) {
this.featureToEdit = feature;
},
removeActiveFeatures() {
this.drawnFeature = null;
this.featureToEdit = null;
},
addSnapInteraction(map) {
// The snap interaction must be added after the Modify and Draw interactions
// in order for its map browser event handlers to be fired first. Its handlers
// are responsible of doing the snapping.
// Since we can't give a list of source to snap,
// we use this workaround, an interaction collection: https://github.com/openlayers/openlayers/issues/7100
let interactions = [];
map.getLayers().forEach((layer) => {
if (layer instanceof VectorLayer) {
let interaction = new Snap({
source: layer.getSource()
});
interactions.push(interaction);
}
});
for(let snap of interactions ) {
map.addInteraction(snap);
}
},
removeSnapInteraction(map) {
// Find the double click interaction that is on the map.
let interactions = [];
map.getInteractions().forEach(function (interaction) {
if (interaction instanceof Snap) {
interactions.push(interaction);
}
});
// Remove the interaction from the map.
for(let snap of interactions ) {
map.removeInteraction(snap);
}
}
};
export default editionService;