mirror of
https://github.com/baserow/baserow.git
synced 2026-12-06 09:18:47 +00:00
Merge branch '686-gallery-view' into 'develop'
Resolve "Gallery view" Closes #686 See merge request bramw/baserow!449
This commit is contained in:
commit
65da2d08cf
36 files changed
+4544
-61
No files matched your search
@@ -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"},
|
||||
|
||||
Whitespace-only changes.
@@ -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.",
|
||||
)
|
||||
@@ -0,0 +1,5 @@
|
||||
from rest_framework.pagination import LimitOffsetPagination
|
||||
|
||||
|
||||
class GalleryLimitOffsetPagination(LimitOffsetPagination):
|
||||
default_limit = 100
|
||||
@@ -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")
|
||||
@@ -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<view_id>[0-9]+)/$", GalleryViewView.as_view(), name="list"),
|
||||
]
|
||||
@@ -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
|
||||
@@ -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 (
|
||||
|
||||
@@ -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"
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -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",
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
@@ -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()
|
||||
|
||||
@@ -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.
|
||||
* **dev.sh users** Fixed bug in dev.sh where UID/GID were not being set correctly,
|
||||
please rebuild any dev images you are using.
|
||||
|
||||
+3
-21
@@ -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
|
||||
|
||||
@@ -144,6 +144,7 @@ export default {
|
||||
},
|
||||
viewType: {
|
||||
grid: 'Grid',
|
||||
gallery: 'Gallery',
|
||||
form: 'Form',
|
||||
},
|
||||
premium: {
|
||||
|
||||
@@ -146,6 +146,7 @@ export default {
|
||||
},
|
||||
viewType: {
|
||||
grid: 'Tableau',
|
||||
gallery: 'Gallerie',
|
||||
form: 'Formulaire',
|
||||
},
|
||||
premium: {
|
||||
|
||||
@@ -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';
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
<template>
|
||||
<div class="card" v-on="$listeners">
|
||||
<div class="card" :class="{ 'card--loading': loading }" v-on="$listeners">
|
||||
<div v-for="field in fields" :key="field.id" class="card__field">
|
||||
<div class="card__field-name">{{ field.name }}</div>
|
||||
<div class="card__field-value">
|
||||
<component
|
||||
:is="getCardComponent(field)"
|
||||
v-if="!loading"
|
||||
:field="field"
|
||||
:value="row['field_' + field.id]"
|
||||
/>
|
||||
@@ -23,7 +24,13 @@ export default {
|
||||
},
|
||||
row: {
|
||||
type: Object,
|
||||
required: true,
|
||||
required: false,
|
||||
default: () => {},
|
||||
},
|
||||
loading: {
|
||||
type: Boolean,
|
||||
required: false,
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
<a
|
||||
ref="createViewLink"
|
||||
v-tooltip="deactivated ? deactivatedText : null"
|
||||
class="select__footer-multiple-item"
|
||||
class="select__footer-create-link"
|
||||
:class="{
|
||||
'select__footer-multiple-item--disabled': deactivated,
|
||||
'select__footer-create-link--disabled': deactivated,
|
||||
}"
|
||||
@click="!deactivated && $refs.createModal.show($refs.createViewLink)"
|
||||
>
|
||||
<i
|
||||
class="select__footer-multiple-icon fas"
|
||||
class="select__footer-create-icon fas"
|
||||
:class="'fa-' + viewType.iconClass"
|
||||
></i>
|
||||
{{ viewType.getName() }}
|
||||
|
||||
@@ -22,7 +22,12 @@
|
||||
v-for="view in searchAndOrder(views)"
|
||||
:ref="'view-' + view.id"
|
||||
:key="view.id"
|
||||
v-sortable="{ id: view.id, update: order, marginTop: -1.5 }"
|
||||
v-sortable="{
|
||||
enabled: !readOnly,
|
||||
id: view.id,
|
||||
update: order,
|
||||
marginTop: -1.5,
|
||||
}"
|
||||
:view="view"
|
||||
:table="table"
|
||||
:read-only="readOnly"
|
||||
@@ -33,10 +38,7 @@
|
||||
{{ $t('viewsContext.noViews') }}
|
||||
</div>
|
||||
<div v-if="!readOnly" class="select__footer">
|
||||
<div class="select__footer-multiple">
|
||||
<div class="select__footer-multiple-label">
|
||||
{{ $t('viewsContext.addView') }}
|
||||
</div>
|
||||
<div class="select__footer-create">
|
||||
<CreateViewLink
|
||||
v-for="(viewType, type) in viewTypes"
|
||||
:key="type"
|
||||
@@ -205,15 +207,13 @@ export default {
|
||||
"en": {
|
||||
"viewsContext": {
|
||||
"searchView": "Search views",
|
||||
"noViews": "No views found",
|
||||
"addView": "Add a view:"
|
||||
"noViews": "No views found"
|
||||
}
|
||||
},
|
||||
"fr": {
|
||||
"viewsContext": {
|
||||
"searchView": "Recherche",
|
||||
"noViews": "Aucune vue trouvée",
|
||||
"addView": "Ajouter une vue:"
|
||||
"noViews": "Aucune vue trouvée"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
<template>
|
||||
<div class="gallery-view">
|
||||
<a
|
||||
v-if="!readOnly"
|
||||
class="gallery-view__add"
|
||||
@click="$refs.rowCreateModal.show()"
|
||||
>
|
||||
<i class="fas fa-plus"></i>
|
||||
</a>
|
||||
<div ref="scroll" class="gallery-view__scroll">
|
||||
<div
|
||||
class="gallery-view__cards"
|
||||
:style="{
|
||||
height: height + 'px',
|
||||
}"
|
||||
>
|
||||
<RowCard
|
||||
v-for="slot in buffer"
|
||||
v-show="slot.left != -1"
|
||||
:key="'card-' + slot.id"
|
||||
:fields="cardFields"
|
||||
:row="slot.row === null ? {} : slot.row"
|
||||
:loading="slot.row === null"
|
||||
class="gallery-view__card"
|
||||
:style="{
|
||||
width: cardWidth + 'px',
|
||||
height: slot.row === null ? cardHeight + 'px' : undefined,
|
||||
transform: `translateX(${slot.left}px) translateY(${slot.top}px)`,
|
||||
}"
|
||||
></RowCard>
|
||||
</div>
|
||||
</div>
|
||||
<RowCreateModal
|
||||
v-if="!readOnly"
|
||||
ref="rowCreateModal"
|
||||
:table="table"
|
||||
:fields="fields"
|
||||
:primary="primary"
|
||||
@created="createRow"
|
||||
@field-updated="$emit('refresh', $event)"
|
||||
@field-deleted="$emit('refresh')"
|
||||
></RowCreateModal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import debounce from 'lodash/debounce'
|
||||
import { mapGetters } from 'vuex'
|
||||
import ResizeObserver from 'resize-observer-polyfill'
|
||||
|
||||
import { getCardHeight } from '@baserow/modules/database/utils/card'
|
||||
import { maxPossibleOrderValue } from '@baserow/modules/database/viewTypes'
|
||||
import RowCard from '@baserow/modules/database/components/card/RowCard'
|
||||
import RowCreateModal from '@baserow/modules/database/components/row/RowCreateModal'
|
||||
|
||||
export default {
|
||||
name: 'GalleryView',
|
||||
components: { RowCard, RowCreateModal },
|
||||
props: {
|
||||
primary: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
fields: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
view: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
table: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
database: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
readOnly: {
|
||||
type: Boolean,
|
||||
required: true,
|
||||
},
|
||||
storePrefix: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
gutterSize: 30,
|
||||
minimumCardWidth: 280,
|
||||
height: 0,
|
||||
cardWidth: 0,
|
||||
buffer: [],
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
firstRows() {
|
||||
return this.allRows.slice(0, 200)
|
||||
},
|
||||
/**
|
||||
* In order for the virtual scrolling to work, we need to know what the height of
|
||||
* the card is to correctly position it.
|
||||
*/
|
||||
cardHeight() {
|
||||
return getCardHeight(this.cardFields, this.$registry)
|
||||
},
|
||||
/**
|
||||
* Returns the visible field objects in the right order.
|
||||
*/
|
||||
cardFields() {
|
||||
return [this.primary]
|
||||
.concat(this.fields)
|
||||
.filter((field) => {
|
||||
const exists = Object.prototype.hasOwnProperty.call(
|
||||
this.fieldOptions,
|
||||
field.id
|
||||
)
|
||||
return !exists || (exists && !this.fieldOptions[field.id].hidden)
|
||||
})
|
||||
.sort((a, b) => {
|
||||
const orderA = this.fieldOptions[a.id]
|
||||
? this.fieldOptions[a.id].order
|
||||
: maxPossibleOrderValue
|
||||
const orderB = this.fieldOptions[b.id]
|
||||
? this.fieldOptions[b.id].order
|
||||
: maxPossibleOrderValue
|
||||
|
||||
// First by order.
|
||||
if (orderA > orderB) {
|
||||
return 1
|
||||
} else if (orderA < orderB) {
|
||||
return -1
|
||||
}
|
||||
|
||||
// Then by id.
|
||||
if (a.id < b.id) {
|
||||
return -1
|
||||
} else if (a.id > b.id) {
|
||||
return 1
|
||||
} else {
|
||||
return 0
|
||||
}
|
||||
})
|
||||
},
|
||||
},
|
||||
watch: {
|
||||
cardHeight() {
|
||||
this.$nextTick(() => {
|
||||
this.updateBuffer()
|
||||
})
|
||||
},
|
||||
allRows() {
|
||||
this.$nextTick(() => {
|
||||
this.updateBuffer()
|
||||
})
|
||||
},
|
||||
},
|
||||
mounted() {
|
||||
this.updateBuffer()
|
||||
this.$el.resizeObserver = new ResizeObserver(() => {
|
||||
this.updateBuffer()
|
||||
})
|
||||
this.$el.resizeObserver.observe(this.$el)
|
||||
|
||||
const fireUpdateBuffer = {
|
||||
last: Date.now(),
|
||||
distance: 0,
|
||||
}
|
||||
|
||||
// Debounce function that's called when the user scrolls really fast. This is to
|
||||
// make sure that the `updateBuffer` method is called with the
|
||||
// `dispatchVisibleRows` parameter to true when the user immediately stops
|
||||
// scrolling fast.
|
||||
const updateBufferDebounced = debounce(() => {
|
||||
this.updateBuffer(true)
|
||||
}, 100)
|
||||
|
||||
this.$el.scrollEvent = (event) => {
|
||||
const now = Date.now()
|
||||
const { scrollTop } = event.target
|
||||
|
||||
const distance = Math.abs(scrollTop - fireUpdateBuffer.distance)
|
||||
const timeDelta = now - fireUpdateBuffer.last
|
||||
|
||||
if (timeDelta > 100) {
|
||||
const velocity = distance / timeDelta
|
||||
|
||||
fireUpdateBuffer.last = now
|
||||
fireUpdateBuffer.distance = scrollTop
|
||||
|
||||
if (velocity < 2.5) {
|
||||
// When scrolling "slow", the dispatchVisibleRows parameter is true so that
|
||||
// the visible rows are fetched if needed.
|
||||
updateBufferDebounced.cancel()
|
||||
this.updateBuffer(true)
|
||||
} else {
|
||||
// Check if the user is scrolling super fast because in that case we don't
|
||||
// fetch the rows when they're not needed.
|
||||
updateBufferDebounced()
|
||||
this.updateBuffer(false)
|
||||
}
|
||||
} else {
|
||||
// If scroll stopped within the 100ms we still want to have a last
|
||||
// updateBuffer(true) call.
|
||||
updateBufferDebounced()
|
||||
this.updateBuffer(false)
|
||||
}
|
||||
}
|
||||
this.$refs.scroll.addEventListener('scroll', this.$el.scrollEvent)
|
||||
},
|
||||
beforeDestroy() {
|
||||
this.$el.resizeObserver.unobserve(this.$el)
|
||||
this.$refs.scroll.removeEventListener('scroll', this.$el.scrollEvent)
|
||||
},
|
||||
beforeCreate() {
|
||||
this.$options.computed = {
|
||||
...(this.$options.computed || {}),
|
||||
...mapGetters({
|
||||
allRows: this.$options.propsData.storePrefix + 'view/gallery/getRows',
|
||||
fieldOptions:
|
||||
this.$options.propsData.storePrefix +
|
||||
'view/gallery/getAllFieldOptions',
|
||||
}),
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
/**
|
||||
* This method makes sure that the correct cards/rows are shown based on the
|
||||
* scroll offset, viewport width, viewport height and card height. Based on these
|
||||
* values we can calculate which how many rows should be visible, which ones are
|
||||
* visible and what their position is without rendering all the rows in the store
|
||||
* at once.
|
||||
*
|
||||
* @TODO make this really virtual scrolling by letting the row persist in the same
|
||||
* slot, even when it changes position. Currently, it updates all the cards when
|
||||
* a new row of cards must be displayed.
|
||||
*
|
||||
* @param dispatchVisibleRows Indicates whether we want to dispatch the visibleRows
|
||||
* action in the store. In some cases, when scrolling really fast through data we
|
||||
* might want to wait a small moment before calling the action, which will make a
|
||||
* request to the backend if needed.
|
||||
*/
|
||||
updateBuffer(dispatchVisibleRows = true) {
|
||||
const el = this.$refs.scroll
|
||||
|
||||
const gutterSize = this.gutterSize
|
||||
const containerWidth = el.clientWidth
|
||||
const containerHeight = el.clientHeight
|
||||
|
||||
const cardsPerRow = Math.min(
|
||||
Math.max(Math.floor(containerWidth / this.minimumCardWidth), 1),
|
||||
20
|
||||
)
|
||||
const cardHeight = this.cardHeight
|
||||
const cardWidth = (containerWidth - gutterSize) / cardsPerRow - gutterSize
|
||||
const totalRows = Math.ceil(this.allRows.length / cardsPerRow)
|
||||
const height = totalRows * (cardHeight + gutterSize) + gutterSize
|
||||
|
||||
this.cardWidth = cardWidth
|
||||
this.height = height
|
||||
|
||||
const scrollTop = el.scrollTop
|
||||
const minimumCardsToRender =
|
||||
(Math.ceil(containerHeight / (cardHeight + gutterSize)) + 1) *
|
||||
cardsPerRow
|
||||
const startIndex =
|
||||
Math.floor(scrollTop / (cardHeight + gutterSize)) * cardsPerRow
|
||||
const endIndex = startIndex + minimumCardsToRender
|
||||
const visibleRows = this.allRows.slice(startIndex, endIndex)
|
||||
|
||||
// Calculate an array containing only the rows that must be displayed and their
|
||||
// position in the gallery as if all the rows are there.
|
||||
this.buffer = visibleRows.map((row, positionInVisible) => {
|
||||
const positionInAll = startIndex + positionInVisible
|
||||
const left =
|
||||
gutterSize + (positionInAll % cardsPerRow) * (gutterSize + cardWidth)
|
||||
const top =
|
||||
gutterSize +
|
||||
Math.floor(positionInAll / cardsPerRow) * (gutterSize + cardHeight)
|
||||
|
||||
return {
|
||||
id: positionInVisible,
|
||||
row,
|
||||
left,
|
||||
top,
|
||||
}
|
||||
})
|
||||
|
||||
if (dispatchVisibleRows) {
|
||||
// Tell the store which rows/cards are visible so that it can fetch the missing
|
||||
// ones if needed.
|
||||
this.$store.dispatch(
|
||||
this.storePrefix + 'view/gallery/fetchMissingRowsInNewRange',
|
||||
{
|
||||
startIndex,
|
||||
endIndex,
|
||||
}
|
||||
)
|
||||
}
|
||||
},
|
||||
async createRow({ row, callback }) {
|
||||
try {
|
||||
await this.$store.dispatch(
|
||||
this.storePrefix + 'view/gallery/createNewRow',
|
||||
{
|
||||
view: this.view,
|
||||
table: this.table,
|
||||
fields: this.fields,
|
||||
primary: this.primary,
|
||||
values: row,
|
||||
}
|
||||
)
|
||||
callback()
|
||||
} catch (error) {
|
||||
callback(error)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,148 @@
|
||||
<template>
|
||||
<ul v-if="!tableLoading" class="header__filter header__filter--full-width">
|
||||
<li class="header__filter-item">
|
||||
<a
|
||||
ref="customizeContextLink"
|
||||
class="header__filter-link"
|
||||
@click="
|
||||
$refs.customizeContext.toggle(
|
||||
$refs.customizeContextLink,
|
||||
'bottom',
|
||||
'left',
|
||||
4
|
||||
)
|
||||
"
|
||||
>
|
||||
<i class="header__filter-icon fas fa-cog"></i>
|
||||
<span class="header__filter-name">{{
|
||||
$t('galleryViewHeader.customizeCards')
|
||||
}}</span>
|
||||
</a>
|
||||
<ViewFieldsContext
|
||||
ref="customizeContext"
|
||||
:fields="allFields"
|
||||
:read-only="readOnly"
|
||||
:field-options="fieldOptions"
|
||||
@update-all-field-options="updateAllFieldOptions"
|
||||
@update-field-options-of-field="updateFieldOptionsOfField"
|
||||
@update-order="orderFieldOptions"
|
||||
></ViewFieldsContext>
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { mapGetters, mapState } from 'vuex'
|
||||
|
||||
import { notifyIf } from '@baserow/modules/core/utils/error'
|
||||
import ViewFieldsContext from '@baserow/modules/database/components/view/ViewFieldsContext'
|
||||
|
||||
export default {
|
||||
name: 'GalleryViewHeader',
|
||||
components: { ViewFieldsContext },
|
||||
props: {
|
||||
database: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
table: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
view: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
fields: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
primary: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
readOnly: {
|
||||
type: Boolean,
|
||||
required: true,
|
||||
},
|
||||
storePrefix: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
computed: {
|
||||
allFields() {
|
||||
return [this.primary].concat(this.fields)
|
||||
},
|
||||
...mapState({
|
||||
tableLoading: (state) => state.table.loading,
|
||||
}),
|
||||
},
|
||||
beforeCreate() {
|
||||
this.$options.computed = {
|
||||
...(this.$options.computed || {}),
|
||||
...mapGetters({
|
||||
fieldOptions:
|
||||
this.$options.propsData.storePrefix +
|
||||
'view/gallery/getAllFieldOptions',
|
||||
}),
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
async updateAllFieldOptions({ newFieldOptions, oldFieldOptions }) {
|
||||
try {
|
||||
await this.$store.dispatch(
|
||||
this.storePrefix + 'view/gallery/updateAllFieldOptions',
|
||||
{
|
||||
newFieldOptions,
|
||||
oldFieldOptions,
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
notifyIf(error, 'view')
|
||||
}
|
||||
},
|
||||
async updateFieldOptionsOfField({ field, values, oldValues }) {
|
||||
try {
|
||||
await this.$store.dispatch(
|
||||
this.storePrefix + 'view/gallery/updateFieldOptionsOfField',
|
||||
{
|
||||
field,
|
||||
values,
|
||||
oldValues,
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
notifyIf(error, 'view')
|
||||
}
|
||||
},
|
||||
async orderFieldOptions({ order }) {
|
||||
try {
|
||||
await this.$store.dispatch(
|
||||
this.storePrefix + 'view/gallery/updateFieldOptionsOrder',
|
||||
{
|
||||
order,
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
notifyIf(error, 'view')
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
</script>
|
||||
|
||||
<i18n>
|
||||
{
|
||||
"en":{
|
||||
"galleryViewHeader":{
|
||||
"customizeCards": "Customize cards"
|
||||
}
|
||||
},
|
||||
"fr":{
|
||||
"settings":{
|
||||
"customizeCards": "Configurer les cartes"
|
||||
}
|
||||
}
|
||||
}
|
||||
</i18n>
|
||||
@@ -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))
|
||||
|
||||
@@ -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)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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
|
||||
)
|
||||
}
|
||||
@@ -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'
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user