From d884cbab98f8613ae0a3baad4ddd4af6a0914bb7 Mon Sep 17 00:00:00 2001 From: Bram Wiepjes Date: Fri, 17 Dec 2021 14:02:54 +0000 Subject: [PATCH] Resolve "Gallery view" --- backend/src/baserow/config/settings/base.py | 1 + .../database/api/views/gallery/__init__.py | 0 .../database/api/views/gallery/errors.py | 8 + .../database/api/views/gallery/pagination.py | 5 + .../database/api/views/gallery/serializers.py | 9 + .../database/api/views/gallery/urls.py | 10 + .../database/api/views/gallery/views.py | 143 ++ backend/src/baserow/contrib/database/apps.py | 3 +- .../database/migrations/0051_gallery_view.py | 87 + .../src/baserow/contrib/database/models.py | 4 + .../baserow/contrib/database/views/models.py | 25 + .../contrib/database/views/view_types.py | 92 +- .../src/baserow/test_utils/fixtures/view.py | 27 + .../views/gallery/test_gallery_view_views.py | 229 ++ .../contrib/database/view/test_view_types.py | 71 + changelog.md | 1 + .../views/kanban/KanbanViewStack.vue | 24 +- web-frontend/locales/en.js | 1 + web-frontend/locales/fr.js | 1 + .../core/assets/scss/components/all.scss | 5 +- .../core/assets/scss/components/card.scss | 50 +- .../core/assets/scss/components/select.scss | 49 +- .../assets/scss/components/views/gallery.scss | 37 + .../database/components/card/RowCard.vue | 11 +- .../components/view/CreateViewLink.vue | 6 +- .../database/components/view/ViewsContext.vue | 18 +- .../components/view/gallery/GalleryView.vue | 322 +++ .../view/gallery/GalleryViewHeader.vue | 148 ++ web-frontend/modules/database/plugin.js | 10 +- .../modules/database/services/view/gallery.js | 58 + .../database/store/view/bufferedRows.js | 733 ++++++ .../database/store/view/fieldOptions.js | 161 ++ .../modules/database/store/view/gallery.js | 52 + web-frontend/modules/database/utils/card.js | 22 + web-frontend/modules/database/viewTypes.js | 185 +- .../database/store/view/bufferedRows.spec.js | 1997 +++++++++++++++++ 36 files changed, 4544 insertions(+), 61 deletions(-) create mode 100644 backend/src/baserow/contrib/database/api/views/gallery/__init__.py create mode 100644 backend/src/baserow/contrib/database/api/views/gallery/errors.py create mode 100644 backend/src/baserow/contrib/database/api/views/gallery/pagination.py create mode 100644 backend/src/baserow/contrib/database/api/views/gallery/serializers.py create mode 100644 backend/src/baserow/contrib/database/api/views/gallery/urls.py create mode 100644 backend/src/baserow/contrib/database/api/views/gallery/views.py create mode 100644 backend/src/baserow/contrib/database/migrations/0051_gallery_view.py create mode 100644 backend/tests/baserow/contrib/database/api/views/gallery/test_gallery_view_views.py create mode 100644 web-frontend/modules/core/assets/scss/components/views/gallery.scss create mode 100644 web-frontend/modules/database/components/view/gallery/GalleryView.vue create mode 100644 web-frontend/modules/database/components/view/gallery/GalleryViewHeader.vue create mode 100644 web-frontend/modules/database/services/view/gallery.js create mode 100644 web-frontend/modules/database/store/view/bufferedRows.js create mode 100644 web-frontend/modules/database/store/view/fieldOptions.js create mode 100644 web-frontend/modules/database/store/view/gallery.js create mode 100644 web-frontend/modules/database/utils/card.js create mode 100644 web-frontend/test/unit/database/store/view/bufferedRows.spec.js diff --git a/backend/src/baserow/config/settings/base.py b/backend/src/baserow/config/settings/base.py index 8765a71449..a5d3916550 100644 --- a/backend/src/baserow/config/settings/base.py +++ b/backend/src/baserow/config/settings/base.py @@ -235,6 +235,7 @@ SPECTACULAR_SETTINGS = { {"name": "Database table view filters"}, {"name": "Database table view sortings"}, {"name": "Database table grid view"}, + {"name": "Database table gallery view"}, {"name": "Database table form view"}, {"name": "Database table kanban view"}, {"name": "Database table rows"}, diff --git a/backend/src/baserow/contrib/database/api/views/gallery/__init__.py b/backend/src/baserow/contrib/database/api/views/gallery/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/backend/src/baserow/contrib/database/api/views/gallery/errors.py b/backend/src/baserow/contrib/database/api/views/gallery/errors.py new file mode 100644 index 0000000000..067e7beb4e --- /dev/null +++ b/backend/src/baserow/contrib/database/api/views/gallery/errors.py @@ -0,0 +1,8 @@ +from rest_framework.status import HTTP_404_NOT_FOUND + + +ERROR_GALLERY_DOES_NOT_EXIST = ( + "ERROR_GALLERY_DOES_NOT_EXIST", + HTTP_404_NOT_FOUND, + "The requested gallery view does not exist.", +) diff --git a/backend/src/baserow/contrib/database/api/views/gallery/pagination.py b/backend/src/baserow/contrib/database/api/views/gallery/pagination.py new file mode 100644 index 0000000000..8672aa6380 --- /dev/null +++ b/backend/src/baserow/contrib/database/api/views/gallery/pagination.py @@ -0,0 +1,5 @@ +from rest_framework.pagination import LimitOffsetPagination + + +class GalleryLimitOffsetPagination(LimitOffsetPagination): + default_limit = 100 diff --git a/backend/src/baserow/contrib/database/api/views/gallery/serializers.py b/backend/src/baserow/contrib/database/api/views/gallery/serializers.py new file mode 100644 index 0000000000..554800b6bc --- /dev/null +++ b/backend/src/baserow/contrib/database/api/views/gallery/serializers.py @@ -0,0 +1,9 @@ +from rest_framework import serializers + +from baserow.contrib.database.views.models import GalleryViewFieldOptions + + +class GalleryViewFieldOptionsSerializer(serializers.ModelSerializer): + class Meta: + model = GalleryViewFieldOptions + fields = ("hidden", "order") diff --git a/backend/src/baserow/contrib/database/api/views/gallery/urls.py b/backend/src/baserow/contrib/database/api/views/gallery/urls.py new file mode 100644 index 0000000000..7ade6bab0d --- /dev/null +++ b/backend/src/baserow/contrib/database/api/views/gallery/urls.py @@ -0,0 +1,10 @@ +from django.urls import re_path + +from .views import GalleryViewView + + +app_name = "baserow.contrib.database.api.views.gallery" + +urlpatterns = [ + re_path(r"(?P[0-9]+)/$", GalleryViewView.as_view(), name="list"), +] diff --git a/backend/src/baserow/contrib/database/api/views/gallery/views.py b/backend/src/baserow/contrib/database/api/views/gallery/views.py new file mode 100644 index 0000000000..22ace27848 --- /dev/null +++ b/backend/src/baserow/contrib/database/api/views/gallery/views.py @@ -0,0 +1,143 @@ +from drf_spectacular.openapi import OpenApiParameter, OpenApiTypes +from drf_spectacular.utils import extend_schema +from rest_framework.permissions import AllowAny +from rest_framework.response import Response +from rest_framework.views import APIView + +from baserow.api.decorators import map_exceptions, allowed_includes +from baserow.api.errors import ERROR_USER_NOT_IN_GROUP +from baserow.api.schemas import get_error_schema +from baserow.api.serializers import get_example_pagination_serializer_class +from baserow.contrib.database.api.rows.serializers import ( + get_example_row_serializer_class, +) +from baserow.contrib.database.api.rows.serializers import ( + get_row_serializer_class, + RowSerializer, +) +from baserow.contrib.database.api.views.gallery.serializers import ( + GalleryViewFieldOptionsSerializer, +) +from baserow.contrib.database.api.views.serializers import FieldOptionsField +from baserow.contrib.database.views.exceptions import ViewDoesNotExist +from baserow.contrib.database.views.handler import ViewHandler +from baserow.contrib.database.views.models import GalleryView +from baserow.contrib.database.views.registries import view_type_registry +from baserow.core.exceptions import UserNotInGroup + +from .errors import ERROR_GALLERY_DOES_NOT_EXIST +from .pagination import GalleryLimitOffsetPagination + + +class GalleryViewView(APIView): + permission_classes = (AllowAny,) + + @extend_schema( + parameters=[ + OpenApiParameter( + name="view_id", + location=OpenApiParameter.PATH, + type=OpenApiTypes.INT, + description="Returns only rows that belong to the related view's " + "table.", + ), + OpenApiParameter( + name="count", + location=OpenApiParameter.QUERY, + type=OpenApiTypes.NONE, + description="If provided only the count will be returned.", + ), + OpenApiParameter( + name="include", + location=OpenApiParameter.QUERY, + type=OpenApiTypes.STR, + description=( + "A comma separated list allowing the values of `field_options` " + "which will add the object/objects with the same name to the " + "response if included. The `field_options` object contains user " + "defined view settings for each field. For example the field's " + "order is included in here." + ), + ), + OpenApiParameter( + name="limit", + location=OpenApiParameter.QUERY, + type=OpenApiTypes.INT, + description="Defines how many rows should be returned.", + ), + OpenApiParameter( + name="offset", + location=OpenApiParameter.QUERY, + type=OpenApiTypes.INT, + description="Can only be used in combination with the `limit` " + "parameter and defines from which offset the rows should " + "be returned.", + ), + OpenApiParameter( + name="search", + location=OpenApiParameter.QUERY, + type=OpenApiTypes.STR, + description="If provided only rows with data that matches the search " + "query are going to be returned.", + ), + ], + tags=["Database table gallery view"], + operation_id="list_database_table_gallery_view_rows", + description=( + "Lists the requested rows of the view's table related to the provided " + "`view_id` if the authorized user has access to the database's group. " + "The response is paginated by a limit/offset style." + ), + responses={ + 200: get_example_pagination_serializer_class( + get_example_row_serializer_class(add_id=True, user_field_names=False), + additional_fields={ + "field_options": FieldOptionsField( + serializer_class=GalleryViewFieldOptionsSerializer, + required=False, + ), + }, + serializer_name="PaginationSerializerWithGalleryViewFieldOptions", + ), + 400: get_error_schema(["ERROR_USER_NOT_IN_GROUP"]), + 404: get_error_schema(["ERROR_GALLERY_DOES_NOT_EXIST"]), + }, + ) + @map_exceptions( + { + UserNotInGroup: ERROR_USER_NOT_IN_GROUP, + ViewDoesNotExist: ERROR_GALLERY_DOES_NOT_EXIST, + } + ) + @allowed_includes("field_options") + def get(self, request, view_id, field_options): + """Lists the rows for the gallery view.""" + + view_handler = ViewHandler() + view = view_handler.get_view(view_id, GalleryView) + view_type = view_type_registry.get_by_model(view) + + view.table.database.group.has_user( + request.user, raise_error=True, allow_if_template=True + ) + model = view.table.get_model() + queryset = view_handler.get_queryset(view, None, model) + + if "count" in request.GET: + return Response({"count": queryset.count()}) + + paginator = GalleryLimitOffsetPagination() + page = paginator.paginate_queryset(queryset, request, self) + serializer_class = get_row_serializer_class( + model, RowSerializer, is_response=True + ) + serializer = serializer_class(page, many=True) + + response = paginator.get_paginated_response(serializer.data) + + if field_options: + context = {"fields": [o["field"] for o in model._field_objects.values()]} + serializer_class = view_type.get_field_options_serializer_class() + response.data.update(**serializer_class(view, context=context).data) + + return response diff --git a/backend/src/baserow/contrib/database/apps.py b/backend/src/baserow/contrib/database/apps.py index 1388022e16..65419ff25a 100644 --- a/backend/src/baserow/contrib/database/apps.py +++ b/backend/src/baserow/contrib/database/apps.py @@ -122,9 +122,10 @@ class DatabaseConfig(AppConfig): ) field_converter_registry.register(FormulaFieldConverter()) - from .views.view_types import GridViewType, FormViewType + from .views.view_types import GridViewType, GalleryViewType, FormViewType view_type_registry.register(GridViewType()) + view_type_registry.register(GalleryViewType()) view_type_registry.register(FormViewType()) from .views.view_filters import ( diff --git a/backend/src/baserow/contrib/database/migrations/0051_gallery_view.py b/backend/src/baserow/contrib/database/migrations/0051_gallery_view.py new file mode 100644 index 0000000000..ac50e7f530 --- /dev/null +++ b/backend/src/baserow/contrib/database/migrations/0051_gallery_view.py @@ -0,0 +1,87 @@ +# Generated by Django 3.2.6 on 2021-12-01 16:32 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ("database", "0050_remove_multiselect_missing_options"), + ] + + operations = [ + migrations.CreateModel( + name="GalleryView", + fields=[ + ( + "view_ptr", + models.OneToOneField( + auto_created=True, + on_delete=django.db.models.deletion.CASCADE, + parent_link=True, + primary_key=True, + serialize=False, + to="database.view", + ), + ), + ], + options={ + "abstract": False, + }, + bases=("database.view",), + ), + migrations.CreateModel( + name="GalleryViewFieldOptions", + fields=[ + ( + "id", + models.AutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "hidden", + models.BooleanField( + default=True, + help_text="Whether or not the field should be hidden in the " + "card.", + ), + ), + ( + "order", + models.SmallIntegerField( + default=32767, + help_text="The order that the field has in the form. Lower " + "value is first.", + ), + ), + ( + "field", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, to="database.field" + ), + ), + ( + "gallery_view", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to="database.galleryview", + ), + ), + ], + options={ + "ordering": ("order", "field_id"), + }, + ), + migrations.AddField( + model_name="galleryview", + name="field_options", + field=models.ManyToManyField( + through="database.GalleryViewFieldOptions", to="database.Field" + ), + ), + ] diff --git a/backend/src/baserow/contrib/database/models.py b/backend/src/baserow/contrib/database/models.py index 05dac7baef..27f95f5cbd 100644 --- a/backend/src/baserow/contrib/database/models.py +++ b/backend/src/baserow/contrib/database/models.py @@ -5,6 +5,8 @@ from .views.models import ( View, GridView, GridViewFieldOptions, + GalleryView, + GalleryViewFieldOptions, FormView, FormViewFieldOptions, ViewFilter, @@ -38,6 +40,8 @@ __all__ = [ "View", "GridView", "GridViewFieldOptions", + "GalleryView", + "GalleryViewFieldOptions", "FormView", "FormViewFieldOptions", "ViewFilter", diff --git a/backend/src/baserow/contrib/database/views/models.py b/backend/src/baserow/contrib/database/views/models.py index c94dcee74d..7a6023f3f1 100644 --- a/backend/src/baserow/contrib/database/views/models.py +++ b/backend/src/baserow/contrib/database/views/models.py @@ -220,6 +220,31 @@ class GridViewFieldOptions(ParentFieldTrashableModelMixin, models.Model): ordering = ("field_id",) +class GalleryView(View): + field_options = models.ManyToManyField(Field, through="GalleryViewFieldOptions") + + +class GalleryViewFieldOptions(ParentFieldTrashableModelMixin, models.Model): + gallery_view = models.ForeignKey(GalleryView, on_delete=models.CASCADE) + field = models.ForeignKey(Field, on_delete=models.CASCADE) + hidden = models.BooleanField( + default=True, + help_text="Whether or not the field should be hidden in the card.", + ) + # The default value is the maximum value of the small integer field because a newly + # created field must always be last. + order = models.SmallIntegerField( + default=32767, + help_text="The order that the field has in the form. Lower value is first.", + ) + + class Meta: + ordering = ( + "order", + "field_id", + ) + + class FormView(View): field_options = models.ManyToManyField(Field, through="FormViewFieldOptions") slug = models.SlugField( diff --git a/backend/src/baserow/contrib/database/views/view_types.py b/backend/src/baserow/contrib/database/views/view_types.py index f4ff677e67..a76890a628 100644 --- a/backend/src/baserow/contrib/database/views/view_types.py +++ b/backend/src/baserow/contrib/database/views/view_types.py @@ -11,12 +11,22 @@ from baserow.contrib.database.fields.registries import field_type_registry from baserow.contrib.database.api.views.grid.serializers import ( GridViewFieldOptionsSerializer, ) +from baserow.contrib.database.api.views.gallery.serializers import ( + GalleryViewFieldOptionsSerializer, +) from baserow.contrib.database.api.views.form.serializers import ( FormViewFieldOptionsSerializer, ) from .handler import ViewHandler -from .models import GridView, GridViewFieldOptions, FormView, FormViewFieldOptions +from .models import ( + GridView, + GridViewFieldOptions, + GalleryView, + GalleryViewFieldOptions, + FormView, + FormViewFieldOptions, +) from .registries import ViewType from .exceptions import FormViewFieldTypeIsNotSupported @@ -112,6 +122,86 @@ class GridViewType(ViewType): return ordered_field_objects, model +class GalleryViewType(ViewType): + type = "gallery" + model_class = GalleryView + field_options_model_class = GalleryViewFieldOptions + field_options_serializer_class = GalleryViewFieldOptionsSerializer + + def get_api_urls(self): + from baserow.contrib.database.api.views.gallery import urls as api_urls + + return [ + path("gallery/", include(api_urls, namespace=self.type)), + ] + + def export_serialized(self, gallery, files_zip, storage): + """ + Adds the serialized gallery view options to the exported dict. + """ + + serialized = super().export_serialized(gallery, files_zip, storage) + serialized_field_options = [] + for field_option in gallery.get_field_options(): + serialized_field_options.append( + { + "id": field_option.id, + "field_id": field_option.field_id, + "hidden": field_option.hidden, + "order": field_option.order, + } + ) + + serialized["field_options"] = serialized_field_options + return serialized + + def import_serialized( + self, table, serialized_values, id_mapping, files_zip, storage + ): + """ + Imports the serialized gallery view field options. + """ + + serialized_copy = serialized_values.copy() + field_options = serialized_copy.pop("field_options") + gallery_view = super().import_serialized( + table, serialized_copy, id_mapping, files_zip, storage + ) + + if "database_gallery_view_field_options" not in id_mapping: + id_mapping["database_gallery_view_field_options"] = {} + + for field_option in field_options: + field_option_copy = field_option.copy() + field_option_id = field_option_copy.pop("id") + field_option_copy["field_id"] = id_mapping["database_fields"][ + field_option["field_id"] + ] + field_option_object = GalleryViewFieldOptions.objects.create( + gallery_view=gallery_view, **field_option_copy + ) + id_mapping["database_gallery_view_field_options"][ + field_option_id + ] = field_option_object.id + + return gallery_view + + def view_created(self, view): + """ + When a gallery view is created, we want to set the first three fields as + visible. + """ + + field_options = view.get_field_options(create_if_not_exists=True) + field_options.sort(key=lambda x: x.field_id) + ids_to_update = [f.id for f in field_options[0:3]] + + if ids_to_update: + GalleryViewFieldOptions.objects.filter(id__in=ids_to_update).update( + hidden=False + ) + + class FormViewType(ViewType): type = "form" model_class = FormView diff --git a/backend/src/baserow/test_utils/fixtures/view.py b/backend/src/baserow/test_utils/fixtures/view.py index 1ca6d418ac..1808204de9 100644 --- a/backend/src/baserow/test_utils/fixtures/view.py +++ b/backend/src/baserow/test_utils/fixtures/view.py @@ -2,6 +2,8 @@ from baserow.contrib.database.fields.models import Field from baserow.contrib.database.views.models import ( GridView, GridViewFieldOptions, + GalleryView, + GalleryViewFieldOptions, FormView, FormViewFieldOptions, ViewFilter, @@ -35,6 +37,31 @@ class ViewFixtures: grid_view=grid_view, field=field, **kwargs ) + def create_gallery_view(self, user=None, **kwargs): + if "table" not in kwargs: + kwargs["table"] = self.create_database_table(user=user) + + if "name" not in kwargs: + kwargs["name"] = self.fake.name() + + if "order" not in kwargs: + kwargs["order"] = 0 + + gallery_view = GalleryView.objects.create(**kwargs) + self.create_gallery_view_field_options(gallery_view) + return gallery_view + + def create_gallery_view_field_options(self, gallery_view, **kwargs): + return [ + self.create_gallery_view_field_option(gallery_view, field, **kwargs) + for field in Field.objects.filter(table=gallery_view.table) + ] + + def create_gallery_view_field_option(self, gallery_view, field, **kwargs): + return GalleryViewFieldOptions.objects.create( + gallery_view=gallery_view, field=field, **kwargs + ) + def create_form_view(self, user=None, **kwargs): if "table" not in kwargs: kwargs["table"] = self.create_database_table(user=user) diff --git a/backend/tests/baserow/contrib/database/api/views/gallery/test_gallery_view_views.py b/backend/tests/baserow/contrib/database/api/views/gallery/test_gallery_view_views.py new file mode 100644 index 0000000000..770d1ed0a0 --- /dev/null +++ b/backend/tests/baserow/contrib/database/api/views/gallery/test_gallery_view_views.py @@ -0,0 +1,229 @@ +import pytest +from django.shortcuts import reverse +from rest_framework.status import ( + HTTP_200_OK, + HTTP_400_BAD_REQUEST, + HTTP_401_UNAUTHORIZED, + HTTP_404_NOT_FOUND, +) + + +@pytest.mark.django_db +def test_list_rows(api_client, data_fixture): + user, token = data_fixture.create_user_and_token( + email="test@test.nl", password="password", first_name="Test1" + ) + table = data_fixture.create_database_table(user=user) + text_field = data_fixture.create_text_field( + table=table, order=0, name="Color", text_default="white" + ) + gallery = data_fixture.create_gallery_view(table=table) + gallery_2 = data_fixture.create_gallery_view() + + model = gallery.table.get_model() + row_1 = model.objects.create(**{f"field_{text_field.id}": "Green"}) + row_2 = model.objects.create() + row_3 = model.objects.create(**{f"field_{text_field.id}": "Orange"}) + row_4 = model.objects.create(**{f"field_{text_field.id}": "Purple"}) + + url = reverse("api:database:views:gallery:list", kwargs={"view_id": 999}) + response = api_client.get(url, **{"HTTP_AUTHORIZATION": f"JWT {token}"}) + assert response.status_code == HTTP_404_NOT_FOUND + assert response.json()["error"] == "ERROR_GALLERY_DOES_NOT_EXIST" + + url = reverse("api:database:views:gallery:list", kwargs={"view_id": gallery_2.id}) + response = api_client.get(url, **{"HTTP_AUTHORIZATION": f"JWT {token}"}) + assert response.status_code == HTTP_400_BAD_REQUEST + assert response.json()["error"] == "ERROR_USER_NOT_IN_GROUP" + + url = reverse("api:database:views:gallery:list", kwargs={"view_id": gallery.id}) + response = api_client.get( + url, {"limit": 2}, **{"HTTP_AUTHORIZATION": f"JWT {token}"} + ) + response_json = response.json() + assert response.status_code == HTTP_200_OK + assert response_json["count"] == 4 + assert response_json["results"][0]["id"] == row_1.id + assert response_json["results"][1]["id"] == row_2.id + assert "field_options" not in response_json + + url = reverse("api:database:views:gallery:list", kwargs={"view_id": gallery.id}) + response = api_client.get( + url, {"limit": 1, "offset": 2}, **{"HTTP_AUTHORIZATION": f"JWT {token}"} + ) + response_json = response.json() + assert response.status_code == HTTP_200_OK + assert response_json["count"] == 4 + assert response_json["results"][0]["id"] == row_3.id + + sort = data_fixture.create_view_sort(view=gallery, field=text_field, order="ASC") + url = reverse("api:database:views:gallery:list", kwargs={"view_id": gallery.id}) + response = api_client.get(url, **{"HTTP_AUTHORIZATION": f"JWT {token}"}) + response_json = response.json() + assert response.status_code == HTTP_200_OK + assert response_json["count"] == 4 + assert response_json["results"][0]["id"] == row_1.id + assert response_json["results"][1]["id"] == row_3.id + assert response_json["results"][2]["id"] == row_4.id + assert response_json["results"][3]["id"] == row_2.id + sort.delete() + + view_filter = data_fixture.create_view_filter( + view=gallery, field=text_field, value="Green" + ) + url = reverse("api:database:views:gallery:list", kwargs={"view_id": gallery.id}) + response = api_client.get(url, **{"HTTP_AUTHORIZATION": f"JWT {token}"}) + response_json = response.json() + assert response.status_code == HTTP_200_OK + assert response_json["count"] == 1 + assert len(response_json["results"]) == 1 + assert response_json["results"][0]["id"] == row_1.id + view_filter.delete() + + url = reverse("api:database:views:gallery:list", kwargs={"view_id": gallery.id}) + response = api_client.get( + url, data={"count": ""}, **{"HTTP_AUTHORIZATION": f"JWT {token}"} + ) + response_json = response.json() + assert response_json["count"] == 4 + assert len(response_json.keys()) == 1 + + row_1.delete() + row_2.delete() + row_3.delete() + row_4.delete() + + url = reverse("api:database:views:gallery:list", kwargs={"view_id": gallery.id}) + response = api_client.get(url, **{"HTTP_AUTHORIZATION": f"JWT {token}"}) + response_json = response.json() + assert response.status_code == HTTP_200_OK + assert response_json["count"] == 0 + assert not response_json["previous"] + assert not response_json["next"] + assert len(response_json["results"]) == 0 + + url = reverse("api:database:views:gallery:list", kwargs={"view_id": gallery.id}) + response = api_client.get(url) + assert response.status_code == HTTP_401_UNAUTHORIZED + + data_fixture.create_template(group=gallery.table.database.group) + url = reverse("api:database:views:gallery:list", kwargs={"view_id": gallery.id}) + response = api_client.get(url) + assert response.status_code == HTTP_200_OK + + +@pytest.mark.django_db +def test_list_rows_include_field_options(api_client, data_fixture): + user, token = data_fixture.create_user_and_token( + email="test@test.nl", password="password", first_name="Test1" + ) + table = data_fixture.create_database_table(user=user) + text_field = data_fixture.create_text_field( + table=table, order=0, name="Color", text_default="white" + ) + gallery = data_fixture.create_gallery_view(table=table) + + # The second field is deliberately created after the creation of the gallery field + # so that the GridViewFieldOptions entry is not created. This should + # automatically be created when the page is fetched. + number_field = data_fixture.create_number_field( + table=table, order=1, name="Horsepower" + ) + + url = reverse("api:database:views:gallery:list", kwargs={"view_id": gallery.id}) + response = api_client.get(url, **{"HTTP_AUTHORIZATION": f"JWT {token}"}) + response_json = response.json() + assert response.status_code == HTTP_200_OK + assert "field_options" not in response_json + + url = reverse("api:database:views:gallery:list", kwargs={"view_id": gallery.id}) + response = api_client.get( + url, {"include": "field_options"}, **{"HTTP_AUTHORIZATION": f"JWT {token}"} + ) + response_json = response.json() + assert response.status_code == HTTP_200_OK + assert len(response_json["field_options"]) == 2 + assert response_json["field_options"][str(text_field.id)]["hidden"] is True + assert response_json["field_options"][str(text_field.id)]["order"] == 32767 + assert response_json["field_options"][str(number_field.id)]["hidden"] is True + assert response_json["field_options"][str(number_field.id)]["order"] == 32767 + assert "filters_disabled" not in response_json + + +@pytest.mark.django_db +def test_patch_gallery_view_field_options(api_client, data_fixture): + user, token = data_fixture.create_user_and_token( + email="test@test.nl", + password="password", + first_name="Test1", + ) + table = data_fixture.create_database_table(user=user) + text_field = data_fixture.create_text_field(table=table) + gallery = data_fixture.create_gallery_view(table=table) + + url = reverse("api:database:views:field_options", kwargs={"view_id": gallery.id}) + response = api_client.patch( + url, + {"field_options": {text_field.id: {"width": 300, "hidden": False}}}, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + response_json = response.json() + assert response.status_code == HTTP_200_OK + assert len(response_json["field_options"]) == 1 + assert response_json["field_options"][str(text_field.id)]["hidden"] is False + assert response_json["field_options"][str(text_field.id)]["order"] == 32767 + options = gallery.get_field_options() + assert len(options) == 1 + assert options[0].field_id == text_field.id + assert options[0].hidden is False + assert options[0].order == 32767 + + +@pytest.mark.django_db +def test_create_gallery_view(api_client, data_fixture): + user, token = data_fixture.create_user_and_token() + table = data_fixture.create_database_table(user=user) + + response = api_client.post( + reverse("api:database:views:list", kwargs={"table_id": table.id}), + { + "name": "Test 2", + "type": "gallery", + "filter_type": "AND", + "filters_disabled": False, + }, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + response_json = response.json() + assert response.status_code == HTTP_200_OK + assert response_json["name"] == "Test 2" + assert response_json["type"] == "gallery" + assert response_json["filter_type"] == "AND" + assert response_json["filters_disabled"] is False + + +@pytest.mark.django_db +def test_update_gallery_view(api_client, data_fixture): + user, token = data_fixture.create_user_and_token() + table = data_fixture.create_database_table(user=user) + gallery_view = data_fixture.create_gallery_view(table=table) + + response = api_client.patch( + reverse("api:database:views:item", kwargs={"view_id": gallery_view.id}), + { + "name": "Test 2", + "type": "gallery", + "filter_type": "AND", + "filters_disabled": False, + }, + format="json", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + response_json = response.json() + assert response.status_code == HTTP_200_OK + assert response_json["name"] == "Test 2" + assert response_json["type"] == "gallery" + assert response_json["filter_type"] == "AND" + assert response_json["filters_disabled"] is False diff --git a/backend/tests/baserow/contrib/database/view/test_view_types.py b/backend/tests/baserow/contrib/database/view/test_view_types.py index 721a967219..cc4e9702b5 100644 --- a/backend/tests/baserow/contrib/database/view/test_view_types.py +++ b/backend/tests/baserow/contrib/database/view/test_view_types.py @@ -8,6 +8,8 @@ from django.core.files.storage import FileSystemStorage from baserow.core.user_files.handler import UserFileHandler from baserow.contrib.database.views.registries import view_type_registry +from baserow.contrib.database.views.handler import ViewHandler +from baserow.contrib.database.views.models import GalleryViewFieldOptions @pytest.mark.django_db @@ -61,6 +63,75 @@ def test_import_export_grid_view(data_fixture): assert field_option.order == imported_field_option.order +@pytest.mark.django_db +def test_import_export_gallery_view(data_fixture, tmpdir): + user = data_fixture.create_user() + + storage = FileSystemStorage(location=str(tmpdir), base_url="http://localhost") + table = data_fixture.create_database_table(user=user) + gallery_view = data_fixture.create_gallery_view(table=table) + text_field = data_fixture.create_text_field(table=table) + field_option = data_fixture.create_gallery_view_field_option( + gallery_view, text_field, order=1 + ) + + files_buffer = BytesIO() + gallery_view_type = view_type_registry.get("gallery") + + with ZipFile(files_buffer, "a", ZIP_DEFLATED, False) as files_zip: + serialized = gallery_view_type.export_serialized( + gallery_view, files_zip=files_zip, storage=storage + ) + + assert serialized["id"] == gallery_view.id + assert serialized["type"] == "gallery" + assert serialized["name"] == gallery_view.name + assert serialized["order"] == 0 + assert len(serialized["field_options"]) == 1 + assert serialized["field_options"][0]["id"] == field_option.id + assert serialized["field_options"][0]["field_id"] == field_option.field_id + assert serialized["field_options"][0]["hidden"] is True + assert serialized["field_options"][0]["order"] == 1 + + imported_single_select_field = data_fixture.create_text_field(table=table) + id_mapping = {"database_fields": {text_field.id: imported_single_select_field.id}} + + with ZipFile(files_buffer, "a", ZIP_DEFLATED, False) as files_zip: + imported_gallery_view = gallery_view_type.import_serialized( + gallery_view.table, serialized, id_mapping, files_zip, storage + ) + + assert gallery_view.id != imported_gallery_view.id + assert gallery_view.name == imported_gallery_view.name + assert gallery_view.order == imported_gallery_view.order + imported_field_options = imported_gallery_view.get_field_options() + assert len(imported_field_options) == 1 + imported_field_option = imported_field_options[0] + assert field_option.id != imported_field_option.id + assert field_option.hidden == imported_field_option.hidden + assert field_option.order == imported_field_option.order + + +@pytest.mark.django_db +def test_newly_created_gallery_view(data_fixture): + user = data_fixture.create_user() + table = data_fixture.create_database_table(user=user) + data_fixture.create_text_field(table=table, primary=True) + data_fixture.create_text_field(table=table) + data_fixture.create_text_field(table=table) + data_fixture.create_text_field(table=table) + + handler = ViewHandler() + handler.create_view(user, table=table, type_name="gallery") + + all_field_options = ( + GalleryViewFieldOptions.objects.all() + .order_by("field_id") + .values_list("hidden", flat=True) + ) + assert list(all_field_options) == [False, False, False, True] + + @pytest.mark.django_db def test_import_export_form_view(data_fixture, tmpdir): user = data_fixture.create_user() diff --git a/changelog.md b/changelog.md index 51ce774582..9a1917c0e6 100644 --- a/changelog.md +++ b/changelog.md @@ -4,6 +4,7 @@ * Fix deleted options that appear in the command line JSON file export. * Fix subtracting date intervals from dates in formulas in some situations not working. +* Added gallery view. * Added length is lower than filter. ## Released (2021-11-25) diff --git a/premium/web-frontend/modules/baserow_premium/components/views/kanban/KanbanViewStack.vue b/premium/web-frontend/modules/baserow_premium/components/views/kanban/KanbanViewStack.vue index ad6c412fa0..8f15e74553 100644 --- a/premium/web-frontend/modules/baserow_premium/components/views/kanban/KanbanViewStack.vue +++ b/premium/web-frontend/modules/baserow_premium/components/views/kanban/KanbanViewStack.vue @@ -135,6 +135,7 @@ import RowCard from '@baserow/modules/database/components/card/RowCard' import InfiniteScroll from '@baserow/modules/core/components/helpers/InfiniteScroll' import { populateRow } from '@baserow_premium/store/view/kanban' import KanbanViewStackContext from '@baserow_premium/components/views/kanban/KanbanViewStackContext' +import { getCardHeight } from '@baserow/modules/database/utils/card' export default { name: 'KanbanViewStack', @@ -200,27 +201,8 @@ export default { * the card is to correctly position it. */ cardHeight() { - // margin-bottom of card.scss.card__field, that we don't have to compensate for - // if there aren't any fields in the card. - const fieldMarginBottom = this.cardFields.length === 0 ? 0 : 10 - - return ( - // Some of these values must be kep in sync with card.scss - this.cardFields.reduce((accumulator, field) => { - const fieldType = this.$registry.get('field', field._.type.type) - return ( - accumulator + - fieldType.getCardValueHeight(field) + - 6 + // margin-bottom of card.scss.card__field-name - 14 + // line-height of card.scss.card__field-name - 10 // margin-bottom of card.scss.card__field - ) - }, 0) + - 16 + // padding-top of card.scss.card - 16 - // padding-bottom of card.scss.card - fieldMarginBottom + - 10 // margin-bottom of kanban.scss.kanban-view__stack-card - ) + // 10 = margin-bottom of kanban.scss.kanban-view__stack-card + return getCardHeight(this.cardFields, this.$registry) + 10 }, /** * Figure out what the stack id that's used in the store is. The representation is diff --git a/web-frontend/locales/en.js b/web-frontend/locales/en.js index b93516f6c8..81eca18898 100644 --- a/web-frontend/locales/en.js +++ b/web-frontend/locales/en.js @@ -144,6 +144,7 @@ export default { }, viewType: { grid: 'Grid', + gallery: 'Gallery', form: 'Form', }, premium: { diff --git a/web-frontend/locales/fr.js b/web-frontend/locales/fr.js index 9d9c0979fd..b70d0ba254 100644 --- a/web-frontend/locales/fr.js +++ b/web-frontend/locales/fr.js @@ -146,6 +146,7 @@ export default { }, viewType: { grid: 'Tableau', + gallery: 'Gallerie', form: 'Formulaire', }, premium: { diff --git a/web-frontend/modules/core/assets/scss/components/all.scss b/web-frontend/modules/core/assets/scss/components/all.scss index 2215a1c7b7..c9d25c041d 100644 --- a/web-frontend/modules/core/assets/scss/components/all.scss +++ b/web-frontend/modules/core/assets/scss/components/all.scss @@ -22,6 +22,8 @@ @import 'fields/file'; @import 'fields/multiple_select'; @import 'fields/array'; +@import 'card'; +@import 'card/all'; @import 'views/grid'; @import 'views/grid/text'; @import 'views/grid/long_text'; @@ -34,6 +36,7 @@ @import 'views/grid/multiple_select'; @import 'views/grid/many_to_many'; @import 'views/grid/array'; +@import 'views/gallery'; @import 'array_field'; @import 'views/form'; @import 'box_page'; @@ -77,7 +80,5 @@ @import 'infinite_scroll'; @import 'formula_field'; @import 'lang_picker'; -@import 'card'; -@import 'card/all'; @import 'webhook'; @import 'tab'; diff --git a/web-frontend/modules/core/assets/scss/components/card.scss b/web-frontend/modules/core/assets/scss/components/card.scss index d4fadf69b9..5fa012a590 100644 --- a/web-frontend/modules/core/assets/scss/components/card.scss +++ b/web-frontend/modules/core/assets/scss/components/card.scss @@ -1,14 +1,41 @@ -// Some of the properties must be kept in sync with `KanbanViewStack.vue::cardHeight`. -// This is because the kanban view needs to know the height of each card in order to -// paginate correctly. If properties that influence the height and added or changed, we -// most likely need to make a change in the KanbanView.vue::cardHeight method. These -// are properties like margin-top, margin-bottom, padding-top, padding-bottom, height, -// line-height, etc +@keyframes card-loading-animation { + 0% { + transform: translate3d(-30%, 0, 0); + } + + 100% { + transform: translate3d(30%, 0, 0); + } +} + +// Some of the properties must be kept in sync with +// `modules/database/utils/card.js::cardHeight`. This is because the kanban and gallery +// view needs to know the height of each card in order to paginate correctly. If +// properties that influence the height and added or changed, we most likely need to +// make a change in the KanbanView.vue::cardHeight method. These are properties like +// margin-top, margin-bottom, padding-top, padding-bottom, height, line-height, etc .card { + position: relative; background-color: $white; box-shadow: 0 1px 3px 0 rgba($black, 0.16); border-radius: 3px; padding: 16px 0; + + &--loading { + overflow: hidden; + + &::before { + z-index: 1; + width: 500%; + margin-left: -250%; + background: linear-gradient(to right, rgba(255, 255, 255, 0) 46%, rgba(255, 255, 255, 0.35) 50%, rgba(255, 255, 255, 0) 54%) 50% 50%; + animation: card-loading-animation 0.8s linear infinite; + content: " "; + pointer-events: none; + + @include absolute(0, 0, 0, 50%); + } + } } .card__field { @@ -24,8 +51,19 @@ line-height: 14px; font-weight: 600; margin-bottom: 6px; + + .card--loading & { + color: $color-neutral-100; + background-color: $color-neutral-100; + } } .card__field-value { width: 100%; + + .card--loading & { + width: 50%; + background-color: $color-neutral-100; + height: 13px; + } } diff --git a/web-frontend/modules/core/assets/scss/components/select.scss b/web-frontend/modules/core/assets/scss/components/select.scss index 40a6242ab5..3325cb412e 100644 --- a/web-frontend/modules/core/assets/scss/components/select.scss +++ b/web-frontend/modules/core/assets/scss/components/select.scss @@ -198,29 +198,50 @@ } } -.select__footer-multiple { +.select__footer-create { display: flex; - padding: 8px 12px; + flex-wrap: wrap; + padding: 8px 12px 4px 12px; } -.select__footer-multiple-label { - @extend %select__item-size; -} - -.select__footer-multiple-item { - @extend %select__item-size; - - margin-left: 8px; - padding: 0 10px; +.select__footer-create-link { + position: relative; + flex: 0 0 calc(50% - 10px); + width: calc(50% - 10px); color: $color-primary-900; border-radius: 3px; + padding: 0 32px 0 10px; + margin-bottom: 4px; + min-width: 0; + line-height: 26px; + font-size: 13px; - &:not(.select__footer-multiple-item--disabled):hover { + &:nth-child(2n+1) { + margin-right: 20px; + } + + &:hover { + text-decoration: none; + } + + &::after { + @extend .fas; + + content: fa-content($fa-var-plus); + color: $color-neutral-200; + margin-top: -6.5px; + line-height: 13px; + font-size: 13px; + + @include absolute(50%, 8px, auto, auto); + } + + &:not(.select__footer-create-link--disabled):hover { text-decoration: none; background-color: $color-neutral-100; } - &.select__footer-multiple-item--disabled { + &.select__footer-create-link--disabled { color: $color-neutral-400; &:hover { @@ -230,7 +251,7 @@ } } -.select__footer-multiple-icon { +.select__footer-create-icon { color: $color-neutral-300; margin-right: 4px; } diff --git a/web-frontend/modules/core/assets/scss/components/views/gallery.scss b/web-frontend/modules/core/assets/scss/components/views/gallery.scss new file mode 100644 index 0000000000..99cdb749dc --- /dev/null +++ b/web-frontend/modules/core/assets/scss/components/views/gallery.scss @@ -0,0 +1,37 @@ +.gallery-view { + overflow: hidden; + + @include absolute(0); +} + +.gallery-view__add { + border: solid 1px $color-neutral-400; + background: $white; + border-radius: 100%; + color: $color-primary-900; + box-shadow: 3px 0 6px 0 rgba($black, 0.16); + z-index: 2; + + @include center-text(40px, 18px); + @include absolute(auto, 20px, 20px, auto); + + &:hover { + background-color: $color-neutral-100; + text-decoration: none; + } +} + +.gallery-view__scroll { + overflow-y: auto; + z-index: 1; + + @include absolute(0); +} + +.gallery-view__cards { + position: relative; +} + +.gallery-view__card { + @include absolute(0, auto, auto, 0); +} diff --git a/web-frontend/modules/database/components/card/RowCard.vue b/web-frontend/modules/database/components/card/RowCard.vue index 6abbc6813d..fc3ba16903 100644 --- a/web-frontend/modules/database/components/card/RowCard.vue +++ b/web-frontend/modules/database/components/card/RowCard.vue @@ -1,10 +1,11 @@ + + diff --git a/web-frontend/modules/database/components/view/gallery/GalleryViewHeader.vue b/web-frontend/modules/database/components/view/gallery/GalleryViewHeader.vue new file mode 100644 index 0000000000..59b6386ec4 --- /dev/null +++ b/web-frontend/modules/database/components/view/gallery/GalleryViewHeader.vue @@ -0,0 +1,148 @@ + + + + + +{ + "en":{ + "galleryViewHeader":{ + "customizeCards": "Customize cards" + } + }, + "fr":{ + "settings":{ + "customizeCards": "Configurer les cartes" + } + } +} + diff --git a/web-frontend/modules/database/plugin.js b/web-frontend/modules/database/plugin.js index f7a02b849b..fb1b1ee050 100644 --- a/web-frontend/modules/database/plugin.js +++ b/web-frontend/modules/database/plugin.js @@ -1,5 +1,9 @@ import { DatabaseApplicationType } from '@baserow/modules/database/applicationTypes' -import { GridViewType, FormViewType } from '@baserow/modules/database/viewTypes' +import { + GridViewType, + GalleryViewType, + FormViewType, +} from '@baserow/modules/database/viewTypes' import { TextFieldType, LongTextFieldType, @@ -62,6 +66,7 @@ import tableStore from '@baserow/modules/database/store/table' import viewStore from '@baserow/modules/database/store/view' import fieldStore from '@baserow/modules/database/store/field' import gridStore from '@baserow/modules/database/store/view/grid' +import galleryStore from '@baserow/modules/database/store/view/gallery' import formStore from '@baserow/modules/database/store/view/form' import rowModal from '@baserow/modules/database/store/rowModal' @@ -146,12 +151,15 @@ export default (context) => { store.registerModule('field', fieldStore) store.registerModule('rowModal', rowModal) store.registerModule('page/view/grid', gridStore) + store.registerModule('page/view/gallery', galleryStore) store.registerModule('page/view/form', formStore) store.registerModule('template/view/grid', gridStore) + store.registerModule('template/view/gallery', galleryStore) store.registerModule('template/view/form', formStore) app.$registry.register('application', new DatabaseApplicationType(context)) app.$registry.register('view', new GridViewType(context)) + app.$registry.register('view', new GalleryViewType(context)) app.$registry.register('view', new FormViewType(context)) app.$registry.register('viewFilter', new EqualViewFilterType(context)) app.$registry.register('viewFilter', new NotEqualViewFilterType(context)) diff --git a/web-frontend/modules/database/services/view/gallery.js b/web-frontend/modules/database/services/view/gallery.js new file mode 100644 index 0000000000..ec71b37e1c --- /dev/null +++ b/web-frontend/modules/database/services/view/gallery.js @@ -0,0 +1,58 @@ +export default (client) => { + return { + fetchRows({ + viewId, + limit = 100, + offset = null, + includeFieldOptions = false, + search = false, + cancelToken = null, + }) { + const config = { + params: { + limit, + }, + } + const include = [] + + if (cancelToken !== null) { + config.cancelToken = cancelToken + } + + if (offset !== null) { + config.params.offset = offset + } + + if (includeFieldOptions) { + include.push('field_options') + } + + if (include.length > 0) { + config.params.include = include.join(',') + } + + if (search) { + config.params.search = search + } + + return client.get(`/database/views/gallery/${viewId}/`, config) + }, + fetchCount({ viewId, search, cancelToken = null }) { + const config = { + params: { + count: true, + }, + } + + if (cancelToken !== null) { + config.cancelToken = cancelToken + } + + if (search) { + config.params.search = search + } + + return client.get(`/database/views/gallery/${viewId}/`, config) + }, + } +} diff --git a/web-frontend/modules/database/store/view/bufferedRows.js b/web-frontend/modules/database/store/view/bufferedRows.js new file mode 100644 index 0000000000..6836c57682 --- /dev/null +++ b/web-frontend/modules/database/store/view/bufferedRows.js @@ -0,0 +1,733 @@ +import Vue from 'vue' +import axios from 'axios' +import { RefreshCancelledError } from '@baserow/modules/core/errors' +import { clone } from '@baserow/modules/core/utils/object' +import { + getRowSortFunction, + matchSearchFilters, +} from '@baserow/modules/database/utils/view' +import RowService from '@baserow/modules/database/services/row' + +/** + * This view store mixin can be used to efficiently keep and maintain the rows of a + * table/view without fetching all the rows at once. It first fetches an initial set + * of rows and creates an array in the state containing these rows and adds a `null` + * object for every un-fetched row. + * + * It can correctly handle when new rows are created, updated or deleted without + * needing every row in the state. Components that make use of this store mixin + * just have to dispatch an action telling which rows are currently visible and the + * store handles the rest. Rows that are un-fetched, so when they are `null`, must + * be shown in a loading state if the user is looking at them. + * + * Example of how the state of rows could look: + * + * ``` + * rows = [ + * { id: 1, order: '1.00000000000000000000', field_1: 'Name' }, + * { id: 2, order: '2.00000000000000000000', field_1: 'Name' }, + * { id: 3, order: '3.00000000000000000000', field_1: 'Name' }, + * { id: 4, order: '4.00000000000000000000', field_1: 'Name' }, + * null, + * null, + * null, + * null, + * { id: 9, order: '10.00000000000000000000', field_1: 'Name' }, + * { id: 10, order: '10.00000000000000000000', field_1: 'Name' }, + * null, + * null + * ] + * ``` + */ +export default ({ service, populateRow }) => { + let lastRequestSource = null + + /** + * This helper function calculates the most optimal `limit` `offset` range of rows + * that must be fetched. Based on the provided visible `startIndex` and `endIndex` + * we know which rows must be fetched because those values are `null` in the + * provided `rows` array. If a request must be made, we want to do so in the most + * efficient manner, so we want to respect the ideal request size by filling up + * the request with other rows before and after the range that must also be fetched. + * This function checks if there are other `null` rows close to the range and if + * so, it tries to include them in the range. + * + * @param rows An array containing the rows that we have fetched already. + * @param requestSize The ideal request when making a request to the server. + * @param startIndex The start index of the visible rows. + * @param endIndex The end index of the visible rows. + */ + const getRangeToFetch = (rows, requestSize, startIndex, endIndex) => { + const visibleRows = rows.slice(startIndex, endIndex + 1) + + const firstNullIndex = visibleRows.findIndex((row) => row === null) + const lastNullIndex = visibleRows.lastIndexOf(null) + + // If all of the visible rows have been fetched, so none of them are `null`, we + // don't have to do anything. + if (firstNullIndex === -1) { + return + } + + // Figure out what the request size is. In almost all cases this is going to + // be the configured request size, but it could be that more rows must be visible + // and in that case we want to increase it + const maxRequestSize = Math.max(startIndex - endIndex, requestSize) + + // The initial offset can be the first `null` found in the range. + let offset = startIndex + firstNullIndex + let limit = lastNullIndex - firstNullIndex + 1 + + // Because we have an ideal request size and this is often higher than the + // visible rows, we want to efficiently fetch additional rows that are close + // to the visible range. + while (limit < maxRequestSize) { + const previous = rows[offset - 1] + const next = rows[offset + limit + 1] + + // If both the previous and next item are not `null`, which means there is + // no un-fetched row before or after the range anymore, we want to stop the for + // loop because there is nothing to fetch. + if (previous !== null && next !== null) { + break + } + if (previous === null) { + offset -= 1 + limit += 1 + } + if (next === null) { + limit += 1 + } + } + + // The `limit` could exceed the `maxRequestSize` if it's an odd number because it + // checks if there is an un-fetched row before and after in one loop. + return { offset, limit: Math.min(limit, maxRequestSize) } + } + + const state = () => ({ + // If another visible rows action has been dispatched whilst a previous action + // is still fetching rows, the new action is temporarily delayed and its + // parameters are stored here. + delayedRequest: null, + // Holds the last requested start and end index of the currently visible rows + visibleRange: { + startIndex: 0, + endIndex: 0, + }, + // The ideal number of rows to fetch when making a request. + requestSize: 100, + // The current view id. + viewId: -1, + // Indicates whether the store is currently fetching another batch of rows. + fetching: false, + // A list of all the rows in the table. The ones that haven't been fetched yet + // are `null`. + rows: [], + }) + + const mutations = { + SET_DELAYED_REQUEST(state, delayedRequestParameters) { + state.delayedRequest = delayedRequestParameters + }, + SET_VISIBLE(state, { startIndex, endIndex }) { + state.visibleRange.startIndex = startIndex + state.visibleRange.endIndex = endIndex + }, + SET_VIEW_ID(state, viewId) { + state.viewId = viewId + }, + SET_ROWS(state, rows) { + Vue.set(state, 'rows', rows) + }, + SET_FETCHING(state, value) { + state.fetching = value + }, + UPDATE_ROWS(state, { offset, rows }) { + for (let i = 0; i < rows.length; i++) { + const rowStoreIndex = i + offset + const rowInStore = state.rows[rowStoreIndex] + const row = rows[i] + + if (rowInStore === undefined || rowInStore === null) { + // If the row doesn't yet exist in the store, we can populate the provided + // row and set it. + state.rows.splice(rowStoreIndex, 1, populateRow(row)) + } else { + // If the row does exist in the store, we can extend it with the provided + // data of the provided row so the state won't be lost. + Object.assign(state.rows[rowStoreIndex], row) + } + } + }, + INSERT_ROW_AT_INDEX(state, { index, row }) { + state.rows.splice(index, 0, row) + }, + DELETE_ROW_AT_INDEX(state, { index }) { + state.rows.splice(index, 1) + }, + MOVE_ROW(state, { oldIndex, newIndex }) { + state.rows.splice(newIndex, 0, state.rows.splice(oldIndex, 1)[0]) + }, + UPDATE_ROW_AT_INDEX(state, { index, values }) { + Object.assign(state.rows[index], values) + }, + ADD_FIELD_TO_ALL_ROWS(state, { field, value }) { + const name = `field_${field.id}` + state.rows.forEach((row) => { + if (row !== null && !Object.prototype.hasOwnProperty.call(row, name)) { + // We have to use the Vue.set function here to make it reactive immediately. + // If we don't do this the value in the field components of the view and modal + // don't have the correct value and will act strange. + Vue.set(row, name, value) + } + }) + }, + } + + const actions = { + /** + * This action fetches the initial set of rows via the provided service. After + * that it will fill the state with the newly fetched rows and the rest will be + * un-fetched `null` objects. + */ + async fetchInitialRows( + context, + { viewId, fields, primary, initialRowArguments = {} } + ) { + const { commit, getters } = context + commit('SET_VIEW_ID', viewId) + const { data } = await service(this.$client).fetchRows({ + viewId, + offset: 0, + limit: getters.getRequestSize, + ...initialRowArguments, + }) + const rows = Array(data.count).fill(null) + data.results.forEach((row, index) => { + rows[index] = populateRow(row) + }) + commit('SET_ROWS', rows) + return data + }, + /** + * Should be called when the different rows are displayed to the user. This + * could for example happen when a user scrolls. It will figure out which rows + * have not been fetched and will make a request with the backend to replace to + * missing ones if needed. + */ + async fetchMissingRowsInNewRange( + { dispatch, getters, commit }, + parameters + ) { + const { startIndex, endIndex } = parameters + + // If the store is already fetching a set of pages, we're temporarily storing + // the parameters so that this action can be dispatched again with the latest + // parameters. + if (getters.getFetching) { + commit('SET_DELAYED_REQUEST', parameters) + return + } + + // Check if the currently visible range isn't to same as the provided one + // because we don't want to do anything in that case. + const currentVisible = getters.getVisibleRange + if ( + currentVisible.startIndex === startIndex && + currentVisible.endIndex === endIndex + ) { + return + } + + // Update the last visible range to make sure this action isn't dispatched + // multiple times. + commit('SET_VISIBLE', { startIndex, endIndex }) + + // Check what the ideal range is to fetch with the backend. + const rangeToFetch = getRangeToFetch( + getters.getRows, + getters.getRequestSize, + startIndex, + endIndex + ) + + // If there is no ideal range or if the limit is 0, then there aren't any rows + // to fetch so we can stop. + if (rangeToFetch === undefined || rangeToFetch.limit === 0) { + return + } + + // We can only make one request at the same time, so we're going to to set the + // fetching state to `true` to prevent multiple requests being fired + // simultaneously. + commit('SET_FETCHING', true) + lastRequestSource = axios.CancelToken.source() + try { + const { data } = await service(this.$client).fetchRows({ + viewId: getters.getViewId, + offset: rangeToFetch.offset, + limit: rangeToFetch.limit, + cancelToken: lastRequestSource.token, + }) + commit('UPDATE_ROWS', { + offset: rangeToFetch.offset, + rows: data.results, + }) + } catch (error) { + if (axios.isCancel(error)) { + throw new RefreshCancelledError() + } else { + lastRequestSource = null + throw error + } + } finally { + // Check if another `fetchMissingRowsInNewRange` action has been dispatched + // while we were fetching the rows. If so, we need to dispatch the same + // action again with the latest parameters. + commit('SET_FETCHING', false) + const delayedRequestParameters = getters.getDelayedRequest + if (delayedRequestParameters !== null) { + commit('SET_DELAYED_REQUEST', null) + await dispatch('fetchMissingRowsInNewRange', delayedRequestParameters) + } + } + }, + /** + * Refreshes the row buffer by clearing all of the rows in the store and + * re-fetching the currently visible rows. This is typically done when a filter has + * changed and we can't trust what's in the store anymore. + */ + async refresh( + { dispatch, commit, getters }, + { fields, primary, includeFieldOptions = false } + ) { + // If another refresh or fetch request is currently running, we need to cancel + // it because the response is most likely going to be outdated and we don't + // need it anymore. + if (lastRequestSource !== null) { + lastRequestSource.cancel('Cancelled in favor of new request') + } + + lastRequestSource = axios.CancelToken.source() + + try { + // We first need to fetch the count of all rows because we need to know how + // many rows there are in total to estimate what are new visible range it + // going to be. + commit('SET_FETCHING', true) + const { + data: { count }, + } = await service(this.$client).fetchCount({ + viewId: getters.getViewId, + cancelToken: lastRequestSource.token, + }) + + // Create a new empty array containing un-fetched rows. + const rows = Array(count).fill(null) + let startIndex = 0 + let endIndex = 0 + + if (count > 0) { + // Figure out which range was previous visible and see if that still fits + // within the new set of rows. Otherwise we're going to fall + const currentVisible = getters.getVisibleRange + startIndex = currentVisible.startIndex + endIndex = currentVisible.endIndex + const difference = count - endIndex + + if (difference < 0) { + startIndex += difference + endIndex += difference + } + + // Based on the newly calculated range we can figure out which rows we want + // to fetch from the backend to populate our store with. These should be the + // rows that the user is going to look at. + const rangeToFetch = getRangeToFetch( + rows, + getters.getRequestSize, + startIndex, + endIndex + ) + + // Only fetch visible rows if there are any. + const { + data: { results }, + } = await service(this.$client).fetchRows({ + viewId: getters.getViewId, + offset: rangeToFetch.offset, + limit: rangeToFetch.limit, + includeFieldOptions, + cancelToken: lastRequestSource.token, + }) + + results.forEach((row, index) => { + rows[rangeToFetch.offset + index] = populateRow(row) + }) + } + + commit('SET_ROWS', rows) + commit('SET_VISIBLE', { startIndex, endIndex }) + } catch (error) { + if (axios.isCancel(error)) { + throw new RefreshCancelledError() + } else { + lastRequestSource = null + throw error + } + } finally { + commit('SET_FETCHING', false) + } + }, + /** + * Adds a field with a provided value to the rows in the store. This will for + * example be called when a new field has been created. + */ + addField({ commit }, { field, value = null }) { + commit('ADD_FIELD_TO_ALL_ROWS', { field, value }) + }, + /** + * Check if the provided row matches the provided view filters. + */ + rowMatchesFilters(context, { view, fields, primary, row, overrides = {} }) { + const values = JSON.parse(JSON.stringify(row)) + Object.assign(values, overrides) + + // The value is always valid if the filters are disabled. + return view.filters_disabled + ? true + : matchSearchFilters( + this.$registry, + view.filter_type, + view.filters, + primary === null ? fields : [primary, ...fields], + values + ) + }, + /** + * Returns the index that the provided row was supposed to have if it was in the + * store. Because some rows haven't been fetched from the backend, we need to + * figure out which `null` object could have been the row in the store. + */ + findIndexOfNotExistingRow({ getters }, { view, fields, primary, row }) { + const sortFunction = getRowSortFunction( + this.$registry, + view.sortings, + fields, + primary + ) + const allRows = getters.getRows + let index = allRows.findIndex((existingRow) => { + return existingRow !== null && sortFunction(row, existingRow) < 0 + }) + let isCertain = true + + if (index === -1 && allRows[allRows.length - 1] !== null) { + // If we don't know where to position the new row and the last row is null, we + // can safely assume it's the last row because when finding the index we + // only check if the new row is before an existing row. + index = allRows.length + } else if (index === -1) { + // If we don't know where to position the new row we can assume near the + // end, but we're not sure where exactly. Because of that we'll add it as + // null to the end. + index = allRows.length + isCertain = false + } else if (allRows[index - 1] === null) { + // If the row must inserted at the beginning of a known chunk of fetched + // rows, we can't know for sure it actually has to be inserted directly before. + // In that case, we will insert it as null. + isCertain = false + } + + return { index, isCertain } + }, + /** + * Returns the index of a row that's in the store. This also works if the row + * hasn't been fetched yet, it will then point to the `null` object representing + * the row. + */ + findIndexOfExistingRow( + { dispatch, getters }, + { view, fields, primary, row } + ) { + const sortFunction = getRowSortFunction( + this.$registry, + view.sortings, + fields, + primary + ) + const allRows = getters.getRows + let index = allRows.findIndex((existingRow) => { + return existingRow !== null && existingRow.id === row.id + }) + let isCertain = true + + if (index === -1) { + // If the row is not found in the index, we will have to figure out what the + // position could be. + index = allRows.findIndex((existingRow) => { + return existingRow !== null && sortFunction(row, existingRow) < 0 + }) + isCertain = false + + if (index === -1 && allRows[allRows.length - 1] === null) { + // If we don't know where to position the existing row and the last row is + // null, we can safely assume it's the last row because when finding the + // index we only check if the new row is before an existing row. + index = allRows.length + } + + if (index >= 0) { + index -= 1 + } + } + + return { index, isCertain } + }, + /** + * Creates a new row and adds it to the store if needed. + */ + async createNewRow( + { dispatch, commit, getters }, + { view, table, fields, primary, values } + ) { + // First prepare an object that we can send to the backend. + const allFields = [primary].concat(fields) + const preparedValues = {} + allFields.forEach((field) => { + const name = `field_${field.id}` + const fieldType = this.$registry.get('field', field._.type.type) + + if (fieldType.isReadOnly) { + return + } + + preparedValues[name] = Object.prototype.hasOwnProperty.call( + values, + name + ) + ? (preparedValues[name] = fieldType.prepareValueForUpdate( + field, + values[name] + )) + : fieldType.getEmptyValue(field) + }) + + const { data } = await RowService(this.$client).create( + table.id, + preparedValues + ) + return await dispatch('afterNewRowCreated', { + view, + fields, + primary, + values: data, + }) + }, + /** + * When a new row is created and it doesn't yet in exist in this store, so we must + * insert it in the right position. Based on the values of the row we can + * calculate if the row should be added (matches filters) and at which position + * (sortings). + * + * Because we only fetch the rows from the backend that are actually needed, it + * could be that we can't figure out where the row should be inserted. In that + * case, we add a `null` in the area that is unknown. The store + * already has other null values for rows that are un-fetched. So the un-fetched + * row representations that are `null` in the array will be fetched automatically + * when the user wants to see them. + */ + async afterNewRowCreated( + { dispatch, getters, commit }, + { view, fields, primary, values } + ) { + let row = clone(values) + populateRow(row) + + // Check if the row matches the filters. If not, we don't have to do anything + // because we know this row does not exist in the view. + if ( + !(await dispatch('rowMatchesFilters', { view, fields, primary, row })) + ) { + return + } + + const { index, isCertain } = await dispatch('findIndexOfNotExistingRow', { + view, + fields, + primary, + row, + }) + + // If we're not completely certain about the target index of the new row, we + // must add it as `null` to the store because then it will automatically be + // fetched when the user looks at it. + if (!isCertain) { + row = null + } + + commit('INSERT_ROW_AT_INDEX', { index, row }) + }, + /** + * When an existing row is updated, the state in the store must also be updated. + * Because we always receive the old and new state we can calculate if the row + * already existed in store. If it does exist, but the row was not fetched yet, + * so in a `null` state, we can still figure out what the index was supposed to + * be and take action on that. + * + * It works very similar to what happens when a row is created. If we can be + * sure about the new position then we can update the and keep it's data. If we + * can't be 100% sure, the row will be updated as `null`. + */ + async afterExistingRowUpdated( + { dispatch, commit }, + { view, fields, primary, row, values } + ) { + const oldRow = clone(row) + let newRow = Object.assign(clone(row), values) + populateRow(oldRow) + populateRow(newRow) + + const oldRowMatches = await dispatch('rowMatchesFilters', { + view, + fields, + primary, + row: oldRow, + }) + const newRowMatches = await dispatch('rowMatchesFilters', { + view, + fields, + primary, + row: newRow, + }) + + if (oldRowMatches && !newRowMatches) { + // If the old row did match the filters, but after the update it does not + // anymore, we can safely remove it from the store. + await dispatch('afterExistingRowDeleted', { + view, + fields, + primary, + row, + }) + } else if (!oldRowMatches && newRowMatches) { + // If the old row didn't match filters, but the updated one does, we need to + // add it to the store. + await dispatch('afterNewRowCreated', { + view, + fields, + primary, + values: newRow, + }) + } else if (oldRowMatches && newRowMatches) { + // If the old and updated row already exists in the store, we need to update is. + const { index: oldIndex, isCertain: oldIsCertain } = await dispatch( + 'findIndexOfExistingRow', + { + view, + fields, + primary, + row: oldRow, + } + ) + const findNewRow = await dispatch('findIndexOfNotExistingRow', { + view, + fields, + primary, + row: newRow, + }) + let { index: newIndex } = findNewRow + const { isCertain: newIsCertain } = findNewRow + + // When finding the new index, the old row still existed in the store. When + // the newIndex is higher than the old index, we need to compensate for this + // because when figuring out the new position, we expected the existing row + // not to be there. + if (newIndex > oldIndex) { + newIndex -= 1 + } + + if (oldIsCertain && newIsCertain) { + // If both the old and updated are certain, we can just update the values + // of the row so the original row, including the state, will persist. + commit('UPDATE_ROW_AT_INDEX', { index: oldIndex, values }) + + if (oldIndex !== newIndex) { + // If the index has changed we want to move the row. We're moving it and + // not recreating it because we want the state to persist. + commit('MOVE_ROW', { oldIndex, newIndex }) + } + } else { + // If either the old and updated row is not certain, which means it's in a + // `null` state, there is no row to persist to we can easily recreate it + // at the right position. + if (!newIsCertain) { + newRow = null + } + + commit('DELETE_ROW_AT_INDEX', { index: oldIndex }) + commit('INSERT_ROW_AT_INDEX', { index: newIndex, row: newRow }) + } + } + }, + /** + * When a new row deleted and it does exist in the store, it must be deleted + * removed from is. Based on the provided values of the row we can figure out if + * it was in the store and we can figure out what index it has. + */ + async afterExistingRowDeleted( + { dispatch, commit }, + { view, fields, primary, row } + ) { + row = clone(row) + populateRow(row) + + // Check if the row matches the filters. If not, we don't have to do anything + // because we know this row does not exist in the view. + if ( + !(await dispatch('rowMatchesFilters', { view, fields, primary, row })) + ) { + return + } + + const { index } = await dispatch('findIndexOfExistingRow', { + view, + fields, + primary, + row, + }) + commit('DELETE_ROW_AT_INDEX', { index }) + }, + } + + const getters = { + getViewId(state) { + return state.viewId + }, + getDelayedRequest(state) { + return state.delayedRequest + }, + getVisibleRange(state) { + return state.visibleRange + }, + getRequestSize(state) { + return state.requestSize + }, + getFetching(state) { + return state.fetching + }, + getRows(state) { + return state.rows + }, + } + + return { + namespaced: true, + state, + getters, + actions, + mutations, + } +} diff --git a/web-frontend/modules/database/store/view/fieldOptions.js b/web-frontend/modules/database/store/view/fieldOptions.js new file mode 100644 index 0000000000..ed2b81a477 --- /dev/null +++ b/web-frontend/modules/database/store/view/fieldOptions.js @@ -0,0 +1,161 @@ +import _ from 'lodash' +import { clone } from '@baserow/modules/core/utils/object' +import ViewService from '@baserow/modules/database/services/view' + +/** + * This store mixin can in combination with a view, if it needs to store options per + * field. I noticed that we needed exactly the same code for the grid, gallery and + * form view, so it made sense to make something reusable. + * + * @TODO add this mixin to the other view stores. Currently it's only used by the + * gallery view. + */ +export default () => { + const state = () => ({ + fieldOptions: {}, + }) + + const mutations = { + REPLACE_ALL_FIELD_OPTIONS(state, fieldOptions) { + state.fieldOptions = fieldOptions + }, + UPDATE_ALL_FIELD_OPTIONS(state, fieldOptions) { + state.fieldOptions = _.merge({}, state.fieldOptions, fieldOptions) + }, + UPDATE_FIELD_OPTIONS_OF_FIELD(state, { fieldId, values }) { + if (Object.prototype.hasOwnProperty.call(state.fieldOptions, fieldId)) { + Object.assign(state.fieldOptions[fieldId], values) + } else { + state.fieldOptions = Object.assign({}, state.fieldOptions, { + [fieldId]: values, + }) + } + }, + DELETE_FIELD_OPTIONS(state, fieldId) { + if (Object.prototype.hasOwnProperty.call(state.fieldOptions, fieldId)) { + delete state.fieldOptions[fieldId] + } + }, + } + + const actions = { + /** + * Updates the field options of a given field and also makes an API request to the + * backend with the changed values. If the request fails the action is reverted. + */ + async updateFieldOptionsOfField( + { commit, getters }, + { field, values, oldValues } + ) { + const viewId = getters.getViewId + commit('UPDATE_FIELD_OPTIONS_OF_FIELD', { + fieldId: field.id, + values, + }) + const updateValues = { field_options: {} } + updateValues.field_options[field.id] = values + + try { + await ViewService(this.$client).updateFieldOptions({ + viewId, + values: updateValues, + }) + } catch (error) { + commit('UPDATE_FIELD_OPTIONS_OF_FIELD', { + fieldId: field.id, + values: oldValues, + }) + throw error + } + }, + /** + * Updates the field options of a given field in the store. So no API request to + * the backend is made. + */ + setFieldOptionsOfField({ commit }, { field, values }) { + commit('UPDATE_FIELD_OPTIONS_OF_FIELD', { + fieldId: field.id, + values, + }) + }, + /** + * Replaces all field options with new values and also makes an API request to the + * backend with the changed values. If the request fails the action is reverted. + */ + async updateAllFieldOptions( + { dispatch, getters }, + { newFieldOptions, oldFieldOptions } + ) { + const viewId = getters.getViewId + dispatch('forceUpdateAllFieldOptions', newFieldOptions) + const updateValues = { field_options: newFieldOptions } + + try { + await ViewService(this.$client).updateFieldOptions({ + viewId, + values: updateValues, + }) + } catch (error) { + dispatch('forceUpdateAllFieldOptions', oldFieldOptions) + throw error + } + }, + /** + * Forcefully updates all field options without making a call to the backend. + */ + forceUpdateAllFieldOptions({ commit }, fieldOptions) { + commit('UPDATE_ALL_FIELD_OPTIONS', fieldOptions) + }, + /** + * Updates the order of all the available field options. The provided order parameter + * should be an array containing the field ids in the correct order. + */ + async updateFieldOptionsOrder({ commit, getters, dispatch }, { order }) { + const oldFieldOptions = clone(getters.getAllFieldOptions) + const newFieldOptions = clone(getters.getAllFieldOptions) + + // Update the order of the field options that have not been provided in the order. + // They will get a position that places them after the provided field ids. + let i = 0 + Object.keys(newFieldOptions).forEach((fieldId) => { + if (!order.includes(parseInt(fieldId))) { + newFieldOptions[fieldId].order = order.length + i + i++ + } + }) + + // Update create the field options and set the correct order value. + order.forEach((fieldId, index) => { + const id = fieldId.toString() + if (Object.prototype.hasOwnProperty.call(newFieldOptions, id)) { + newFieldOptions[fieldId.toString()].order = index + } + }) + + return await dispatch('updateAllFieldOptions', { + oldFieldOptions, + newFieldOptions, + }) + }, + /** + * Deletes the field options of the provided field id if they exist. + */ + forceDeleteFieldOptions({ commit }, fieldId) { + commit('DELETE_FIELD_OPTIONS', fieldId) + }, + } + + const getters = { + getAllFieldOptions(state) { + return state.fieldOptions + }, + } + + return { + namespaced: true, + state, + getters, + actions, + mutations, + } +} diff --git a/web-frontend/modules/database/store/view/gallery.js b/web-frontend/modules/database/store/view/gallery.js new file mode 100644 index 0000000000..f92193ec58 --- /dev/null +++ b/web-frontend/modules/database/store/view/gallery.js @@ -0,0 +1,52 @@ +import bufferedRows from '@baserow/modules/database/store/view/bufferedRows' +import fieldOptions from '@baserow/modules/database/store/view/fieldOptions' +import GalleryService from '@baserow/modules/database/services/view/gallery' + +export function populateRow(row) { + row._ = {} + return row +} + +const galleryBufferedRows = bufferedRows({ + service: GalleryService, + populateRow, +}) + +const galleryFieldOptions = fieldOptions() + +export const state = () => ({ + ...galleryBufferedRows.state(), + ...galleryFieldOptions.state(), +}) + +export const mutations = { + ...galleryBufferedRows.mutations, + ...galleryFieldOptions.mutations, +} + +export const actions = { + async fetchInitial({ dispatch, commit }, { viewId, fields, primary }) { + const data = await dispatch('fetchInitialRows', { + viewId, + fields, + primary, + initialRowArguments: { includeFieldOptions: true }, + }) + await dispatch('forceUpdateAllFieldOptions', data.field_options) + }, + ...galleryBufferedRows.actions, + ...galleryFieldOptions.actions, +} + +export const getters = { + ...galleryBufferedRows.getters, + ...galleryFieldOptions.getters, +} + +export default { + namespaced: true, + state, + getters, + actions, + mutations, +} diff --git a/web-frontend/modules/database/utils/card.js b/web-frontend/modules/database/utils/card.js new file mode 100644 index 0000000000..e2df6c973d --- /dev/null +++ b/web-frontend/modules/database/utils/card.js @@ -0,0 +1,22 @@ +export const getCardHeight = (fields, registry) => { + // margin-bottom of card.scss.card__field, that we don't have to compensate for + // if there aren't any fields in the card. + const fieldMarginBottom = fields.length === 0 ? 0 : 10 + + return ( + // Some of these values must be kep in sync with card.scss + fields.reduce((accumulator, field) => { + const fieldType = registry.get('field', field._.type.type) + return ( + accumulator + + fieldType.getCardValueHeight(field) + + 6 + // margin-bottom of card.scss.card__field-name + 14 + // line-height of card.scss.card__field-name + 10 // margin-bottom of card.scss.card__field + ) + }, 0) + + 16 + // padding-top of card.scss.card + 16 - // padding-bottom of card.scss.card + fieldMarginBottom + ) +} diff --git a/web-frontend/modules/database/viewTypes.js b/web-frontend/modules/database/viewTypes.js index 0e35b6ea87..75f6df7dcc 100644 --- a/web-frontend/modules/database/viewTypes.js +++ b/web-frontend/modules/database/viewTypes.js @@ -2,6 +2,8 @@ import { Registerable } from '@baserow/modules/core/registry' import ViewForm from '@baserow/modules/database/components/view/ViewForm' import GridView from '@baserow/modules/database/components/view/grid/GridView' import GridViewHeader from '@baserow/modules/database/components/view/grid/GridViewHeader' +import GalleryView from '@baserow/modules/database/components/view/gallery/GalleryView' +import GalleryViewHeader from '@baserow/modules/database/components/view/gallery/GalleryViewHeader' import FormView from '@baserow/modules/database/components/view/form/FormView' import FormViewHeader from '@baserow/modules/database/components/view/form/FormViewHeader' @@ -265,7 +267,7 @@ export class GridViewType extends ViewType { } getIconClass() { - return 'th' + return 'bars' } getName() { @@ -471,6 +473,187 @@ export class GridViewType extends ViewType { } } +/** + * This class can be used if the view store uses the `bufferedRows` mixin. It will + * enable real time collaboration and will make sure that the rows are in the store + * are updated properly. + */ +class BaseBufferedRowView extends ViewType { + getDefaultFieldOptionValues() { + return {} + } + + async fetch({ store }, view, fields, primary, storePrefix = '') { + await store.dispatch(`${storePrefix}view/${this.getType()}/fetchInitial`, { + viewId: view.id, + fields, + primary, + }) + } + + async refresh( + { store }, + view, + fields, + primary, + storePrefix = '', + includeFieldOptions = false + ) { + await store.dispatch(storePrefix + 'view/' + this.getType() + '/refresh', { + fields, + primary, + includeFieldOptions, + }) + } + + async fieldRestored( + { dispatch }, + table, + selectedView, + field, + fieldType, + storePrefix = '' + ) { + // There might be new filters and sorts associated with the restored field, + // ensure we fetch them. For now we have to fetch all filters/sorts however in the + // future we should instead just fetch them for this particular restored field. + await dispatch('view/refreshView', { view: selectedView }, { root: true }) + } + + async fieldCreated({ dispatch }, table, field, fieldType, storePrefix = '') { + const value = fieldType.getEmptyValue(field) + await dispatch( + storePrefix + 'view/' + this.getType() + '/addField', + { field, value }, + { root: true } + ) + await dispatch( + storePrefix + 'view/' + this.getType() + '/setFieldOptionsOfField', + { + field, + values: this.getDefaultFieldOptionValues(), + }, + { root: true } + ) + } + + async fieldDeleted({ dispatch }, field, fieldType, storePrefix = '') { + await dispatch( + storePrefix + 'view/' + this.getType() + '/forceDeleteFieldOptions', + field.id, + { + root: true, + } + ) + } + + async fieldOptionsUpdated({ store }, view, fieldOptions, storePrefix) { + await store.dispatch( + storePrefix + 'view/' + this.getType() + '/forceUpdateAllFieldOptions', + fieldOptions, + { + root: true, + } + ) + } + + async rowCreated( + { store }, + tableId, + fields, + primary, + values, + metadata, + storePrefix = '' + ) { + if (this.isCurrentView(store, tableId)) { + await store.dispatch( + storePrefix + 'view/' + this.getType() + '/afterNewRowCreated', + { + view: store.getters['view/getSelected'], + fields, + primary, + values, + } + ) + } + } + + async rowUpdated( + { store }, + tableId, + fields, + primary, + row, + values, + metadata, + storePrefix = '' + ) { + if (this.isCurrentView(store, tableId)) { + await store.dispatch( + storePrefix + 'view/' + this.getType() + '/afterExistingRowUpdated', + { + view: store.getters['view/getSelected'], + fields, + primary, + row, + values, + } + ) + } + } + + async rowDeleted({ store }, tableId, fields, primary, row, storePrefix = '') { + if (this.isCurrentView(store, tableId)) { + await store.dispatch( + storePrefix + 'view/' + this.getType() + '/afterExistingRowDeleted', + { + view: store.getters['view/getSelected'], + fields, + primary, + row, + } + ) + } + } +} + +export class GalleryViewType extends BaseBufferedRowView { + static getType() { + return 'gallery' + } + + getIconClass() { + return 'th-large' + } + + getColorClass() { + return 'color-error' + } + + getName() { + const { i18n } = this.app + return i18n.t('viewType.gallery') + } + + getHeaderComponent() { + return GalleryViewHeader + } + + getComponent() { + return GalleryView + } + + getDefaultFieldOptionValues() { + // The default values should be the same as in the `GalleryViewFieldOptions` + // model in the backend to stay consistent. + return { + hidden: true, + order: maxPossibleOrderValue, + } + } +} + export class FormViewType extends ViewType { static getType() { return 'form' diff --git a/web-frontend/test/unit/database/store/view/bufferedRows.spec.js b/web-frontend/test/unit/database/store/view/bufferedRows.spec.js new file mode 100644 index 0000000000..381f77ec76 --- /dev/null +++ b/web-frontend/test/unit/database/store/view/bufferedRows.spec.js @@ -0,0 +1,1997 @@ +import bufferedRows from '@baserow/modules/database/store/view/bufferedRows' +import { TestApp } from '@baserow/test/helpers/testApp' +import { ContainsViewFilterType } from '@baserow/modules/database/viewFilters' + +describe('Buffered rows view store helper', () => { + let testApp = null + let store = null + + beforeEach(() => { + testApp = new TestApp() + store = testApp.store + }) + + afterEach(() => { + testApp.afterEach() + }) + + test('fetchMissingRowsInNewRange', async () => { + // A test client that has 100 rows from id 1 through 100. It returns the + // requested rows they are available. + const service = () => { + return { + fetchRows({ viewId, limit = 100, offset = null }) { + const all = Array(14) + .fill(null) + .map((row, index) => { + return { id: index + 1 } + }) + + const data = { + results: all.slice(offset, offset + limit), + } + return { data } + }, + } + } + const populateRow = (row) => { + row._ = {} + return row + } + const testStore = bufferedRows({ service, populateRow }) + + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 0, + endIndex: 0, + }, + requestSize: 4, + viewId: 1, + rows: [ + { id: 1 }, + { id: 2 }, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + await store.dispatch('test/fetchMissingRowsInNewRange', { + startIndex: 0, + endIndex: 1, + }) + const rowsInStore = store.getters['test/getRows'] + expect(rowsInStore[0].id).toBe(1) + expect(rowsInStore[1].id).toBe(2) + expect(rowsInStore[2]).toBe(null) + expect(rowsInStore[3]).toBe(null) + expect(rowsInStore[4]).toBe(null) + expect(rowsInStore[5]).toBe(null) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8]).toBe(null) + expect(rowsInStore[9]).toBe(null) + expect(rowsInStore[10]).toBe(null) + expect(rowsInStore[11]).toBe(null) + expect(rowsInStore[12]).toBe(null) + expect(rowsInStore[13]).toBe(null) + + await store.dispatch('test/fetchMissingRowsInNewRange', { + startIndex: 1, + endIndex: 2, + }) + expect(rowsInStore[0].id).toBe(1) + expect(rowsInStore[1].id).toBe(2) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(4) + expect(rowsInStore[4].id).toBe(5) + expect(rowsInStore[5].id).toBe(6) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8]).toBe(null) + expect(rowsInStore[9]).toBe(null) + expect(rowsInStore[10]).toBe(null) + expect(rowsInStore[11]).toBe(null) + expect(rowsInStore[12]).toBe(null) + expect(rowsInStore[13]).toBe(null) + + await store.dispatch('test/fetchMissingRowsInNewRange', { + startIndex: 10, + endIndex: 11, + }) + expect(rowsInStore[0].id).toBe(1) + expect(rowsInStore[1].id).toBe(2) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(4) + expect(rowsInStore[4].id).toBe(5) + expect(rowsInStore[5].id).toBe(6) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8]).toBe(null) + expect(rowsInStore[9].id).toBe(10) + expect(rowsInStore[10].id).toBe(11) + expect(rowsInStore[11].id).toBe(12) + expect(rowsInStore[12].id).toBe(13) + expect(rowsInStore[13]).toBe(null) + + await store.dispatch('test/fetchMissingRowsInNewRange', { + startIndex: 8, + endIndex: 11, + }) + expect(rowsInStore[0].id).toBe(1) + expect(rowsInStore[1].id).toBe(2) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(4) + expect(rowsInStore[4].id).toBe(5) + expect(rowsInStore[5].id).toBe(6) + expect(rowsInStore[6].id).toBe(7) + expect(rowsInStore[7].id).toBe(8) + expect(rowsInStore[8].id).toBe(9) + expect(rowsInStore[9].id).toBe(10) + expect(rowsInStore[10].id).toBe(11) + expect(rowsInStore[11].id).toBe(12) + expect(rowsInStore[12].id).toBe(13) + expect(rowsInStore[13]).toBe(null) + + store.state.test.rows[12]._ = { tmp: true } + await store.dispatch('test/fetchMissingRowsInNewRange', { + startIndex: 12, + endIndex: 14, + }) + expect(rowsInStore[0].id).toBe(1) + expect(rowsInStore[1].id).toBe(2) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(4) + expect(rowsInStore[4].id).toBe(5) + expect(rowsInStore[5].id).toBe(6) + expect(rowsInStore[6].id).toBe(7) + expect(rowsInStore[7].id).toBe(8) + expect(rowsInStore[8].id).toBe(9) + expect(rowsInStore[9].id).toBe(10) + expect(rowsInStore[10].id).toBe(11) + expect(rowsInStore[11].id).toBe(12) + expect(rowsInStore[12].id).toBe(13) + // Check if the state has not been overwritten. + expect(rowsInStore[12]._.tmp).toBe(true) + expect(rowsInStore[13].id).toBe(14) + }) + + test('refresh', async () => { + const service = () => { + return { + fetchRows({ viewId, limit = 100, offset = null }) { + const all = Array(30) + .fill(null) + .map((row, index) => { + return { id: index + 1 } + }) + + const data = { + results: all.slice(offset, offset + limit), + } + return { data } + }, + fetchCount() { + const data = { count: 30 } + return { data } + }, + } + } + const populateRow = (row) => { + row._ = {} + return row + } + const testStore = bufferedRows({ service, populateRow }) + + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 10, + endIndex: 13, + }, + requestSize: 8, + viewId: 1, + rows: [ + { id: 1 }, + { id: 2 }, + { id: 3 }, + { id: 4 }, + { id: 5 }, + { id: 6 }, + { id: 7 }, + { id: 8 }, + { id: 9 }, + { id: 10 }, + { id: 11 }, + { id: 12 }, + { id: 13 }, + { id: 14 }, + { id: 15 }, + { id: 16 }, + { id: 17 }, + { id: 18 }, + { id: 19 }, + { id: 20 }, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + await store.dispatch('test/refresh', {}) + const rowsInStore = store.getters['test/getRows'] + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1]).toBe(null) + expect(rowsInStore[2]).toBe(null) + expect(rowsInStore[3]).toBe(null) + expect(rowsInStore[4]).toBe(null) + expect(rowsInStore[5]).toBe(null) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8].id).toBe(9) + expect(rowsInStore[9].id).toBe(10) + expect(rowsInStore[10].id).toBe(11) + expect(rowsInStore[11].id).toBe(12) + expect(rowsInStore[12].id).toBe(13) + expect(rowsInStore[13].id).toBe(14) + expect(rowsInStore[14].id).toBe(15) + expect(rowsInStore[15].id).toBe(16) + expect(rowsInStore[16]).toBe(null) + expect(rowsInStore[17]).toBe(null) + expect(rowsInStore[18]).toBe(null) + expect(rowsInStore[19]).toBe(null) + }) + + test('refresh with less', async () => { + const service = () => { + return { + fetchRows({ viewId, limit = 100, offset = null }) { + const all = Array(10) + .fill(null) + .map((row, index) => { + return { id: index + 1 } + }) + + const data = { + results: all.slice(offset, offset + limit), + } + return { data } + }, + fetchCount() { + const data = { count: 10 } + return { data } + }, + } + } + const populateRow = (row) => { + row._ = {} + return row + } + const testStore = bufferedRows({ service, populateRow }) + + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 9, + endIndex: 12, + }, + requestSize: 8, + viewId: 1, + rows: [ + { id: 1 }, + { id: 2 }, + { id: 3 }, + { id: 4 }, + { id: 5 }, + { id: 6 }, + { id: 7 }, + { id: 8 }, + { id: 9 }, + { id: 10 }, + { id: 11 }, + { id: 12 }, + { id: 13 }, + { id: 14 }, + { id: 15 }, + { id: 16 }, + { id: 17 }, + { id: 18 }, + { id: 19 }, + { id: 20 }, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + await store.dispatch('test/refresh', {}) + const rowsInStore = store.getters['test/getRows'] + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1]).toBe(null) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(4) + expect(rowsInStore[4].id).toBe(5) + expect(rowsInStore[5].id).toBe(6) + expect(rowsInStore[6].id).toBe(7) + expect(rowsInStore[7].id).toBe(8) + expect(rowsInStore[8].id).toBe(9) + expect(rowsInStore[9].id).toBe(10) + }) + + test('refresh to empty', async () => { + const service = () => { + return { + fetchRows({ viewId, limit = 100, offset = null }) { + return { data: { results: [] } } + }, + fetchCount() { + return { data: { count: 0 } } + }, + } + } + const populateRow = (row) => { + row._ = {} + return row + } + const testStore = bufferedRows({ service, populateRow }) + + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 0, + endIndex: 1, + }, + requestSize: 2, + viewId: 1, + rows: [{ id: 1 }, { id: 2 }, null, null], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + await store.dispatch('test/refresh', {}) + expect(store.getters['test/getRows'].length).toBe(0) + expect(store.getters['test/getVisibleRange']).toStrictEqual({ + startIndex: 0, + endIndex: 0, + }) + }) + + test('find index of not existing row', async () => { + const view = { + id: 1, + filters_disabled: false, + filter_type: 'AND', + filters: [], + sortings: [], + } + const fields = [] + const primary = { + id: 1, + name: 'Test 1', + type: 'text', + primary: true, + } + const populateRow = (row) => { + row._ = {} + return row + } + + const testStore = bufferedRows({ service: null, populateRow }) + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 0, + endIndex: 0, + }, + requestSize: 4, + viewId: 1, + rows: [ + { id: 1, order: '1.00000000000000000000', field_1: 'Row 1' }, + { id: 2, order: '2.00000000000000000000', field_1: 'Row 2' }, + { id: 3, order: '3.00000000000000000000', field_1: 'Row 3' }, + { id: 4, order: '4.00000000000000000000', field_1: 'Row 4' }, + null, + null, + null, + null, + { id: 10, order: '10.00000000000000000000', field_1: 'Row 10' }, + { id: 11, order: '11.00000000000000000000', field_1: 'Row 11' }, + { id: 12, order: '12.00000000000000000000', field_1: 'Row 12' }, + { id: 14, order: '14.00000000000000000000', field_1: 'Row 14' }, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + let index = await store.dispatch('test/findIndexOfNotExistingRow', { + view, + fields, + primary, + row: { + id: 0, + order: '0.00000000000000000000', + field_1: 'Row 0', + }, + }) + expect(index).toStrictEqual({ index: 0, isCertain: true }) + + index = await store.dispatch('test/findIndexOfNotExistingRow', { + view, + fields, + primary, + row: { + id: 5, + order: '3.50000000000000000000', + field_1: 'Row 5', + }, + }) + expect(index).toStrictEqual({ index: 3, isCertain: true }) + + index = await store.dispatch('test/findIndexOfNotExistingRow', { + view, + fields, + primary, + row: { + id: 5, + order: '5.00000000000000000000', + field_1: 'Row 5', + }, + }) + expect(index).toStrictEqual({ index: 8, isCertain: false }) + + index = await store.dispatch('test/findIndexOfNotExistingRow', { + view, + fields, + primary, + row: { + id: 13, + order: '13.50000000000000000000', + field_1: 'Row 13', + }, + }) + expect(index).toStrictEqual({ index: 11, isCertain: true }) + + index = await store.dispatch('test/findIndexOfNotExistingRow', { + view, + fields, + primary, + row: { + id: 100, + order: '100.00000000000000000000', + field_1: 'Row 100', + }, + }) + expect(index).toStrictEqual({ index: 12, isCertain: true }) + }) + + test('find index of not existing row with null at beginning and end', async () => { + const view = { + id: 1, + filters_disabled: false, + filter_type: 'AND', + filters: [], + sortings: [], + } + const fields = [] + const primary = { + id: 1, + name: 'Test 1', + type: 'text', + primary: true, + } + const populateRow = (row) => { + row._ = {} + return row + } + + const testStore = bufferedRows({ service: null, populateRow }) + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 0, + endIndex: 0, + }, + requestSize: 4, + viewId: 1, + rows: [ + null, + null, + { id: 3, order: '3.00000000000000000000', field_1: 'Row 3' }, + { id: 5, order: '5.00000000000000000000', field_1: 'Row 5' }, + { id: 6, order: '6.00000000000000000000', field_1: 'Row 6' }, + { id: 7, order: '7.00000000000000000000', field_1: 'Row 7' }, + null, + null, + { id: 10, order: '10.00000000000000000000', field_1: 'Row 10' }, + { id: 11, order: '11.00000000000000000000', field_1: 'Row 11' }, + { id: 12, order: '12.00000000000000000000', field_1: 'Row 12' }, + { id: 14, order: '14.00000000000000000000', field_1: 'Row 14' }, + null, + null, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + let index = await store.dispatch('test/findIndexOfNotExistingRow', { + view, + fields, + primary, + row: { + id: 4, + order: '4.00000000000000000000', + field_1: 'Row 4', + }, + }) + expect(index).toStrictEqual({ index: 3, isCertain: true }) + + index = await store.dispatch('test/findIndexOfNotExistingRow', { + view, + fields, + primary, + row: { + id: 2, + order: '2.00000000000000000000', + field_1: 'Row 2', + }, + }) + expect(index).toStrictEqual({ index: 2, isCertain: false }) + + index = await store.dispatch('test/findIndexOfNotExistingRow', { + view, + fields, + primary, + row: { + id: 13, + order: '13.00000000000000000000', + field_1: 'Row 13', + }, + }) + expect(index).toStrictEqual({ index: 11, isCertain: true }) + + index = await store.dispatch('test/findIndexOfNotExistingRow', { + view, + fields, + primary, + row: { + id: 100, + order: '100.00000000000000000000', + field_1: 'Row 100', + }, + }) + expect(index).toStrictEqual({ index: 14, isCertain: false }) + }) + + test('find index of existing row', async () => { + const view = { + id: 1, + filters_disabled: false, + filter_type: 'AND', + filters: [], + sortings: [], + } + const fields = [] + const primary = { + id: 1, + name: 'Test 1', + type: 'text', + primary: true, + } + const populateRow = (row) => { + row._ = {} + return row + } + + const testStore = bufferedRows({ service: null, populateRow }) + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 0, + endIndex: 0, + }, + requestSize: 4, + viewId: 1, + rows: [ + { id: 1, order: '1.00000000000000000000', field_1: 'Row 1' }, + { id: 2, order: '2.00000000000000000000', field_1: 'Row 2' }, + { id: 3, order: '3.00000000000000000000', field_1: 'Row 3' }, + { id: 4, order: '4.00000000000000000000', field_1: 'Row 4' }, + null, + null, + null, + null, + { id: 10, order: '10.00000000000000000000', field_1: 'Row 10' }, + { id: 11, order: '11.00000000000000000000', field_1: 'Row 11' }, + { id: 12, order: '12.00000000000000000000', field_1: 'Row 12' }, + { id: 14, order: '14.00000000000000000000', field_1: 'Row 14' }, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + let index = await store.dispatch('test/findIndexOfExistingRow', { + view, + fields, + primary, + row: { + id: 1, + order: '1.00000000000000000000', + field_1: 'Row 1', + }, + }) + expect(index).toStrictEqual({ index: 0, isCertain: true }) + + index = await store.dispatch('test/findIndexOfExistingRow', { + view, + fields, + primary, + row: { + id: 3, + order: '3.00000000000000000000', + field_1: 'Row 3', + }, + }) + expect(index).toStrictEqual({ index: 2, isCertain: true }) + + index = await store.dispatch('test/findIndexOfExistingRow', { + view, + fields, + primary, + row: { + id: 4, + order: '4.00000000000000000000', + field_1: 'Row 4', + }, + }) + expect(index).toStrictEqual({ index: 3, isCertain: true }) + + index = await store.dispatch('test/findIndexOfExistingRow', { + view, + fields, + primary, + row: { + id: 5, + order: '5.00000000000000000000', + field_1: 'Row 5', + }, + }) + expect(index).toStrictEqual({ index: 7, isCertain: false }) + + index = await store.dispatch('test/findIndexOfExistingRow', { + view, + fields, + primary, + row: { + id: 10, + order: '10.00000000000000000000', + field_1: 'Row 10', + }, + }) + expect(index).toStrictEqual({ index: 8, isCertain: true }) + + index = await store.dispatch('test/findIndexOfExistingRow', { + view, + fields, + primary, + row: { + id: 14, + order: '14.00000000000000000000', + field_1: 'Row 14', + }, + }) + expect(index).toStrictEqual({ index: 11, isCertain: true }) + + index = await store.dispatch('test/findIndexOfExistingRow', { + view, + fields, + primary, + row: { + id: 15, + order: '15.00000000000000000000', + field_1: 'Row 15', + }, + }) + // This one is for sure not found. + expect(index).toStrictEqual({ index: -1, isCertain: false }) + }) + + test('find index of existing row with null at the start and end', async () => { + const view = { + id: 1, + filters_disabled: false, + filter_type: 'AND', + filters: [], + sortings: [], + } + const fields = [] + const primary = { + id: 1, + name: 'Test 1', + type: 'text', + primary: true, + } + const populateRow = (row) => { + row._ = {} + return row + } + + const testStore = bufferedRows({ service: null, populateRow }) + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 0, + endIndex: 0, + }, + requestSize: 4, + viewId: 1, + rows: [ + null, + null, + { id: 1, order: '1.00000000000000000000', field_1: 'Row 1' }, + { id: 2, order: '2.00000000000000000000', field_1: 'Row 2' }, + { id: 3, order: '3.00000000000000000000', field_1: 'Row 3' }, + { id: 4, order: '4.00000000000000000000', field_1: 'Row 4' }, + null, + null, + { id: 10, order: '10.00000000000000000000', field_1: 'Row 10' }, + { id: 11, order: '11.00000000000000000000', field_1: 'Row 11' }, + { id: 12, order: '12.00000000000000000000', field_1: 'Row 12' }, + { id: 14, order: '14.00000000000000000000', field_1: 'Row 14' }, + null, + null, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + let index = await store.dispatch('test/findIndexOfExistingRow', { + view, + fields, + primary, + row: { + id: 1, + order: '1.00000000000000000000', + field_1: 'Row 1', + }, + }) + expect(index).toStrictEqual({ index: 2, isCertain: true }) + + index = await store.dispatch('test/findIndexOfExistingRow', { + view, + fields, + primary, + row: { + id: 0, + order: '0.00000000000000000000', + field_1: 'Row 0', + }, + }) + expect(index).toStrictEqual({ index: 1, isCertain: false }) + + index = await store.dispatch('test/findIndexOfExistingRow', { + view, + fields, + primary, + row: { + id: 4, + order: '4.00000000000000000000', + field_1: 'Row 4', + }, + }) + expect(index).toStrictEqual({ index: 5, isCertain: true }) + + index = await store.dispatch('test/findIndexOfExistingRow', { + view, + fields, + primary, + row: { + id: 6, + order: '6.00000000000000000000', + field_1: 'Row 6', + }, + }) + expect(index).toStrictEqual({ index: 7, isCertain: false }) + + index = await store.dispatch('test/findIndexOfExistingRow', { + view, + fields, + primary, + row: { + id: 12, + order: '12.00000000000000000000', + field_1: 'Row 12', + }, + }) + expect(index).toStrictEqual({ index: 10, isCertain: true }) + + index = await store.dispatch('test/findIndexOfExistingRow', { + view, + fields, + primary, + row: { + id: 15, + order: '15.00000000000000000000', + field_1: 'Row 15', + }, + }) + expect(index).toStrictEqual({ index: 13, isCertain: false }) + }) + + test('test row matches filters', async () => { + const view = { + id: 1, + filters_disabled: false, + filter_type: 'AND', + filters: [ + { + id: 1, + view: 1, + field: 1, + type: ContainsViewFilterType.getType(), + value: 'value', + }, + ], + sortings: [], + } + const fields = [] + const primary = { + id: 1, + name: 'Test 1', + type: 'text', + primary: true, + } + + const testStore = bufferedRows({ service: null, populateRow: null }) + store.registerModule('test', testStore) + + expect( + await store.dispatch('test/rowMatchesFilters', { + view, + fields, + primary, + row: { id: 12, order: '12.00000000000000000000', field_1: 'Value 12' }, + }) + ).toBe(true) + expect( + await store.dispatch('test/rowMatchesFilters', { + view, + fields, + primary, + row: { + id: 12, + order: '12.00000000000000000000', + field_1: 'Not matching 12', + }, + }) + ).toBe(false) + expect( + await store.dispatch('test/rowMatchesFilters', { + view, + fields, + primary, + row: { + id: 12, + order: '12.00000000000000000000', + field_1: 'Not matching 12', + }, + overrides: { field_1: 'Value' }, + }) + ).toBe(true) + view.filters_disabled = true + expect( + await store.dispatch('test/rowMatchesFilters', { + view, + fields, + primary, + row: { + id: 12, + order: '12.00000000000000000000', + field_1: 'Not matching 12', + }, + }) + ).toBe(true) + }) + + test('test created new row', async () => { + const view = { + id: 1, + filters_disabled: false, + filter_type: 'AND', + filters: [], + sortings: [], + } + const fields = [] + const primary = { + id: 1, + name: 'Test 1', + type: 'text', + primary: true, + } + const populateRow = (row) => { + row._ = {} + return row + } + + const testStore = bufferedRows({ service: null, populateRow }) + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 0, + endIndex: 0, + }, + requestSize: 4, + viewId: 1, + rows: [ + null, + { id: 3, order: '3.00000000000000000000', field_1: 'Row 3' }, + { id: 5, order: '5.00000000000000000000', field_1: 'Row 5' }, + { id: 6, order: '6.00000000000000000000', field_1: 'Row 6' }, + { id: 7, order: '7.00000000000000000000', field_1: 'Row 7' }, + null, + { id: 10, order: '10.00000000000000000000', field_1: 'Row 10' }, + { id: 11, order: '11.00000000000000000000', field_1: 'Row 11' }, + { id: 12, order: '12.00000000000000000000', field_1: 'Row 12' }, + { id: 14, order: '14.00000000000000000000', field_1: 'Row 14' }, + null, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + await store.dispatch('test/afterNewRowCreated', { + view, + fields, + primary, + values: { + id: 2, + order: '2.00000000000000000000', + field_1: 'Row 2', + }, + }) + let rowsInStore = store.getters['test/getRows'] + expect(rowsInStore[0]).toBe(null) + // This is the newly created row. We couldn't be 100% sure this was the right + // position, so it's added as null. + expect(rowsInStore[1]).toBe(null) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(5) + expect(rowsInStore[4].id).toBe(6) + expect(rowsInStore[5].id).toBe(7) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7].id).toBe(10) + expect(rowsInStore[8].id).toBe(11) + expect(rowsInStore[9].id).toBe(12) + expect(rowsInStore[10].id).toBe(14) + expect(rowsInStore[11]).toBe(null) + + await store.dispatch('test/afterNewRowCreated', { + view, + fields, + primary, + values: { + id: 4, + order: '4.00000000000000000000', + field_1: 'Row 4', + }, + }) + rowsInStore = store.getters['test/getRows'] + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1]).toBe(null) + expect(rowsInStore[2].id).toBe(3) + // This is the newly created row. Because there was one before and after, we + // were 100% sure the row was supposed to be at this position. + expect(rowsInStore[3].id).toBe(4) + expect(rowsInStore[4].id).toBe(5) + expect(rowsInStore[5].id).toBe(6) + expect(rowsInStore[6].id).toBe(7) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8].id).toBe(10) + expect(rowsInStore[9].id).toBe(11) + expect(rowsInStore[10].id).toBe(12) + expect(rowsInStore[11].id).toBe(14) + expect(rowsInStore[12]).toBe(null) + + await store.dispatch('test/afterNewRowCreated', { + view, + fields, + primary, + values: { + id: 13, + order: '13.00000000000000000000', + field_1: 'Row 13', + }, + }) + rowsInStore = store.getters['test/getRows'] + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1]).toBe(null) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(4) + expect(rowsInStore[4].id).toBe(5) + expect(rowsInStore[5].id).toBe(6) + expect(rowsInStore[6].id).toBe(7) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8].id).toBe(10) + expect(rowsInStore[9].id).toBe(11) + expect(rowsInStore[10].id).toBe(12) + // We again know for sure the row was supposed to be at this position. + expect(rowsInStore[11].id).toBe(13) + expect(rowsInStore[12].id).toBe(14) + expect(rowsInStore[13]).toBe(null) + + await store.dispatch('test/afterNewRowCreated', { + view, + fields, + primary, + values: { + id: 16, + order: '16.00000000000000000000', + field_1: 'Row 16', + }, + }) + rowsInStore = store.getters['test/getRows'] + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1]).toBe(null) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(4) + expect(rowsInStore[4].id).toBe(5) + expect(rowsInStore[5].id).toBe(6) + expect(rowsInStore[6].id).toBe(7) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8].id).toBe(10) + expect(rowsInStore[9].id).toBe(11) + expect(rowsInStore[10].id).toBe(12) + expect(rowsInStore[11].id).toBe(13) + expect(rowsInStore[12].id).toBe(14) + expect(rowsInStore[13]).toBe(null) + // We didn't know for sure that this was the last row, so it had to be added as + // null. + expect(rowsInStore[14]).toBe(null) + + store.getters['test/getRows'][14] = { + id: 16, + order: '16.00000000000000000000', + field_1: 'Row 16', + } + await store.dispatch('test/afterNewRowCreated', { + view, + fields, + primary, + values: { + id: 17, + order: '17.00000000000000000000', + field_1: 'Row 17', + }, + }) + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1]).toBe(null) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(4) + expect(rowsInStore[4].id).toBe(5) + expect(rowsInStore[5].id).toBe(6) + expect(rowsInStore[6].id).toBe(7) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8].id).toBe(10) + expect(rowsInStore[9].id).toBe(11) + expect(rowsInStore[10].id).toBe(12) + expect(rowsInStore[11].id).toBe(13) + expect(rowsInStore[12].id).toBe(14) + expect(rowsInStore[13]).toBe(null) + expect(rowsInStore[14].id).toBe(16) + // Because we've made id 16 known and it was the last item, we do know for sure + // where 17 belonged. + expect(rowsInStore[15].id).toBe(17) + + store.getters['test/getRows'][0] = { + id: 1, + order: '1.00000000000000000000', + field_1: 'Row 1', + } + await store.dispatch('test/afterNewRowCreated', { + view, + fields, + primary, + values: { + id: 0, + order: '0.00000000000000000000', + field_1: 'Row 0', + }, + }) + // Because we've made first row known, we know for sure if one needs to be + // placed first. + expect(rowsInStore[0].id).toBe(0) + expect(rowsInStore[1].id).toBe(1) + expect(rowsInStore[2]).toBe(null) + expect(rowsInStore[3].id).toBe(3) + expect(rowsInStore[4].id).toBe(4) + expect(rowsInStore[5].id).toBe(5) + expect(rowsInStore[6].id).toBe(6) + expect(rowsInStore[7].id).toBe(7) + expect(rowsInStore[8]).toBe(null) + expect(rowsInStore[9].id).toBe(10) + expect(rowsInStore[10].id).toBe(11) + expect(rowsInStore[11].id).toBe(12) + expect(rowsInStore[12].id).toBe(13) + expect(rowsInStore[13].id).toBe(14) + expect(rowsInStore[14]).toBe(null) + expect(rowsInStore[15].id).toBe(16) + expect(rowsInStore[16].id).toBe(17) + }) + + test('test created new row ignored if filtered', async () => { + const view = { + id: 1, + filters_disabled: false, + filter_type: 'AND', + filters: [ + { + id: 1, + view: 1, + field: 1, + type: ContainsViewFilterType.getType(), + value: 'value', + }, + ], + sortings: [], + } + const fields = [] + const primary = { + id: 1, + name: 'Test 1', + type: 'text', + primary: true, + } + const populateRow = (row) => { + row._ = {} + return row + } + + const testStore = bufferedRows({ service: null, populateRow }) + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 0, + endIndex: 0, + }, + requestSize: 4, + viewId: 1, + rows: [ + null, + { id: 3, order: '3.00000000000000000000', field_1: 'Row 3' }, + { id: 5, order: '5.00000000000000000000', field_1: 'Row 5' }, + { id: 6, order: '6.00000000000000000000', field_1: 'Row 6' }, + { id: 7, order: '7.00000000000000000000', field_1: 'Row 7' }, + null, + { id: 10, order: '10.00000000000000000000', field_1: 'Row 10' }, + { id: 11, order: '11.00000000000000000000', field_1: 'Row 11' }, + { id: 12, order: '12.00000000000000000000', field_1: 'Row 12' }, + { id: 14, order: '14.00000000000000000000', field_1: 'Row 14' }, + null, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + await store.dispatch('test/afterNewRowCreated', { + view, + fields, + primary, + values: { + id: 4, + order: '4.00000000000000000000', + field_1: 'Row 2', + }, + }) + const rowsInStore = store.getters['test/getRows'] + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1].id).toBe(3) + expect(rowsInStore[2].id).toBe(5) + expect(rowsInStore[3].id).toBe(6) + expect(rowsInStore[4].id).toBe(7) + expect(rowsInStore[5]).toBe(null) + expect(rowsInStore[6].id).toBe(10) + expect(rowsInStore[7].id).toBe(11) + expect(rowsInStore[8].id).toBe(12) + expect(rowsInStore[9].id).toBe(14) + expect(rowsInStore[10]).toBe(null) + }) + + test('test updated existing row without filters', async () => { + const view = { + id: 1, + filters_disabled: false, + filter_type: 'AND', + filters: [], + sortings: [], + } + const fields = [] + const primary = { + id: 1, + name: 'Test 1', + type: 'text', + primary: true, + } + const populateRow = (row) => { + row._ = {} + return row + } + + const testStore = bufferedRows({ service: null, populateRow }) + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 0, + endIndex: 0, + }, + requestSize: 4, + viewId: 1, + rows: [ + null, + { id: 3, order: '3.00000000000000000000', field_1: 'Row 3' }, + { + id: 5, + order: '5.00000000000000000000', + field_1: 'Row 5', + _: { tmp: true }, + }, + { id: 6, order: '6.00000000000000000000', field_1: 'Row 6' }, + { id: 7, order: '7.00000000000000000000', field_1: 'Row 7' }, + null, + null, + null, + { id: 11, order: '11.00000000000000000000', field_1: 'Row 11' }, + { id: 12, order: '12.00000000000000000000', field_1: 'Row 12' }, + { id: 14, order: '14.00000000000000000000', field_1: 'Row 14' }, + null, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 5, + order: '5.00000000000000000000', + field_1: 'Row 5', + }, + values: { + field_1: 'Row 5 updated', + }, + }) + const rowsInStore = store.getters['test/getRows'] + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1].id).toBe(3) + expect(rowsInStore[2].id).toBe(5) + expect(rowsInStore[2]._.tmp).toBe(true) + expect(rowsInStore[2].field_1).toBe('Row 5 updated') + expect(rowsInStore[3].id).toBe(6) + expect(rowsInStore[4].id).toBe(7) + expect(rowsInStore[5]).toBe(null) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8].id).toBe(11) + expect(rowsInStore[9].id).toBe(12) + expect(rowsInStore[10].id).toBe(14) + expect(rowsInStore[11]).toBe(null) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 5, + order: '5.00000000000000000000', + field_1: 'Row 5 updated', + }, + values: { + order: '6.50000000000000000000', + }, + }) + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1].id).toBe(3) + expect(rowsInStore[2].id).toBe(6) + expect(rowsInStore[3].id).toBe(5) + expect(rowsInStore[3]._.tmp).toBe(true) + expect(rowsInStore[4].id).toBe(7) + expect(rowsInStore[5]).toBe(null) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8].id).toBe(11) + expect(rowsInStore[9].id).toBe(12) + expect(rowsInStore[10].id).toBe(14) + expect(rowsInStore[11]).toBe(null) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 5, + order: '6.50000000000000000000', + field_1: 'Row 5 updated', + }, + values: { + order: '7.50000000000000000000', + }, + }) + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1].id).toBe(3) + expect(rowsInStore[2].id).toBe(6) + expect(rowsInStore[3].id).toBe(7) + expect(rowsInStore[4]).toBe(null) + expect(rowsInStore[5]).toBe(null) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8].id).toBe(11) + expect(rowsInStore[9].id).toBe(12) + expect(rowsInStore[10].id).toBe(14) + expect(rowsInStore[11]).toBe(null) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 5, + order: '7.50000000000000000000', + field_1: 'Row 5 updated', + }, + values: { + order: '14.50000000000000000000', + }, + }) + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1].id).toBe(3) + expect(rowsInStore[2].id).toBe(6) + expect(rowsInStore[3].id).toBe(7) + expect(rowsInStore[4]).toBe(null) + expect(rowsInStore[5]).toBe(null) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7].id).toBe(11) + expect(rowsInStore[8].id).toBe(12) + expect(rowsInStore[9].id).toBe(14) + expect(rowsInStore[10]).toBe(null) + expect(rowsInStore[11]).toBe(null) + }) + + test('test updated existing row with filters', async () => { + const view = { + id: 1, + filters_disabled: false, + filter_type: 'AND', + filters: [ + { + id: 1, + view: 1, + field: 1, + type: ContainsViewFilterType.getType(), + value: 'value', + }, + ], + sortings: [], + } + const fields = [] + const primary = { + id: 1, + name: 'Test 1', + type: 'text', + primary: true, + } + const populateRow = (row) => { + row._ = {} + return row + } + + const testStore = bufferedRows({ service: null, populateRow }) + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 0, + endIndex: 0, + }, + requestSize: 4, + viewId: 1, + rows: [ + null, + { id: 3, order: '3.00000000000000000000', field_1: 'Row 3' }, + { id: 5, order: '5.00000000000000000000', field_1: 'Row 5' }, + { id: 6, order: '6.00000000000000000000', field_1: 'Row 6' }, + { id: 7, order: '7.00000000000000000000', field_1: 'Row 7' }, + null, + null, + null, + { id: 11, order: '11.00000000000000000000', field_1: 'Row 11' }, + { id: 12, order: '12.00000000000000000000', field_1: 'Row 12' }, + { id: 14, order: '14.00000000000000000000', field_1: 'Row 14' }, + null, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 1, + order: '1.00000000000000000000', + field_1: 'Row 1', + }, + values: { + field_1: 'Row 1 value', + }, + }) + const rowsInStore = store.getters['test/getRows'] + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1]).toBe(null) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(5) + expect(rowsInStore[4].id).toBe(6) + expect(rowsInStore[5].id).toBe(7) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8]).toBe(null) + expect(rowsInStore[9].id).toBe(11) + expect(rowsInStore[10].id).toBe(12) + expect(rowsInStore[11].id).toBe(14) + expect(rowsInStore[12]).toBe(null) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 4, + order: '4.00000000000000000000', + field_1: 'Row 4', + }, + values: { + field_1: 'Row 4 value', + }, + }) + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1]).toBe(null) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(4) + expect(rowsInStore[4].id).toBe(5) + expect(rowsInStore[5].id).toBe(6) + expect(rowsInStore[6].id).toBe(7) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8]).toBe(null) + expect(rowsInStore[9]).toBe(null) + expect(rowsInStore[10].id).toBe(11) + expect(rowsInStore[11].id).toBe(12) + expect(rowsInStore[12].id).toBe(14) + expect(rowsInStore[13]).toBe(null) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 4, + order: '4.00000000000000000000', + field_1: 'Row 4 value', + }, + values: { + field_1: 'Row 4', + }, + }) + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1]).toBe(null) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(5) + expect(rowsInStore[4].id).toBe(6) + expect(rowsInStore[5].id).toBe(7) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8]).toBe(null) + expect(rowsInStore[9].id).toBe(11) + expect(rowsInStore[10].id).toBe(12) + expect(rowsInStore[11].id).toBe(14) + expect(rowsInStore[12]).toBe(null) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 15, + order: '15.00000000000000000000', + field_1: 'Row 15 value', + }, + values: { + field_1: 'Row 15', + }, + }) + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1]).toBe(null) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(5) + expect(rowsInStore[4].id).toBe(6) + expect(rowsInStore[5].id).toBe(7) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8]).toBe(null) + expect(rowsInStore[9].id).toBe(11) + expect(rowsInStore[10].id).toBe(12) + expect(rowsInStore[11].id).toBe(14) + }) + + test('test updated existing row with sorting', async () => { + const view = { + id: 1, + filters_disabled: false, + filter_type: 'AND', + filters: [], + sortings: [ + { + id: 1, + view: 1, + field: 1, + order: 'ASC', + }, + ], + } + const fields = [] + const primary = { + id: 1, + name: 'Test 1', + type: 'text', + primary: true, + } + const populateRow = (row) => { + row._ = {} + return row + } + + const testStore = bufferedRows({ service: null, populateRow }) + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 0, + endIndex: 0, + }, + requestSize: 4, + viewId: 1, + rows: [ + { id: 1, order: '1.00000000000000000000', field_1: 'A' }, + { id: 2, order: '2.00000000000000000000', field_1: 'B' }, + { id: 3, order: '3.00000000000000000000', field_1: 'C' }, + { id: 4, order: '4.00000000000000000000', field_1: 'D' }, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 3, + order: '3.00000000000000000000', + field_1: 'C', + }, + values: { + field_1: 'C2', + }, + }) + const rowsInStore = store.getters['test/getRows'] + expect(rowsInStore[0].id).toBe(1) + expect(rowsInStore[1].id).toBe(2) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(4) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 3, + order: '3.00000000000000000000', + field_1: 'C2', + }, + values: { + field_1: 'C', + }, + }) + expect(rowsInStore[0].id).toBe(1) + expect(rowsInStore[1].id).toBe(2) + expect(rowsInStore[2].id).toBe(3) + expect(rowsInStore[3].id).toBe(4) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 3, + order: '3.00000000000000000000', + field_1: 'C', + }, + values: { + field_1: 'E', + }, + }) + expect(rowsInStore[0].id).toBe(1) + expect(rowsInStore[1].id).toBe(2) + expect(rowsInStore[2].id).toBe(4) + expect(rowsInStore[3].id).toBe(3) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 3, + order: '3.00000000000000000000', + field_1: 'E', + }, + values: { + field_1: '0', + }, + }) + expect(rowsInStore[0].id).toBe(3) + expect(rowsInStore[1].id).toBe(1) + expect(rowsInStore[2].id).toBe(2) + expect(rowsInStore[3].id).toBe(4) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 3, + order: '3.00000000000000000000', + field_1: '0', + }, + values: { + field_1: '0', + }, + }) + expect(rowsInStore[0].id).toBe(3) + expect(rowsInStore[1].id).toBe(1) + expect(rowsInStore[2].id).toBe(2) + expect(rowsInStore[3].id).toBe(4) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 3, + order: '3.00000000000000000000', + field_1: '0', + }, + values: { + field_1: 'A1', + }, + }) + expect(rowsInStore[0].id).toBe(1) + expect(rowsInStore[1].id).toBe(3) + expect(rowsInStore[2].id).toBe(2) + expect(rowsInStore[3].id).toBe(4) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 3, + order: '3.00000000000000000000', + field_1: 'A1', + }, + values: { + field_1: 'D1', + }, + }) + expect(rowsInStore[0].id).toBe(1) + expect(rowsInStore[1].id).toBe(2) + expect(rowsInStore[2].id).toBe(4) + expect(rowsInStore[3].id).toBe(3) + }) + + test('test updated existing with sorting from null', async () => { + const view = { + id: 1, + filters_disabled: false, + filter_type: 'AND', + filters: [], + sortings: [ + { + id: 1, + view: 1, + field: 1, + order: 'ASC', + }, + ], + } + const fields = [] + const primary = { + id: 1, + name: 'Test 1', + type: 'text', + primary: true, + } + const populateRow = (row) => { + row._ = {} + return row + } + + const testStore = bufferedRows({ service: null, populateRow }) + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 0, + endIndex: 0, + }, + requestSize: 4, + viewId: 1, + rows: [ + { id: 1, order: '1.00000000000000000000', field_1: '1' }, + { id: 2, order: '2.00000000000000000000', field_1: '2' }, + { id: 3, order: '3.00000000000000000000', field_1: '3' }, + { id: 4, order: '4.00000000000000000000', field_1: '4' }, + null, + null, + null, + null, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + await store.dispatch('test/afterExistingRowUpdated', { + view, + fields, + primary, + row: { + id: 7, + order: '7.00000000000000000000', + field_1: '7', + }, + values: { + field_1: '22', + }, + }) + const rowsInStore = store.getters['test/getRows'] + expect(rowsInStore[0].id).toBe(1) + expect(rowsInStore[1].id).toBe(2) + expect(rowsInStore[2].id).toBe(7) + expect(rowsInStore[3].id).toBe(3) + expect(rowsInStore[4].id).toBe(4) + expect(rowsInStore[5]).toBe(null) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7]).toBe(null) + }) + + test('test deleted existing row', async () => { + const view = { + id: 1, + filters_disabled: false, + filter_type: 'AND', + filters: [], + sortings: [], + } + const fields = [] + const primary = { + id: 1, + name: 'Test 1', + type: 'text', + primary: true, + } + const populateRow = (row) => { + row._ = {} + return row + } + + const testStore = bufferedRows({ service: null, populateRow }) + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 0, + endIndex: 0, + }, + requestSize: 4, + viewId: 1, + rows: [ + null, + { id: 3, order: '3.00000000000000000000', field_1: 'Row 3' }, + { id: 5, order: '5.00000000000000000000', field_1: 'Row 5' }, + { id: 6, order: '6.00000000000000000000', field_1: 'Row 6' }, + { id: 7, order: '7.00000000000000000000', field_1: 'Row 7' }, + null, + null, + null, + { id: 11, order: '11.00000000000000000000', field_1: 'Row 11' }, + { id: 12, order: '12.00000000000000000000', field_1: 'Row 12' }, + { id: 14, order: '14.00000000000000000000', field_1: 'Row 14' }, + null, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + await store.dispatch('test/afterExistingRowDeleted', { + view, + fields, + primary, + row: { + id: 1, + order: '1.00000000000000000000', + field_1: 'Row 1', + }, + }) + const rowsInStore = store.getters['test/getRows'] + expect(rowsInStore[0].id).toBe(3) + expect(rowsInStore[1].id).toBe(5) + expect(rowsInStore[2].id).toBe(6) + expect(rowsInStore[3].id).toBe(7) + expect(rowsInStore[4]).toBe(null) + expect(rowsInStore[5]).toBe(null) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7].id).toBe(11) + expect(rowsInStore[8].id).toBe(12) + expect(rowsInStore[9].id).toBe(14) + expect(rowsInStore[10]).toBe(null) + + await store.dispatch('test/afterExistingRowDeleted', { + view, + fields, + primary, + row: { + id: 15, + order: '15.00000000000000000000', + field_1: 'Row 15', + }, + }) + expect(rowsInStore[0].id).toBe(3) + expect(rowsInStore[1].id).toBe(5) + expect(rowsInStore[2].id).toBe(6) + expect(rowsInStore[3].id).toBe(7) + expect(rowsInStore[4]).toBe(null) + expect(rowsInStore[5]).toBe(null) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7].id).toBe(11) + expect(rowsInStore[8].id).toBe(12) + expect(rowsInStore[9].id).toBe(14) + + await store.dispatch('test/afterExistingRowDeleted', { + view, + fields, + primary, + row: { + id: 9, + order: '9.00000000000000000000', + field_1: 'Row 9', + }, + }) + expect(rowsInStore[0].id).toBe(3) + expect(rowsInStore[1].id).toBe(5) + expect(rowsInStore[2].id).toBe(6) + expect(rowsInStore[3].id).toBe(7) + expect(rowsInStore[4]).toBe(null) + expect(rowsInStore[5]).toBe(null) + expect(rowsInStore[6].id).toBe(11) + expect(rowsInStore[7].id).toBe(12) + expect(rowsInStore[8].id).toBe(14) + + await store.dispatch('test/afterExistingRowDeleted', { + view, + fields, + primary, + row: { + id: 5, + order: '5.00000000000000000000', + field_1: 'Row 5', + }, + }) + expect(rowsInStore[0].id).toBe(3) + expect(rowsInStore[1].id).toBe(6) + expect(rowsInStore[2].id).toBe(7) + expect(rowsInStore[3]).toBe(null) + expect(rowsInStore[4]).toBe(null) + expect(rowsInStore[5].id).toBe(11) + expect(rowsInStore[6].id).toBe(12) + expect(rowsInStore[7].id).toBe(14) + + await store.dispatch('test/afterExistingRowDeleted', { + view, + fields, + primary, + row: { + id: 14, + order: '14.00000000000000000000', + field_1: 'Row 14', + }, + }) + expect(rowsInStore[0].id).toBe(3) + expect(rowsInStore[1].id).toBe(6) + expect(rowsInStore[2].id).toBe(7) + expect(rowsInStore[3]).toBe(null) + expect(rowsInStore[4]).toBe(null) + expect(rowsInStore[5].id).toBe(11) + expect(rowsInStore[6].id).toBe(12) + }) + + test('test deleted existing row ignored if filtered', async () => { + const view = { + id: 1, + filters_disabled: false, + filter_type: 'AND', + filters: [ + { + id: 1, + view: 1, + field: 1, + type: ContainsViewFilterType.getType(), + value: 'value', + }, + ], + sortings: [], + } + const fields = [] + const primary = { + id: 1, + name: 'Test 1', + type: 'text', + primary: true, + } + const populateRow = (row) => { + row._ = {} + return row + } + + const testStore = bufferedRows({ service: null, populateRow }) + const state = Object.assign(testStore.state(), { + visibleRange: { + startIndex: 0, + endIndex: 0, + }, + requestSize: 4, + viewId: 1, + rows: [ + null, + { id: 3, order: '3.00000000000000000000', field_1: 'Row 3' }, + { id: 5, order: '5.00000000000000000000', field_1: 'Row 5' }, + { id: 6, order: '6.00000000000000000000', field_1: 'Row 6' }, + { id: 7, order: '7.00000000000000000000', field_1: 'Row 7' }, + null, + null, + null, + { id: 11, order: '11.00000000000000000000', field_1: 'Row 11' }, + { id: 12, order: '12.00000000000000000000', field_1: 'Row 12' }, + { id: 14, order: '14.00000000000000000000', field_1: 'Row 14' }, + null, + ], + }) + testStore.state = () => state + store.registerModule('test', testStore) + + await store.dispatch('test/afterExistingRowDeleted', { + view, + fields, + primary, + row: { + id: 100, + order: '100.00000000000000000000', + field_1: 'Row 1', + }, + }) + const rowsInStore = store.getters['test/getRows'] + // Nothing should have been updated because the deleted row didn't match the + // filters. + expect(rowsInStore[0]).toBe(null) + expect(rowsInStore[1].id).toBe(3) + expect(rowsInStore[2].id).toBe(5) + expect(rowsInStore[3].id).toBe(6) + expect(rowsInStore[4].id).toBe(7) + expect(rowsInStore[5]).toBe(null) + expect(rowsInStore[6]).toBe(null) + expect(rowsInStore[7]).toBe(null) + expect(rowsInStore[8].id).toBe(11) + expect(rowsInStore[9].id).toBe(12) + expect(rowsInStore[10].id).toBe(14) + expect(rowsInStore[11]).toBe(null) + }) +})