diff --git a/.env b/.env index b21bb0ee3..4b36cdf8c 100644 --- a/.env +++ b/.env @@ -8,7 +8,7 @@ PROJECT_NAME="TAD" # TAD backend BACKEND_CORS_ORIGINS="http://localhost,https://localhost,http://127.0.0.1,https://127.0.0.1" SECRET_KEY=changethis -APP_DATABASE_SCHEME="postgresql" +APP_DATABASE_SCHEME="sqlite" APP_DATABASE_USER=tad APP_DATABASE_DB=tad APP_DATABASE_PASSWORD=changethis diff --git a/.env.test b/.env.test index 4b36cdf8c..21e66d393 100644 --- a/.env.test +++ b/.env.test @@ -22,3 +22,5 @@ POSTGRES_PASSWORD=changethis # Database viewer PGADMIN_DEFAULT_PASSWORD=changethis + +APP_DATABASE_FILE=database.sqlite3 diff --git a/.gitignore b/.gitignore index a0cbd2215..b2a562978 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,7 @@ __pypackages__/ #mypyr .mypy_cache/ +/.idea/ # macos .DS_Store diff --git a/pyproject.toml b/pyproject.toml index 4fc746c67..03c4257a5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,6 +30,8 @@ jinja2 = "^3.1.4" pydantic-settings = "^2.2.1" psycopg2-binary = "^2.9.9" uvicorn = {extras = ["standard"], version = "^0.30.1"} +playwright = "^1.44.0" +pytest-playwright = "^0.5.0" [tool.poetry.group.test.dependencies] @@ -77,7 +79,8 @@ reportMissingImports = true reportMissingTypeStubs = true reportUnnecessaryIsInstance = false exclude = [ - "tad/migrations" + "tad/migrations", + ".venv" ] [tool.coverage.run] diff --git a/tad/api/main.py b/tad/api/main.py index 6f604c7ee..5b8437689 100644 --- a/tad/api/main.py +++ b/tad/api/main.py @@ -1,7 +1,9 @@ from fastapi import APIRouter -from tad.api.routes import health, root +from tad.api.routes import health, pages, root, tasks api_router = APIRouter() api_router.include_router(root.router) api_router.include_router(health.router, prefix="/health", tags=["health"]) +api_router.include_router(pages.router, prefix="/pages", tags=["pages"]) +api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"]) diff --git a/tad/api/routes/pages.py b/tad/api/routes/pages.py new file mode 100644 index 000000000..2f17fc96a --- /dev/null +++ b/tad/api/routes/pages.py @@ -0,0 +1,25 @@ +from typing import Annotated + +from fastapi import APIRouter, Depends, Request +from fastapi.responses import HTMLResponse +from fastapi.templating import Jinja2Templates + +from tad.services.statuses import StatusesService +from tad.services.tasks import TasksService + +router = APIRouter() +templates = Jinja2Templates(directory="tad/site/templates") + + +@router.get("/", response_class=HTMLResponse) +async def default_layout( + request: Request, + status_service: Annotated[StatusesService, Depends(StatusesService)], + tasks_service: Annotated[TasksService, Depends(TasksService)], +): + context = { + "page_title": "This is the page title", + "tasks_service": tasks_service, + "statuses_service": status_service, + } + return templates.TemplateResponse(request=request, name="default_layout.jinja", context=context) diff --git a/tad/api/routes/root.py b/tad/api/routes/root.py index a33a202e5..abe4fb080 100644 --- a/tad/api/routes/root.py +++ b/tad/api/routes/root.py @@ -1,7 +1,7 @@ from fastapi import APIRouter, Request from fastapi.responses import HTMLResponse -from tad.api.deps import templates +from tad.repositories.deps import templates router = APIRouter() diff --git a/tad/api/routes/tasks.py b/tad/api/routes/tasks.py new file mode 100644 index 000000000..e085922c9 --- /dev/null +++ b/tad/api/routes/tasks.py @@ -0,0 +1,48 @@ +from typing import Annotated, Any + +from fastapi import APIRouter, Depends, Request, status +from fastapi.responses import HTMLResponse +from fastapi.templating import Jinja2Templates + +from tad.models.task import MoveTask +from tad.services.tasks import TasksService + +router = APIRouter() +templates = Jinja2Templates(directory="tad/site/templates") + + +@router.post("/move", response_class=HTMLResponse) +async def move_task( + request: Request, move_task: MoveTask, tasks_service: Annotated[TasksService, Depends(TasksService)] +) -> HTMLResponse: + """ + Move a task through an API call. + :param tasks_service: the task service + :param request: the request object + :param move_task: the move task object + :return: a HTMLResponse object, in this case the html code of the card that was moved + """ + try: + task = tasks_service.move_task( + convert_to_int_if_is_int(move_task.id), + convert_to_int_if_is_int(move_task.status_id), + convert_to_int_if_is_int(move_task.previous_sibling_id), + convert_to_int_if_is_int(move_task.next_sibling_id), + ) + # todo(Robbert) add error handling for input error or task error handling + return templates.TemplateResponse(request=request, name="task.jinja", context={"task": task}) + except Exception: + return templates.TemplateResponse( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, request=request, name="error.jinja" + ) + + +def convert_to_int_if_is_int(value: Any) -> int | Any: + """ + If the given value is of type int, return it as int, otherwise return the input value as is. + :param value: the value to convert + :return: the value as int or the original type + """ + if value is not None and isinstance(value, str) and value.isdigit(): + return int(value) + return value diff --git a/tad/core/config.py b/tad/core/config.py index 0023c856d..6f2fea18d 100644 --- a/tad/core/config.py +++ b/tad/core/config.py @@ -15,6 +15,8 @@ # Self type is not available in Python 3.10 so create our own with TypeVar SelfSettings = TypeVar("SelfSettings", bound="Settings") +logger = logging.getLogger(__name__) + class Settings(BaseSettings): # todo(berry): investigate yaml, toml or json file support for SettingsConfigDict @@ -42,8 +44,8 @@ def server_host(self) -> str: PROJECT_NAME: str = "TAD" PROJECT_DESCRIPTION: str = "Transparency of Algorithmic Decision making" - STATIC_DIR: str = "tad/static" - TEMPLATE_DIR: str = "tad/templates" + STATIC_DIR: str = "tad/site/static/" + TEMPLATE_DIR: str = "tad/site/templates" # todo(berry): create submodel for database settings APP_DATABASE_SCHEME: DatabaseSchemaType = "sqlite" diff --git a/tad/core/db.py b/tad/core/db.py index d5317814f..dda4f7c4a 100644 --- a/tad/core/db.py +++ b/tad/core/db.py @@ -1,10 +1,18 @@ +from sqlalchemy.engine.base import Engine from sqlmodel import Session, create_engine, select from tad.core.config import settings -engine = create_engine(settings.SQLALCHEMY_DATABASE_URI) +_engine: None | Engine = None + + +def get_engine() -> Engine: + global _engine + if _engine is None: + _engine = create_engine(settings.SQLALCHEMY_DATABASE_URI) + return _engine async def check_db(): - with Session(engine) as session: + with Session(get_engine()) as session: session.exec(select(1)) diff --git a/tad/main.py b/tad/main.py index 7a2390d2c..68740234f 100644 --- a/tad/main.py +++ b/tad/main.py @@ -18,11 +18,13 @@ validation_exception_handler as tad_validation_exception_handler, ) from tad.core.log import configure_logging -from tad.middleware.route_logging import RequestLoggingMiddleware from tad.utils.mask import Mask +from .middleware.route_logging import RequestLoggingMiddleware + configure_logging(settings.LOGGING_LEVEL, settings.LOGGING_CONFIG) + logger = logging.getLogger(__name__) mask = Mask(mask_keywords=["database_uri"]) @@ -52,7 +54,6 @@ async def lifespan(app: FastAPI): ) app.add_middleware(RequestLoggingMiddleware) - app.mount("/static", StaticFiles(directory=settings.STATIC_DIR), name="static") @@ -67,3 +68,5 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE app.include_router(api_router) + +# todo (robbert) add init code for example tasks and statuses diff --git a/tad/migrations/versions/eb2eed884ae9_a_message.py b/tad/migrations/versions/eb2eed884ae9_a_message.py new file mode 100644 index 000000000..0fc315225 --- /dev/null +++ b/tad/migrations/versions/eb2eed884ae9_a_message.py @@ -0,0 +1,67 @@ +"""a message + +Revision ID: eb2eed884ae9 +Revises: +Create Date: 2024-05-14 13:36:23.551663 + +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +import sqlmodel.sql.sqltypes +from alembic import op + +# revision identifiers, used by Alembic. +revision: str = "eb2eed884ae9" +down_revision: str | None = None +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table( + "hero", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.PrimaryKeyConstraint("id"), + ) + op.create_table( + "status", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column("sort_order", sa.Float(), nullable=False), + sa.PrimaryKeyConstraint("id"), + ) + op.create_table( + "user", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column("avatar", sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.PrimaryKeyConstraint("id"), + ) + op.create_table( + "task", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("title", sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column("description", sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column("sort_order", sa.Float(), nullable=False), + sa.Column("status_id", sa.Integer(), nullable=False), + sa.Column("user_id", sa.Integer(), nullable=True), + sa.ForeignKeyConstraint( + ["user_id"], + ["user.id"], + ), + sa.PrimaryKeyConstraint("id"), + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table("task") + op.drop_table("user") + op.drop_table("status") + op.drop_table("hero") + # ### end Alembic commands ### diff --git a/tad/models/__init__.py b/tad/models/__init__.py index e8084bec2..629df5cdc 100644 --- a/tad/models/__init__.py +++ b/tad/models/__init__.py @@ -1,3 +1,6 @@ from .hero import Hero +from .status import Status +from .task import Task +from .user import User -__all__ = ["Hero"] +__all__ = ["Hero", "Task", "Status", "User"] diff --git a/tad/models/status.py b/tad/models/status.py new file mode 100644 index 000000000..d8af1819e --- /dev/null +++ b/tad/models/status.py @@ -0,0 +1,7 @@ +from sqlmodel import Field, SQLModel # type: ignore + + +class Status(SQLModel, table=True): + id: int = Field(default=None, primary_key=True) + name: str + sort_order: float diff --git a/tad/models/task.py b/tad/models/task.py new file mode 100644 index 000000000..a652aaa03 --- /dev/null +++ b/tad/models/task.py @@ -0,0 +1,30 @@ +from pydantic import BaseModel, ValidationInfo, field_validator +from pydantic import Field as PydanticField # type: ignore +from sqlmodel import Field as SQLField # type: ignore +from sqlmodel import SQLModel + + +class Task(SQLModel, table=True): + id: int = SQLField(default=None, primary_key=True) + title: str + description: str + sort_order: float + status_id: int | None = SQLField(default=None, foreign_key="status.id") + user_id: int | None = SQLField(default=None, foreign_key="user.id") + # todo(robbert) Tasks probably are grouped (and sub-grouped), so we probably need a reference to a group_id + + +class MoveTask(BaseModel): + # todo(robbert) values from htmx json are all strings, using type int does not work for + # sibling variables (they are optional) + id: str = PydanticField(None, alias="taskId", strict=False) + status_id: str = PydanticField(None, alias="statusId", strict=False) + previous_sibling_id: str | None = PydanticField(None, alias="previousSiblingId", strict=False) + next_sibling_id: str | None = PydanticField(None, alias="nextSiblingId", strict=False) + + @field_validator("id", "status_id", "previous_sibling_id", "next_sibling_id") + @classmethod + def check_is_int(cls, value: str, info: ValidationInfo) -> str: + if isinstance(value, str) and value.isdigit(): + assert value.isdigit(), f"{info.field_name} must be an integer" # noqa: S101 + return value diff --git a/tad/models/user.py b/tad/models/user.py new file mode 100644 index 000000000..7b3d273c3 --- /dev/null +++ b/tad/models/user.py @@ -0,0 +1,7 @@ +from sqlmodel import Field, SQLModel # type: ignore + + +class User(SQLModel, table=True): + id: int = Field(default=None, primary_key=True) + name: str + avatar: str | None diff --git a/tad/static/css/styles.css b/tad/repositories/__init__.py similarity index 100% rename from tad/static/css/styles.css rename to tad/repositories/__init__.py diff --git a/tad/api/deps.py b/tad/repositories/deps.py similarity index 51% rename from tad/api/deps.py rename to tad/repositories/deps.py index 1a7c86223..988da5f84 100644 --- a/tad/api/deps.py +++ b/tad/repositories/deps.py @@ -1,19 +1,14 @@ from collections.abc import Generator -from typing import Annotated -from fastapi import Depends from fastapi.templating import Jinja2Templates from sqlmodel import Session from tad.core.config import settings -from tad.core.db import engine +from tad.core.db import get_engine templates = Jinja2Templates(directory=settings.TEMPLATE_DIR) -def get_db() -> Generator[Session, None, None]: - with Session(engine) as session: +def get_session() -> Generator[Session, None, None]: + with Session(get_engine()) as session: yield session - - -SessionDep = Annotated[Session, Depends(get_db)] diff --git a/tad/repositories/exceptions.py b/tad/repositories/exceptions.py new file mode 100644 index 000000000..863e32ea3 --- /dev/null +++ b/tad/repositories/exceptions.py @@ -0,0 +1,8 @@ +from tad.core.exceptions import TADError + + +class RepositoryError(TADError): + def __init__(self, message: str = "Repository error"): + self.message: str = message + exception_name: str = self.__class__.__name__ + super().__init__(f"{exception_name}: {self.message}") diff --git a/tad/repositories/statuses.py b/tad/repositories/statuses.py new file mode 100644 index 000000000..1855bdf6d --- /dev/null +++ b/tad/repositories/statuses.py @@ -0,0 +1,56 @@ +import logging +from collections.abc import Sequence +from typing import Annotated + +from fastapi import Depends +from sqlalchemy.exc import NoResultFound +from sqlmodel import Session, select + +from tad.models import Status +from tad.repositories.deps import get_session +from tad.repositories.exceptions import RepositoryError + +logger = logging.getLogger(__name__) + + +class StatusesRepository: + """ + The StatusRepository provides access to the repository layer. + """ + + def __init__(self, session: Annotated[Session, Depends(get_session)]): + self.session = session + + def find_all(self) -> Sequence[Status]: + """ + Returns a list of all statuses in the repository. + :return: the list of all statuses + """ + return self.session.exec(select(Status)).all() + + def save(self, status: Status) -> Status: + """ + Stores the given status in the repository. + :param status: the status to store + :return: the updated status after storing + """ + self.session.add(status) + try: + self.session.commit() + self.session.refresh(status) + except Exception as e: + self.session.rollback() + raise RepositoryError from e + return status + + def find_by_id(self, status_id: int) -> Status: + """ + Returns the status with the given id or an exception if the id does not exist. + :param status_id: the id of the status + :return: the status with the given id or an exception + """ + try: + statement = select(Status).where(Status.id == status_id) + return self.session.exec(statement).one() + except NoResultFound as e: + raise RepositoryError from e diff --git a/tad/repositories/tasks.py b/tad/repositories/tasks.py new file mode 100644 index 000000000..6de4f4df8 --- /dev/null +++ b/tad/repositories/tasks.py @@ -0,0 +1,66 @@ +import logging +from collections.abc import Sequence +from typing import Annotated + +from fastapi import Depends +from sqlalchemy.exc import NoResultFound +from sqlmodel import Session, select + +from tad.models import Task +from tad.repositories.deps import get_session +from tad.repositories.exceptions import RepositoryError + +logger = logging.getLogger(__name__) + + +class TasksRepository: + """ + The TasksRepository provides access to the repository layer. + """ + + def __init__(self, session: Annotated[Session, Depends(get_session)]): + self.session = session + + def find_all(self) -> Sequence[Task]: + """ + Returns all tasks in the repository. + :return: all tasks in the repository + """ + return self.session.exec(select(Task)).all() + + def find_by_status_id(self, status_id: int) -> Sequence[Task]: + """ + Returns all tasks in the repository for the given status_id. + :param status_id: the status_id to filter on + :return: a list of tasks in the repository for the given status_id + """ + # todo (Robbert): we 'type ignore' Task.sort_order because it works correctly, but pyright does not agree + statement = select(Task).where(Task.status_id == status_id).order_by(Task.sort_order) # type: ignore + return self.session.exec(statement).all() + + def save(self, task: Task) -> Task: + """ + Stores the given task in the repository or throws a RepositoryException + :param task: the task to store + :return: the updated task after storing + """ + try: + self.session.add(task) + self.session.commit() + self.session.refresh(task) + except Exception as e: + self.session.rollback() + raise RepositoryError from e + return task + + def find_by_id(self, task_id: int) -> Task: + """ + Returns the task with the given id. + :param task_id: the id of the task to find + :return: the task with the given id or an exception if no task was found + """ + statement = select(Task).where(Task.id == task_id) + try: + return self.session.exec(statement).one() + except NoResultFound as e: + raise RepositoryError from e diff --git a/tad/static/js/main.js b/tad/services/__init__.py similarity index 100% rename from tad/static/js/main.js rename to tad/services/__init__.py diff --git a/tad/services/statuses.py b/tad/services/statuses.py new file mode 100644 index 000000000..ea0bea7de --- /dev/null +++ b/tad/services/statuses.py @@ -0,0 +1,21 @@ +import logging +from collections.abc import Sequence +from typing import Annotated + +from fastapi import Depends + +from tad.models import Status +from tad.repositories.statuses import StatusesRepository + +logger = logging.getLogger(__name__) + + +class StatusesService: + def __init__(self, repository: Annotated[StatusesRepository, Depends(StatusesRepository)]): + self.repository = repository + + def get_status(self, status_id: int) -> Status: + return self.repository.find_by_id(status_id) + + def get_statuses(self) -> Sequence[Status]: + return self.repository.find_all() diff --git a/tad/services/tasks.py b/tad/services/tasks.py new file mode 100644 index 000000000..fc52b66c7 --- /dev/null +++ b/tad/services/tasks.py @@ -0,0 +1,71 @@ +import logging +from collections.abc import Sequence +from typing import Annotated + +from fastapi import Depends + +from tad.models.task import Task +from tad.models.user import User +from tad.repositories.tasks import TasksRepository +from tad.services.statuses import StatusesService + +logger = logging.getLogger(__name__) + + +class TasksService: + def __init__( + self, + statuses_service: Annotated[StatusesService, Depends(StatusesService)], + repository: Annotated[TasksRepository, Depends(TasksRepository)], + ): + self.repository = repository + self.statuses_service = statuses_service + + def get_tasks(self, status_id: int) -> Sequence[Task]: + return self.repository.find_by_status_id(status_id) + + def assign_task(self, task: Task, user: User) -> Task: + task.user_id = user.id + return self.repository.save(task) + + def move_task( + self, task_id: int, status_id: int, previous_sibling_id: int | None = None, next_sibling_id: int | None = None + ) -> Task: + """ + Updates the task with the given task_id + :param task_id: the id of the task + :param status_id: the id of the status of the task + :param previous_sibling_id: the id of the previous sibling of the task + :param next_sibling_id: the id of the next sibling of the task + :return: the updated task + """ + status = self.statuses_service.get_status(status_id) + task = self.repository.find_by_id(task_id) + + if status.name == "done": + # TODO implement logic for done + logging.warning("Task is done, we need to update a system card") + + # assign the task to the current user + if status.name == "in_progress": + task.user_id = 1 + + # update the status for the task (this may not be needed if the status has not changed) + task.status_id = status_id + + # update order position of the card + if not previous_sibling_id and not next_sibling_id: + task.sort_order = 10 + elif previous_sibling_id and next_sibling_id: + previous_task = self.repository.find_by_id(previous_sibling_id) + next_task = self.repository.find_by_id(next_sibling_id) + new_sort_order = previous_task.sort_order + ((next_task.sort_order - previous_task.sort_order) / 2) + task.sort_order = new_sort_order + elif previous_sibling_id and not next_sibling_id: + previous_task = self.repository.find_by_id(previous_sibling_id) + task.sort_order = previous_task.sort_order + 10 + elif not previous_sibling_id and next_sibling_id: + next_task = self.repository.find_by_id(next_sibling_id) + task.sort_order = next_task.sort_order / 2 + + return self.repository.save(task) diff --git a/tad/site/static/css/10cols.css b/tad/site/static/css/10cols.css new file mode 100644 index 000000000..332c07085 --- /dev/null +++ b/tad/site/static/css/10cols.css @@ -0,0 +1,78 @@ +/* GRID OF TEN ============================================================================= */ + + +.span_10_of_10 { + width: 100%; +} + +.span_9_of_10 { + width: 89.84%; +} + +.span_8_of_10 { + width: 79.68%; +} + +.span_7_of_10 { + width: 69.52%; +} + +.span_6_of_10 { + width: 59.36%; +} + +.span_5_of_10 { + width: 49.2%; +} + +.span_4_of_10 { + width: 39.04%; +} + +.span_3_of_10 { + width: 28.88%; +} + +.span_2_of_10 { + width: 18.72%; +} + +.span_1_of_10 { + width: 8.56%; +} + + +/* GO FULL WIDTH AT LESS THAN 480 PIXELS */ + +@media only screen and (max-width: 480px) { + .span_10_of_10 { + width: 100%; + } + .span_9_of_10 { + width: 100%; + } + .span_8_of_10 { + width: 100%; + } + .span_7_of_10 { + width: 100%; + } + .span_6_of_10 { + width: 100%; + } + .span_5_of_10 { + width: 100%; + } + .span_4_of_10 { + width: 100%; + } + .span_3_of_10 { + width: 100%; + } + .span_2_of_10 { + width: 100%; + } + .span_1_of_10 { + width: 100%; + } +} diff --git a/tad/site/static/css/11cols.css b/tad/site/static/css/11cols.css new file mode 100644 index 000000000..a5624a7a9 --- /dev/null +++ b/tad/site/static/css/11cols.css @@ -0,0 +1,84 @@ +/* GRID OF ELEVEN ============================================================================= */ + +.span_11_of_11 { + width: 100%; +} + +.span_10_of_11 { + width: 90.76%; +} + +.span_9_of_11 { + width: 81.52%; +} + +.span_8_of_11 { + width: 72.29%; +} + +.span_7_of_11 { + width: 63.05%; +} + +.span_6_of_11 { + width: 53.81%; +} + +.span_5_of_11 { + width: 44.58%; +} + +.span_4_of_11 { + width: 35.34%; +} + +.span_3_of_11 { + width: 26.1%; +} + +.span_2_of_11 { + width: 16.87%; +} + +.span_1_of_11 { + width: 7.63%; +} + + +/* GO FULL WIDTH AT LESS THAN 480 PIXELS */ + +@media only screen and (max-width: 480px) { + .span_11_of_11 { + width: 100%; + } + .span_10_of_11 { + width: 100%; + } + .span_9_of_11 { + width: 100%; + } + .span_8_of_11 { + width: 100%; + } + .span_7_of_11 { + width: 100%; + } + .span_6_of_11 { + width: 100%; + } + .span_5_of_11 { + width: 100%; + } + .span_4_of_11 { + width: 100%; + } + .span_3_of_11 { + width: 100%; + } + .span_2_of_11 { + width: 100%; + } + .span_1_of_11 { + width: 100%; + } +} diff --git a/tad/site/static/css/12cols.css b/tad/site/static/css/12cols.css new file mode 100644 index 000000000..58299ba09 --- /dev/null +++ b/tad/site/static/css/12cols.css @@ -0,0 +1,91 @@ +/* GRID OF TWELVE ============================================================================= */ + +.span_12_of_12 { + width: 100%; +} + +.span_11_of_12 { + width: 91.53%; +} + +.span_10_of_12 { + width: 83.06%; +} + +.span_9_of_12 { + width: 74.6%; +} + +.span_8_of_12 { + width: 66.13%; +} + +.span_7_of_12 { + width: 57.66%; +} + +.span_6_of_12 { + width: 49.2%; +} + +.span_5_of_12 { + width: 40.73%; +} + +.span_4_of_12 { + width: 32.26%; +} + +.span_3_of_12 { + width: 23.8%; +} + +.span_2_of_12 { + width: 15.33%; +} + +.span_1_of_12 { + width: 6.86%; +} + + +/* GO FULL WIDTH AT LESS THAN 480 PIXELS */ + +@media only screen and (max-width: 480px) { + .span_12_of_12 { + width: 100%; + } + .span_11_of_12 { + width: 100%; + } + .span_10_of_12 { + width: 100%; + } + .span_9_of_12 { + width: 100%; + } + .span_8_of_12 { + width: 100%; + } + .span_7_of_12 { + width: 100%; + } + .span_6_of_12 { + width: 100%; + } + .span_5_of_12 { + width: 100%; + } + .span_4_of_12 { + width: 100%; + } + .span_3_of_12 { + width: 100%; + } + .span_2_of_12 { + width: 100%; + } + .span_1_of_12 { + width: 100%; + } +} diff --git a/tad/site/static/css/2cols.css b/tad/site/static/css/2cols.css new file mode 100644 index 000000000..995dc0cb4 --- /dev/null +++ b/tad/site/static/css/2cols.css @@ -0,0 +1,21 @@ +/* GRID OF TWO ============================================================================= */ + + +.span_2_of_2 { + width: 100%; +} + +.span_1_of_2 { + width: 49.2%; +} + +/* GO FULL WIDTH AT LESS THAN 480 PIXELS */ + +@media only screen and (max-width: 480px) { + .span_2_of_2 { + width: 100%; + } + .span_1_of_2 { + width: 100%; + } +} diff --git a/tad/site/static/css/3cols.css b/tad/site/static/css/3cols.css new file mode 100644 index 000000000..4a07902d2 --- /dev/null +++ b/tad/site/static/css/3cols.css @@ -0,0 +1,29 @@ +/* GRID OF THREE ============================================================================= */ + + +.span_3_of_3 { + width: 100%; +} + +.span_2_of_3 { + width: 66.13%; +} + +.span_1_of_3 { + width: 32.26%; +} + + +/* GO FULL WIDTH AT LESS THAN 480 PIXELS */ + +@media only screen and (max-width: 480px) { + .span_3_of_3 { + width: 100%; + } + .span_2_of_3 { + width: 100%; + } + .span_1_of_3 { + width: 100%; + } +} diff --git a/tad/site/static/css/4cols.css b/tad/site/static/css/4cols.css new file mode 100644 index 000000000..0f693919f --- /dev/null +++ b/tad/site/static/css/4cols.css @@ -0,0 +1,36 @@ +/* GRID OF FOUR ============================================================================= */ + + +.span_4_of_4 { + width: 100%; +} + +.span_3_of_4 { + width: 74.6%; +} + +.span_2_of_4 { + width: 49.2%; +} + +.span_1_of_4 { + width: 23.8%; +} + + +/* GO FULL WIDTH AT LESS THAN 480 PIXELS */ + +@media only screen and (max-width: 480px) { + .span_4_of_4 { + width: 100%; + } + .span_3_of_4 { + width: 100%; + } + .span_2_of_4 { + width: 100%; + } + .span_1_of_4 { + width: 100%; + } +} diff --git a/tad/site/static/css/5cols.css b/tad/site/static/css/5cols.css new file mode 100644 index 000000000..cd62f96ff --- /dev/null +++ b/tad/site/static/css/5cols.css @@ -0,0 +1,43 @@ +/* GRID OF FIVE ============================================================================= */ + + +.span_5_of_5 { + width: 100%; +} + +.span_4_of_5 { + width: 79.68%; +} + +.span_3_of_5 { + width: 59.36%; +} + +.span_2_of_5 { + width: 39.04%; +} + +.span_1_of_5 { + width: 18.72%; +} + + +/* GO FULL WIDTH AT LESS THAN 480 PIXELS */ + +@media only screen and (max-width: 480px) { + .span_5_of_5 { + width: 100%; + } + .span_4_of_5 { + width: 100%; + } + .span_3_of_5 { + width: 100%; + } + .span_2_of_5 { + width: 100%; + } + .span_1_of_5 { + width: 100%; + } +} diff --git a/tad/site/static/css/6cols.css b/tad/site/static/css/6cols.css new file mode 100644 index 000000000..7c46d9ab4 --- /dev/null +++ b/tad/site/static/css/6cols.css @@ -0,0 +1,50 @@ +/* GRID OF SIX ============================================================================= */ + + +.span_6_of_6 { + width: 100%; +} + +.span_5_of_6 { + width: 83.06%; +} + +.span_4_of_6 { + width: 66.13%; +} + +.span_3_of_6 { + width: 49.2%; +} + +.span_2_of_6 { + width: 32.26%; +} + +.span_1_of_6 { + width: 15.33%; +} + + +/* GO FULL WIDTH AT LESS THAN 480 PIXELS */ + +@media only screen and (max-width: 480px) { + .span_6_of_6 { + width: 100%; + } + .span_5_of_6 { + width: 100%; + } + .span_4_of_6 { + width: 100%; + } + .span_3_of_6 { + width: 100%; + } + .span_2_of_6 { + width: 100%; + } + .span_1_of_6 { + width: 100%; + } +} diff --git a/tad/site/static/css/7cols.css b/tad/site/static/css/7cols.css new file mode 100644 index 000000000..ae81184e3 --- /dev/null +++ b/tad/site/static/css/7cols.css @@ -0,0 +1,57 @@ +/* GRID OF SEVEN ============================================================================= */ + + +.span_7_of_7 { + width: 100%; +} + +.span_6_of_7 { + width: 85.48%; +} + +.span_5_of_7 { + width: 70.97%; +} + +.span_4_of_7 { + width: 56.45%; +} + +.span_3_of_7 { + width: 41.94%; +} + +.span_2_of_7 { + width: 27.42%; +} + +.span_1_of_7 { + width: 12.91%; +} + + +/* GO FULL WIDTH AT LESS THAN 480 PIXELS */ + +@media only screen and (max-width: 480px) { + .span_7_of_7 { + width: 100%; + } + .span_6_of_7 { + width: 100%; + } + .span_5_of_7 { + width: 100%; + } + .span_4_of_7 { + width: 100%; + } + .span_3_of_7 { + width: 100%; + } + .span_2_of_7 { + width: 100%; + } + .span_1_of_7 { + width: 100%; + } +} diff --git a/tad/site/static/css/8cols.css b/tad/site/static/css/8cols.css new file mode 100644 index 000000000..0ac2a476d --- /dev/null +++ b/tad/site/static/css/8cols.css @@ -0,0 +1,64 @@ +/* GRID OF EIGHT ============================================================================= */ + + +.span_8_of_8 { + width: 100%; +} + +.span_7_of_8 { + width: 87.3%; +} + +.span_6_of_8 { + width: 74.6%; +} + +.span_5_of_8 { + width: 61.9%; +} + +.span_4_of_8 { + width: 49.2%; +} + +.span_3_of_8 { + width: 36.5%; +} + +.span_2_of_8 { + width: 23.8%; +} + +.span_1_of_8 { + width: 11.1%; +} + + +/* GO FULL WIDTH AT LESS THAN 480 PIXELS */ + +@media only screen and (max-width: 480px) { + .span_8_of_8 { + width: 100%; + } + .span_7_of_8 { + width: 100%; + } + .span_6_of_8 { + width: 100%; + } + .span_5_of_8 { + width: 100%; + } + .span_4_of_8 { + width: 100%; + } + .span_3_of_8 { + width: 100%; + } + .span_2_of_8 { + width: 100%; + } + .span_1_of_8 { + width: 100%; + } +} diff --git a/tad/site/static/css/9cols.css b/tad/site/static/css/9cols.css new file mode 100644 index 000000000..25e834a5a --- /dev/null +++ b/tad/site/static/css/9cols.css @@ -0,0 +1,71 @@ +/* GRID OF NINE ============================================================================= */ + + +.span_9_of_9 { + width: 100%; +} + +.span_8_of_9 { + width: 88.71%; +} + +.span_7_of_9 { + width: 77.42%; +} + +.span_6_of_9 { + width: 66.13%; +} + +.span_5_of_9 { + width: 54.84%; +} + +.span_4_of_9 { + width: 43.55%; +} + +.span_3_of_9 { + width: 32.26%; +} + +.span_2_of_9 { + width: 20.97%; +} + +.span_1_of_9 { + width: 9.68%; +} + + +/* GO FULL WIDTH AT LESS THAN 480 PIXELS */ + +@media only screen and (max-width: 480px) { + .span_9_of_9 { + width: 100%; + } + .span_8_of_9 { + width: 100%; + } + .span_7_of_9 { + width: 100%; + } + .span_6_of_9 { + width: 100%; + } + .span_5_of_9 { + width: 100%; + } + .span_4_of_9 { + width: 100%; + } + .span_3_of_9 { + width: 100%; + } + .span_2_of_9 { + width: 100%; + } + .span_1_of_9 { + width: 100%; + } +} diff --git a/tad/site/static/css/col.css b/tad/site/static/css/col.css new file mode 100644 index 000000000..e07140a90 --- /dev/null +++ b/tad/site/static/css/col.css @@ -0,0 +1,42 @@ + +/* SECTIONS ============================================================================= */ + +.section { + clear: both; + padding: 0px; + margin: 0px; +} + +/* GROUPING ============================================================================= */ + + +.group:before, +.group:after { + content:""; + display:table; +} +.group:after { + clear:both; +} +.group { + zoom:1; /* For IE 6/7 (trigger hasLayout) */ +} + +/* GRID COLUMN SETUP ==================================================================== */ + +.col { + display: block; + float:left; + margin: 1% 0 1% 1.6%; +} + +.col:first-child { margin-left: 0; } /* all browsers except IE6 and lower */ + + +/* REMOVE MARGINS AS ALL GO FULL WIDTH AT 480 PIXELS */ + +@media only screen and (max-width: 480px) { + .col { + margin: 1% 0 1% 0%; + } +} diff --git a/tad/site/static/css/html5reset.css b/tad/site/static/css/html5reset.css new file mode 100644 index 000000000..1b135a09c --- /dev/null +++ b/tad/site/static/css/html5reset.css @@ -0,0 +1,96 @@ +/* html5reset.css - 01/11/2011 */ + +html, body, div, span, object, iframe, +h1, h2, h3, h4, h5, h6, p, blockquote, pre, +abbr, address, cite, code, +del, dfn, em, img, ins, kbd, q, samp, +small, strong, sub, sup, var, +b, i, +dl, dt, dd, ol, ul, li, +fieldset, form, label, legend, +table, caption, tbody, tfoot, thead, tr, th, td, +article, aside, canvas, details, figcaption, figure, +footer, header, hgroup, menu, nav, section, summary, +time, mark, audio, video { + margin: 0; + padding: 0; + border: 0; + outline: 0; + /*font-size: 100%;*/ + vertical-align: baseline; + background: transparent; +} + +body { + line-height: 1; +} + +article,aside,details,figcaption,figure, +footer,header,hgroup,menu,nav,section { + display: block; +} + +nav ul { + list-style: none; +} + +blockquote, q { + quotes: none; +} + +blockquote:before, blockquote:after, +q:before, q:after { + content: ''; + content: none; +} + +a { + margin: 0; + padding: 0; + font-size: 100%; + vertical-align: baseline; + background: transparent; +} + +/* change colours to suit your needs */ +ins { + background-color: #ff9; + color: #000; + text-decoration: none; +} + +/* change colours to suit your needs */ +mark { + background-color: #ff9; + color: #000; + font-style: italic; + font-weight: bold; +} + +del { + text-decoration: line-through; +} + +abbr[title], dfn[title] { + border-bottom: 1px dotted; + cursor: help; +} + +table { + border-collapse: collapse; + border-spacing: 0; +} + +/* change border colour to suit your needs */ +hr { + display: block; + height: 1px; + border: 0; + border-top: 1px solid #cccccc; + margin: 1em 0; + padding: 0; +} + +input, select { + vertical-align: middle; +} diff --git a/tad/site/static/css/layout.css b/tad/site/static/css/layout.css new file mode 100644 index 000000000..ba95ff452 --- /dev/null +++ b/tad/site/static/css/layout.css @@ -0,0 +1,113 @@ +@font-face { + font-family: "Rijksoverheid Sans"; + src: url(../fonts/ROsanswebtextregular.woff) format("opentype"); + font-style: normal; + font-weight: 400 +} + +@font-face { + font-family: "Rijksoverheid Sans"; + src: url(../fonts/ROsanswebtextitalic.woff) format("opentype"); + font-style: italic; + font-weight: 400 +} + +@font-face { + font-family: "Rijksoverheid Sans"; + src: url(../fonts/ROsanswebtextbold.woff) format("opentype"); + font-weight: 700; + font-style: normal +} + +body, html { + padding: 0; + margin: 0; + background-color: #FFFFFF; + font-family: "Rijksoverheid Sans", sans-serif; +} + +.header { + margin-bottom: 2em; + border-bottom-color: rgb(178, 215, 238); + border-bottom-style: solid; + border-bottom-width: 0.5em; +} + +.header_logo_container { + padding: 0.75em 0; +} + +.header_subtitle_container { + color: #154273; + font-size: 1.125em; + line-height: 1.5em; +} + +.header_logo_image { + width: 180px; + max-width: 180px; +} + +.container { + max-width: 74em; + margin: 0 auto; + padding: 0 1em; +} + +.header_nav { + background-color: rgb(0, 123, 199); + height: 50px; +} + +.visually-hidden { + display: none; +} + +.margin-bottom--large { + margin-bottom: 1em; +} + +.margin-bottom--small { + margin-bottom: 0.5em; +} + +.margin-bottom--extra-small { + margin-bottom: 0.25em; +} + +.progress_cards_container { + min-height: 30em; + background-color: rgb(229, 241, 249); + border-radius: 10px; + margin: 0 0.5em; + overflow: hidden; +} + +.progress_card_container { + margin: 0.5em; + border: 1px solid rgb(21, 66, 115); + padding: 0.5em; + border-radius: 10px; + background-color: #ffffff; + box-shadow: rgba(00, 00, 00, 0.12) 0 3px 6px 0; + cursor: move; + user-select: none; +} + +.progress_card_assignees_container { + display: flex; + justify-content: flex-end; +} + +.progress_card_assignees_image { + border-radius: 50%; + height: 35px; +} + +.text-center-horizontal { + text-align: center; +} + +.as-inline-block { + display: inline-block; +} diff --git a/tad/static/favicon.ico b/tad/site/static/favicon.ico similarity index 100% rename from tad/static/favicon.ico rename to tad/site/static/favicon.ico diff --git a/tad/site/static/fonts/ROsanswebtextbold.woff b/tad/site/static/fonts/ROsanswebtextbold.woff new file mode 100644 index 000000000..6f0e3c819 Binary files /dev/null and b/tad/site/static/fonts/ROsanswebtextbold.woff differ diff --git a/tad/site/static/fonts/ROsanswebtextitalic.woff b/tad/site/static/fonts/ROsanswebtextitalic.woff new file mode 100644 index 000000000..7e74d6692 Binary files /dev/null and b/tad/site/static/fonts/ROsanswebtextitalic.woff differ diff --git a/tad/site/static/fonts/ROsanswebtextregular.woff b/tad/site/static/fonts/ROsanswebtextregular.woff new file mode 100644 index 000000000..624c3f89a Binary files /dev/null and b/tad/site/static/fonts/ROsanswebtextregular.woff differ diff --git a/tad/site/static/images/img_avatar.png b/tad/site/static/images/img_avatar.png new file mode 100644 index 000000000..2b8318559 Binary files /dev/null and b/tad/site/static/images/img_avatar.png differ diff --git a/tad/site/static/images/img_avatar2.png b/tad/site/static/images/img_avatar2.png new file mode 100644 index 000000000..04ad35fab Binary files /dev/null and b/tad/site/static/images/img_avatar2.png differ diff --git a/tad/site/static/images/logo.svg b/tad/site/static/images/logo.svg new file mode 100644 index 000000000..f7cfde292 --- /dev/null +++ b/tad/site/static/images/logo.svg @@ -0,0 +1 @@ + diff --git a/tad/site/static/js/tad.js b/tad/site/static/js/tad.js new file mode 100644 index 000000000..7971e06f9 --- /dev/null +++ b/tad/site/static/js/tad.js @@ -0,0 +1,37 @@ +window.onload = function () { + + const columns = document.getElementsByClassName("progress_cards_container"); + for (var i = 0; i < columns.length; i++) { + new Sortable(columns[i], { + group: 'shared', // set both lists to same group + animation: 150, + onEnd: function (evt) { + console.log(evt); + let previousSiblingId = evt.item.previousElementSibling ? evt.item.previousElementSibling.getAttribute("data-id") : ""; + let nextSiblingId = evt.item.nextElementSibling ? evt.item.nextElementSibling.getAttribute("data-id") : ""; + let data = { + "taskId": evt.item.getAttribute("data-id"), + "statusId": evt.to.getAttribute("data-id"), + "previousSiblingId": previousSiblingId, + "nextSiblingId": nextSiblingId + } + + let headers = { + 'Content-Type': 'application/json' + }; + let targetId = "#" + evt.item.getAttribute("id"); + let form = document.getElementById("cardMovedForm"); + document.getElementsByName("taskId")[0].value = evt.item.getAttribute("data-id"); + document.getElementsByName("statusId")[0].value = evt.to.getAttribute("data-id"); + document.getElementsByName("previousSiblingId")[0].value = previousSiblingId; + document.getElementsByName("nextSiblingId")[0].value = nextSiblingId; + form.setAttribute("hx-target", targetId); + htmx.trigger("#cardMovedForm", "cardmoved"); + + // TODO: this must be a JSON post, but I can not get it to work with HTMX... + // https://htmx.org/api/#ajax + //htmx.ajax('POST', "/tasks/move", {values: JSON.stringify({ data: data }), headers: headers, target: targetId, swap: 'outerHTML'}) + } + }); + } +} diff --git a/tad/static/vendor/htmx/1.9.12.min.js b/tad/site/static/vendor/htmx/js/1.9.12.min.js similarity index 100% rename from tad/static/vendor/htmx/1.9.12.min.js rename to tad/site/static/vendor/htmx/js/1.9.12.min.js diff --git a/tad/site/static/vendor/htmx/js/htmx.min.js b/tad/site/static/vendor/htmx/js/htmx.min.js new file mode 100644 index 000000000..2519eec50 --- /dev/null +++ b/tad/site/static/vendor/htmx/js/htmx.min.js @@ -0,0 +1 @@ +(function(e,t){if(typeof define==="function"&&define.amd){define([],t)}else if(typeof module==="object"&&module.exports){module.exports=t()}else{e.htmx=e.htmx||t()}})(typeof self!=="undefined"?self:this,function(){return function(){"use strict";var Q={onLoad:B,process:zt,on:de,off:ge,trigger:ce,ajax:Nr,find:C,findAll:f,closest:v,values:function(e,t){var r=dr(e,t||"post");return r.values},remove:_,addClass:z,removeClass:n,toggleClass:$,takeClass:W,defineExtension:Ur,removeExtension:Fr,logAll:V,logNone:j,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",useTemplateFragments:false,scrollBehavior:"smooth",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get"],selfRequestsOnly:false,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null},parseInterval:d,_:t,createEventSource:function(e){return new EventSource(e,{withCredentials:true})},createWebSocket:function(e){var t=new WebSocket(e,[]);t.binaryType=Q.config.wsBinaryType;return t},version:"1.9.11"};var r={addTriggerHandler:Lt,bodyContains:se,canAccessLocalStorage:U,findThisElement:xe,filterValues:yr,hasAttribute:o,getAttributeValue:te,getClosestAttributeValue:ne,getClosestMatch:c,getExpressionVars:Hr,getHeaders:xr,getInputValues:dr,getInternalData:ae,getSwapSpecification:wr,getTriggerSpecs:it,getTarget:ye,makeFragment:l,mergeObjects:le,makeSettleInfo:T,oobSwap:Ee,querySelectorExt:ue,selectAndSwap:je,settleImmediately:nr,shouldCancel:ut,triggerEvent:ce,triggerErrorEvent:fe,withExtensions:R};var w=["get","post","put","delete","patch"];var i=w.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");var S=e("head"),q=e("title"),H=e("svg",true);function e(e,t=false){return new RegExp(`<${e}(\\s[^>]*>|>)([\\s\\S]*?)<\\/${e}>`,t?"gim":"im")}function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e.getAttribute&&e.getAttribute(t)}function o(e,t){return e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){return e.parentElement}function re(){return document}function c(e,t){while(e&&!t(e)){e=u(e)}return e?e:null}function L(e,t,r){var n=te(t,r);var i=te(t,"hx-disinherit");if(e!==t&&i&&(i==="*"||i.split(" ").indexOf(r)>=0)){return"unset"}else{return n}}function ne(t,r){var n=null;c(t,function(e){return n=L(t,e,r)});if(n!=="unset"){return n}}function h(e,t){var r=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;return r&&r.call(e,t)}function A(e){var t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;var r=t.exec(e);if(r){return r[1].toLowerCase()}else{return""}}function s(e,t){var r=new DOMParser;var n=r.parseFromString(e,"text/html");var i=n.body;while(t>0){t--;i=i.firstChild}if(i==null){i=re().createDocumentFragment()}return i}function N(e){return/",0);var a=i.querySelector("template").content;if(Q.config.allowScriptTags){oe(a.querySelectorAll("script"),function(e){if(Q.config.inlineScriptNonce){e.nonce=Q.config.inlineScriptNonce}e.htmxExecuted=navigator.userAgent.indexOf("Firefox")===-1})}else{oe(a.querySelectorAll("script"),function(e){_(e)})}return a}switch(r){case"thead":case"tbody":case"tfoot":case"colgroup":case"caption":return s(""+n+"
",1);case"col":return s(""+n+"
",2);case"tr":return s(""+n+"
",2);case"td":case"th":return s(""+n+"
",3);case"script":case"style":return s("
"+n+"
",1);default:return s(n,0)}}function ie(e){if(e){e()}}function I(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return I(e,"Function")}function P(e){return I(e,"Object")}function ae(e){var t="htmx-internal-data";var r=e[t];if(!r){r=e[t]={}}return r}function M(e){var t=[];if(e){for(var r=0;r=0}function se(e){if(e.getRootNode&&e.getRootNode()instanceof window.ShadowRoot){return re().body.contains(e.getRootNode().host)}else{return re().body.contains(e)}}function D(e){return e.trim().split(/\s+/)}function le(e,t){for(var r in t){if(t.hasOwnProperty(r)){e[r]=t[r]}}return e}function E(e){try{return JSON.parse(e)}catch(e){b(e);return null}}function U(){var e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function F(t){try{var e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function t(e){return Tr(re().body,function(){return eval(e)})}function B(t){var e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,r){if(console){console.log(t,e,r)}}}function j(){Q.logger=null}function C(e,t){if(t){return e.querySelector(t)}else{return C(re(),e)}}function f(e,t){if(t){return e.querySelectorAll(t)}else{return f(re(),e)}}function _(e,t){e=p(e);if(t){setTimeout(function(){_(e);e=null},t)}else{e.parentElement.removeChild(e)}}function z(e,t,r){e=p(e);if(r){setTimeout(function(){z(e,t);e=null},r)}else{e.classList&&e.classList.add(t)}}function n(e,t,r){e=p(e);if(r){setTimeout(function(){n(e,t);e=null},r)}else{if(e.classList){e.classList.remove(t);if(e.classList.length===0){e.removeAttribute("class")}}}}function $(e,t){e=p(e);e.classList.toggle(t)}function W(e,t){e=p(e);oe(e.parentElement.children,function(e){n(e,t)});z(e,t)}function v(e,t){e=p(e);if(e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&u(e));return null}}function g(e,t){return e.substring(0,t.length)===t}function G(e,t){return e.substring(e.length-t.length)===t}function J(e){var t=e.trim();if(g(t,"<")&&G(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function Z(e,t){if(t.indexOf("closest ")===0){return[v(e,J(t.substr(8)))]}else if(t.indexOf("find ")===0){return[C(e,J(t.substr(5)))]}else if(t==="next"){return[e.nextElementSibling]}else if(t.indexOf("next ")===0){return[K(e,J(t.substr(5)))]}else if(t==="previous"){return[e.previousElementSibling]}else if(t.indexOf("previous ")===0){return[Y(e,J(t.substr(9)))]}else if(t==="document"){return[document]}else if(t==="window"){return[window]}else if(t==="body"){return[document.body]}else{return re().querySelectorAll(J(t))}}var K=function(e,t){var r=re().querySelectorAll(t);for(var n=0;n=0;n--){var i=r[n];if(i.compareDocumentPosition(e)===Node.DOCUMENT_POSITION_FOLLOWING){return i}}};function ue(e,t){if(t){return Z(e,t)[0]}else{return Z(re().body,e)[0]}}function p(e){if(I(e,"String")){return C(e)}else{return e}}function ve(e,t,r){if(k(t)){return{target:re().body,event:e,listener:t}}else{return{target:p(e),event:t,listener:r}}}function de(t,r,n){jr(function(){var e=ve(t,r,n);e.target.addEventListener(e.event,e.listener)});var e=k(r);return e?r:n}function ge(t,r,n){jr(function(){var e=ve(t,r,n);e.target.removeEventListener(e.event,e.listener)});return k(r)?r:n}var pe=re().createElement("output");function me(e,t){var r=ne(e,t);if(r){if(r==="this"){return[xe(e,t)]}else{var n=Z(e,r);if(n.length===0){b('The selector "'+r+'" on '+t+" returned no matches!");return[pe]}else{return n}}}}function xe(e,t){return c(e,function(e){return te(e,t)!=null})}function ye(e){var t=ne(e,"hx-target");if(t){if(t==="this"){return xe(e,"hx-target")}else{return ue(e,t)}}else{var r=ae(e);if(r.boosted){return re().body}else{return e}}}function be(e){var t=Q.config.attributesToSettle;for(var r=0;r0){o=e.substr(0,e.indexOf(":"));t=e.substr(e.indexOf(":")+1,e.length)}else{o=e}var r=re().querySelectorAll(t);if(r){oe(r,function(e){var t;var r=i.cloneNode(true);t=re().createDocumentFragment();t.appendChild(r);if(!Se(o,e)){t=r}var n={shouldSwap:true,target:e,fragment:t};if(!ce(e,"htmx:oobBeforeSwap",n))return;e=n.target;if(n["shouldSwap"]){Be(o,e,e,t,a)}oe(a.elts,function(e){ce(e,"htmx:oobAfterSwap",n)})});i.parentNode.removeChild(i)}else{i.parentNode.removeChild(i);fe(re().body,"htmx:oobErrorNoTarget",{content:i})}return e}function Ce(e,t,r){var n=ne(e,"hx-select-oob");if(n){var i=n.split(",");for(var a=0;a0){var r=t.replace("'","\\'");var n=e.tagName.replace(":","\\:");var i=o.querySelector(n+"[id='"+r+"']");if(i&&i!==o){var a=e.cloneNode();we(e,i);s.tasks.push(function(){we(e,a)})}}})}function Oe(e){return function(){n(e,Q.config.addedClass);zt(e);Nt(e);qe(e);ce(e,"htmx:load")}}function qe(e){var t="[autofocus]";var r=h(e,t)?e:e.querySelector(t);if(r!=null){r.focus()}}function a(e,t,r,n){Te(e,r,n);while(r.childNodes.length>0){var i=r.firstChild;z(i,Q.config.addedClass);e.insertBefore(i,t);if(i.nodeType!==Node.TEXT_NODE&&i.nodeType!==Node.COMMENT_NODE){n.tasks.push(Oe(i))}}}function He(e,t){var r=0;while(r-1){var t=e.replace(H,"");var r=t.match(q);if(r){return r[2]}}}function je(e,t,r,n,i,a){i.title=Ve(n);var o=l(n);if(o){Ce(r,o,i);o=Fe(r,o,a);Re(o);return Be(e,r,t,o,i)}}function _e(e,t,r){var n=e.getResponseHeader(t);if(n.indexOf("{")===0){var i=E(n);for(var a in i){if(i.hasOwnProperty(a)){var o=i[a];if(!P(o)){o={value:o}}ce(r,a,o)}}}else{var s=n.split(",");for(var l=0;l0){var o=t[0];if(o==="]"){n--;if(n===0){if(a===null){i=i+"true"}t.shift();i+=")})";try{var s=Tr(e,function(){return Function(i)()},function(){return true});s.source=i;return s}catch(e){fe(re().body,"htmx:syntax:error",{error:e,source:i});return null}}}else if(o==="["){n++}if(Qe(o,a,r)){i+="(("+r+"."+o+") ? ("+r+"."+o+") : (window."+o+"))"}else{i=i+o}a=t.shift()}}}function y(e,t){var r="";while(e.length>0&&!t.test(e[0])){r+=e.shift()}return r}function tt(e){var t;if(e.length>0&&Ze.test(e[0])){e.shift();t=y(e,Ke).trim();e.shift()}else{t=y(e,x)}return t}var rt="input, textarea, select";function nt(e,t,r){var n=[];var i=Ye(t);do{y(i,Je);var a=i.length;var o=y(i,/[,\[\s]/);if(o!==""){if(o==="every"){var s={trigger:"every"};y(i,Je);s.pollInterval=d(y(i,/[,\[\s]/));y(i,Je);var l=et(e,i,"event");if(l){s.eventFilter=l}n.push(s)}else if(o.indexOf("sse:")===0){n.push({trigger:"sse",sseEvent:o.substr(4)})}else{var u={trigger:o};var l=et(e,i,"event");if(l){u.eventFilter=l}while(i.length>0&&i[0]!==","){y(i,Je);var f=i.shift();if(f==="changed"){u.changed=true}else if(f==="once"){u.once=true}else if(f==="consume"){u.consume=true}else if(f==="delay"&&i[0]===":"){i.shift();u.delay=d(y(i,x))}else if(f==="from"&&i[0]===":"){i.shift();if(Ze.test(i[0])){var c=tt(i)}else{var c=y(i,x);if(c==="closest"||c==="find"||c==="next"||c==="previous"){i.shift();var h=tt(i);if(h.length>0){c+=" "+h}}}u.from=c}else if(f==="target"&&i[0]===":"){i.shift();u.target=tt(i)}else if(f==="throttle"&&i[0]===":"){i.shift();u.throttle=d(y(i,x))}else if(f==="queue"&&i[0]===":"){i.shift();u.queue=y(i,x)}else if(f==="root"&&i[0]===":"){i.shift();u[f]=tt(i)}else if(f==="threshold"&&i[0]===":"){i.shift();u[f]=y(i,x)}else{fe(e,"htmx:syntax:error",{token:i.shift()})}}n.push(u)}}if(i.length===a){fe(e,"htmx:syntax:error",{token:i.shift()})}y(i,Je)}while(i[0]===","&&i.shift());if(r){r[t]=n}return n}function it(e){var t=te(e,"hx-trigger");var r=[];if(t){var n=Q.config.triggerSpecsCache;r=n&&n[t]||nt(e,t,n)}if(r.length>0){return r}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,rt)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function at(e){ae(e).cancelled=true}function ot(e,t,r){var n=ae(e);n.timeout=setTimeout(function(){if(se(e)&&n.cancelled!==true){if(!ct(r,e,Wt("hx:poll:trigger",{triggerSpec:r,target:e}))){t(e)}ot(e,t,r)}},r.pollInterval)}function st(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function lt(t,r,e){if(t.tagName==="A"&&st(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"){r.boosted=true;var n,i;if(t.tagName==="A"){n="get";i=ee(t,"href")}else{var a=ee(t,"method");n=a?a.toLowerCase():"get";if(n==="get"){}i=ee(t,"action")}e.forEach(function(e){ht(t,function(e,t){if(v(e,Q.config.disableSelector)){m(e);return}he(n,i,e,t)},r,e,true)})}}function ut(e,t){if(e.type==="submit"||e.type==="click"){if(t.tagName==="FORM"){return true}if(h(t,'input[type="submit"], button')&&v(t,"form")!==null){return true}if(t.tagName==="A"&&t.href&&(t.getAttribute("href")==="#"||t.getAttribute("href").indexOf("#")!==0)){return true}}return false}function ft(e,t){return ae(e).boosted&&e.tagName==="A"&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function ct(e,t,r){var n=e.eventFilter;if(n){try{return n.call(t,r)!==true}catch(e){fe(re().body,"htmx:eventFilter:error",{error:e,source:n.source});return true}}return false}function ht(a,o,e,s,l){var u=ae(a);var t;if(s.from){t=Z(a,s.from)}else{t=[a]}if(s.changed){t.forEach(function(e){var t=ae(e);t.lastValue=e.value})}oe(t,function(n){var i=function(e){if(!se(a)){n.removeEventListener(s.trigger,i);return}if(ft(a,e)){return}if(l||ut(e,a)){e.preventDefault()}if(ct(s,a,e)){return}var t=ae(e);t.triggerSpec=s;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(a)<0){t.handledFor.push(a);if(s.consume){e.stopPropagation()}if(s.target&&e.target){if(!h(e.target,s.target)){return}}if(s.once){if(u.triggeredOnce){return}else{u.triggeredOnce=true}}if(s.changed){var r=ae(n);if(r.lastValue===n.value){return}r.lastValue=n.value}if(u.delayed){clearTimeout(u.delayed)}if(u.throttle){return}if(s.throttle>0){if(!u.throttle){o(a,e);u.throttle=setTimeout(function(){u.throttle=null},s.throttle)}}else if(s.delay>0){u.delayed=setTimeout(function(){o(a,e)},s.delay)}else{ce(a,"htmx:trigger");o(a,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:s.trigger,listener:i,on:n});n.addEventListener(s.trigger,i)})}var vt=false;var dt=null;function gt(){if(!dt){dt=function(){vt=true};window.addEventListener("scroll",dt);setInterval(function(){if(vt){vt=false;oe(re().querySelectorAll("[hx-trigger='revealed'],[data-hx-trigger='revealed']"),function(e){pt(e)})}},200)}}function pt(t){if(!o(t,"data-hx-revealed")&&X(t)){t.setAttribute("data-hx-revealed","true");var e=ae(t);if(e.initHash){ce(t,"revealed")}else{t.addEventListener("htmx:afterProcessNode",function(e){ce(t,"revealed")},{once:true})}}}function mt(e,t,r){var n=D(r);for(var i=0;i=0){var t=wt(n);setTimeout(function(){xt(s,r,n+1)},t)}};t.onopen=function(e){n=0};ae(s).webSocket=t;t.addEventListener("message",function(e){if(yt(s)){return}var t=e.data;R(s,function(e){t=e.transformResponse(t,null,s)});var r=T(s);var n=l(t);var i=M(n.children);for(var a=0;a0){ce(u,"htmx:validation:halted",i);return}t.send(JSON.stringify(l));if(ut(e,u)){e.preventDefault()}})}else{fe(u,"htmx:noWebSocketSourceError")}}function wt(e){var t=Q.config.wsReconnectDelay;if(typeof t==="function"){return t(e)}if(t==="full-jitter"){var r=Math.min(e,6);var n=1e3*Math.pow(2,r);return n*Math.random()}b('htmx.config.wsReconnectDelay must either be a function or the string "full-jitter"')}function St(e,t,r){var n=D(r);for(var i=0;i0){setTimeout(i,n)}else{i()}}function Ht(t,i,e){var a=false;oe(w,function(r){if(o(t,"hx-"+r)){var n=te(t,"hx-"+r);a=true;i.path=n;i.verb=r;e.forEach(function(e){Lt(t,e,i,function(e,t){if(v(e,Q.config.disableSelector)){m(e);return}he(r,n,e,t)})})}});return a}function Lt(n,e,t,r){if(e.sseEvent){Rt(n,r,e.sseEvent)}else if(e.trigger==="revealed"){gt();ht(n,r,t,e);pt(n)}else if(e.trigger==="intersect"){var i={};if(e.root){i.root=ue(n,e.root)}if(e.threshold){i.threshold=parseFloat(e.threshold)}var a=new IntersectionObserver(function(e){for(var t=0;t0){t.polling=true;ot(n,r,e)}else{ht(n,r,t,e)}}function At(e){if(!e.htmxExecuted&&Q.config.allowScriptTags&&(e.type==="text/javascript"||e.type==="module"||e.type==="")){var t=re().createElement("script");oe(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}var r=e.parentElement;try{r.insertBefore(t,e)}catch(e){b(e)}finally{if(e.parentElement){e.parentElement.removeChild(e)}}}}function Nt(e){if(h(e,"script")){At(e)}oe(f(e,"script"),function(e){At(e)})}function It(e){var t=e.attributes;for(var r=0;r0){var o=n.shift();var s=o.match(/^\s*([a-zA-Z:\-\.]+:)(.*)/);if(a===0&&s){o.split(":");i=s[1].slice(0,-1);r[i]=s[2]}else{r[i]+=o}a+=Ft(o)}for(var l in r){Bt(e,l,r[l])}}}function jt(e){Ae(e);for(var t=0;tQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(re().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Yt(e){if(!U()){return null}e=F(e);var t=E(localStorage.getItem("htmx-history-cache"))||[];for(var r=0;r=200&&this.status<400){ce(re().body,"htmx:historyCacheMissLoad",o);var e=l(this.response);e=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;var t=Zt();var r=T(t);var n=Ve(this.response);if(n){var i=C("title");if(i){i.innerHTML=n}else{window.document.title=n}}Ue(t,e,r);nr(r.tasks);Jt=a;ce(re().body,"htmx:historyRestore",{path:a,cacheMiss:true,serverResponse:this.response})}else{fe(re().body,"htmx:historyCacheMissLoadError",o)}};e.send()}function ar(e){er();e=e||location.pathname+location.search;var t=Yt(e);if(t){var r=l(t.content);var n=Zt();var i=T(n);Ue(n,r,i);nr(i.tasks);document.title=t.title;setTimeout(function(){window.scrollTo(0,t.scroll)},0);Jt=e;ce(re().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{ir(e)}}}function or(e){var t=me(e,"hx-indicator");if(t==null){t=[e]}oe(t,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)+1;e.classList["add"].call(e.classList,Q.config.requestClass)});return t}function sr(e){var t=me(e,"hx-disabled-elt");if(t==null){t=[]}oe(t,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","")});return t}function lr(e,t){oe(e,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)-1;if(t.requestCount===0){e.classList["remove"].call(e.classList,Q.config.requestClass)}});oe(t,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)-1;if(t.requestCount===0){e.removeAttribute("disabled")}})}function ur(e,t){for(var r=0;r=0}function wr(e,t){var r=t?t:ne(e,"hx-swap");var n={swapStyle:ae(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ae(e).boosted&&!br(e)){n["show"]="top"}if(r){var i=D(r);if(i.length>0){for(var a=0;a0?l.join(":"):null;n["scroll"]=u;n["scrollTarget"]=f}else if(o.indexOf("show:")===0){var c=o.substr(5);var l=c.split(":");var h=l.pop();var f=l.length>0?l.join(":"):null;n["show"]=h;n["showTarget"]=f}else if(o.indexOf("focus-scroll:")===0){var v=o.substr("focus-scroll:".length);n["focusScroll"]=v=="true"}else if(a==0){n["swapStyle"]=o}else{b("Unknown modifier in hx-swap: "+o)}}}}return n}function Sr(e){return ne(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function Er(t,r,n){var i=null;R(r,function(e){if(i==null){i=e.encodeParameters(t,n,r)}});if(i!=null){return i}else{if(Sr(r)){return mr(n)}else{return pr(n)}}}function T(e){return{tasks:[],elts:[e]}}function Cr(e,t){var r=e[0];var n=e[e.length-1];if(t.scroll){var i=null;if(t.scrollTarget){i=ue(r,t.scrollTarget)}if(t.scroll==="top"&&(r||i)){i=i||r;i.scrollTop=0}if(t.scroll==="bottom"&&(n||i)){i=i||n;i.scrollTop=i.scrollHeight}}if(t.show){var i=null;if(t.showTarget){var a=t.showTarget;if(t.showTarget==="window"){a="body"}i=ue(r,a)}if(t.show==="top"&&(r||i)){i=i||r;i.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(n||i)){i=i||n;i.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function Rr(e,t,r,n){if(n==null){n={}}if(e==null){return n}var i=te(e,t);if(i){var a=i.trim();var o=r;if(a==="unset"){return null}if(a.indexOf("javascript:")===0){a=a.substr(11);o=true}else if(a.indexOf("js:")===0){a=a.substr(3);o=true}if(a.indexOf("{")!==0){a="{"+a+"}"}var s;if(o){s=Tr(e,function(){return Function("return ("+a+")")()},{})}else{s=E(a)}for(var l in s){if(s.hasOwnProperty(l)){if(n[l]==null){n[l]=s[l]}}}}return Rr(u(e),t,r,n)}function Tr(e,t,r){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return r}}function Or(e,t){return Rr(e,"hx-vars",true,t)}function qr(e,t){return Rr(e,"hx-vals",false,t)}function Hr(e){return le(Or(e),qr(e))}function Lr(t,r,n){if(n!==null){try{t.setRequestHeader(r,n)}catch(e){t.setRequestHeader(r,encodeURIComponent(n));t.setRequestHeader(r+"-URI-AutoEncoded","true")}}}function Ar(t){if(t.responseURL&&typeof URL!=="undefined"){try{var e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(re().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function O(e,t){return t.test(e.getAllResponseHeaders())}function Nr(e,t,r){e=e.toLowerCase();if(r){if(r instanceof Element||I(r,"String")){return he(e,t,null,null,{targetOverride:p(r),returnPromise:true})}else{return he(e,t,p(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:p(r.target),swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return he(e,t,null,null,{returnPromise:true})}}function Ir(e){var t=[];while(e){t.push(e);e=e.parentElement}return t}function kr(e,t,r){var n;var i;if(typeof URL==="function"){i=new URL(t,document.location.href);var a=document.location.origin;n=a===i.origin}else{i=t;n=g(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!n){return false}}return ce(e,"htmx:validateUrl",le({url:i,sameHost:n},r))}function he(t,r,n,i,a,e){var o=null;var s=null;a=a!=null?a:{};if(a.returnPromise&&typeof Promise!=="undefined"){var l=new Promise(function(e,t){o=e;s=t})}if(n==null){n=re().body}var M=a.handler||Mr;var X=a.select||null;if(!se(n)){ie(o);return l}var u=a.targetOverride||ye(n);if(u==null||u==pe){fe(n,"htmx:targetError",{target:te(n,"hx-target")});ie(s);return l}var f=ae(n);var c=f.lastButtonClicked;if(c){var h=ee(c,"formaction");if(h!=null){r=h}var v=ee(c,"formmethod");if(v!=null){if(v.toLowerCase()!=="dialog"){t=v}}}var d=ne(n,"hx-confirm");if(e===undefined){var D=function(e){return he(t,r,n,i,a,!!e)};var U={target:u,elt:n,path:r,verb:t,triggeringEvent:i,etc:a,issueRequest:D,question:d};if(ce(n,"htmx:confirm",U)===false){ie(o);return l}}var g=n;var p=ne(n,"hx-sync");var m=null;var x=false;if(p){var F=p.split(":");var B=F[0].trim();if(B==="this"){g=xe(n,"hx-sync")}else{g=ue(n,B)}p=(F[1]||"drop").trim();f=ae(g);if(p==="drop"&&f.xhr&&f.abortable!==true){ie(o);return l}else if(p==="abort"){if(f.xhr){ie(o);return l}else{x=true}}else if(p==="replace"){ce(g,"htmx:abort")}else if(p.indexOf("queue")===0){var V=p.split(" ");m=(V[1]||"last").trim()}}if(f.xhr){if(f.abortable){ce(g,"htmx:abort")}else{if(m==null){if(i){var y=ae(i);if(y&&y.triggerSpec&&y.triggerSpec.queue){m=y.triggerSpec.queue}}if(m==null){m="last"}}if(f.queuedRequests==null){f.queuedRequests=[]}if(m==="first"&&f.queuedRequests.length===0){f.queuedRequests.push(function(){he(t,r,n,i,a)})}else if(m==="all"){f.queuedRequests.push(function(){he(t,r,n,i,a)})}else if(m==="last"){f.queuedRequests=[];f.queuedRequests.push(function(){he(t,r,n,i,a)})}ie(o);return l}}var b=new XMLHttpRequest;f.xhr=b;f.abortable=x;var w=function(){f.xhr=null;f.abortable=false;if(f.queuedRequests!=null&&f.queuedRequests.length>0){var e=f.queuedRequests.shift();e()}};var j=ne(n,"hx-prompt");if(j){var S=prompt(j);if(S===null||!ce(n,"htmx:prompt",{prompt:S,target:u})){ie(o);w();return l}}if(d&&!e){if(!confirm(d)){ie(o);w();return l}}var E=xr(n,u,S);if(t!=="get"&&!Sr(n)){E["Content-Type"]="application/x-www-form-urlencoded"}if(a.headers){E=le(E,a.headers)}var _=dr(n,t);var C=_.errors;var R=_.values;if(a.values){R=le(R,a.values)}var z=Hr(n);var $=le(R,z);var T=yr($,n);if(Q.config.getCacheBusterParam&&t==="get"){T["org.htmx.cache-buster"]=ee(u,"id")||"true"}if(r==null||r===""){r=re().location.href}var O=Rr(n,"hx-request");var W=ae(n).boosted;var q=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;var H={boosted:W,useUrlParams:q,parameters:T,unfilteredParameters:$,headers:E,target:u,verb:t,errors:C,withCredentials:a.credentials||O.credentials||Q.config.withCredentials,timeout:a.timeout||O.timeout||Q.config.timeout,path:r,triggeringEvent:i};if(!ce(n,"htmx:configRequest",H)){ie(o);w();return l}r=H.path;t=H.verb;E=H.headers;T=H.parameters;C=H.errors;q=H.useUrlParams;if(C&&C.length>0){ce(n,"htmx:validation:halted",H);ie(o);w();return l}var G=r.split("#");var J=G[0];var L=G[1];var A=r;if(q){A=J;var Z=Object.keys(T).length!==0;if(Z){if(A.indexOf("?")<0){A+="?"}else{A+="&"}A+=pr(T);if(L){A+="#"+L}}}if(!kr(n,A,H)){fe(n,"htmx:invalidPath",H);ie(s);return l}b.open(t.toUpperCase(),A,true);b.overrideMimeType("text/html");b.withCredentials=H.withCredentials;b.timeout=H.timeout;if(O.noHeaders){}else{for(var N in E){if(E.hasOwnProperty(N)){var K=E[N];Lr(b,N,K)}}}var I={xhr:b,target:u,requestConfig:H,etc:a,boosted:W,select:X,pathInfo:{requestPath:r,finalRequestPath:A,anchor:L}};b.onload=function(){try{var e=Ir(n);I.pathInfo.responsePath=Ar(b);M(n,I);lr(k,P);ce(n,"htmx:afterRequest",I);ce(n,"htmx:afterOnLoad",I);if(!se(n)){var t=null;while(e.length>0&&t==null){var r=e.shift();if(se(r)){t=r}}if(t){ce(t,"htmx:afterRequest",I);ce(t,"htmx:afterOnLoad",I)}}ie(o);w()}catch(e){fe(n,"htmx:onLoadError",le({error:e},I));throw e}};b.onerror=function(){lr(k,P);fe(n,"htmx:afterRequest",I);fe(n,"htmx:sendError",I);ie(s);w()};b.onabort=function(){lr(k,P);fe(n,"htmx:afterRequest",I);fe(n,"htmx:sendAbort",I);ie(s);w()};b.ontimeout=function(){lr(k,P);fe(n,"htmx:afterRequest",I);fe(n,"htmx:timeout",I);ie(s);w()};if(!ce(n,"htmx:beforeRequest",I)){ie(o);w();return l}var k=or(n);var P=sr(n);oe(["loadstart","loadend","progress","abort"],function(t){oe([b,b.upload],function(e){e.addEventListener(t,function(e){ce(n,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});ce(n,"htmx:beforeSend",I);var Y=q?null:Er(b,n,T);b.send(Y);return l}function Pr(e,t){var r=t.xhr;var n=null;var i=null;if(O(r,/HX-Push:/i)){n=r.getResponseHeader("HX-Push");i="push"}else if(O(r,/HX-Push-Url:/i)){n=r.getResponseHeader("HX-Push-Url");i="push"}else if(O(r,/HX-Replace-Url:/i)){n=r.getResponseHeader("HX-Replace-Url");i="replace"}if(n){if(n==="false"){return{}}else{return{type:i,path:n}}}var a=t.pathInfo.finalRequestPath;var o=t.pathInfo.responsePath;var s=ne(e,"hx-push-url");var l=ne(e,"hx-replace-url");var u=ae(e).boosted;var f=null;var c=null;if(s){f="push";c=s}else if(l){f="replace";c=l}else if(u){f="push";c=o||a}if(c){if(c==="false"){return{}}if(c==="true"){c=o||a}if(t.pathInfo.anchor&&c.indexOf("#")===-1){c=c+"#"+t.pathInfo.anchor}return{type:f,path:c}}else{return{}}}function Mr(l,u){var f=u.xhr;var c=u.target;var e=u.etc;var t=u.requestConfig;var h=u.select;if(!ce(l,"htmx:beforeOnLoad",u))return;if(O(f,/HX-Trigger:/i)){_e(f,"HX-Trigger",l)}if(O(f,/HX-Location:/i)){er();var r=f.getResponseHeader("HX-Location");var v;if(r.indexOf("{")===0){v=E(r);r=v["path"];delete v["path"]}Nr("GET",r,v).then(function(){tr(r)});return}var n=O(f,/HX-Refresh:/i)&&"true"===f.getResponseHeader("HX-Refresh");if(O(f,/HX-Redirect:/i)){location.href=f.getResponseHeader("HX-Redirect");n&&location.reload();return}if(n){location.reload();return}if(O(f,/HX-Retarget:/i)){if(f.getResponseHeader("HX-Retarget")==="this"){u.target=l}else{u.target=ue(l,f.getResponseHeader("HX-Retarget"))}}var d=Pr(l,u);var i=f.status>=200&&f.status<400&&f.status!==204;var g=f.response;var a=f.status>=400;var p=Q.config.ignoreTitle;var o=le({shouldSwap:i,serverResponse:g,isError:a,ignoreTitle:p},u);if(!ce(c,"htmx:beforeSwap",o))return;c=o.target;g=o.serverResponse;a=o.isError;p=o.ignoreTitle;u.target=c;u.failed=a;u.successful=!a;if(o.shouldSwap){if(f.status===286){at(l)}R(l,function(e){g=e.transformResponse(g,f,l)});if(d.type){er()}var s=e.swapOverride;if(O(f,/HX-Reswap:/i)){s=f.getResponseHeader("HX-Reswap")}var v=wr(l,s);if(v.hasOwnProperty("ignoreTitle")){p=v.ignoreTitle}c.classList.add(Q.config.swappingClass);var m=null;var x=null;var y=function(){try{var e=document.activeElement;var t={};try{t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null}}catch(e){}var r;if(h){r=h}if(O(f,/HX-Reselect:/i)){r=f.getResponseHeader("HX-Reselect")}if(d.type){ce(re().body,"htmx:beforeHistoryUpdate",le({history:d},u));if(d.type==="push"){tr(d.path);ce(re().body,"htmx:pushedIntoHistory",{path:d.path})}else{rr(d.path);ce(re().body,"htmx:replacedInHistory",{path:d.path})}}var n=T(c);je(v.swapStyle,c,l,g,n,r);if(t.elt&&!se(t.elt)&&ee(t.elt,"id")){var i=document.getElementById(ee(t.elt,"id"));var a={preventScroll:v.focusScroll!==undefined?!v.focusScroll:!Q.config.defaultFocusScroll};if(i){if(t.start&&i.setSelectionRange){try{i.setSelectionRange(t.start,t.end)}catch(e){}}i.focus(a)}}c.classList.remove(Q.config.swappingClass);oe(n.elts,function(e){if(e.classList){e.classList.add(Q.config.settlingClass)}ce(e,"htmx:afterSwap",u)});if(O(f,/HX-Trigger-After-Swap:/i)){var o=l;if(!se(l)){o=re().body}_e(f,"HX-Trigger-After-Swap",o)}var s=function(){oe(n.tasks,function(e){e.call()});oe(n.elts,function(e){if(e.classList){e.classList.remove(Q.config.settlingClass)}ce(e,"htmx:afterSettle",u)});if(u.pathInfo.anchor){var e=re().getElementById(u.pathInfo.anchor);if(e){e.scrollIntoView({block:"start",behavior:"auto"})}}if(n.title&&!p){var t=C("title");if(t){t.innerHTML=n.title}else{window.document.title=n.title}}Cr(n.elts,v);if(O(f,/HX-Trigger-After-Settle:/i)){var r=l;if(!se(l)){r=re().body}_e(f,"HX-Trigger-After-Settle",r)}ie(m)};if(v.settleDelay>0){setTimeout(s,v.settleDelay)}else{s()}}catch(e){fe(l,"htmx:swapError",u);ie(x);throw e}};var b=Q.config.globalViewTransitions;if(v.hasOwnProperty("transition")){b=v.transition}if(b&&ce(l,"htmx:beforeTransition",u)&&typeof Promise!=="undefined"&&document.startViewTransition){var w=new Promise(function(e,t){m=e;x=t});var S=y;y=function(){document.startViewTransition(function(){S();return w})}}if(v.swapDelay>0){setTimeout(y,v.swapDelay)}else{y()}}if(a){fe(l,"htmx:responseError",le({error:"Response Status Error Code "+f.status+" from "+u.pathInfo.requestPath},u))}}var Xr={};function Dr(){return{init:function(e){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,r){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,r,n){return false},encodeParameters:function(e,t,r){return null}}}function Ur(e,t){if(t.init){t.init(r)}Xr[e]=le(Dr(),t)}function Fr(e){delete Xr[e]}function Br(e,r,n){if(e==undefined){return r}if(r==undefined){r=[]}if(n==undefined){n=[]}var t=te(e,"hx-ext");if(t){oe(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){n.push(e.slice(7));return}if(n.indexOf(e)<0){var t=Xr[e];if(t&&r.indexOf(t)<0){r.push(t)}}})}return Br(u(e),r,n)}var Vr=false;re().addEventListener("DOMContentLoaded",function(){Vr=true});function jr(e){if(Vr||re().readyState==="complete"){e()}else{re().addEventListener("DOMContentLoaded",e)}}function _r(){if(Q.config.includeIndicatorStyles!==false){re().head.insertAdjacentHTML("beforeend","")}}function zr(){var e=re().querySelector('meta[name="htmx-config"]');if(e){return E(e.content)}else{return null}}function $r(){var e=zr();if(e){Q.config=le(Q.config,e)}}jr(function(){$r();_r();var e=re().body;zt(e);var t=re().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){var t=e.target;var r=ae(t);if(r&&r.xhr){r.xhr.abort()}});const r=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){ar();oe(t,function(e){ce(e,"htmx:restored",{document:re(),triggerEvent:ce})})}else{if(r){r(e)}}};setTimeout(function(){ce(e,"htmx:load",{});e=null},0)});return Q}()}); diff --git a/tad/site/static/vendor/htmx/js/hyperscript.min.js b/tad/site/static/vendor/htmx/js/hyperscript.min.js new file mode 100644 index 000000000..9e11f0b5e --- /dev/null +++ b/tad/site/static/vendor/htmx/js/hyperscript.min.js @@ -0,0 +1 @@ +(function(e,r){if(typeof define==="function"&&define.amd){define([],r)}else{e._hyperscript=r()}})(typeof self!=="undefined"?self:this,function(){return function(){"use strict";function M(e,r){for(var t in r){if(r.hasOwnProperty(t)){e[t]=r[t]}}return e}function r(e){try{return JSON.parse(e)}catch(e){t(e);return null}}function t(e){if(console.error){console.error(e)}else if(console.log){console.log("ERROR: ",e)}}function u(e,r){return new(e.bind.apply(e,[e].concat(r)))}var _=typeof self!=="undefined"?self:typeof global!=="undefined"?global:this;var j=function(){var b={"+":"PLUS","-":"MINUS","*":"MULTIPLY","/":"DIVIDE",".":"PERIOD","..":"ELLIPSIS","\\":"BACKSLASH",":":"COLON","%":"PERCENT","|":"PIPE","!":"EXCLAMATION","?":"QUESTION","#":"POUND","&":"AMPERSAND",$:"DOLLAR",";":"SEMI",",":"COMMA","(":"L_PAREN",")":"R_PAREN","<":"L_ANG",">":"R_ANG","<=":"LTE_ANG",">=":"GTE_ANG","==":"EQ","===":"EQQ","!=":"NEQ","!==":"NEQQ","{":"L_BRACE","}":"R_BRACE","[":"L_BRACKET","]":"R_BRACKET","=":"EQUALS"};function w(e){return R(e)||C(e)||e==="-"||e==="_"||e===":"}function N(e){return R(e)||C(e)||e==="-"||e==="_"||e===":"}function I(e){return e===" "||e==="\t"||A(e)}function O(e){return"[Line: "+e.line+", Column: "+e.col+"]"}function A(e){return e==="\r"||e==="\n"}function C(e){return e>="0"&&e<="9"}function R(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}function S(e){return e==="_"||e==="$"}function L(e){return e==="`"||e==="^"}function P(i,o,e){u();var r=null;function u(){while(y(0,true).type==="WHITESPACE"){o.push(i.shift())}}function s(e,r){D.raiseParseError(e,r)}function t(e){var r=l(e);if(r){return r}else{s(this,"Expected '"+e+"' but found '"+k().value+"'")}}function n(e,r,t){for(var n=0;n=0){return v()}}function p(e,r){var t=m(e,r);if(t){return t}else{s(this,"Expected '"+e+"' but found '"+k().value+"'")}}function m(e,r){var r=r||"IDENTIFIER";if(k()&&k().value===e&&k().type===r){return v()}}function v(){var e=i.shift();o.push(e);r=e;u();return e}function h(e,r){var t=[];var n=y(0,true);while((r==null||n.type!==r)&&(e==null||n.value!==e)&&n.type!=="EOF"){var a=i.shift();o.push(a);t.push(n);n=y(0,true)}u();return t}function d(){if(o[o.length-1]&&o[o.length-1].type==="WHITESPACE"){return o[o.length-1].value}else{return""}}function E(){return h(null,"WHITESPACE")}function T(){return i.length>0}function y(e,r){var t;var n=0;do{if(!r){while(i[n]&&i[n].type==="WHITESPACE"){n++}}t=i[n];e--;n++}while(e>-1);if(t){return t}else{return{type:"EOF",value:"<<>>"}}}function k(){return y(0)}function x(){return r}function g(){return e.substring(this.startToken.start,this.endToken.end)}function q(){return e.split("\n")[this.startToken.line-1]}return{matchAnyToken:a,matchAnyOpToken:n,matchOpToken:l,requireOpToken:t,matchTokenType:f,requireTokenType:c,consumeToken:v,matchToken:m,requireToken:p,list:i,consumed:o,source:e,hasMore:T,currentToken:k,lastMatch:x,token:y,consumeUntil:h,consumeUntilWhitespace:E,lastWhitespace:d,sourceFor:g,lineFor:q}}function F(e){if(e.length>0){var r=e[e.length-1];if(r.type==="IDENTIFIER"||r.type==="CLASS_REF"||r.type==="ID_REF"){return false}if(r.op&&(r.value===">"||r.value===")")){return false}}return true}function e(e,r){var t=[];var n=e;var a=0;var i=0;var o=1;var u="";var s=0;function l(){return r&&s===0}while(a0){var i=r.shift();var o=a[i];if(o==null){o={};a[i]=o}a=o}a[t]=n}function C(e,r){var t=[];var n=e;while(n.meta.caller){n=n.meta.caller}if(n.meta.traceMap){return n.meta.traceMap.get(r,t)}}function R(e,r){var a=[];var t=null;while(e!=null){a.push(e);t=e;e=e.meta.caller}if(t.meta.traceMap==null){t.meta.traceMap=new Map}if(!t.meta.traceMap.get(r)){var n={trace:a,print:function(e){e=e||console.error;e("hypertrace /// ");var r=0;for(var t=0;t",n.meta.feature.displayName.padEnd(r+2),"-",n.meta.owner)}}};t.meta.traceMap.set(r,n)}}function S(e){return e.replace(/:/g,function(e){return"\\"+e})}function L(e,r){if(e==null){throw new Error(r.sourceFor()+" is null")}}function P(e){return e==undefined||e.length===0}var F="document"in _?document.currentScript.src:null;return{typeCheck:w,forEach:n,triggerEvent:o,matchesSelector:t,getScript:c,processNode:g,evaluate:x,parse:k,getScriptSelector:E,resolveSymbol:N,makeContext:d,findNext:I,unifiedEval:e,convertValue:T,unifiedExec:v,resolveProperty:O,assignToNamespace:A,registerHyperTrace:R,getHyperTrace:C,getInternalData:b,escapeSelector:S,nullCheck:L,isEmpty:P,hyperscriptUrl:F,HALT:l}}();{D.addLeafExpression("parenthesized",function(e,r,t){if(t.matchOpToken("(")){var n=e.requireElement("expression",t);t.requireOpToken(")");return{type:"parenthesized",expr:n,evaluate:function(e){return n.evaluate(e)}}}});D.addLeafExpression("string",function(e,r,t){var n=t.matchTokenType("STRING");if(n){var a=n.value;if(n.template){var i=j.tokenize(a,true);var o=e.parseStringTemplate(i)}else{var o=[]}return{type:"string",token:n,args:o,op:function(e){var r="";for(var t=1;t");var i=a.map(function(e){if(e.type==="STRING"){return'"'+e.value+'"'}else{return e.value}}).join("");return{type:"queryRef",css:i,evaluate:function(){return document.querySelectorAll(this.css)}}}});D.addGrammarElement("attributeRef",function(e,r,t){if(t.matchOpToken("[")){var n=t.consumeUntil("]");var a=n.map(function(e){return e.value}).join("");var i=a.split("=");var o=i[0];var u=i[1];t.requireOpToken("]");return{type:"attribute_expression",name:o,value:u,args:[u],op:function(e,r){if(this.value){return{name:this.name,value:r}}else{return{name:this.name}}},evaluate:function(e){return r.unifiedEval(this,e)}}}});D.addGrammarElement("objectKey",function(e,r,t){var n;if(n=t.matchTokenType("STRING")){return{type:"objectKey",key:n.value,evaluate:function(){return this.key}}}else if(t.matchOpToken("[")){var a=e.parseElement("expression",t);t.requireOpToken("]");return{type:"objectKey",expr:a,args:[a],op:function(e,r){return r},evaluate:function(e){return r.unifiedEval(this,e)}}}else{var i="";do{n=t.matchTokenType("IDENTIFIER")||t.matchOpToken("-");if(n)i+=n.value}while(n);return{type:"objectKey",key:i,evaluate:function(){return this.key}}}});D.addLeafExpression("objectLiteral",function(e,r,t){if(t.matchOpToken("{")){var n=[];var a=[];if(!t.matchOpToken("}")){do{var i=e.requireElement("objectKey",t);t.requireOpToken(":");var o=e.requireElement("expression",t);a.push(o);n.push(i)}while(t.matchOpToken(","));t.requireOpToken("}")}return{type:"objectLiteral",args:[n,a],op:function(e,r,t){var n={};for(var a=0;a");var i=e.requireElement("expression",t);return{type:"blockLiteral",args:n,expr:i,evaluate:function(r){var e=function(){for(var e=0;e0){return n}else{return null}},evaluate:function(e){return a.unifiedEval(this,e)}};return e.parseElement("indirectExpression",r,n)}});D.addIndirectExpression("asExpression",function(e,t,r,n){if(r.matchToken("as")){var a=e.requireElement("dotOrColonPath",r).evaluate();var i={type:"asExpression",root:n,args:[n],op:function(e,r){return t.convertValue(r,a)},evaluate:function(e){return t.unifiedEval(this,e)}};return e.parseElement("indirectExpression",r,i)}});D.addIndirectExpression("functionCall",function(e,a,r,i){if(r.matchOpToken("(")){var t=[];if(!r.matchOpToken(")")){do{t.push(e.requireElement("expression",r))}while(r.matchOpToken(","));r.requireOpToken(")")}if(i.root){var n={type:"functionCall",root:i,argExressions:t,args:[i.root,t],op:function(e,r,t){a.nullCheck(r,i.root);var n=r[i.prop.value];a.nullCheck(n,i);if(n.hyperfunc){t.push(e)}return n.apply(r,t)},evaluate:function(e){return a.unifiedEval(this,e)}}}else{var n={type:"functionCall",root:i,argExressions:t,args:[i,t],op:function(e,r,t){a.nullCheck(r,i);if(r.hyperfunc){t.push(e)}var n=r.apply(null,t);return n},evaluate:function(e){return a.unifiedEval(this,e)}}}return e.parseElement("indirectExpression",r,n)}});D.addIndirectExpression("arrayIndex",function(e,r,t,n){if(t.matchOpToken("[")){var a=false;var i=false;var o=null;var u=null;if(t.matchOpToken("..")){a=true;o=e.requireElement("expression",t)}else{o=e.requireElement("expression",t);if(t.matchOpToken("..")){i=true;var s=t.currentToken();if(s.type!=="R_BRACKET"){u=e.parseElement("expression",t)}}}t.requireOpToken("]");var l={type:"arrayIndex",root:n,firstIndex:o,secondIndex:u,args:[n,o,u],op:function(e,r,t,n){if(a){return r.slice(0,t+1)}else if(i){if(n!=null){return r.slice(t,n+1)}else{return r.slice(t)}}else{return r[t]}},evaluate:function(e){return G.unifiedEval(this,e,o,u)}};return D.parseElement("indirectExpression",t,l)}});D.addGrammarElement("postfixExpression",function(e,n,r){var t=e.parseElement("primaryExpression",r);if(r.matchOpToken(":")){var a=r.requireTokenType("IDENTIFIER");var i=!r.matchOpToken("!");return{type:"typeCheck",typeName:a,root:t,nullOk:i,args:[t],op:function(e,r){var t=n.typeCheck(r,this.typeName.value,this.nullOk);if(t){return r}else{throw new Error("Typecheck failed! Expected: "+this.typeName.value)}},evaluate:function(e){return n.unifiedEval(this,e)}}}else{return t}});D.addGrammarElement("logicalNot",function(e,r,t){if(t.matchToken("not")){var n=e.requireElement("unaryExpression",t);return{type:"logicalNot",root:n,args:[n],op:function(e,r){return!r},evaluate:function(e){return r.unifiedEval(this,e)}}}});D.addGrammarElement("noExpression",function(e,t,r){if(r.matchToken("no")){var n=e.requireElement("unaryExpression",r);return{type:"noExpression",root:n,args:[n],op:function(e,r){return t.isEmpty(r)},evaluate:function(e){return t.unifiedEval(this,e)}}}});D.addGrammarElement("negativeNumber",function(e,r,t){if(t.matchOpToken("-")){var n=e.requireElement("unaryExpression",t);return{type:"negativeNumber",root:n,args:[n],op:function(e,r){return-1*r},evaluate:function(e){return r.unifiedEval(this,e)}}}});D.addGrammarElement("unaryExpression",function(e,r,t){return e.parseAnyOf(["logicalNot","positionalExpression","noExpression","negativeNumber","postfixExpression"],t)});D.addGrammarElement("positionalExpression",function(e,r,t){var n=t.matchAnyToken("first","last","random");if(n){t.matchAnyToken("in","from","of");var a=e.requireElement("unaryExpression",t);return{type:"positionalExpression",rhs:a,operator:n.value,args:[a],op:function(e,r){if(!Array.isArray(r)){if(r.children){r=r.children}else{r=Array.from(r)}}if(this.operator==="first"){return r[0]}else if(this.operator==="last"){return r[r.length-1]}else if(this.operator==="random"){return r[Math.floor(Math.random()*r.length)]}},evaluate:function(e){return r.unifiedEval(this,e)}}}});D.addGrammarElement("mathOperator",function(e,r,t){var n=e.parseElement("unaryExpression",t);var a,i=null;a=t.matchAnyOpToken("+","-","*","/","%");while(a){i=i||a;var o=a.value;if(i.value!==o){e.raiseParseError(t,"You must parenthesize math operations with different operators")}var u=e.parseElement("unaryExpression",t);n={type:"mathOperator",lhs:n,rhs:u,operator:o,args:[n,u],op:function(e,r,t){if(this.operator==="+"){return r+t}else if(this.operator==="-"){return r-t}else if(this.operator==="*"){return r*t}else if(this.operator==="/"){return r/t}else if(this.operator==="%"){return r%t}},evaluate:function(e){return r.unifiedEval(this,e)}};a=t.matchAnyOpToken("+","-","*","/","%")}return n});D.addGrammarElement("mathExpression",function(e,r,t){return e.parseAnyOf(["mathOperator","unaryExpression"],t)});D.addGrammarElement("comparisonOperator",function(e,n,r){var t=e.parseElement("mathExpression",r);var a=r.matchAnyOpToken("<",">","<=",">=","==","===","!=","!==");var i=a?a.value:null;var o=true;var u=false;if(i==null){if(r.matchToken("is")||r.matchToken("am")){if(r.matchToken("not")){if(r.matchToken("in")){i="not in"}else if(r.matchToken("a")){i="not a";u=true}else if(r.matchToken("empty")){i="not empty";o=false}else{i="!="}}else if(r.matchToken("in")){i="in"}else if(r.matchToken("a")){i="a";u=true}else if(r.matchToken("empty")){i="empty";o=false}else{i="=="}}else if(r.matchToken("matches")||r.matchToken("match")){i="match"}else if(r.matchToken("contains")||r.matchToken("contain")){i="contain"}else if(r.matchToken("do")||r.matchToken("does")){r.requireToken("not");if(r.matchToken("matches")||r.matchToken("match")){i="not match"}else if(r.matchToken("contains")||r.matchToken("contain")){i="not contain"}else{e.raiseParseError(r,"Expected matches or contains")}}}if(i){if(u){var s=r.requireTokenType("IDENTIFIER");var l=!r.matchOpToken("!")}else if(o){var c=e.requireElement("mathExpression",r);if(i==="match"||i==="not match"){c=c.css?c.css:c}}t={type:"comparisonOperator",operator:i,typeName:s,nullOk:l,lhs:t,rhs:c,args:[t,c],op:function(e,r,t){if(this.operator==="=="){return r==t}else if(this.operator==="!="){return r!=t}if(this.operator==="in"){return t!=null&&Array.from(t).indexOf(r)>=0}if(this.operator==="not in"){return t==null||Array.from(t).indexOf(r)<0}if(this.operator==="match"){return r!=null&&r.matches(t)}if(this.operator==="not match"){return r==null||!r.matches(t)}if(this.operator==="contain"){return r!=null&&r.contains(t)}if(this.operator==="not contain"){return r==null||!r.contains(t)}if(this.operator==="==="){return r===t}else if(this.operator==="!=="){return r!==t}else if(this.operator==="<"){return r"){return r>t}else if(this.operator==="<="){return r<=t}else if(this.operator===">="){return r>=t}else if(this.operator==="empty"){return n.isEmpty(r)}else if(this.operator==="not empty"){return!n.isEmpty(r)}else if(this.operator==="a"){return n.typeCheck(r,this.typeName.value,this.nullOk)}else if(this.operator==="not a"){return!n.typeCheck(r,this.typeName.value,this.nullOk)}else{throw"Unknown comparison : "+this.operator}},evaluate:function(e){return n.unifiedEval(this,e)}}}return t});D.addGrammarElement("comparisonExpression",function(e,r,t){return e.parseAnyOf(["comparisonOperator","mathExpression"],t)});D.addGrammarElement("logicalOperator",function(e,r,t){var n=e.parseElement("comparisonExpression",t);var a,i=null;a=t.matchToken("and")||t.matchToken("or");while(a){i=i||a;if(i.value!==a.value){e.raiseParseError(t,"You must parenthesize logical operations with different operators")}var o=e.requireElement("comparisonExpression",t);n={type:"logicalOperator",operator:a.value,lhs:n,rhs:o,args:[n,o],op:function(e,r,t){if(this.operator==="and"){return r&&t}else{return r||t}},evaluate:function(e){return r.unifiedEval(this,e)}};a=t.matchToken("and")||t.matchToken("or")}return n});D.addGrammarElement("logicalExpression",function(e,r,t){return e.parseAnyOf(["logicalOperator","mathExpression"],t)});D.addGrammarElement("asyncExpression",function(e,r,t){if(t.matchToken("async")){var n=e.requireElement("logicalExpression",t);var a={type:"asyncExpression",value:n,evaluate:function(e){return{asyncWrapper:true,value:this.value.evaluate(e)}}};return a}else{return e.parseElement("logicalExpression",t)}});D.addGrammarElement("expression",function(e,r,t){t.matchToken("the");return e.parseElement("asyncExpression",t)});D.addGrammarElement("targetExpression",function(e,r,t){t.matchToken("the");var n=e.parseElement("primaryExpression",t);if(n.type==="symbol"||n.type==="idRef"||n.type==="inExpression"||n.type==="queryRef"||n.type==="classRef"||n.type==="ofExpression"||n.type==="propertyAccess"||n.type==="closestExpr"||n.type==="possessive"){return n}else{D.raiseParseError(t,"A target expression must be writable")}return n});D.addGrammarElement("hyperscript",function(e,r,t){var n=[];if(t.hasMore()){do{var a=e.requireElement("feature",t);n.push(a);t.matchToken("end")}while(e.featureStart(t.currentToken())||t.currentToken().value==="(");if(t.hasMore()){e.raiseParseError(t)}}return{type:"hyperscript",features:n,apply:function(r,t){G.forEach(n,function(e){e.install(r,t)})}}});var C=function(e){var r=[];if(e.token(0).value==="("&&(e.token(1).value===")"||e.token(2).value===","||e.token(2).value===")")){e.matchOpToken("(");do{r.push(e.requireTokenType("IDENTIFIER"))}while(e.matchOpToken(","));e.requireOpToken(")")}return r};D.addFeature("on",function(e,s,r){if(r.matchToken("on")){var t=false;if(r.matchToken("every")){t=true}var n=[];var a=null;do{var i=e.requireElement("dotOrColonPath",r,"Expected event name");var o=i.evaluate();if(a){a=a+" or "+o}else{a="on "+o}var u=C(r);var l=null;if(r.matchOpToken("[")){l=e.requireElement("expression",r);r.requireOpToken("]")}if(r.currentToken().type==="NUMBER"){var c=r.consumeToken();var f=parseInt(c.value);if(r.matchToken("to")){var p=r.consumeToken();var m=parseInt(p.value)}else if(r.matchToken("and")){var v=true;r.requireToken("on")}}var h=null;var d=false;if(r.matchToken("from")){if(r.matchToken("elsewhere")){d=true}else{h=e.parseElement("targetExpression",r);if(!h){e.raiseParseError('Expected either target value or "elsewhere".',r)}}}if(h===null&&d===false&&r.matchToken("elsewhere")){d=true}if(r.matchToken("in")){var E=e.parseAnyOf(["idRef","queryRef","classRef"],r)}if(r.matchToken("debounced")){r.requireToken("at");var T=e.requireElement("timeExpression",r);var y=T.evaluate({})}else if(r.matchToken("throttled")){r.requireToken("at");var T=e.requireElement("timeExpression",r);var k=T.evaluate({})}n.push({execCount:0,every:t,on:o,args:u,filter:l,from:h,inExpr:E,elsewhere:d,startCount:f,endCount:m,unbounded:v,debounceTime:y,throttleTime:k})}while(r.matchToken("or"));var x=[];var g=true;if(!t){if(r.matchToken("queue")){if(r.matchToken("all")){var q=true;var g=false}else if(r.matchToken("first")){var b=true}else if(r.matchToken("none")){var w=true}else{r.requireToken("last")}}}var N=e.requireElement("commandList",r);var I={type:"implicitReturn",op:function(e){e.meta.resolve();return s.HALT},execute:function(e){}};if(N){var O=N;while(O.next){O=O.next}O.next=I}else{N=I}var A={displayName:a,events:n,start:N,every:t,executing:false,execCount:0,queue:x,execute:function(n){if(this.executing&&this.every===false){if(w||b&&x.length>0){return}if(g){A.queue.length=0}A.queue.push(n);return}this.execCount++;this.executing=true;n.meta.resolve=function(){A.executing=false;var e=A.queue.shift();if(e){setTimeout(function(){A.execute(e)},1)}};n.meta.reject=function(e){console.error(e.message?e.message:e);var r=s.getHyperTrace(n,e);if(r){r.print()}s.triggerEvent(n.me,"exception",{error:e});A.executing=false;var t=A.queue.shift();if(t){setTimeout(function(){A.execute(t)},1)}};N.execute(n)},install:function(u,e){s.forEach(A.events,function(o){var e;if(o.elsewhere){e=[document]}else if(o.from){e=o.from.evaluate({me:u})}else{e=[u]}s.forEach(e,function(i){i.addEventListener(o.on,function(e){var r=s.makeContext(u,A,u,e);if(o.elsewhere&&u.contains(e.target)){return}if(o.from){r.result=i}s.forEach(o.args,function(e){r[e.value]=r.event[e.value]||(r.event.detail?r.event.detail[e.value]:null)});if(o.filter){var t=r.meta.context;r.meta.context=r.event;try{var n=o.filter.evaluate(r);if(n){}else{return}}finally{r.meta.context=t}}if(o.inExpr){var a=e.target;while(true){if(a.matches&&a.matches(o.inExpr.css)){r.result=a;break}else{a=a.parentElement;if(a==null){return}}}}o.execCount++;if(o.startCount){if(o.endCount){if(o.execCounto.endCount){return}}else if(o.unbounded){if(o.execCount + * @author owenm + * @license MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.Sortable = factory()); +}(this, (function () { 'use strict'; + + function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + } + keys.push.apply(keys, symbols); + } + return keys; + } + function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + return target; + } + function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + return _typeof(obj); + } + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; + } + function _extends() { + _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends.apply(this, arguments); + } + function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + return target; + } + function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; + var target = _objectWithoutPropertiesLoose(source, excluded); + var key, i; + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; + } + } + return target; + } + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); + } + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); + } + function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); + } + function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); + } + function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + return arr2; + } + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var version = "1.15.2"; + + function userAgent(pattern) { + if (typeof window !== 'undefined' && window.navigator) { + return !! /*@__PURE__*/navigator.userAgent.match(pattern); + } + } + var IE11OrLess = userAgent(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i); + var Edge = userAgent(/Edge/i); + var FireFox = userAgent(/firefox/i); + var Safari = userAgent(/safari/i) && !userAgent(/chrome/i) && !userAgent(/android/i); + var IOS = userAgent(/iP(ad|od|hone)/i); + var ChromeForAndroid = userAgent(/chrome/i) && userAgent(/android/i); + + var captureMode = { + capture: false, + passive: false + }; + function on(el, event, fn) { + el.addEventListener(event, fn, !IE11OrLess && captureMode); + } + function off(el, event, fn) { + el.removeEventListener(event, fn, !IE11OrLess && captureMode); + } + function matches( /**HTMLElement*/el, /**String*/selector) { + if (!selector) return; + selector[0] === '>' && (selector = selector.substring(1)); + if (el) { + try { + if (el.matches) { + return el.matches(selector); + } else if (el.msMatchesSelector) { + return el.msMatchesSelector(selector); + } else if (el.webkitMatchesSelector) { + return el.webkitMatchesSelector(selector); + } + } catch (_) { + return false; + } + } + return false; + } + function getParentOrHost(el) { + return el.host && el !== document && el.host.nodeType ? el.host : el.parentNode; + } + function closest( /**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx, includeCTX) { + if (el) { + ctx = ctx || document; + do { + if (selector != null && (selector[0] === '>' ? el.parentNode === ctx && matches(el, selector) : matches(el, selector)) || includeCTX && el === ctx) { + return el; + } + if (el === ctx) break; + /* jshint boss:true */ + } while (el = getParentOrHost(el)); + } + return null; + } + var R_SPACE = /\s+/g; + function toggleClass(el, name, state) { + if (el && name) { + if (el.classList) { + el.classList[state ? 'add' : 'remove'](name); + } else { + var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' '); + el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' '); + } + } + } + function css(el, prop, val) { + var style = el && el.style; + if (style) { + if (val === void 0) { + if (document.defaultView && document.defaultView.getComputedStyle) { + val = document.defaultView.getComputedStyle(el, ''); + } else if (el.currentStyle) { + val = el.currentStyle; + } + return prop === void 0 ? val : val[prop]; + } else { + if (!(prop in style) && prop.indexOf('webkit') === -1) { + prop = '-webkit-' + prop; + } + style[prop] = val + (typeof val === 'string' ? '' : 'px'); + } + } + } + function matrix(el, selfOnly) { + var appliedTransforms = ''; + if (typeof el === 'string') { + appliedTransforms = el; + } else { + do { + var transform = css(el, 'transform'); + if (transform && transform !== 'none') { + appliedTransforms = transform + ' ' + appliedTransforms; + } + /* jshint boss:true */ + } while (!selfOnly && (el = el.parentNode)); + } + var matrixFn = window.DOMMatrix || window.WebKitCSSMatrix || window.CSSMatrix || window.MSCSSMatrix; + /*jshint -W056 */ + return matrixFn && new matrixFn(appliedTransforms); + } + function find(ctx, tagName, iterator) { + if (ctx) { + var list = ctx.getElementsByTagName(tagName), + i = 0, + n = list.length; + if (iterator) { + for (; i < n; i++) { + iterator(list[i], i); + } + } + return list; + } + return []; + } + function getWindowScrollingElement() { + var scrollingElement = document.scrollingElement; + if (scrollingElement) { + return scrollingElement; + } else { + return document.documentElement; + } + } + + /** + * Returns the "bounding client rect" of given element + * @param {HTMLElement} el The element whose boundingClientRect is wanted + * @param {[Boolean]} relativeToContainingBlock Whether the rect should be relative to the containing block of (including) the container + * @param {[Boolean]} relativeToNonStaticParent Whether the rect should be relative to the relative parent of (including) the contaienr + * @param {[Boolean]} undoScale Whether the container's scale() should be undone + * @param {[HTMLElement]} container The parent the element will be placed in + * @return {Object} The boundingClientRect of el, with specified adjustments + */ + function getRect(el, relativeToContainingBlock, relativeToNonStaticParent, undoScale, container) { + if (!el.getBoundingClientRect && el !== window) return; + var elRect, top, left, bottom, right, height, width; + if (el !== window && el.parentNode && el !== getWindowScrollingElement()) { + elRect = el.getBoundingClientRect(); + top = elRect.top; + left = elRect.left; + bottom = elRect.bottom; + right = elRect.right; + height = elRect.height; + width = elRect.width; + } else { + top = 0; + left = 0; + bottom = window.innerHeight; + right = window.innerWidth; + height = window.innerHeight; + width = window.innerWidth; + } + if ((relativeToContainingBlock || relativeToNonStaticParent) && el !== window) { + // Adjust for translate() + container = container || el.parentNode; + + // solves #1123 (see: https://stackoverflow.com/a/37953806/6088312) + // Not needed on <= IE11 + if (!IE11OrLess) { + do { + if (container && container.getBoundingClientRect && (css(container, 'transform') !== 'none' || relativeToNonStaticParent && css(container, 'position') !== 'static')) { + var containerRect = container.getBoundingClientRect(); + + // Set relative to edges of padding box of container + top -= containerRect.top + parseInt(css(container, 'border-top-width')); + left -= containerRect.left + parseInt(css(container, 'border-left-width')); + bottom = top + elRect.height; + right = left + elRect.width; + break; + } + /* jshint boss:true */ + } while (container = container.parentNode); + } + } + if (undoScale && el !== window) { + // Adjust for scale() + var elMatrix = matrix(container || el), + scaleX = elMatrix && elMatrix.a, + scaleY = elMatrix && elMatrix.d; + if (elMatrix) { + top /= scaleY; + left /= scaleX; + width /= scaleX; + height /= scaleY; + bottom = top + height; + right = left + width; + } + } + return { + top: top, + left: left, + bottom: bottom, + right: right, + width: width, + height: height + }; + } + + /** + * Checks if a side of an element is scrolled past a side of its parents + * @param {HTMLElement} el The element who's side being scrolled out of view is in question + * @param {String} elSide Side of the element in question ('top', 'left', 'right', 'bottom') + * @param {String} parentSide Side of the parent in question ('top', 'left', 'right', 'bottom') + * @return {HTMLElement} The parent scroll element that the el's side is scrolled past, or null if there is no such element + */ + function isScrolledPast(el, elSide, parentSide) { + var parent = getParentAutoScrollElement(el, true), + elSideVal = getRect(el)[elSide]; + + /* jshint boss:true */ + while (parent) { + var parentSideVal = getRect(parent)[parentSide], + visible = void 0; + if (parentSide === 'top' || parentSide === 'left') { + visible = elSideVal >= parentSideVal; + } else { + visible = elSideVal <= parentSideVal; + } + if (!visible) return parent; + if (parent === getWindowScrollingElement()) break; + parent = getParentAutoScrollElement(parent, false); + } + return false; + } + + /** + * Gets nth child of el, ignoring hidden children, sortable's elements (does not ignore clone if it's visible) + * and non-draggable elements + * @param {HTMLElement} el The parent element + * @param {Number} childNum The index of the child + * @param {Object} options Parent Sortable's options + * @return {HTMLElement} The child at index childNum, or null if not found + */ + function getChild(el, childNum, options, includeDragEl) { + var currentChild = 0, + i = 0, + children = el.children; + while (i < children.length) { + if (children[i].style.display !== 'none' && children[i] !== Sortable.ghost && (includeDragEl || children[i] !== Sortable.dragged) && closest(children[i], options.draggable, el, false)) { + if (currentChild === childNum) { + return children[i]; + } + currentChild++; + } + i++; + } + return null; + } + + /** + * Gets the last child in the el, ignoring ghostEl or invisible elements (clones) + * @param {HTMLElement} el Parent element + * @param {selector} selector Any other elements that should be ignored + * @return {HTMLElement} The last child, ignoring ghostEl + */ + function lastChild(el, selector) { + var last = el.lastElementChild; + while (last && (last === Sortable.ghost || css(last, 'display') === 'none' || selector && !matches(last, selector))) { + last = last.previousElementSibling; + } + return last || null; + } + + /** + * Returns the index of an element within its parent for a selected set of + * elements + * @param {HTMLElement} el + * @param {selector} selector + * @return {number} + */ + function index(el, selector) { + var index = 0; + if (!el || !el.parentNode) { + return -1; + } + + /* jshint boss:true */ + while (el = el.previousElementSibling) { + if (el.nodeName.toUpperCase() !== 'TEMPLATE' && el !== Sortable.clone && (!selector || matches(el, selector))) { + index++; + } + } + return index; + } + + /** + * Returns the scroll offset of the given element, added with all the scroll offsets of parent elements. + * The value is returned in real pixels. + * @param {HTMLElement} el + * @return {Array} Offsets in the format of [left, top] + */ + function getRelativeScrollOffset(el) { + var offsetLeft = 0, + offsetTop = 0, + winScroller = getWindowScrollingElement(); + if (el) { + do { + var elMatrix = matrix(el), + scaleX = elMatrix.a, + scaleY = elMatrix.d; + offsetLeft += el.scrollLeft * scaleX; + offsetTop += el.scrollTop * scaleY; + } while (el !== winScroller && (el = el.parentNode)); + } + return [offsetLeft, offsetTop]; + } + + /** + * Returns the index of the object within the given array + * @param {Array} arr Array that may or may not hold the object + * @param {Object} obj An object that has a key-value pair unique to and identical to a key-value pair in the object you want to find + * @return {Number} The index of the object in the array, or -1 + */ + function indexOfObject(arr, obj) { + for (var i in arr) { + if (!arr.hasOwnProperty(i)) continue; + for (var key in obj) { + if (obj.hasOwnProperty(key) && obj[key] === arr[i][key]) return Number(i); + } + } + return -1; + } + function getParentAutoScrollElement(el, includeSelf) { + // skip to window + if (!el || !el.getBoundingClientRect) return getWindowScrollingElement(); + var elem = el; + var gotSelf = false; + do { + // we don't need to get elem css if it isn't even overflowing in the first place (performance) + if (elem.clientWidth < elem.scrollWidth || elem.clientHeight < elem.scrollHeight) { + var elemCSS = css(elem); + if (elem.clientWidth < elem.scrollWidth && (elemCSS.overflowX == 'auto' || elemCSS.overflowX == 'scroll') || elem.clientHeight < elem.scrollHeight && (elemCSS.overflowY == 'auto' || elemCSS.overflowY == 'scroll')) { + if (!elem.getBoundingClientRect || elem === document.body) return getWindowScrollingElement(); + if (gotSelf || includeSelf) return elem; + gotSelf = true; + } + } + /* jshint boss:true */ + } while (elem = elem.parentNode); + return getWindowScrollingElement(); + } + function extend(dst, src) { + if (dst && src) { + for (var key in src) { + if (src.hasOwnProperty(key)) { + dst[key] = src[key]; + } + } + } + return dst; + } + function isRectEqual(rect1, rect2) { + return Math.round(rect1.top) === Math.round(rect2.top) && Math.round(rect1.left) === Math.round(rect2.left) && Math.round(rect1.height) === Math.round(rect2.height) && Math.round(rect1.width) === Math.round(rect2.width); + } + var _throttleTimeout; + function throttle(callback, ms) { + return function () { + if (!_throttleTimeout) { + var args = arguments, + _this = this; + if (args.length === 1) { + callback.call(_this, args[0]); + } else { + callback.apply(_this, args); + } + _throttleTimeout = setTimeout(function () { + _throttleTimeout = void 0; + }, ms); + } + }; + } + function cancelThrottle() { + clearTimeout(_throttleTimeout); + _throttleTimeout = void 0; + } + function scrollBy(el, x, y) { + el.scrollLeft += x; + el.scrollTop += y; + } + function clone(el) { + var Polymer = window.Polymer; + var $ = window.jQuery || window.Zepto; + if (Polymer && Polymer.dom) { + return Polymer.dom(el).cloneNode(true); + } else if ($) { + return $(el).clone(true)[0]; + } else { + return el.cloneNode(true); + } + } + function setRect(el, rect) { + css(el, 'position', 'absolute'); + css(el, 'top', rect.top); + css(el, 'left', rect.left); + css(el, 'width', rect.width); + css(el, 'height', rect.height); + } + function unsetRect(el) { + css(el, 'position', ''); + css(el, 'top', ''); + css(el, 'left', ''); + css(el, 'width', ''); + css(el, 'height', ''); + } + function getChildContainingRectFromElement(container, options, ghostEl) { + var rect = {}; + Array.from(container.children).forEach(function (child) { + var _rect$left, _rect$top, _rect$right, _rect$bottom; + if (!closest(child, options.draggable, container, false) || child.animated || child === ghostEl) return; + var childRect = getRect(child); + rect.left = Math.min((_rect$left = rect.left) !== null && _rect$left !== void 0 ? _rect$left : Infinity, childRect.left); + rect.top = Math.min((_rect$top = rect.top) !== null && _rect$top !== void 0 ? _rect$top : Infinity, childRect.top); + rect.right = Math.max((_rect$right = rect.right) !== null && _rect$right !== void 0 ? _rect$right : -Infinity, childRect.right); + rect.bottom = Math.max((_rect$bottom = rect.bottom) !== null && _rect$bottom !== void 0 ? _rect$bottom : -Infinity, childRect.bottom); + }); + rect.width = rect.right - rect.left; + rect.height = rect.bottom - rect.top; + rect.x = rect.left; + rect.y = rect.top; + return rect; + } + var expando = 'Sortable' + new Date().getTime(); + + function AnimationStateManager() { + var animationStates = [], + animationCallbackId; + return { + captureAnimationState: function captureAnimationState() { + animationStates = []; + if (!this.options.animation) return; + var children = [].slice.call(this.el.children); + children.forEach(function (child) { + if (css(child, 'display') === 'none' || child === Sortable.ghost) return; + animationStates.push({ + target: child, + rect: getRect(child) + }); + var fromRect = _objectSpread2({}, animationStates[animationStates.length - 1].rect); + + // If animating: compensate for current animation + if (child.thisAnimationDuration) { + var childMatrix = matrix(child, true); + if (childMatrix) { + fromRect.top -= childMatrix.f; + fromRect.left -= childMatrix.e; + } + } + child.fromRect = fromRect; + }); + }, + addAnimationState: function addAnimationState(state) { + animationStates.push(state); + }, + removeAnimationState: function removeAnimationState(target) { + animationStates.splice(indexOfObject(animationStates, { + target: target + }), 1); + }, + animateAll: function animateAll(callback) { + var _this = this; + if (!this.options.animation) { + clearTimeout(animationCallbackId); + if (typeof callback === 'function') callback(); + return; + } + var animating = false, + animationTime = 0; + animationStates.forEach(function (state) { + var time = 0, + target = state.target, + fromRect = target.fromRect, + toRect = getRect(target), + prevFromRect = target.prevFromRect, + prevToRect = target.prevToRect, + animatingRect = state.rect, + targetMatrix = matrix(target, true); + if (targetMatrix) { + // Compensate for current animation + toRect.top -= targetMatrix.f; + toRect.left -= targetMatrix.e; + } + target.toRect = toRect; + if (target.thisAnimationDuration) { + // Could also check if animatingRect is between fromRect and toRect + if (isRectEqual(prevFromRect, toRect) && !isRectEqual(fromRect, toRect) && + // Make sure animatingRect is on line between toRect & fromRect + (animatingRect.top - toRect.top) / (animatingRect.left - toRect.left) === (fromRect.top - toRect.top) / (fromRect.left - toRect.left)) { + // If returning to same place as started from animation and on same axis + time = calculateRealTime(animatingRect, prevFromRect, prevToRect, _this.options); + } + } + + // if fromRect != toRect: animate + if (!isRectEqual(toRect, fromRect)) { + target.prevFromRect = fromRect; + target.prevToRect = toRect; + if (!time) { + time = _this.options.animation; + } + _this.animate(target, animatingRect, toRect, time); + } + if (time) { + animating = true; + animationTime = Math.max(animationTime, time); + clearTimeout(target.animationResetTimer); + target.animationResetTimer = setTimeout(function () { + target.animationTime = 0; + target.prevFromRect = null; + target.fromRect = null; + target.prevToRect = null; + target.thisAnimationDuration = null; + }, time); + target.thisAnimationDuration = time; + } + }); + clearTimeout(animationCallbackId); + if (!animating) { + if (typeof callback === 'function') callback(); + } else { + animationCallbackId = setTimeout(function () { + if (typeof callback === 'function') callback(); + }, animationTime); + } + animationStates = []; + }, + animate: function animate(target, currentRect, toRect, duration) { + if (duration) { + css(target, 'transition', ''); + css(target, 'transform', ''); + var elMatrix = matrix(this.el), + scaleX = elMatrix && elMatrix.a, + scaleY = elMatrix && elMatrix.d, + translateX = (currentRect.left - toRect.left) / (scaleX || 1), + translateY = (currentRect.top - toRect.top) / (scaleY || 1); + target.animatingX = !!translateX; + target.animatingY = !!translateY; + css(target, 'transform', 'translate3d(' + translateX + 'px,' + translateY + 'px,0)'); + this.forRepaintDummy = repaint(target); // repaint + + css(target, 'transition', 'transform ' + duration + 'ms' + (this.options.easing ? ' ' + this.options.easing : '')); + css(target, 'transform', 'translate3d(0,0,0)'); + typeof target.animated === 'number' && clearTimeout(target.animated); + target.animated = setTimeout(function () { + css(target, 'transition', ''); + css(target, 'transform', ''); + target.animated = false; + target.animatingX = false; + target.animatingY = false; + }, duration); + } + } + }; + } + function repaint(target) { + return target.offsetWidth; + } + function calculateRealTime(animatingRect, fromRect, toRect, options) { + return Math.sqrt(Math.pow(fromRect.top - animatingRect.top, 2) + Math.pow(fromRect.left - animatingRect.left, 2)) / Math.sqrt(Math.pow(fromRect.top - toRect.top, 2) + Math.pow(fromRect.left - toRect.left, 2)) * options.animation; + } + + var plugins = []; + var defaults = { + initializeByDefault: true + }; + var PluginManager = { + mount: function mount(plugin) { + // Set default static properties + for (var option in defaults) { + if (defaults.hasOwnProperty(option) && !(option in plugin)) { + plugin[option] = defaults[option]; + } + } + plugins.forEach(function (p) { + if (p.pluginName === plugin.pluginName) { + throw "Sortable: Cannot mount plugin ".concat(plugin.pluginName, " more than once"); + } + }); + plugins.push(plugin); + }, + pluginEvent: function pluginEvent(eventName, sortable, evt) { + var _this = this; + this.eventCanceled = false; + evt.cancel = function () { + _this.eventCanceled = true; + }; + var eventNameGlobal = eventName + 'Global'; + plugins.forEach(function (plugin) { + if (!sortable[plugin.pluginName]) return; + // Fire global events if it exists in this sortable + if (sortable[plugin.pluginName][eventNameGlobal]) { + sortable[plugin.pluginName][eventNameGlobal](_objectSpread2({ + sortable: sortable + }, evt)); + } + + // Only fire plugin event if plugin is enabled in this sortable, + // and plugin has event defined + if (sortable.options[plugin.pluginName] && sortable[plugin.pluginName][eventName]) { + sortable[plugin.pluginName][eventName](_objectSpread2({ + sortable: sortable + }, evt)); + } + }); + }, + initializePlugins: function initializePlugins(sortable, el, defaults, options) { + plugins.forEach(function (plugin) { + var pluginName = plugin.pluginName; + if (!sortable.options[pluginName] && !plugin.initializeByDefault) return; + var initialized = new plugin(sortable, el, sortable.options); + initialized.sortable = sortable; + initialized.options = sortable.options; + sortable[pluginName] = initialized; + + // Add default options from plugin + _extends(defaults, initialized.defaults); + }); + for (var option in sortable.options) { + if (!sortable.options.hasOwnProperty(option)) continue; + var modified = this.modifyOption(sortable, option, sortable.options[option]); + if (typeof modified !== 'undefined') { + sortable.options[option] = modified; + } + } + }, + getEventProperties: function getEventProperties(name, sortable) { + var eventProperties = {}; + plugins.forEach(function (plugin) { + if (typeof plugin.eventProperties !== 'function') return; + _extends(eventProperties, plugin.eventProperties.call(sortable[plugin.pluginName], name)); + }); + return eventProperties; + }, + modifyOption: function modifyOption(sortable, name, value) { + var modifiedValue; + plugins.forEach(function (plugin) { + // Plugin must exist on the Sortable + if (!sortable[plugin.pluginName]) return; + + // If static option listener exists for this option, call in the context of the Sortable's instance of this plugin + if (plugin.optionListeners && typeof plugin.optionListeners[name] === 'function') { + modifiedValue = plugin.optionListeners[name].call(sortable[plugin.pluginName], value); + } + }); + return modifiedValue; + } + }; + + function dispatchEvent(_ref) { + var sortable = _ref.sortable, + rootEl = _ref.rootEl, + name = _ref.name, + targetEl = _ref.targetEl, + cloneEl = _ref.cloneEl, + toEl = _ref.toEl, + fromEl = _ref.fromEl, + oldIndex = _ref.oldIndex, + newIndex = _ref.newIndex, + oldDraggableIndex = _ref.oldDraggableIndex, + newDraggableIndex = _ref.newDraggableIndex, + originalEvent = _ref.originalEvent, + putSortable = _ref.putSortable, + extraEventProperties = _ref.extraEventProperties; + sortable = sortable || rootEl && rootEl[expando]; + if (!sortable) return; + var evt, + options = sortable.options, + onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1); + // Support for new CustomEvent feature + if (window.CustomEvent && !IE11OrLess && !Edge) { + evt = new CustomEvent(name, { + bubbles: true, + cancelable: true + }); + } else { + evt = document.createEvent('Event'); + evt.initEvent(name, true, true); + } + evt.to = toEl || rootEl; + evt.from = fromEl || rootEl; + evt.item = targetEl || rootEl; + evt.clone = cloneEl; + evt.oldIndex = oldIndex; + evt.newIndex = newIndex; + evt.oldDraggableIndex = oldDraggableIndex; + evt.newDraggableIndex = newDraggableIndex; + evt.originalEvent = originalEvent; + evt.pullMode = putSortable ? putSortable.lastPutMode : undefined; + var allEventProperties = _objectSpread2(_objectSpread2({}, extraEventProperties), PluginManager.getEventProperties(name, sortable)); + for (var option in allEventProperties) { + evt[option] = allEventProperties[option]; + } + if (rootEl) { + rootEl.dispatchEvent(evt); + } + if (options[onName]) { + options[onName].call(sortable, evt); + } + } + + var _excluded = ["evt"]; + var pluginEvent = function pluginEvent(eventName, sortable) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + originalEvent = _ref.evt, + data = _objectWithoutProperties(_ref, _excluded); + PluginManager.pluginEvent.bind(Sortable)(eventName, sortable, _objectSpread2({ + dragEl: dragEl, + parentEl: parentEl, + ghostEl: ghostEl, + rootEl: rootEl, + nextEl: nextEl, + lastDownEl: lastDownEl, + cloneEl: cloneEl, + cloneHidden: cloneHidden, + dragStarted: moved, + putSortable: putSortable, + activeSortable: Sortable.active, + originalEvent: originalEvent, + oldIndex: oldIndex, + oldDraggableIndex: oldDraggableIndex, + newIndex: newIndex, + newDraggableIndex: newDraggableIndex, + hideGhostForTarget: _hideGhostForTarget, + unhideGhostForTarget: _unhideGhostForTarget, + cloneNowHidden: function cloneNowHidden() { + cloneHidden = true; + }, + cloneNowShown: function cloneNowShown() { + cloneHidden = false; + }, + dispatchSortableEvent: function dispatchSortableEvent(name) { + _dispatchEvent({ + sortable: sortable, + name: name, + originalEvent: originalEvent + }); + } + }, data)); + }; + function _dispatchEvent(info) { + dispatchEvent(_objectSpread2({ + putSortable: putSortable, + cloneEl: cloneEl, + targetEl: dragEl, + rootEl: rootEl, + oldIndex: oldIndex, + oldDraggableIndex: oldDraggableIndex, + newIndex: newIndex, + newDraggableIndex: newDraggableIndex + }, info)); + } + var dragEl, + parentEl, + ghostEl, + rootEl, + nextEl, + lastDownEl, + cloneEl, + cloneHidden, + oldIndex, + newIndex, + oldDraggableIndex, + newDraggableIndex, + activeGroup, + putSortable, + awaitingDragStarted = false, + ignoreNextClick = false, + sortables = [], + tapEvt, + touchEvt, + lastDx, + lastDy, + tapDistanceLeft, + tapDistanceTop, + moved, + lastTarget, + lastDirection, + pastFirstInvertThresh = false, + isCircumstantialInvert = false, + targetMoveDistance, + // For positioning ghost absolutely + ghostRelativeParent, + ghostRelativeParentInitialScroll = [], + // (left, top) + + _silent = false, + savedInputChecked = []; + + /** @const */ + var documentExists = typeof document !== 'undefined', + PositionGhostAbsolutely = IOS, + CSSFloatProperty = Edge || IE11OrLess ? 'cssFloat' : 'float', + // This will not pass for IE9, because IE9 DnD only works on anchors + supportDraggable = documentExists && !ChromeForAndroid && !IOS && 'draggable' in document.createElement('div'), + supportCssPointerEvents = function () { + if (!documentExists) return; + // false when <= IE11 + if (IE11OrLess) { + return false; + } + var el = document.createElement('x'); + el.style.cssText = 'pointer-events:auto'; + return el.style.pointerEvents === 'auto'; + }(), + _detectDirection = function _detectDirection(el, options) { + var elCSS = css(el), + elWidth = parseInt(elCSS.width) - parseInt(elCSS.paddingLeft) - parseInt(elCSS.paddingRight) - parseInt(elCSS.borderLeftWidth) - parseInt(elCSS.borderRightWidth), + child1 = getChild(el, 0, options), + child2 = getChild(el, 1, options), + firstChildCSS = child1 && css(child1), + secondChildCSS = child2 && css(child2), + firstChildWidth = firstChildCSS && parseInt(firstChildCSS.marginLeft) + parseInt(firstChildCSS.marginRight) + getRect(child1).width, + secondChildWidth = secondChildCSS && parseInt(secondChildCSS.marginLeft) + parseInt(secondChildCSS.marginRight) + getRect(child2).width; + if (elCSS.display === 'flex') { + return elCSS.flexDirection === 'column' || elCSS.flexDirection === 'column-reverse' ? 'vertical' : 'horizontal'; + } + if (elCSS.display === 'grid') { + return elCSS.gridTemplateColumns.split(' ').length <= 1 ? 'vertical' : 'horizontal'; + } + if (child1 && firstChildCSS["float"] && firstChildCSS["float"] !== 'none') { + var touchingSideChild2 = firstChildCSS["float"] === 'left' ? 'left' : 'right'; + return child2 && (secondChildCSS.clear === 'both' || secondChildCSS.clear === touchingSideChild2) ? 'vertical' : 'horizontal'; + } + return child1 && (firstChildCSS.display === 'block' || firstChildCSS.display === 'flex' || firstChildCSS.display === 'table' || firstChildCSS.display === 'grid' || firstChildWidth >= elWidth && elCSS[CSSFloatProperty] === 'none' || child2 && elCSS[CSSFloatProperty] === 'none' && firstChildWidth + secondChildWidth > elWidth) ? 'vertical' : 'horizontal'; + }, + _dragElInRowColumn = function _dragElInRowColumn(dragRect, targetRect, vertical) { + var dragElS1Opp = vertical ? dragRect.left : dragRect.top, + dragElS2Opp = vertical ? dragRect.right : dragRect.bottom, + dragElOppLength = vertical ? dragRect.width : dragRect.height, + targetS1Opp = vertical ? targetRect.left : targetRect.top, + targetS2Opp = vertical ? targetRect.right : targetRect.bottom, + targetOppLength = vertical ? targetRect.width : targetRect.height; + return dragElS1Opp === targetS1Opp || dragElS2Opp === targetS2Opp || dragElS1Opp + dragElOppLength / 2 === targetS1Opp + targetOppLength / 2; + }, + /** + * Detects first nearest empty sortable to X and Y position using emptyInsertThreshold. + * @param {Number} x X position + * @param {Number} y Y position + * @return {HTMLElement} Element of the first found nearest Sortable + */ + _detectNearestEmptySortable = function _detectNearestEmptySortable(x, y) { + var ret; + sortables.some(function (sortable) { + var threshold = sortable[expando].options.emptyInsertThreshold; + if (!threshold || lastChild(sortable)) return; + var rect = getRect(sortable), + insideHorizontally = x >= rect.left - threshold && x <= rect.right + threshold, + insideVertically = y >= rect.top - threshold && y <= rect.bottom + threshold; + if (insideHorizontally && insideVertically) { + return ret = sortable; + } + }); + return ret; + }, + _prepareGroup = function _prepareGroup(options) { + function toFn(value, pull) { + return function (to, from, dragEl, evt) { + var sameGroup = to.options.group.name && from.options.group.name && to.options.group.name === from.options.group.name; + if (value == null && (pull || sameGroup)) { + // Default pull value + // Default pull and put value if same group + return true; + } else if (value == null || value === false) { + return false; + } else if (pull && value === 'clone') { + return value; + } else if (typeof value === 'function') { + return toFn(value(to, from, dragEl, evt), pull)(to, from, dragEl, evt); + } else { + var otherGroup = (pull ? to : from).options.group.name; + return value === true || typeof value === 'string' && value === otherGroup || value.join && value.indexOf(otherGroup) > -1; + } + }; + } + var group = {}; + var originalGroup = options.group; + if (!originalGroup || _typeof(originalGroup) != 'object') { + originalGroup = { + name: originalGroup + }; + } + group.name = originalGroup.name; + group.checkPull = toFn(originalGroup.pull, true); + group.checkPut = toFn(originalGroup.put); + group.revertClone = originalGroup.revertClone; + options.group = group; + }, + _hideGhostForTarget = function _hideGhostForTarget() { + if (!supportCssPointerEvents && ghostEl) { + css(ghostEl, 'display', 'none'); + } + }, + _unhideGhostForTarget = function _unhideGhostForTarget() { + if (!supportCssPointerEvents && ghostEl) { + css(ghostEl, 'display', ''); + } + }; + + // #1184 fix - Prevent click event on fallback if dragged but item not changed position + if (documentExists && !ChromeForAndroid) { + document.addEventListener('click', function (evt) { + if (ignoreNextClick) { + evt.preventDefault(); + evt.stopPropagation && evt.stopPropagation(); + evt.stopImmediatePropagation && evt.stopImmediatePropagation(); + ignoreNextClick = false; + return false; + } + }, true); + } + var nearestEmptyInsertDetectEvent = function nearestEmptyInsertDetectEvent(evt) { + if (dragEl) { + evt = evt.touches ? evt.touches[0] : evt; + var nearest = _detectNearestEmptySortable(evt.clientX, evt.clientY); + if (nearest) { + // Create imitation event + var event = {}; + for (var i in evt) { + if (evt.hasOwnProperty(i)) { + event[i] = evt[i]; + } + } + event.target = event.rootEl = nearest; + event.preventDefault = void 0; + event.stopPropagation = void 0; + nearest[expando]._onDragOver(event); + } + } + }; + var _checkOutsideTargetEl = function _checkOutsideTargetEl(evt) { + if (dragEl) { + dragEl.parentNode[expando]._isOutsideThisEl(evt.target); + } + }; + + /** + * @class Sortable + * @param {HTMLElement} el + * @param {Object} [options] + */ + function Sortable(el, options) { + if (!(el && el.nodeType && el.nodeType === 1)) { + throw "Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(el)); + } + this.el = el; // root element + this.options = options = _extends({}, options); + + // Export instance + el[expando] = this; + var defaults = { + group: null, + sort: true, + disabled: false, + store: null, + handle: null, + draggable: /^[uo]l$/i.test(el.nodeName) ? '>li' : '>*', + swapThreshold: 1, + // percentage; 0 <= x <= 1 + invertSwap: false, + // invert always + invertedSwapThreshold: null, + // will be set to same as swapThreshold if default + removeCloneOnHide: true, + direction: function direction() { + return _detectDirection(el, this.options); + }, + ghostClass: 'sortable-ghost', + chosenClass: 'sortable-chosen', + dragClass: 'sortable-drag', + ignore: 'a, img', + filter: null, + preventOnFilter: true, + animation: 0, + easing: null, + setData: function setData(dataTransfer, dragEl) { + dataTransfer.setData('Text', dragEl.textContent); + }, + dropBubble: false, + dragoverBubble: false, + dataIdAttr: 'data-id', + delay: 0, + delayOnTouchOnly: false, + touchStartThreshold: (Number.parseInt ? Number : window).parseInt(window.devicePixelRatio, 10) || 1, + forceFallback: false, + fallbackClass: 'sortable-fallback', + fallbackOnBody: false, + fallbackTolerance: 0, + fallbackOffset: { + x: 0, + y: 0 + }, + supportPointer: Sortable.supportPointer !== false && 'PointerEvent' in window && !Safari, + emptyInsertThreshold: 5 + }; + PluginManager.initializePlugins(this, el, defaults); + + // Set default options + for (var name in defaults) { + !(name in options) && (options[name] = defaults[name]); + } + _prepareGroup(options); + + // Bind all private methods + for (var fn in this) { + if (fn.charAt(0) === '_' && typeof this[fn] === 'function') { + this[fn] = this[fn].bind(this); + } + } + + // Setup drag mode + this.nativeDraggable = options.forceFallback ? false : supportDraggable; + if (this.nativeDraggable) { + // Touch start threshold cannot be greater than the native dragstart threshold + this.options.touchStartThreshold = 1; + } + + // Bind events + if (options.supportPointer) { + on(el, 'pointerdown', this._onTapStart); + } else { + on(el, 'mousedown', this._onTapStart); + on(el, 'touchstart', this._onTapStart); + } + if (this.nativeDraggable) { + on(el, 'dragover', this); + on(el, 'dragenter', this); + } + sortables.push(this.el); + + // Restore sorting + options.store && options.store.get && this.sort(options.store.get(this) || []); + + // Add animation state manager + _extends(this, AnimationStateManager()); + } + Sortable.prototype = /** @lends Sortable.prototype */{ + constructor: Sortable, + _isOutsideThisEl: function _isOutsideThisEl(target) { + if (!this.el.contains(target) && target !== this.el) { + lastTarget = null; + } + }, + _getDirection: function _getDirection(evt, target) { + return typeof this.options.direction === 'function' ? this.options.direction.call(this, evt, target, dragEl) : this.options.direction; + }, + _onTapStart: function _onTapStart( /** Event|TouchEvent */evt) { + if (!evt.cancelable) return; + var _this = this, + el = this.el, + options = this.options, + preventOnFilter = options.preventOnFilter, + type = evt.type, + touch = evt.touches && evt.touches[0] || evt.pointerType && evt.pointerType === 'touch' && evt, + target = (touch || evt).target, + originalTarget = evt.target.shadowRoot && (evt.path && evt.path[0] || evt.composedPath && evt.composedPath()[0]) || target, + filter = options.filter; + _saveInputCheckedState(el); + + // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group. + if (dragEl) { + return; + } + if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) { + return; // only left button and enabled + } + + // cancel dnd if original target is content editable + if (originalTarget.isContentEditable) { + return; + } + + // Safari ignores further event handling after mousedown + if (!this.nativeDraggable && Safari && target && target.tagName.toUpperCase() === 'SELECT') { + return; + } + target = closest(target, options.draggable, el, false); + if (target && target.animated) { + return; + } + if (lastDownEl === target) { + // Ignoring duplicate `down` + return; + } + + // Get the index of the dragged element within its parent + oldIndex = index(target); + oldDraggableIndex = index(target, options.draggable); + + // Check filter + if (typeof filter === 'function') { + if (filter.call(this, evt, target, this)) { + _dispatchEvent({ + sortable: _this, + rootEl: originalTarget, + name: 'filter', + targetEl: target, + toEl: el, + fromEl: el + }); + pluginEvent('filter', _this, { + evt: evt + }); + preventOnFilter && evt.cancelable && evt.preventDefault(); + return; // cancel dnd + } + } else if (filter) { + filter = filter.split(',').some(function (criteria) { + criteria = closest(originalTarget, criteria.trim(), el, false); + if (criteria) { + _dispatchEvent({ + sortable: _this, + rootEl: criteria, + name: 'filter', + targetEl: target, + fromEl: el, + toEl: el + }); + pluginEvent('filter', _this, { + evt: evt + }); + return true; + } + }); + if (filter) { + preventOnFilter && evt.cancelable && evt.preventDefault(); + return; // cancel dnd + } + } + if (options.handle && !closest(originalTarget, options.handle, el, false)) { + return; + } + + // Prepare `dragstart` + this._prepareDragStart(evt, touch, target); + }, + _prepareDragStart: function _prepareDragStart( /** Event */evt, /** Touch */touch, /** HTMLElement */target) { + var _this = this, + el = _this.el, + options = _this.options, + ownerDocument = el.ownerDocument, + dragStartFn; + if (target && !dragEl && target.parentNode === el) { + var dragRect = getRect(target); + rootEl = el; + dragEl = target; + parentEl = dragEl.parentNode; + nextEl = dragEl.nextSibling; + lastDownEl = target; + activeGroup = options.group; + Sortable.dragged = dragEl; + tapEvt = { + target: dragEl, + clientX: (touch || evt).clientX, + clientY: (touch || evt).clientY + }; + tapDistanceLeft = tapEvt.clientX - dragRect.left; + tapDistanceTop = tapEvt.clientY - dragRect.top; + this._lastX = (touch || evt).clientX; + this._lastY = (touch || evt).clientY; + dragEl.style['will-change'] = 'all'; + dragStartFn = function dragStartFn() { + pluginEvent('delayEnded', _this, { + evt: evt + }); + if (Sortable.eventCanceled) { + _this._onDrop(); + return; + } + // Delayed drag has been triggered + // we can re-enable the events: touchmove/mousemove + _this._disableDelayedDragEvents(); + if (!FireFox && _this.nativeDraggable) { + dragEl.draggable = true; + } + + // Bind the events: dragstart/dragend + _this._triggerDragStart(evt, touch); + + // Drag start event + _dispatchEvent({ + sortable: _this, + name: 'choose', + originalEvent: evt + }); + + // Chosen item + toggleClass(dragEl, options.chosenClass, true); + }; + + // Disable "draggable" + options.ignore.split(',').forEach(function (criteria) { + find(dragEl, criteria.trim(), _disableDraggable); + }); + on(ownerDocument, 'dragover', nearestEmptyInsertDetectEvent); + on(ownerDocument, 'mousemove', nearestEmptyInsertDetectEvent); + on(ownerDocument, 'touchmove', nearestEmptyInsertDetectEvent); + on(ownerDocument, 'mouseup', _this._onDrop); + on(ownerDocument, 'touchend', _this._onDrop); + on(ownerDocument, 'touchcancel', _this._onDrop); + + // Make dragEl draggable (must be before delay for FireFox) + if (FireFox && this.nativeDraggable) { + this.options.touchStartThreshold = 4; + dragEl.draggable = true; + } + pluginEvent('delayStart', this, { + evt: evt + }); + + // Delay is impossible for native DnD in Edge or IE + if (options.delay && (!options.delayOnTouchOnly || touch) && (!this.nativeDraggable || !(Edge || IE11OrLess))) { + if (Sortable.eventCanceled) { + this._onDrop(); + return; + } + // If the user moves the pointer or let go the click or touch + // before the delay has been reached: + // disable the delayed drag + on(ownerDocument, 'mouseup', _this._disableDelayedDrag); + on(ownerDocument, 'touchend', _this._disableDelayedDrag); + on(ownerDocument, 'touchcancel', _this._disableDelayedDrag); + on(ownerDocument, 'mousemove', _this._delayedDragTouchMoveHandler); + on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler); + options.supportPointer && on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler); + _this._dragStartTimer = setTimeout(dragStartFn, options.delay); + } else { + dragStartFn(); + } + } + }, + _delayedDragTouchMoveHandler: function _delayedDragTouchMoveHandler( /** TouchEvent|PointerEvent **/e) { + var touch = e.touches ? e.touches[0] : e; + if (Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) >= Math.floor(this.options.touchStartThreshold / (this.nativeDraggable && window.devicePixelRatio || 1))) { + this._disableDelayedDrag(); + } + }, + _disableDelayedDrag: function _disableDelayedDrag() { + dragEl && _disableDraggable(dragEl); + clearTimeout(this._dragStartTimer); + this._disableDelayedDragEvents(); + }, + _disableDelayedDragEvents: function _disableDelayedDragEvents() { + var ownerDocument = this.el.ownerDocument; + off(ownerDocument, 'mouseup', this._disableDelayedDrag); + off(ownerDocument, 'touchend', this._disableDelayedDrag); + off(ownerDocument, 'touchcancel', this._disableDelayedDrag); + off(ownerDocument, 'mousemove', this._delayedDragTouchMoveHandler); + off(ownerDocument, 'touchmove', this._delayedDragTouchMoveHandler); + off(ownerDocument, 'pointermove', this._delayedDragTouchMoveHandler); + }, + _triggerDragStart: function _triggerDragStart( /** Event */evt, /** Touch */touch) { + touch = touch || evt.pointerType == 'touch' && evt; + if (!this.nativeDraggable || touch) { + if (this.options.supportPointer) { + on(document, 'pointermove', this._onTouchMove); + } else if (touch) { + on(document, 'touchmove', this._onTouchMove); + } else { + on(document, 'mousemove', this._onTouchMove); + } + } else { + on(dragEl, 'dragend', this); + on(rootEl, 'dragstart', this._onDragStart); + } + try { + if (document.selection) { + // Timeout neccessary for IE9 + _nextTick(function () { + document.selection.empty(); + }); + } else { + window.getSelection().removeAllRanges(); + } + } catch (err) {} + }, + _dragStarted: function _dragStarted(fallback, evt) { + awaitingDragStarted = false; + if (rootEl && dragEl) { + pluginEvent('dragStarted', this, { + evt: evt + }); + if (this.nativeDraggable) { + on(document, 'dragover', _checkOutsideTargetEl); + } + var options = this.options; + + // Apply effect + !fallback && toggleClass(dragEl, options.dragClass, false); + toggleClass(dragEl, options.ghostClass, true); + Sortable.active = this; + fallback && this._appendGhost(); + + // Drag start event + _dispatchEvent({ + sortable: this, + name: 'start', + originalEvent: evt + }); + } else { + this._nulling(); + } + }, + _emulateDragOver: function _emulateDragOver() { + if (touchEvt) { + this._lastX = touchEvt.clientX; + this._lastY = touchEvt.clientY; + _hideGhostForTarget(); + var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY); + var parent = target; + while (target && target.shadowRoot) { + target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY); + if (target === parent) break; + parent = target; + } + dragEl.parentNode[expando]._isOutsideThisEl(target); + if (parent) { + do { + if (parent[expando]) { + var inserted = void 0; + inserted = parent[expando]._onDragOver({ + clientX: touchEvt.clientX, + clientY: touchEvt.clientY, + target: target, + rootEl: parent + }); + if (inserted && !this.options.dragoverBubble) { + break; + } + } + target = parent; // store last element + } + /* jshint boss:true */ while (parent = parent.parentNode); + } + _unhideGhostForTarget(); + } + }, + _onTouchMove: function _onTouchMove( /**TouchEvent*/evt) { + if (tapEvt) { + var options = this.options, + fallbackTolerance = options.fallbackTolerance, + fallbackOffset = options.fallbackOffset, + touch = evt.touches ? evt.touches[0] : evt, + ghostMatrix = ghostEl && matrix(ghostEl, true), + scaleX = ghostEl && ghostMatrix && ghostMatrix.a, + scaleY = ghostEl && ghostMatrix && ghostMatrix.d, + relativeScrollOffset = PositionGhostAbsolutely && ghostRelativeParent && getRelativeScrollOffset(ghostRelativeParent), + dx = (touch.clientX - tapEvt.clientX + fallbackOffset.x) / (scaleX || 1) + (relativeScrollOffset ? relativeScrollOffset[0] - ghostRelativeParentInitialScroll[0] : 0) / (scaleX || 1), + dy = (touch.clientY - tapEvt.clientY + fallbackOffset.y) / (scaleY || 1) + (relativeScrollOffset ? relativeScrollOffset[1] - ghostRelativeParentInitialScroll[1] : 0) / (scaleY || 1); + + // only set the status to dragging, when we are actually dragging + if (!Sortable.active && !awaitingDragStarted) { + if (fallbackTolerance && Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) < fallbackTolerance) { + return; + } + this._onDragStart(evt, true); + } + if (ghostEl) { + if (ghostMatrix) { + ghostMatrix.e += dx - (lastDx || 0); + ghostMatrix.f += dy - (lastDy || 0); + } else { + ghostMatrix = { + a: 1, + b: 0, + c: 0, + d: 1, + e: dx, + f: dy + }; + } + var cssMatrix = "matrix(".concat(ghostMatrix.a, ",").concat(ghostMatrix.b, ",").concat(ghostMatrix.c, ",").concat(ghostMatrix.d, ",").concat(ghostMatrix.e, ",").concat(ghostMatrix.f, ")"); + css(ghostEl, 'webkitTransform', cssMatrix); + css(ghostEl, 'mozTransform', cssMatrix); + css(ghostEl, 'msTransform', cssMatrix); + css(ghostEl, 'transform', cssMatrix); + lastDx = dx; + lastDy = dy; + touchEvt = touch; + } + evt.cancelable && evt.preventDefault(); + } + }, + _appendGhost: function _appendGhost() { + // Bug if using scale(): https://stackoverflow.com/questions/2637058 + // Not being adjusted for + if (!ghostEl) { + var container = this.options.fallbackOnBody ? document.body : rootEl, + rect = getRect(dragEl, true, PositionGhostAbsolutely, true, container), + options = this.options; + + // Position absolutely + if (PositionGhostAbsolutely) { + // Get relatively positioned parent + ghostRelativeParent = container; + while (css(ghostRelativeParent, 'position') === 'static' && css(ghostRelativeParent, 'transform') === 'none' && ghostRelativeParent !== document) { + ghostRelativeParent = ghostRelativeParent.parentNode; + } + if (ghostRelativeParent !== document.body && ghostRelativeParent !== document.documentElement) { + if (ghostRelativeParent === document) ghostRelativeParent = getWindowScrollingElement(); + rect.top += ghostRelativeParent.scrollTop; + rect.left += ghostRelativeParent.scrollLeft; + } else { + ghostRelativeParent = getWindowScrollingElement(); + } + ghostRelativeParentInitialScroll = getRelativeScrollOffset(ghostRelativeParent); + } + ghostEl = dragEl.cloneNode(true); + toggleClass(ghostEl, options.ghostClass, false); + toggleClass(ghostEl, options.fallbackClass, true); + toggleClass(ghostEl, options.dragClass, true); + css(ghostEl, 'transition', ''); + css(ghostEl, 'transform', ''); + css(ghostEl, 'box-sizing', 'border-box'); + css(ghostEl, 'margin', 0); + css(ghostEl, 'top', rect.top); + css(ghostEl, 'left', rect.left); + css(ghostEl, 'width', rect.width); + css(ghostEl, 'height', rect.height); + css(ghostEl, 'opacity', '0.8'); + css(ghostEl, 'position', PositionGhostAbsolutely ? 'absolute' : 'fixed'); + css(ghostEl, 'zIndex', '100000'); + css(ghostEl, 'pointerEvents', 'none'); + Sortable.ghost = ghostEl; + container.appendChild(ghostEl); + + // Set transform-origin + css(ghostEl, 'transform-origin', tapDistanceLeft / parseInt(ghostEl.style.width) * 100 + '% ' + tapDistanceTop / parseInt(ghostEl.style.height) * 100 + '%'); + } + }, + _onDragStart: function _onDragStart( /**Event*/evt, /**boolean*/fallback) { + var _this = this; + var dataTransfer = evt.dataTransfer; + var options = _this.options; + pluginEvent('dragStart', this, { + evt: evt + }); + if (Sortable.eventCanceled) { + this._onDrop(); + return; + } + pluginEvent('setupClone', this); + if (!Sortable.eventCanceled) { + cloneEl = clone(dragEl); + cloneEl.removeAttribute("id"); + cloneEl.draggable = false; + cloneEl.style['will-change'] = ''; + this._hideClone(); + toggleClass(cloneEl, this.options.chosenClass, false); + Sortable.clone = cloneEl; + } + + // #1143: IFrame support workaround + _this.cloneId = _nextTick(function () { + pluginEvent('clone', _this); + if (Sortable.eventCanceled) return; + if (!_this.options.removeCloneOnHide) { + rootEl.insertBefore(cloneEl, dragEl); + } + _this._hideClone(); + _dispatchEvent({ + sortable: _this, + name: 'clone' + }); + }); + !fallback && toggleClass(dragEl, options.dragClass, true); + + // Set proper drop events + if (fallback) { + ignoreNextClick = true; + _this._loopId = setInterval(_this._emulateDragOver, 50); + } else { + // Undo what was set in _prepareDragStart before drag started + off(document, 'mouseup', _this._onDrop); + off(document, 'touchend', _this._onDrop); + off(document, 'touchcancel', _this._onDrop); + if (dataTransfer) { + dataTransfer.effectAllowed = 'move'; + options.setData && options.setData.call(_this, dataTransfer, dragEl); + } + on(document, 'drop', _this); + + // #1276 fix: + css(dragEl, 'transform', 'translateZ(0)'); + } + awaitingDragStarted = true; + _this._dragStartId = _nextTick(_this._dragStarted.bind(_this, fallback, evt)); + on(document, 'selectstart', _this); + moved = true; + if (Safari) { + css(document.body, 'user-select', 'none'); + } + }, + // Returns true - if no further action is needed (either inserted or another condition) + _onDragOver: function _onDragOver( /**Event*/evt) { + var el = this.el, + target = evt.target, + dragRect, + targetRect, + revert, + options = this.options, + group = options.group, + activeSortable = Sortable.active, + isOwner = activeGroup === group, + canSort = options.sort, + fromSortable = putSortable || activeSortable, + vertical, + _this = this, + completedFired = false; + if (_silent) return; + function dragOverEvent(name, extra) { + pluginEvent(name, _this, _objectSpread2({ + evt: evt, + isOwner: isOwner, + axis: vertical ? 'vertical' : 'horizontal', + revert: revert, + dragRect: dragRect, + targetRect: targetRect, + canSort: canSort, + fromSortable: fromSortable, + target: target, + completed: completed, + onMove: function onMove(target, after) { + return _onMove(rootEl, el, dragEl, dragRect, target, getRect(target), evt, after); + }, + changed: changed + }, extra)); + } + + // Capture animation state + function capture() { + dragOverEvent('dragOverAnimationCapture'); + _this.captureAnimationState(); + if (_this !== fromSortable) { + fromSortable.captureAnimationState(); + } + } + + // Return invocation when dragEl is inserted (or completed) + function completed(insertion) { + dragOverEvent('dragOverCompleted', { + insertion: insertion + }); + if (insertion) { + // Clones must be hidden before folding animation to capture dragRectAbsolute properly + if (isOwner) { + activeSortable._hideClone(); + } else { + activeSortable._showClone(_this); + } + if (_this !== fromSortable) { + // Set ghost class to new sortable's ghost class + toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : activeSortable.options.ghostClass, false); + toggleClass(dragEl, options.ghostClass, true); + } + if (putSortable !== _this && _this !== Sortable.active) { + putSortable = _this; + } else if (_this === Sortable.active && putSortable) { + putSortable = null; + } + + // Animation + if (fromSortable === _this) { + _this._ignoreWhileAnimating = target; + } + _this.animateAll(function () { + dragOverEvent('dragOverAnimationComplete'); + _this._ignoreWhileAnimating = null; + }); + if (_this !== fromSortable) { + fromSortable.animateAll(); + fromSortable._ignoreWhileAnimating = null; + } + } + + // Null lastTarget if it is not inside a previously swapped element + if (target === dragEl && !dragEl.animated || target === el && !target.animated) { + lastTarget = null; + } + + // no bubbling and not fallback + if (!options.dragoverBubble && !evt.rootEl && target !== document) { + dragEl.parentNode[expando]._isOutsideThisEl(evt.target); + + // Do not detect for empty insert if already inserted + !insertion && nearestEmptyInsertDetectEvent(evt); + } + !options.dragoverBubble && evt.stopPropagation && evt.stopPropagation(); + return completedFired = true; + } + + // Call when dragEl has been inserted + function changed() { + newIndex = index(dragEl); + newDraggableIndex = index(dragEl, options.draggable); + _dispatchEvent({ + sortable: _this, + name: 'change', + toEl: el, + newIndex: newIndex, + newDraggableIndex: newDraggableIndex, + originalEvent: evt + }); + } + if (evt.preventDefault !== void 0) { + evt.cancelable && evt.preventDefault(); + } + target = closest(target, options.draggable, el, true); + dragOverEvent('dragOver'); + if (Sortable.eventCanceled) return completedFired; + if (dragEl.contains(evt.target) || target.animated && target.animatingX && target.animatingY || _this._ignoreWhileAnimating === target) { + return completed(false); + } + ignoreNextClick = false; + if (activeSortable && !options.disabled && (isOwner ? canSort || (revert = parentEl !== rootEl) // Reverting item into the original list + : putSortable === this || (this.lastPutMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) && group.checkPut(this, activeSortable, dragEl, evt))) { + vertical = this._getDirection(evt, target) === 'vertical'; + dragRect = getRect(dragEl); + dragOverEvent('dragOverValid'); + if (Sortable.eventCanceled) return completedFired; + if (revert) { + parentEl = rootEl; // actualization + capture(); + this._hideClone(); + dragOverEvent('revert'); + if (!Sortable.eventCanceled) { + if (nextEl) { + rootEl.insertBefore(dragEl, nextEl); + } else { + rootEl.appendChild(dragEl); + } + } + return completed(true); + } + var elLastChild = lastChild(el, options.draggable); + if (!elLastChild || _ghostIsLast(evt, vertical, this) && !elLastChild.animated) { + // Insert to end of list + + // If already at end of list: Do not insert + if (elLastChild === dragEl) { + return completed(false); + } + + // if there is a last element, it is the target + if (elLastChild && el === evt.target) { + target = elLastChild; + } + if (target) { + targetRect = getRect(target); + } + if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) { + capture(); + if (elLastChild && elLastChild.nextSibling) { + // the last draggable element is not the last node + el.insertBefore(dragEl, elLastChild.nextSibling); + } else { + el.appendChild(dragEl); + } + parentEl = el; // actualization + + changed(); + return completed(true); + } + } else if (elLastChild && _ghostIsFirst(evt, vertical, this)) { + // Insert to start of list + var firstChild = getChild(el, 0, options, true); + if (firstChild === dragEl) { + return completed(false); + } + target = firstChild; + targetRect = getRect(target); + if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, false) !== false) { + capture(); + el.insertBefore(dragEl, firstChild); + parentEl = el; // actualization + + changed(); + return completed(true); + } + } else if (target.parentNode === el) { + targetRect = getRect(target); + var direction = 0, + targetBeforeFirstSwap, + differentLevel = dragEl.parentNode !== el, + differentRowCol = !_dragElInRowColumn(dragEl.animated && dragEl.toRect || dragRect, target.animated && target.toRect || targetRect, vertical), + side1 = vertical ? 'top' : 'left', + scrolledPastTop = isScrolledPast(target, 'top', 'top') || isScrolledPast(dragEl, 'top', 'top'), + scrollBefore = scrolledPastTop ? scrolledPastTop.scrollTop : void 0; + if (lastTarget !== target) { + targetBeforeFirstSwap = targetRect[side1]; + pastFirstInvertThresh = false; + isCircumstantialInvert = !differentRowCol && options.invertSwap || differentLevel; + } + direction = _getSwapDirection(evt, target, targetRect, vertical, differentRowCol ? 1 : options.swapThreshold, options.invertedSwapThreshold == null ? options.swapThreshold : options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target); + var sibling; + if (direction !== 0) { + // Check if target is beside dragEl in respective direction (ignoring hidden elements) + var dragIndex = index(dragEl); + do { + dragIndex -= direction; + sibling = parentEl.children[dragIndex]; + } while (sibling && (css(sibling, 'display') === 'none' || sibling === ghostEl)); + } + // If dragEl is already beside target: Do not insert + if (direction === 0 || sibling === target) { + return completed(false); + } + lastTarget = target; + lastDirection = direction; + var nextSibling = target.nextElementSibling, + after = false; + after = direction === 1; + var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after); + if (moveVector !== false) { + if (moveVector === 1 || moveVector === -1) { + after = moveVector === 1; + } + _silent = true; + setTimeout(_unsilent, 30); + capture(); + if (after && !nextSibling) { + el.appendChild(dragEl); + } else { + target.parentNode.insertBefore(dragEl, after ? nextSibling : target); + } + + // Undo chrome's scroll adjustment (has no effect on other browsers) + if (scrolledPastTop) { + scrollBy(scrolledPastTop, 0, scrollBefore - scrolledPastTop.scrollTop); + } + parentEl = dragEl.parentNode; // actualization + + // must be done before animation + if (targetBeforeFirstSwap !== undefined && !isCircumstantialInvert) { + targetMoveDistance = Math.abs(targetBeforeFirstSwap - getRect(target)[side1]); + } + changed(); + return completed(true); + } + } + if (el.contains(dragEl)) { + return completed(false); + } + } + return false; + }, + _ignoreWhileAnimating: null, + _offMoveEvents: function _offMoveEvents() { + off(document, 'mousemove', this._onTouchMove); + off(document, 'touchmove', this._onTouchMove); + off(document, 'pointermove', this._onTouchMove); + off(document, 'dragover', nearestEmptyInsertDetectEvent); + off(document, 'mousemove', nearestEmptyInsertDetectEvent); + off(document, 'touchmove', nearestEmptyInsertDetectEvent); + }, + _offUpEvents: function _offUpEvents() { + var ownerDocument = this.el.ownerDocument; + off(ownerDocument, 'mouseup', this._onDrop); + off(ownerDocument, 'touchend', this._onDrop); + off(ownerDocument, 'pointerup', this._onDrop); + off(ownerDocument, 'touchcancel', this._onDrop); + off(document, 'selectstart', this); + }, + _onDrop: function _onDrop( /**Event*/evt) { + var el = this.el, + options = this.options; + + // Get the index of the dragged element within its parent + newIndex = index(dragEl); + newDraggableIndex = index(dragEl, options.draggable); + pluginEvent('drop', this, { + evt: evt + }); + parentEl = dragEl && dragEl.parentNode; + + // Get again after plugin event + newIndex = index(dragEl); + newDraggableIndex = index(dragEl, options.draggable); + if (Sortable.eventCanceled) { + this._nulling(); + return; + } + awaitingDragStarted = false; + isCircumstantialInvert = false; + pastFirstInvertThresh = false; + clearInterval(this._loopId); + clearTimeout(this._dragStartTimer); + _cancelNextTick(this.cloneId); + _cancelNextTick(this._dragStartId); + + // Unbind events + if (this.nativeDraggable) { + off(document, 'drop', this); + off(el, 'dragstart', this._onDragStart); + } + this._offMoveEvents(); + this._offUpEvents(); + if (Safari) { + css(document.body, 'user-select', ''); + } + css(dragEl, 'transform', ''); + if (evt) { + if (moved) { + evt.cancelable && evt.preventDefault(); + !options.dropBubble && evt.stopPropagation(); + } + ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl); + if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') { + // Remove clone(s) + cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl); + } + if (dragEl) { + if (this.nativeDraggable) { + off(dragEl, 'dragend', this); + } + _disableDraggable(dragEl); + dragEl.style['will-change'] = ''; + + // Remove classes + // ghostClass is added in dragStarted + if (moved && !awaitingDragStarted) { + toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : this.options.ghostClass, false); + } + toggleClass(dragEl, this.options.chosenClass, false); + + // Drag stop event + _dispatchEvent({ + sortable: this, + name: 'unchoose', + toEl: parentEl, + newIndex: null, + newDraggableIndex: null, + originalEvent: evt + }); + if (rootEl !== parentEl) { + if (newIndex >= 0) { + // Add event + _dispatchEvent({ + rootEl: parentEl, + name: 'add', + toEl: parentEl, + fromEl: rootEl, + originalEvent: evt + }); + + // Remove event + _dispatchEvent({ + sortable: this, + name: 'remove', + toEl: parentEl, + originalEvent: evt + }); + + // drag from one list and drop into another + _dispatchEvent({ + rootEl: parentEl, + name: 'sort', + toEl: parentEl, + fromEl: rootEl, + originalEvent: evt + }); + _dispatchEvent({ + sortable: this, + name: 'sort', + toEl: parentEl, + originalEvent: evt + }); + } + putSortable && putSortable.save(); + } else { + if (newIndex !== oldIndex) { + if (newIndex >= 0) { + // drag & drop within the same list + _dispatchEvent({ + sortable: this, + name: 'update', + toEl: parentEl, + originalEvent: evt + }); + _dispatchEvent({ + sortable: this, + name: 'sort', + toEl: parentEl, + originalEvent: evt + }); + } + } + } + if (Sortable.active) { + /* jshint eqnull:true */ + if (newIndex == null || newIndex === -1) { + newIndex = oldIndex; + newDraggableIndex = oldDraggableIndex; + } + _dispatchEvent({ + sortable: this, + name: 'end', + toEl: parentEl, + originalEvent: evt + }); + + // Save sorting + this.save(); + } + } + } + this._nulling(); + }, + _nulling: function _nulling() { + pluginEvent('nulling', this); + rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = cloneHidden = tapEvt = touchEvt = moved = newIndex = newDraggableIndex = oldIndex = oldDraggableIndex = lastTarget = lastDirection = putSortable = activeGroup = Sortable.dragged = Sortable.ghost = Sortable.clone = Sortable.active = null; + savedInputChecked.forEach(function (el) { + el.checked = true; + }); + savedInputChecked.length = lastDx = lastDy = 0; + }, + handleEvent: function handleEvent( /**Event*/evt) { + switch (evt.type) { + case 'drop': + case 'dragend': + this._onDrop(evt); + break; + case 'dragenter': + case 'dragover': + if (dragEl) { + this._onDragOver(evt); + _globalDragOver(evt); + } + break; + case 'selectstart': + evt.preventDefault(); + break; + } + }, + /** + * Serializes the item into an array of string. + * @returns {String[]} + */ + toArray: function toArray() { + var order = [], + el, + children = this.el.children, + i = 0, + n = children.length, + options = this.options; + for (; i < n; i++) { + el = children[i]; + if (closest(el, options.draggable, this.el, false)) { + order.push(el.getAttribute(options.dataIdAttr) || _generateId(el)); + } + } + return order; + }, + /** + * Sorts the elements according to the array. + * @param {String[]} order order of the items + */ + sort: function sort(order, useAnimation) { + var items = {}, + rootEl = this.el; + this.toArray().forEach(function (id, i) { + var el = rootEl.children[i]; + if (closest(el, this.options.draggable, rootEl, false)) { + items[id] = el; + } + }, this); + useAnimation && this.captureAnimationState(); + order.forEach(function (id) { + if (items[id]) { + rootEl.removeChild(items[id]); + rootEl.appendChild(items[id]); + } + }); + useAnimation && this.animateAll(); + }, + /** + * Save the current sorting + */ + save: function save() { + var store = this.options.store; + store && store.set && store.set(this); + }, + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * @param {HTMLElement} el + * @param {String} [selector] default: `options.draggable` + * @returns {HTMLElement|null} + */ + closest: function closest$1(el, selector) { + return closest(el, selector || this.options.draggable, this.el, false); + }, + /** + * Set/get option + * @param {string} name + * @param {*} [value] + * @returns {*} + */ + option: function option(name, value) { + var options = this.options; + if (value === void 0) { + return options[name]; + } else { + var modifiedValue = PluginManager.modifyOption(this, name, value); + if (typeof modifiedValue !== 'undefined') { + options[name] = modifiedValue; + } else { + options[name] = value; + } + if (name === 'group') { + _prepareGroup(options); + } + } + }, + /** + * Destroy + */ + destroy: function destroy() { + pluginEvent('destroy', this); + var el = this.el; + el[expando] = null; + off(el, 'mousedown', this._onTapStart); + off(el, 'touchstart', this._onTapStart); + off(el, 'pointerdown', this._onTapStart); + if (this.nativeDraggable) { + off(el, 'dragover', this); + off(el, 'dragenter', this); + } + // Remove draggable attributes + Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) { + el.removeAttribute('draggable'); + }); + this._onDrop(); + this._disableDelayedDragEvents(); + sortables.splice(sortables.indexOf(this.el), 1); + this.el = el = null; + }, + _hideClone: function _hideClone() { + if (!cloneHidden) { + pluginEvent('hideClone', this); + if (Sortable.eventCanceled) return; + css(cloneEl, 'display', 'none'); + if (this.options.removeCloneOnHide && cloneEl.parentNode) { + cloneEl.parentNode.removeChild(cloneEl); + } + cloneHidden = true; + } + }, + _showClone: function _showClone(putSortable) { + if (putSortable.lastPutMode !== 'clone') { + this._hideClone(); + return; + } + if (cloneHidden) { + pluginEvent('showClone', this); + if (Sortable.eventCanceled) return; + + // show clone at dragEl or original position + if (dragEl.parentNode == rootEl && !this.options.group.revertClone) { + rootEl.insertBefore(cloneEl, dragEl); + } else if (nextEl) { + rootEl.insertBefore(cloneEl, nextEl); + } else { + rootEl.appendChild(cloneEl); + } + if (this.options.group.revertClone) { + this.animate(dragEl, cloneEl); + } + css(cloneEl, 'display', ''); + cloneHidden = false; + } + } + }; + function _globalDragOver( /**Event*/evt) { + if (evt.dataTransfer) { + evt.dataTransfer.dropEffect = 'move'; + } + evt.cancelable && evt.preventDefault(); + } + function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvent, willInsertAfter) { + var evt, + sortable = fromEl[expando], + onMoveFn = sortable.options.onMove, + retVal; + // Support for new CustomEvent feature + if (window.CustomEvent && !IE11OrLess && !Edge) { + evt = new CustomEvent('move', { + bubbles: true, + cancelable: true + }); + } else { + evt = document.createEvent('Event'); + evt.initEvent('move', true, true); + } + evt.to = toEl; + evt.from = fromEl; + evt.dragged = dragEl; + evt.draggedRect = dragRect; + evt.related = targetEl || toEl; + evt.relatedRect = targetRect || getRect(toEl); + evt.willInsertAfter = willInsertAfter; + evt.originalEvent = originalEvent; + fromEl.dispatchEvent(evt); + if (onMoveFn) { + retVal = onMoveFn.call(sortable, evt, originalEvent); + } + return retVal; + } + function _disableDraggable(el) { + el.draggable = false; + } + function _unsilent() { + _silent = false; + } + function _ghostIsFirst(evt, vertical, sortable) { + var firstElRect = getRect(getChild(sortable.el, 0, sortable.options, true)); + var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl); + var spacer = 10; + return vertical ? evt.clientX < childContainingRect.left - spacer || evt.clientY < firstElRect.top && evt.clientX < firstElRect.right : evt.clientY < childContainingRect.top - spacer || evt.clientY < firstElRect.bottom && evt.clientX < firstElRect.left; + } + function _ghostIsLast(evt, vertical, sortable) { + var lastElRect = getRect(lastChild(sortable.el, sortable.options.draggable)); + var childContainingRect = getChildContainingRectFromElement(sortable.el, sortable.options, ghostEl); + var spacer = 10; + return vertical ? evt.clientX > childContainingRect.right + spacer || evt.clientY > lastElRect.bottom && evt.clientX > lastElRect.left : evt.clientY > childContainingRect.bottom + spacer || evt.clientX > lastElRect.right && evt.clientY > lastElRect.top; + } + function _getSwapDirection(evt, target, targetRect, vertical, swapThreshold, invertedSwapThreshold, invertSwap, isLastTarget) { + var mouseOnAxis = vertical ? evt.clientY : evt.clientX, + targetLength = vertical ? targetRect.height : targetRect.width, + targetS1 = vertical ? targetRect.top : targetRect.left, + targetS2 = vertical ? targetRect.bottom : targetRect.right, + invert = false; + if (!invertSwap) { + // Never invert or create dragEl shadow when target movemenet causes mouse to move past the end of regular swapThreshold + if (isLastTarget && targetMoveDistance < targetLength * swapThreshold) { + // multiplied only by swapThreshold because mouse will already be inside target by (1 - threshold) * targetLength / 2 + // check if past first invert threshold on side opposite of lastDirection + if (!pastFirstInvertThresh && (lastDirection === 1 ? mouseOnAxis > targetS1 + targetLength * invertedSwapThreshold / 2 : mouseOnAxis < targetS2 - targetLength * invertedSwapThreshold / 2)) { + // past first invert threshold, do not restrict inverted threshold to dragEl shadow + pastFirstInvertThresh = true; + } + if (!pastFirstInvertThresh) { + // dragEl shadow (target move distance shadow) + if (lastDirection === 1 ? mouseOnAxis < targetS1 + targetMoveDistance // over dragEl shadow + : mouseOnAxis > targetS2 - targetMoveDistance) { + return -lastDirection; + } + } else { + invert = true; + } + } else { + // Regular + if (mouseOnAxis > targetS1 + targetLength * (1 - swapThreshold) / 2 && mouseOnAxis < targetS2 - targetLength * (1 - swapThreshold) / 2) { + return _getInsertDirection(target); + } + } + } + invert = invert || invertSwap; + if (invert) { + // Invert of regular + if (mouseOnAxis < targetS1 + targetLength * invertedSwapThreshold / 2 || mouseOnAxis > targetS2 - targetLength * invertedSwapThreshold / 2) { + return mouseOnAxis > targetS1 + targetLength / 2 ? 1 : -1; + } + } + return 0; + } + + /** + * Gets the direction dragEl must be swapped relative to target in order to make it + * seem that dragEl has been "inserted" into that element's position + * @param {HTMLElement} target The target whose position dragEl is being inserted at + * @return {Number} Direction dragEl must be swapped + */ + function _getInsertDirection(target) { + if (index(dragEl) < index(target)) { + return 1; + } else { + return -1; + } + } + + /** + * Generate id + * @param {HTMLElement} el + * @returns {String} + * @private + */ + function _generateId(el) { + var str = el.tagName + el.className + el.src + el.href + el.textContent, + i = str.length, + sum = 0; + while (i--) { + sum += str.charCodeAt(i); + } + return sum.toString(36); + } + function _saveInputCheckedState(root) { + savedInputChecked.length = 0; + var inputs = root.getElementsByTagName('input'); + var idx = inputs.length; + while (idx--) { + var el = inputs[idx]; + el.checked && savedInputChecked.push(el); + } + } + function _nextTick(fn) { + return setTimeout(fn, 0); + } + function _cancelNextTick(id) { + return clearTimeout(id); + } + + // Fixed #973: + if (documentExists) { + on(document, 'touchmove', function (evt) { + if ((Sortable.active || awaitingDragStarted) && evt.cancelable) { + evt.preventDefault(); + } + }); + } + + // Export utils + Sortable.utils = { + on: on, + off: off, + css: css, + find: find, + is: function is(el, selector) { + return !!closest(el, selector, el, false); + }, + extend: extend, + throttle: throttle, + closest: closest, + toggleClass: toggleClass, + clone: clone, + index: index, + nextTick: _nextTick, + cancelNextTick: _cancelNextTick, + detectDirection: _detectDirection, + getChild: getChild + }; + + /** + * Get the Sortable instance of an element + * @param {HTMLElement} element The element + * @return {Sortable|undefined} The instance of Sortable + */ + Sortable.get = function (element) { + return element[expando]; + }; + + /** + * Mount a plugin to Sortable + * @param {...SortablePlugin|SortablePlugin[]} plugins Plugins being mounted + */ + Sortable.mount = function () { + for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) { + plugins[_key] = arguments[_key]; + } + if (plugins[0].constructor === Array) plugins = plugins[0]; + plugins.forEach(function (plugin) { + if (!plugin.prototype || !plugin.prototype.constructor) { + throw "Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(plugin)); + } + if (plugin.utils) Sortable.utils = _objectSpread2(_objectSpread2({}, Sortable.utils), plugin.utils); + PluginManager.mount(plugin); + }); + }; + + /** + * Create sortable instance + * @param {HTMLElement} el + * @param {Object} [options] + */ + Sortable.create = function (el, options) { + return new Sortable(el, options); + }; + + // Export + Sortable.version = version; + + var autoScrolls = [], + scrollEl, + scrollRootEl, + scrolling = false, + lastAutoScrollX, + lastAutoScrollY, + touchEvt$1, + pointerElemChangedInterval; + function AutoScrollPlugin() { + function AutoScroll() { + this.defaults = { + scroll: true, + forceAutoScrollFallback: false, + scrollSensitivity: 30, + scrollSpeed: 10, + bubbleScroll: true + }; + + // Bind all private methods + for (var fn in this) { + if (fn.charAt(0) === '_' && typeof this[fn] === 'function') { + this[fn] = this[fn].bind(this); + } + } + } + AutoScroll.prototype = { + dragStarted: function dragStarted(_ref) { + var originalEvent = _ref.originalEvent; + if (this.sortable.nativeDraggable) { + on(document, 'dragover', this._handleAutoScroll); + } else { + if (this.options.supportPointer) { + on(document, 'pointermove', this._handleFallbackAutoScroll); + } else if (originalEvent.touches) { + on(document, 'touchmove', this._handleFallbackAutoScroll); + } else { + on(document, 'mousemove', this._handleFallbackAutoScroll); + } + } + }, + dragOverCompleted: function dragOverCompleted(_ref2) { + var originalEvent = _ref2.originalEvent; + // For when bubbling is canceled and using fallback (fallback 'touchmove' always reached) + if (!this.options.dragOverBubble && !originalEvent.rootEl) { + this._handleAutoScroll(originalEvent); + } + }, + drop: function drop() { + if (this.sortable.nativeDraggable) { + off(document, 'dragover', this._handleAutoScroll); + } else { + off(document, 'pointermove', this._handleFallbackAutoScroll); + off(document, 'touchmove', this._handleFallbackAutoScroll); + off(document, 'mousemove', this._handleFallbackAutoScroll); + } + clearPointerElemChangedInterval(); + clearAutoScrolls(); + cancelThrottle(); + }, + nulling: function nulling() { + touchEvt$1 = scrollRootEl = scrollEl = scrolling = pointerElemChangedInterval = lastAutoScrollX = lastAutoScrollY = null; + autoScrolls.length = 0; + }, + _handleFallbackAutoScroll: function _handleFallbackAutoScroll(evt) { + this._handleAutoScroll(evt, true); + }, + _handleAutoScroll: function _handleAutoScroll(evt, fallback) { + var _this = this; + var x = (evt.touches ? evt.touches[0] : evt).clientX, + y = (evt.touches ? evt.touches[0] : evt).clientY, + elem = document.elementFromPoint(x, y); + touchEvt$1 = evt; + + // IE does not seem to have native autoscroll, + // Edge's autoscroll seems too conditional, + // MACOS Safari does not have autoscroll, + // Firefox and Chrome are good + if (fallback || this.options.forceAutoScrollFallback || Edge || IE11OrLess || Safari) { + autoScroll(evt, this.options, elem, fallback); + + // Listener for pointer element change + var ogElemScroller = getParentAutoScrollElement(elem, true); + if (scrolling && (!pointerElemChangedInterval || x !== lastAutoScrollX || y !== lastAutoScrollY)) { + pointerElemChangedInterval && clearPointerElemChangedInterval(); + // Detect for pointer elem change, emulating native DnD behaviour + pointerElemChangedInterval = setInterval(function () { + var newElem = getParentAutoScrollElement(document.elementFromPoint(x, y), true); + if (newElem !== ogElemScroller) { + ogElemScroller = newElem; + clearAutoScrolls(); + } + autoScroll(evt, _this.options, newElem, fallback); + }, 10); + lastAutoScrollX = x; + lastAutoScrollY = y; + } + } else { + // if DnD is enabled (and browser has good autoscrolling), first autoscroll will already scroll, so get parent autoscroll of first autoscroll + if (!this.options.bubbleScroll || getParentAutoScrollElement(elem, true) === getWindowScrollingElement()) { + clearAutoScrolls(); + return; + } + autoScroll(evt, this.options, getParentAutoScrollElement(elem, false), false); + } + } + }; + return _extends(AutoScroll, { + pluginName: 'scroll', + initializeByDefault: true + }); + } + function clearAutoScrolls() { + autoScrolls.forEach(function (autoScroll) { + clearInterval(autoScroll.pid); + }); + autoScrolls = []; + } + function clearPointerElemChangedInterval() { + clearInterval(pointerElemChangedInterval); + } + var autoScroll = throttle(function (evt, options, rootEl, isFallback) { + // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521 + if (!options.scroll) return; + var x = (evt.touches ? evt.touches[0] : evt).clientX, + y = (evt.touches ? evt.touches[0] : evt).clientY, + sens = options.scrollSensitivity, + speed = options.scrollSpeed, + winScroller = getWindowScrollingElement(); + var scrollThisInstance = false, + scrollCustomFn; + + // New scroll root, set scrollEl + if (scrollRootEl !== rootEl) { + scrollRootEl = rootEl; + clearAutoScrolls(); + scrollEl = options.scroll; + scrollCustomFn = options.scrollFn; + if (scrollEl === true) { + scrollEl = getParentAutoScrollElement(rootEl, true); + } + } + var layersOut = 0; + var currentParent = scrollEl; + do { + var el = currentParent, + rect = getRect(el), + top = rect.top, + bottom = rect.bottom, + left = rect.left, + right = rect.right, + width = rect.width, + height = rect.height, + canScrollX = void 0, + canScrollY = void 0, + scrollWidth = el.scrollWidth, + scrollHeight = el.scrollHeight, + elCSS = css(el), + scrollPosX = el.scrollLeft, + scrollPosY = el.scrollTop; + if (el === winScroller) { + canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll' || elCSS.overflowX === 'visible'); + canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll' || elCSS.overflowY === 'visible'); + } else { + canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll'); + canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll'); + } + var vx = canScrollX && (Math.abs(right - x) <= sens && scrollPosX + width < scrollWidth) - (Math.abs(left - x) <= sens && !!scrollPosX); + var vy = canScrollY && (Math.abs(bottom - y) <= sens && scrollPosY + height < scrollHeight) - (Math.abs(top - y) <= sens && !!scrollPosY); + if (!autoScrolls[layersOut]) { + for (var i = 0; i <= layersOut; i++) { + if (!autoScrolls[i]) { + autoScrolls[i] = {}; + } + } + } + if (autoScrolls[layersOut].vx != vx || autoScrolls[layersOut].vy != vy || autoScrolls[layersOut].el !== el) { + autoScrolls[layersOut].el = el; + autoScrolls[layersOut].vx = vx; + autoScrolls[layersOut].vy = vy; + clearInterval(autoScrolls[layersOut].pid); + if (vx != 0 || vy != 0) { + scrollThisInstance = true; + /* jshint loopfunc:true */ + autoScrolls[layersOut].pid = setInterval(function () { + // emulate drag over during autoscroll (fallback), emulating native DnD behaviour + if (isFallback && this.layer === 0) { + Sortable.active._onTouchMove(touchEvt$1); // To move ghost if it is positioned absolutely + } + var scrollOffsetY = autoScrolls[this.layer].vy ? autoScrolls[this.layer].vy * speed : 0; + var scrollOffsetX = autoScrolls[this.layer].vx ? autoScrolls[this.layer].vx * speed : 0; + if (typeof scrollCustomFn === 'function') { + if (scrollCustomFn.call(Sortable.dragged.parentNode[expando], scrollOffsetX, scrollOffsetY, evt, touchEvt$1, autoScrolls[this.layer].el) !== 'continue') { + return; + } + } + scrollBy(autoScrolls[this.layer].el, scrollOffsetX, scrollOffsetY); + }.bind({ + layer: layersOut + }), 24); + } + } + layersOut++; + } while (options.bubbleScroll && currentParent !== winScroller && (currentParent = getParentAutoScrollElement(currentParent, false))); + scrolling = scrollThisInstance; // in case another function catches scrolling as false in between when it is not + }, 30); + + var drop = function drop(_ref) { + var originalEvent = _ref.originalEvent, + putSortable = _ref.putSortable, + dragEl = _ref.dragEl, + activeSortable = _ref.activeSortable, + dispatchSortableEvent = _ref.dispatchSortableEvent, + hideGhostForTarget = _ref.hideGhostForTarget, + unhideGhostForTarget = _ref.unhideGhostForTarget; + if (!originalEvent) return; + var toSortable = putSortable || activeSortable; + hideGhostForTarget(); + var touch = originalEvent.changedTouches && originalEvent.changedTouches.length ? originalEvent.changedTouches[0] : originalEvent; + var target = document.elementFromPoint(touch.clientX, touch.clientY); + unhideGhostForTarget(); + if (toSortable && !toSortable.el.contains(target)) { + dispatchSortableEvent('spill'); + this.onSpill({ + dragEl: dragEl, + putSortable: putSortable + }); + } + }; + function Revert() {} + Revert.prototype = { + startIndex: null, + dragStart: function dragStart(_ref2) { + var oldDraggableIndex = _ref2.oldDraggableIndex; + this.startIndex = oldDraggableIndex; + }, + onSpill: function onSpill(_ref3) { + var dragEl = _ref3.dragEl, + putSortable = _ref3.putSortable; + this.sortable.captureAnimationState(); + if (putSortable) { + putSortable.captureAnimationState(); + } + var nextSibling = getChild(this.sortable.el, this.startIndex, this.options); + if (nextSibling) { + this.sortable.el.insertBefore(dragEl, nextSibling); + } else { + this.sortable.el.appendChild(dragEl); + } + this.sortable.animateAll(); + if (putSortable) { + putSortable.animateAll(); + } + }, + drop: drop + }; + _extends(Revert, { + pluginName: 'revertOnSpill' + }); + function Remove() {} + Remove.prototype = { + onSpill: function onSpill(_ref4) { + var dragEl = _ref4.dragEl, + putSortable = _ref4.putSortable; + var parentSortable = putSortable || this.sortable; + parentSortable.captureAnimationState(); + dragEl.parentNode && dragEl.parentNode.removeChild(dragEl); + parentSortable.animateAll(); + }, + drop: drop + }; + _extends(Remove, { + pluginName: 'removeOnSpill' + }); + + var lastSwapEl; + function SwapPlugin() { + function Swap() { + this.defaults = { + swapClass: 'sortable-swap-highlight' + }; + } + Swap.prototype = { + dragStart: function dragStart(_ref) { + var dragEl = _ref.dragEl; + lastSwapEl = dragEl; + }, + dragOverValid: function dragOverValid(_ref2) { + var completed = _ref2.completed, + target = _ref2.target, + onMove = _ref2.onMove, + activeSortable = _ref2.activeSortable, + changed = _ref2.changed, + cancel = _ref2.cancel; + if (!activeSortable.options.swap) return; + var el = this.sortable.el, + options = this.options; + if (target && target !== el) { + var prevSwapEl = lastSwapEl; + if (onMove(target) !== false) { + toggleClass(target, options.swapClass, true); + lastSwapEl = target; + } else { + lastSwapEl = null; + } + if (prevSwapEl && prevSwapEl !== lastSwapEl) { + toggleClass(prevSwapEl, options.swapClass, false); + } + } + changed(); + completed(true); + cancel(); + }, + drop: function drop(_ref3) { + var activeSortable = _ref3.activeSortable, + putSortable = _ref3.putSortable, + dragEl = _ref3.dragEl; + var toSortable = putSortable || this.sortable; + var options = this.options; + lastSwapEl && toggleClass(lastSwapEl, options.swapClass, false); + if (lastSwapEl && (options.swap || putSortable && putSortable.options.swap)) { + if (dragEl !== lastSwapEl) { + toSortable.captureAnimationState(); + if (toSortable !== activeSortable) activeSortable.captureAnimationState(); + swapNodes(dragEl, lastSwapEl); + toSortable.animateAll(); + if (toSortable !== activeSortable) activeSortable.animateAll(); + } + } + }, + nulling: function nulling() { + lastSwapEl = null; + } + }; + return _extends(Swap, { + pluginName: 'swap', + eventProperties: function eventProperties() { + return { + swapItem: lastSwapEl + }; + } + }); + } + function swapNodes(n1, n2) { + var p1 = n1.parentNode, + p2 = n2.parentNode, + i1, + i2; + if (!p1 || !p2 || p1.isEqualNode(n2) || p2.isEqualNode(n1)) return; + i1 = index(n1); + i2 = index(n2); + if (p1.isEqualNode(p2) && i1 < i2) { + i2++; + } + p1.insertBefore(n2, p1.children[i1]); + p2.insertBefore(n1, p2.children[i2]); + } + + var multiDragElements = [], + multiDragClones = [], + lastMultiDragSelect, + // for selection with modifier key down (SHIFT) + multiDragSortable, + initialFolding = false, + // Initial multi-drag fold when drag started + folding = false, + // Folding any other time + dragStarted = false, + dragEl$1, + clonesFromRect, + clonesHidden; + function MultiDragPlugin() { + function MultiDrag(sortable) { + // Bind all private methods + for (var fn in this) { + if (fn.charAt(0) === '_' && typeof this[fn] === 'function') { + this[fn] = this[fn].bind(this); + } + } + if (!sortable.options.avoidImplicitDeselect) { + if (sortable.options.supportPointer) { + on(document, 'pointerup', this._deselectMultiDrag); + } else { + on(document, 'mouseup', this._deselectMultiDrag); + on(document, 'touchend', this._deselectMultiDrag); + } + } + on(document, 'keydown', this._checkKeyDown); + on(document, 'keyup', this._checkKeyUp); + this.defaults = { + selectedClass: 'sortable-selected', + multiDragKey: null, + avoidImplicitDeselect: false, + setData: function setData(dataTransfer, dragEl) { + var data = ''; + if (multiDragElements.length && multiDragSortable === sortable) { + multiDragElements.forEach(function (multiDragElement, i) { + data += (!i ? '' : ', ') + multiDragElement.textContent; + }); + } else { + data = dragEl.textContent; + } + dataTransfer.setData('Text', data); + } + }; + } + MultiDrag.prototype = { + multiDragKeyDown: false, + isMultiDrag: false, + delayStartGlobal: function delayStartGlobal(_ref) { + var dragged = _ref.dragEl; + dragEl$1 = dragged; + }, + delayEnded: function delayEnded() { + this.isMultiDrag = ~multiDragElements.indexOf(dragEl$1); + }, + setupClone: function setupClone(_ref2) { + var sortable = _ref2.sortable, + cancel = _ref2.cancel; + if (!this.isMultiDrag) return; + for (var i = 0; i < multiDragElements.length; i++) { + multiDragClones.push(clone(multiDragElements[i])); + multiDragClones[i].sortableIndex = multiDragElements[i].sortableIndex; + multiDragClones[i].draggable = false; + multiDragClones[i].style['will-change'] = ''; + toggleClass(multiDragClones[i], this.options.selectedClass, false); + multiDragElements[i] === dragEl$1 && toggleClass(multiDragClones[i], this.options.chosenClass, false); + } + sortable._hideClone(); + cancel(); + }, + clone: function clone(_ref3) { + var sortable = _ref3.sortable, + rootEl = _ref3.rootEl, + dispatchSortableEvent = _ref3.dispatchSortableEvent, + cancel = _ref3.cancel; + if (!this.isMultiDrag) return; + if (!this.options.removeCloneOnHide) { + if (multiDragElements.length && multiDragSortable === sortable) { + insertMultiDragClones(true, rootEl); + dispatchSortableEvent('clone'); + cancel(); + } + } + }, + showClone: function showClone(_ref4) { + var cloneNowShown = _ref4.cloneNowShown, + rootEl = _ref4.rootEl, + cancel = _ref4.cancel; + if (!this.isMultiDrag) return; + insertMultiDragClones(false, rootEl); + multiDragClones.forEach(function (clone) { + css(clone, 'display', ''); + }); + cloneNowShown(); + clonesHidden = false; + cancel(); + }, + hideClone: function hideClone(_ref5) { + var _this = this; + var sortable = _ref5.sortable, + cloneNowHidden = _ref5.cloneNowHidden, + cancel = _ref5.cancel; + if (!this.isMultiDrag) return; + multiDragClones.forEach(function (clone) { + css(clone, 'display', 'none'); + if (_this.options.removeCloneOnHide && clone.parentNode) { + clone.parentNode.removeChild(clone); + } + }); + cloneNowHidden(); + clonesHidden = true; + cancel(); + }, + dragStartGlobal: function dragStartGlobal(_ref6) { + var sortable = _ref6.sortable; + if (!this.isMultiDrag && multiDragSortable) { + multiDragSortable.multiDrag._deselectMultiDrag(); + } + multiDragElements.forEach(function (multiDragElement) { + multiDragElement.sortableIndex = index(multiDragElement); + }); + + // Sort multi-drag elements + multiDragElements = multiDragElements.sort(function (a, b) { + return a.sortableIndex - b.sortableIndex; + }); + dragStarted = true; + }, + dragStarted: function dragStarted(_ref7) { + var _this2 = this; + var sortable = _ref7.sortable; + if (!this.isMultiDrag) return; + if (this.options.sort) { + // Capture rects, + // hide multi drag elements (by positioning them absolute), + // set multi drag elements rects to dragRect, + // show multi drag elements, + // animate to rects, + // unset rects & remove from DOM + + sortable.captureAnimationState(); + if (this.options.animation) { + multiDragElements.forEach(function (multiDragElement) { + if (multiDragElement === dragEl$1) return; + css(multiDragElement, 'position', 'absolute'); + }); + var dragRect = getRect(dragEl$1, false, true, true); + multiDragElements.forEach(function (multiDragElement) { + if (multiDragElement === dragEl$1) return; + setRect(multiDragElement, dragRect); + }); + folding = true; + initialFolding = true; + } + } + sortable.animateAll(function () { + folding = false; + initialFolding = false; + if (_this2.options.animation) { + multiDragElements.forEach(function (multiDragElement) { + unsetRect(multiDragElement); + }); + } + + // Remove all auxiliary multidrag items from el, if sorting enabled + if (_this2.options.sort) { + removeMultiDragElements(); + } + }); + }, + dragOver: function dragOver(_ref8) { + var target = _ref8.target, + completed = _ref8.completed, + cancel = _ref8.cancel; + if (folding && ~multiDragElements.indexOf(target)) { + completed(false); + cancel(); + } + }, + revert: function revert(_ref9) { + var fromSortable = _ref9.fromSortable, + rootEl = _ref9.rootEl, + sortable = _ref9.sortable, + dragRect = _ref9.dragRect; + if (multiDragElements.length > 1) { + // Setup unfold animation + multiDragElements.forEach(function (multiDragElement) { + sortable.addAnimationState({ + target: multiDragElement, + rect: folding ? getRect(multiDragElement) : dragRect + }); + unsetRect(multiDragElement); + multiDragElement.fromRect = dragRect; + fromSortable.removeAnimationState(multiDragElement); + }); + folding = false; + insertMultiDragElements(!this.options.removeCloneOnHide, rootEl); + } + }, + dragOverCompleted: function dragOverCompleted(_ref10) { + var sortable = _ref10.sortable, + isOwner = _ref10.isOwner, + insertion = _ref10.insertion, + activeSortable = _ref10.activeSortable, + parentEl = _ref10.parentEl, + putSortable = _ref10.putSortable; + var options = this.options; + if (insertion) { + // Clones must be hidden before folding animation to capture dragRectAbsolute properly + if (isOwner) { + activeSortable._hideClone(); + } + initialFolding = false; + // If leaving sort:false root, or already folding - Fold to new location + if (options.animation && multiDragElements.length > 1 && (folding || !isOwner && !activeSortable.options.sort && !putSortable)) { + // Fold: Set all multi drag elements's rects to dragEl's rect when multi-drag elements are invisible + var dragRectAbsolute = getRect(dragEl$1, false, true, true); + multiDragElements.forEach(function (multiDragElement) { + if (multiDragElement === dragEl$1) return; + setRect(multiDragElement, dragRectAbsolute); + + // Move element(s) to end of parentEl so that it does not interfere with multi-drag clones insertion if they are inserted + // while folding, and so that we can capture them again because old sortable will no longer be fromSortable + parentEl.appendChild(multiDragElement); + }); + folding = true; + } + + // Clones must be shown (and check to remove multi drags) after folding when interfering multiDragElements are moved out + if (!isOwner) { + // Only remove if not folding (folding will remove them anyways) + if (!folding) { + removeMultiDragElements(); + } + if (multiDragElements.length > 1) { + var clonesHiddenBefore = clonesHidden; + activeSortable._showClone(sortable); + + // Unfold animation for clones if showing from hidden + if (activeSortable.options.animation && !clonesHidden && clonesHiddenBefore) { + multiDragClones.forEach(function (clone) { + activeSortable.addAnimationState({ + target: clone, + rect: clonesFromRect + }); + clone.fromRect = clonesFromRect; + clone.thisAnimationDuration = null; + }); + } + } else { + activeSortable._showClone(sortable); + } + } + } + }, + dragOverAnimationCapture: function dragOverAnimationCapture(_ref11) { + var dragRect = _ref11.dragRect, + isOwner = _ref11.isOwner, + activeSortable = _ref11.activeSortable; + multiDragElements.forEach(function (multiDragElement) { + multiDragElement.thisAnimationDuration = null; + }); + if (activeSortable.options.animation && !isOwner && activeSortable.multiDrag.isMultiDrag) { + clonesFromRect = _extends({}, dragRect); + var dragMatrix = matrix(dragEl$1, true); + clonesFromRect.top -= dragMatrix.f; + clonesFromRect.left -= dragMatrix.e; + } + }, + dragOverAnimationComplete: function dragOverAnimationComplete() { + if (folding) { + folding = false; + removeMultiDragElements(); + } + }, + drop: function drop(_ref12) { + var evt = _ref12.originalEvent, + rootEl = _ref12.rootEl, + parentEl = _ref12.parentEl, + sortable = _ref12.sortable, + dispatchSortableEvent = _ref12.dispatchSortableEvent, + oldIndex = _ref12.oldIndex, + putSortable = _ref12.putSortable; + var toSortable = putSortable || this.sortable; + if (!evt) return; + var options = this.options, + children = parentEl.children; + + // Multi-drag selection + if (!dragStarted) { + if (options.multiDragKey && !this.multiDragKeyDown) { + this._deselectMultiDrag(); + } + toggleClass(dragEl$1, options.selectedClass, !~multiDragElements.indexOf(dragEl$1)); + if (!~multiDragElements.indexOf(dragEl$1)) { + multiDragElements.push(dragEl$1); + dispatchEvent({ + sortable: sortable, + rootEl: rootEl, + name: 'select', + targetEl: dragEl$1, + originalEvent: evt + }); + + // Modifier activated, select from last to dragEl + if (evt.shiftKey && lastMultiDragSelect && sortable.el.contains(lastMultiDragSelect)) { + var lastIndex = index(lastMultiDragSelect), + currentIndex = index(dragEl$1); + if (~lastIndex && ~currentIndex && lastIndex !== currentIndex) { + // Must include lastMultiDragSelect (select it), in case modified selection from no selection + // (but previous selection existed) + var n, i; + if (currentIndex > lastIndex) { + i = lastIndex; + n = currentIndex; + } else { + i = currentIndex; + n = lastIndex + 1; + } + for (; i < n; i++) { + if (~multiDragElements.indexOf(children[i])) continue; + toggleClass(children[i], options.selectedClass, true); + multiDragElements.push(children[i]); + dispatchEvent({ + sortable: sortable, + rootEl: rootEl, + name: 'select', + targetEl: children[i], + originalEvent: evt + }); + } + } + } else { + lastMultiDragSelect = dragEl$1; + } + multiDragSortable = toSortable; + } else { + multiDragElements.splice(multiDragElements.indexOf(dragEl$1), 1); + lastMultiDragSelect = null; + dispatchEvent({ + sortable: sortable, + rootEl: rootEl, + name: 'deselect', + targetEl: dragEl$1, + originalEvent: evt + }); + } + } + + // Multi-drag drop + if (dragStarted && this.isMultiDrag) { + folding = false; + // Do not "unfold" after around dragEl if reverted + if ((parentEl[expando].options.sort || parentEl !== rootEl) && multiDragElements.length > 1) { + var dragRect = getRect(dragEl$1), + multiDragIndex = index(dragEl$1, ':not(.' + this.options.selectedClass + ')'); + if (!initialFolding && options.animation) dragEl$1.thisAnimationDuration = null; + toSortable.captureAnimationState(); + if (!initialFolding) { + if (options.animation) { + dragEl$1.fromRect = dragRect; + multiDragElements.forEach(function (multiDragElement) { + multiDragElement.thisAnimationDuration = null; + if (multiDragElement !== dragEl$1) { + var rect = folding ? getRect(multiDragElement) : dragRect; + multiDragElement.fromRect = rect; + + // Prepare unfold animation + toSortable.addAnimationState({ + target: multiDragElement, + rect: rect + }); + } + }); + } + + // Multi drag elements are not necessarily removed from the DOM on drop, so to reinsert + // properly they must all be removed + removeMultiDragElements(); + multiDragElements.forEach(function (multiDragElement) { + if (children[multiDragIndex]) { + parentEl.insertBefore(multiDragElement, children[multiDragIndex]); + } else { + parentEl.appendChild(multiDragElement); + } + multiDragIndex++; + }); + + // If initial folding is done, the elements may have changed position because they are now + // unfolding around dragEl, even though dragEl may not have his index changed, so update event + // must be fired here as Sortable will not. + if (oldIndex === index(dragEl$1)) { + var update = false; + multiDragElements.forEach(function (multiDragElement) { + if (multiDragElement.sortableIndex !== index(multiDragElement)) { + update = true; + return; + } + }); + if (update) { + dispatchSortableEvent('update'); + dispatchSortableEvent('sort'); + } + } + } + + // Must be done after capturing individual rects (scroll bar) + multiDragElements.forEach(function (multiDragElement) { + unsetRect(multiDragElement); + }); + toSortable.animateAll(); + } + multiDragSortable = toSortable; + } + + // Remove clones if necessary + if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') { + multiDragClones.forEach(function (clone) { + clone.parentNode && clone.parentNode.removeChild(clone); + }); + } + }, + nullingGlobal: function nullingGlobal() { + this.isMultiDrag = dragStarted = false; + multiDragClones.length = 0; + }, + destroyGlobal: function destroyGlobal() { + this._deselectMultiDrag(); + off(document, 'pointerup', this._deselectMultiDrag); + off(document, 'mouseup', this._deselectMultiDrag); + off(document, 'touchend', this._deselectMultiDrag); + off(document, 'keydown', this._checkKeyDown); + off(document, 'keyup', this._checkKeyUp); + }, + _deselectMultiDrag: function _deselectMultiDrag(evt) { + if (typeof dragStarted !== "undefined" && dragStarted) return; + + // Only deselect if selection is in this sortable + if (multiDragSortable !== this.sortable) return; + + // Only deselect if target is not item in this sortable + if (evt && closest(evt.target, this.options.draggable, this.sortable.el, false)) return; + + // Only deselect if left click + if (evt && evt.button !== 0) return; + while (multiDragElements.length) { + var el = multiDragElements[0]; + toggleClass(el, this.options.selectedClass, false); + multiDragElements.shift(); + dispatchEvent({ + sortable: this.sortable, + rootEl: this.sortable.el, + name: 'deselect', + targetEl: el, + originalEvent: evt + }); + } + }, + _checkKeyDown: function _checkKeyDown(evt) { + if (evt.key === this.options.multiDragKey) { + this.multiDragKeyDown = true; + } + }, + _checkKeyUp: function _checkKeyUp(evt) { + if (evt.key === this.options.multiDragKey) { + this.multiDragKeyDown = false; + } + } + }; + return _extends(MultiDrag, { + // Static methods & properties + pluginName: 'multiDrag', + utils: { + /** + * Selects the provided multi-drag item + * @param {HTMLElement} el The element to be selected + */ + select: function select(el) { + var sortable = el.parentNode[expando]; + if (!sortable || !sortable.options.multiDrag || ~multiDragElements.indexOf(el)) return; + if (multiDragSortable && multiDragSortable !== sortable) { + multiDragSortable.multiDrag._deselectMultiDrag(); + multiDragSortable = sortable; + } + toggleClass(el, sortable.options.selectedClass, true); + multiDragElements.push(el); + }, + /** + * Deselects the provided multi-drag item + * @param {HTMLElement} el The element to be deselected + */ + deselect: function deselect(el) { + var sortable = el.parentNode[expando], + index = multiDragElements.indexOf(el); + if (!sortable || !sortable.options.multiDrag || !~index) return; + toggleClass(el, sortable.options.selectedClass, false); + multiDragElements.splice(index, 1); + } + }, + eventProperties: function eventProperties() { + var _this3 = this; + var oldIndicies = [], + newIndicies = []; + multiDragElements.forEach(function (multiDragElement) { + oldIndicies.push({ + multiDragElement: multiDragElement, + index: multiDragElement.sortableIndex + }); + + // multiDragElements will already be sorted if folding + var newIndex; + if (folding && multiDragElement !== dragEl$1) { + newIndex = -1; + } else if (folding) { + newIndex = index(multiDragElement, ':not(.' + _this3.options.selectedClass + ')'); + } else { + newIndex = index(multiDragElement); + } + newIndicies.push({ + multiDragElement: multiDragElement, + index: newIndex + }); + }); + return { + items: _toConsumableArray(multiDragElements), + clones: [].concat(multiDragClones), + oldIndicies: oldIndicies, + newIndicies: newIndicies + }; + }, + optionListeners: { + multiDragKey: function multiDragKey(key) { + key = key.toLowerCase(); + if (key === 'ctrl') { + key = 'Control'; + } else if (key.length > 1) { + key = key.charAt(0).toUpperCase() + key.substr(1); + } + return key; + } + } + }); + } + function insertMultiDragElements(clonesInserted, rootEl) { + multiDragElements.forEach(function (multiDragElement, i) { + var target = rootEl.children[multiDragElement.sortableIndex + (clonesInserted ? Number(i) : 0)]; + if (target) { + rootEl.insertBefore(multiDragElement, target); + } else { + rootEl.appendChild(multiDragElement); + } + }); + } + + /** + * Insert multi-drag clones + * @param {[Boolean]} elementsInserted Whether the multi-drag elements are inserted + * @param {HTMLElement} rootEl + */ + function insertMultiDragClones(elementsInserted, rootEl) { + multiDragClones.forEach(function (clone, i) { + var target = rootEl.children[clone.sortableIndex + (elementsInserted ? Number(i) : 0)]; + if (target) { + rootEl.insertBefore(clone, target); + } else { + rootEl.appendChild(clone); + } + }); + } + function removeMultiDragElements() { + multiDragElements.forEach(function (multiDragElement) { + if (multiDragElement === dragEl$1) return; + multiDragElement.parentNode && multiDragElement.parentNode.removeChild(multiDragElement); + }); + } + + Sortable.mount(new AutoScrollPlugin()); + Sortable.mount(Remove, Revert); + + Sortable.mount(new SwapPlugin()); + Sortable.mount(new MultiDragPlugin()); + + return Sortable; + +}))); diff --git a/tad/site/templates/default_layout.jinja b/tad/site/templates/default_layout.jinja new file mode 100644 index 000000000..d3e248c58 --- /dev/null +++ b/tad/site/templates/default_layout.jinja @@ -0,0 +1,90 @@ +{% macro render_task_card(task) -%} + {% include "task.jinja" %} +{%- endmacro -%} + +{% macro render_task_column(status) -%} +
+

{{ status.name }}

+
+ {% for task in tasks_service.get_tasks(status.id) %} + {{ render_task_card(task) }} + {% endfor %} +
+
+{% endmacro -%} + + + + + {{ page_title }} + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+ Transparency of Algorithmic Decision making (TAD) +
+
+
+ +
+
+
+ + + + +
+

Project X

+
+ +
+
+ + {% for status in statuses_service.get_statuses() %} + {{ render_task_column(status) }} + {% endfor %} +{#
#} +{#

In progress

#} +{#
#} +{#
#} +{#
#} +{#
#} +{#

Review

#} +{#
#} +{#
#} +{#
#} +{#
#} +{#

Done

#} +{#
#} +{#
#} +{#
#} +
+
+ + + diff --git a/tad/site/templates/error.jinja b/tad/site/templates/error.jinja new file mode 100644 index 000000000..ea51d2618 --- /dev/null +++ b/tad/site/templates/error.jinja @@ -0,0 +1,3 @@ +
+

This is an error message

+
diff --git a/tad/site/templates/root/index.html b/tad/site/templates/root/index.html new file mode 100644 index 000000000..682bb0157 --- /dev/null +++ b/tad/site/templates/root/index.html @@ -0,0 +1,12 @@ +{% extends "/root/layout.html" %} + +{% block title %}Home Page page{% endblock %} + +{% block content %} +

Welcome to the Home Page

+

This is a simple Jinja template example.

+

+ View project task overview +

+ +{% endblock %} diff --git a/tad/templates/layout.html b/tad/site/templates/root/layout.html similarity index 100% rename from tad/templates/layout.html rename to tad/site/templates/root/layout.html diff --git a/tad/site/templates/task.jinja b/tad/site/templates/task.jinja new file mode 100644 index 000000000..81b7abda8 --- /dev/null +++ b/tad/site/templates/task.jinja @@ -0,0 +1,9 @@ +
+

{{ task.title }}

+
{{ task.description }}
+ {% if task.user_id %} +
+ Assigned to Avatar +
+ {% endif %} +
diff --git a/tad/templates/root/index.html b/tad/templates/root/index.html deleted file mode 100644 index ce9e75d6b..000000000 --- a/tad/templates/root/index.html +++ /dev/null @@ -1,8 +0,0 @@ -{% extends "layout.html" %} - -{% block title %}Home Page{% endblock %} - -{% block content %} -

Welcome to the Home Page

-

This is a simple Jinja template example.

-{% endblock %} diff --git a/tests/api/routes/test_pages.py b/tests/api/routes/test_pages.py new file mode 100644 index 000000000..b65e4ec0c --- /dev/null +++ b/tests/api/routes/test_pages.py @@ -0,0 +1,8 @@ +from fastapi.testclient import TestClient + + +def test_get_main_page(client: TestClient) -> None: + response = client.get("/pages/") + assert response.status_code == 200 + assert response.headers["content-type"] == "text/html; charset=utf-8" + assert b"" in response.content diff --git a/tests/api/routes/test_status.py b/tests/api/routes/test_status.py new file mode 100644 index 000000000..f396cc895 --- /dev/null +++ b/tests/api/routes/test_status.py @@ -0,0 +1,20 @@ +from fastapi.testclient import TestClient +from tad.models.task import MoveTask + +from tests.database_test_utils import DatabaseTestUtils + + +def test_post_move_task(client: TestClient, db: DatabaseTestUtils) -> None: + db.init( + [ + {"table": "status", "id": 2}, + {"table": "task", "id": 1, "status_id": 2}, + {"table": "task", "id": 2, "status_id": 2}, + {"table": "task", "id": 3, "status_id": 2}, + ] + ) + move_task: MoveTask = MoveTask(taskId="2", statusId="2", previousSiblingId="1", nextSiblingId="3") + response = client.post("/tasks/move", json=move_task.model_dump(by_alias=True)) + assert response.status_code == 200 + assert response.headers["content-type"] == "text/html; charset=utf-8" + assert b'class="progress_card_container"' in response.content diff --git a/tests/api/routes/test_tasks_move.py b/tests/api/routes/test_tasks_move.py new file mode 100644 index 000000000..a97b041dd --- /dev/null +++ b/tests/api/routes/test_tasks_move.py @@ -0,0 +1,29 @@ +from fastapi.testclient import TestClient + +from tests.database_test_utils import DatabaseTestUtils + + +def test_post_task_move(client: TestClient, db: DatabaseTestUtils) -> None: + db.init( + [ + {"table": "status", "id": 1}, + {"table": "task", "id": 1, "status_id": 1}, + {"table": "task", "id": 2, "status_id": 1}, + ] + ) + response = client.post( + "/tasks/move", json={"taskId": "1", "statusId": "1", "previousSiblingId": "2", "nextSiblingId": ""} + ) + assert response.status_code == 200 + assert response.headers["content-type"] == "text/html; charset=utf-8" + assert b'id="card-1"' in response.content + + +def test_post_task_move_error(client: TestClient, db: DatabaseTestUtils) -> None: + db.init() + response = client.post( + "/tasks/move", json={"taskId": "1", "statusId": "1", "previousSiblingId": "2", "nextSiblingId": ""} + ) + assert response.status_code == 500 + assert response.headers["content-type"] == "text/html; charset=utf-8" + assert b"This is an error message" in response.content diff --git a/tests/conftest.py b/tests/conftest.py index 77538545b..eb3849ab6 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,28 +1,90 @@ +import os from collections.abc import Generator +from multiprocessing import Process +from time import sleep +from typing import Any import pytest +import uvicorn +from _pytest.fixtures import SubRequest from fastapi.testclient import TestClient -from sqlmodel import Session, SQLModel, create_engine -from sqlmodel.pool import StaticPool +from playwright.sync_api import Page, Playwright, sync_playwright +from sqlmodel import Session +from tad.core.config import settings +from tad.core.db import get_engine from tad.main import app -# needed to make sure create_all knows about the models -from tad.models import * # noqa: F403 +from tests.database_test_utils import DatabaseTestUtils + + +class TestSettings: + HTTP_SERVER_SCHEME: str = "http://" + HTTP_SERVER_HOST: str = "127.0.0.1" + HTTP_SERVER_PORT: int = 8000 + + +def run_server() -> None: + uvicorn.run(app, host=TestSettings.HTTP_SERVER_HOST, port=TestSettings.HTTP_SERVER_PORT) + + +def wait_for_server_ready(url: str, timeout: int = 30) -> None: + # todo we can not use playwright because it gives async errors, so we need another + # wait to check the server for being up + sleep(5) + + +@pytest.fixture(scope="module") +def server() -> Generator[Any, Any, Any]: + # todo (robbert) use a better way to get the test database in the app configuration + os.environ["APP_DATABASE_FILE"] = "database.sqlite3.test" + process = Process(target=run_server) + process.start() + server_address = ( + TestSettings.HTTP_SERVER_SCHEME + TestSettings.HTTP_SERVER_HOST + ":" + str(TestSettings.HTTP_SERVER_PORT) + ) + wait_for_server_ready(server_address) + yield server_address + process.terminate() + del os.environ["APP_DATABASE_FILE"] + + +@pytest.fixture(scope="session") +def get_session() -> Generator[Session, Any, Any]: + with Session(get_engine()) as session: + yield session + + +def pytest_configure() -> None: + """ + Called after the Session object has been created and + before performing collection and entering the run test loop. + """ + # todo (robbert) creating an in memory database does not work right, tables seem to get lost? + settings.APP_DATABASE_FILE = "database.sqlite3.test" # set to none so we'll use an in memory database @pytest.fixture(scope="module") -def client(db: Session) -> Generator[TestClient, None, None]: +def client() -> Generator[TestClient, None, None]: with TestClient(app, raise_server_exceptions=True) as c: c.timeout = 5 yield c -@pytest.fixture(scope="module") -def db() -> Generator[Session, None, None]: - engine = create_engine("sqlite://", poolclass=StaticPool) - SQLModel.metadata.create_all(engine) +@pytest.fixture(scope="session") +def playwright(): + with sync_playwright() as p: + yield p + + +@pytest.fixture(params=["chromium", "firefox", "webkit"]) +def browser(playwright: Playwright, request: SubRequest) -> Generator[Page, Any, Any]: + browser = getattr(playwright, request.param).launch(headless=True) + context = browser.new_context() + page = context.new_page() + yield page + browser.close() - with Session(engine) as session: - yield session - SQLModel.metadata.drop_all(engine) +@pytest.fixture() +def db(): + return DatabaseTestUtils() diff --git a/tests/core/test_config.py b/tests/core/test_config.py index f7c8bbc34..3ca07a165 100644 --- a/tests/core/test_config.py +++ b/tests/core/test_config.py @@ -14,6 +14,7 @@ def test_default_settings(): assert settings.PROJECT_NAME == "TAD" assert settings.PROJECT_DESCRIPTION == "Transparency of Algorithmic Decision making" assert settings.APP_DATABASE_SCHEME == "sqlite" + # todo (robbert) we change the database for the test and use the default config assert settings.SQLALCHEMY_DATABASE_URI == "sqlite:///database.sqlite3" diff --git a/tests/core/test_db.py b/tests/core/test_db.py index 5c8aab814..23470d99c 100644 --- a/tests/core/test_db.py +++ b/tests/core/test_db.py @@ -6,7 +6,7 @@ @pytest.mark.skip(reason="not working yet") -async def test_check_dabase(): +async def test_check_database(): mock_session = Mock(spec=Session) with patch("sqlmodel.Session", return_value=mock_session): diff --git a/tests/database_test_utils.py b/tests/database_test_utils.py new file mode 100644 index 000000000..2d3cef33f --- /dev/null +++ b/tests/database_test_utils.py @@ -0,0 +1,113 @@ +from typing import Any + +from sqlalchemy import text +from sqlmodel import Session, SQLModel +from tad.core.db import get_engine + + +class DatabaseTestUtils: + """ + Class to use for testing database calls. On creation, this class destroys and recreates the database tables. + """ + + def __init__(self): + self.clear() + + def clear(self) -> None: + """ + Drops and recreates the database tables. + :return: None + """ + SQLModel.metadata.drop_all(get_engine()) + SQLModel.metadata.create_all(get_engine()) + + def _enrich_with_default_values(self, specification: dict[str, str | int]) -> dict[str, str | int]: + """ + If a known table dictionary is given, like a task or status, default values will be added + and an enriched dictionary is returned. + :param specification: the dictionary to be enriched + :return: an enriched dictionary + """ + default_specification: dict[str, str | int] = {} + if specification["table"] == "task": + default_specification["title"] = "Test task " + str(specification["id"]) + default_specification["description"] = "Test task description " + str(specification["id"]) + default_specification["sort_order"] = specification["id"] + default_specification["status_id"] = 1 + elif specification["table"] == "status": + default_specification["name"] = "Status " + str(specification["id"]) + default_specification["sort_order"] = specification["id"] + return default_specification | specification + + def _fix_missing_relations(self, specification: dict[str, Any]) -> None: + """ + If a dictionary with a known table is given, like a task, the related item, + for example a status, will be created in the database if the id does not + exist yet. We do this to comply with database relationships and make it + easier to set up tests with minimal effort. + :param specification: a dictionary with a table specification + :return: None + """ + if specification["table"] == "task": + status_specification = {"id": specification["status_id"], "table": "status"} + if not self.item_exists(status_specification): + self.init([status_specification]) + + def get_items(self, specification: dict[str, str | int]) -> Any: + """ + Create a query based on the dictionary specification and return the result + :param specification: a dictionary with a table specification + :return: the results of the query + """ + values = ", ".join( + key + "=" + str(val) if str(val).isnumeric() else str('"' + val + '"') # type: ignore + for key, val in specification.items() # type: ignore + if key != "table" # type: ignore + ) + table = specification["table"] + statement = f"SELECT * FROM {table} WHERE {values}" # noqa S608 + with Session(get_engine()) as session: + return session.exec(text(statement)).all() # type: ignore + + def item_exists(self, specification: dict[str, Any]) -> bool: + """ + Check if an item exists in the database with the table and id given + in the dictionary + :param specification: a dictionary with a table specification + :return: True if the item exists in the database, False otherwise + """ + result = self.get_items(specification) + return len(result) != 0 + + def init(self, specifications: list[dict[str, str | int]] | None = None) -> None: + """ + Given an array of specifications, create the database entries. + + Example: [{'table': 'task', 'id': 1 'title': 'Test task 1', 'description': 'Test task description 1'}] + + The example below will be enriched so all required fields for a task will have a value. + + Example: [{'table': 'task', 'id': 1}] + + Example: [{"table": "status", "id": 1},{"table": "task", "id": 1, "status_id": 1}] + + :param specifications: an array of dictionaries with table specifications + :return: None + """ + if specifications is None: + return + for specification in specifications: + specification = self._enrich_with_default_values(specification) + exists_specification = {"table": specification["table"], "id": specification["id"]} + if not self.item_exists(exists_specification): + self._fix_missing_relations(specification) + table = specification.pop("table") + keys = ", ".join(key for key in specification) + values = ", ".join( + str(val) if str(val).isnumeric() else str("'" + val + "'") + for val in specification.values() # type: ignore + ) + statement = f"INSERT INTO {table} ({keys}) VALUES ({values})" # noqa S608 + with Session(get_engine()) as session: + session.exec(text(statement)) # type: ignore + session.commit() diff --git a/tests/e2e/__init__.py b/tests/e2e/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/e2e/test_move_task.py b/tests/e2e/test_move_task.py new file mode 100644 index 000000000..2e804503d --- /dev/null +++ b/tests/e2e/test_move_task.py @@ -0,0 +1,71 @@ +from playwright.sync_api import Page, expect + +from tests.database_test_utils import DatabaseTestUtils + + +def test_move_task_to_column(server: str, browser: Page, db: DatabaseTestUtils) -> None: + """ + Test moving a task in the browser to another column and verify that after a reload + it is in the right column. + :param start_server: the start server fixture + :return: None + """ + db.init( + [ + {"table": "status", "id": 1}, + {"table": "status", "id": 2}, + {"table": "status", "id": 3}, + {"table": "status", "id": 4}, + {"table": "task", "id": 1, "status_id": 1}, + ] + ) + + browser.goto(f"{server}/pages/") + + expect(browser.locator("#column-1 #card-1")).to_be_visible() + expect(browser.locator("#column-3")).to_be_visible() + + # todo (Robbert) action below is performed twice, because once does not work, we need find out why and fix it + browser.locator("#card-1").drag_to(browser.locator("#column-3")) + browser.locator("#card-1").drag_to(browser.locator("#column-3")) + + browser.reload() + + card = browser.locator("#column-3 #card-1") + expect(card).to_have_id("card-1") + expect(card).to_be_visible() + + +def test_move_task_order_in_same_column(server: str, browser: Page, db: DatabaseTestUtils) -> None: + """ + Test moving a task in the browser below another task and verify that after a reload + it is in the right position in the column. + :return: None + """ + db.init( + [ + {"table": "task", "id": 1, "status_id": 1}, + {"table": "task", "id": 2, "status_id": 1}, + {"table": "task", "id": 3, "status_id": 1}, + ] + ) + + browser.goto(f"{server}/pages/") + + expect(browser.locator("#column-1 #card-1")).to_be_visible() + expect(browser.locator("#column-1")).to_be_visible() + + # todo (robbert) code below doesn't do what it should do, card is not moved + task = browser.locator("#card-1") + task.hover() + browser.mouse.down() + browser.mouse.move(0, 50) + browser.mouse.up() + # https://playwright.dev/docs/input + browser.reload() + + tasks_in_column = browser.locator("#column-1").locator(".progress_card_container").all() + # todo (robbert) this order should be changed if code above works correctly + expect(tasks_in_column[0]).to_have_id("card-1") + expect(tasks_in_column[1]).to_have_id("card-2") + expect(tasks_in_column[2]).to_have_id("card-3") diff --git a/tests/repositories/test_statuses.py b/tests/repositories/test_statuses.py new file mode 100644 index 000000000..0d9e2a9d3 --- /dev/null +++ b/tests/repositories/test_statuses.py @@ -0,0 +1,63 @@ +import pytest +from sqlmodel import Session +from tad.models import Status +from tad.repositories.exceptions import RepositoryError +from tad.repositories.statuses import StatusesRepository +from tests.database_test_utils import DatabaseTestUtils + + +def test_find_all(get_session: Session, db: DatabaseTestUtils): + db.init( + [ + {"table": "status", "id": 1}, + {"table": "status", "id": 2}, + ] + ) + status_repository: StatusesRepository = StatusesRepository(get_session) + results = status_repository.find_all() + assert results[0].id == 1 + assert results[1].id == 2 + assert len(results) == 2 + + +def test_find_all_no_results(get_session: Session, db: DatabaseTestUtils): + db.init() + status_repository: StatusesRepository = StatusesRepository(get_session) + results = status_repository.find_all() + assert len(results) == 0 + + +def test_save(get_session: Session, db: DatabaseTestUtils): + db.init() + status_repository: StatusesRepository = StatusesRepository(get_session) + status: Status = Status(id=1, name="test", sort_order=10) + status_repository.save(status) + result = db.get_items({"table": "status", "id": 1}) + assert result[0].id == 1 + assert result[0].name == "test" + assert result[0].sort_order == 10 + + +def test_save_failed(get_session: Session, db: DatabaseTestUtils): + db.init() + status_repository: StatusesRepository = StatusesRepository(get_session) + status: Status = Status(id=1, name="test", sort_order=10) + status_repository.save(status) + status: Status = Status(id=1, name="test has duplicate id", sort_order=10) + with pytest.raises(RepositoryError): + status_repository.save(status) + + +def test_find_by_id(get_session: Session, db: DatabaseTestUtils): + db.init([{"table": "status", "id": 1, "name": "test for find by id"}]) + status_repository: StatusesRepository = StatusesRepository(get_session) + result: Status = status_repository.find_by_id(1) + assert result.id == 1 + assert result.name == "test for find by id" + + +def test_find_by_id_failed(get_session: Session, db: DatabaseTestUtils): + db.init() + status_repository: StatusesRepository = StatusesRepository(get_session) + with pytest.raises(RepositoryError): + status_repository.find_by_id(1) diff --git a/tests/repositories/test_tasks.py b/tests/repositories/test_tasks.py new file mode 100644 index 000000000..112d7bfb9 --- /dev/null +++ b/tests/repositories/test_tasks.py @@ -0,0 +1,80 @@ +import pytest +from sqlmodel import Session +from tad.models import Task +from tad.repositories.exceptions import RepositoryError +from tad.repositories.tasks import TasksRepository +from tests.database_test_utils import DatabaseTestUtils + + +def test_find_all(get_session: Session, db: DatabaseTestUtils): + db.init( + [ + {"table": "task", "id": 1, "status_id": 1}, + {"table": "task", "id": 2, "status_id": 1}, + ] + ) + tasks_repository: TasksRepository = TasksRepository(get_session) + results = tasks_repository.find_all() + assert results[0].id == 1 + assert results[1].id == 2 + assert len(results) == 2 + + +def test_find_all_no_results(get_session: Session, db: DatabaseTestUtils): + db.init() + tasks_repository: TasksRepository = TasksRepository(get_session) + results = tasks_repository.find_all() + assert len(results) == 0 + + +def test_save(get_session: Session, db: DatabaseTestUtils): + db.init() + tasks_repository: TasksRepository = TasksRepository(get_session) + task: Task = Task(id=1, title="Test title", description="Test description", sort_order=10) + tasks_repository.save(task) + result = db.get_items({"table": "task", "id": 1}) + assert result[0].id == 1 + assert result[0].title == "Test title" + assert result[0].description == "Test description" + assert result[0].sort_order == 10 + + +@pytest.mark.filterwarnings("ignore:New instance") +def test_save_failed(get_session: Session, db: DatabaseTestUtils): + db.init() + tasks_repository: TasksRepository = TasksRepository(get_session) + task: Task = Task(id=1, title="Test title", description="Test description", sort_order=10) + tasks_repository.save(task) + task_duplicate: Task = Task(id=1, title="Test title duplicate", description="Test description", sort_order=10) + with pytest.raises(RepositoryError): + tasks_repository.save(task_duplicate) + + +def test_find_by_id(get_session: Session, db: DatabaseTestUtils): + db.init([{"table": "task", "id": 1, "title": "test for find by id"}]) + tasks_repository: TasksRepository = TasksRepository(get_session) + result: Task = tasks_repository.find_by_id(1) + assert result.id == 1 + assert result.title == "test for find by id" + + +def test_find_by_id_failed(get_session: Session, db: DatabaseTestUtils): + db.init() + tasks_repository: TasksRepository = TasksRepository(get_session) + with pytest.raises(RepositoryError): + tasks_repository.find_by_id(1) + + +def test_find_by_status_id(get_session: Session, db: DatabaseTestUtils): + db.init( + [ + {"table": "status", "id": 1}, + {"table": "task", "id": 1, "status_id": 1}, + {"table": "task", "id": 2, "status_id": 1}, + ] + ) + tasks_repository: TasksRepository = TasksRepository(get_session) + results = tasks_repository.find_by_status_id(1) + assert len(results) == 2 + assert results[0].id == 1 + assert results[1].id == 2 diff --git a/tests/services/test_statuses_service.py b/tests/services/test_statuses_service.py new file mode 100644 index 000000000..ba69fca98 --- /dev/null +++ b/tests/services/test_statuses_service.py @@ -0,0 +1,38 @@ +from collections.abc import Generator, Sequence +from typing import Any +from unittest.mock import patch + +import pytest +from tad.models import Status +from tad.repositories.statuses import StatusesRepository +from tad.services.statuses import StatusesService + + +class MockStatusesRepository: + def __init__(self): + pass + + def find_by_id(self, status_id: int) -> Status: + return Status(id=status_id, name="Test status", sort_order=1) + + def find_all(self) -> Sequence[Status]: + return [self.find_by_id(1)] + + +@pytest.fixture(scope="module") +def mock_statuses_repository() -> Generator[MockStatusesRepository, Any, Any]: + with patch("tad.services.statuses.StatusesRepository"): + mock_statuses_repository = MockStatusesRepository() + yield mock_statuses_repository + + +def test_get_status(mock_statuses_repository: StatusesRepository): + statuses_service = StatusesService(mock_statuses_repository) + status: Status = statuses_service.get_status(1) + assert status.id == 1 + + +def test_get_statuses(mock_statuses_repository: StatusesRepository): + statuses_service = StatusesService(mock_statuses_repository) + statuses = statuses_service.get_statuses() + assert len(statuses) == 1 diff --git a/tests/services/test_tasks_service.py b/tests/services/test_tasks_service.py new file mode 100644 index 000000000..77c8bea18 --- /dev/null +++ b/tests/services/test_tasks_service.py @@ -0,0 +1,115 @@ +from collections.abc import Sequence +from unittest.mock import patch + +import pytest +from tad.models import Status, Task, User +from tad.repositories.statuses import StatusesRepository +from tad.repositories.tasks import TasksRepository +from tad.services.statuses import StatusesService +from tad.services.tasks import TasksService + + +class MockStatusesRepository: + def __init__(self): + self._statuses: list[Status] = [] + self.reset() + + def reset(self): + self._statuses.clear() + self._statuses.append(Status(id=1, name="todo", sort_order=1)) + self._statuses.append(Status(id=2, name="in_progress", sort_order=1)) + self._statuses.append(Status(id=3, name="review", sort_order=1)) + self._statuses.append(Status(id=4, name="done", sort_order=1)) + + def find_by_id(self, status_id: int) -> Status: + return next(filter(lambda x: x.id == status_id, self._statuses)) + + +class MockTasksRepository: + def __init__(self): + self._tasks: list[Task] = [] + self.reset() + + def reset(self): + self._tasks.clear() + self._tasks.append(Task(id=1, title="Test 1", description="Description 1", status_id=1, sort_order=10)) + self._tasks.append(Task(id=2, title="Test 2", description="Description 2", status_id=1, sort_order=20)) + self._tasks.append(Task(id=3, title="Test 3", description="Description 3", status_id=1, sort_order=30)) + self._tasks.append(Task(id=4, title="Test 4", description="Description 4", status_id=2, sort_order=10)) + self._tasks.append(Task(id=5, title="Test 5", description="Description 5", status_id=3, sort_order=20)) + + def find_all(self): + return self._tasks + + def find_by_status_id(self, status_id: int) -> Sequence[Task]: + return list(filter(lambda x: x.status_id == status_id, self._tasks)) + + def find_by_id(self, task_id: int) -> Task: + return next(filter(lambda x: x.id == task_id, self._tasks)) + + def save(self, task: Task) -> Task: + return task + + +@pytest.fixture(scope="module") +def mock_tasks_repository(): + with patch("tad.services.tasks.TasksRepository"): + mock_tasks_repository = MockTasksRepository() + yield mock_tasks_repository + + +@pytest.fixture(scope="module") +def mock_statuses_repository(): + with patch("tad.services.statuses.StatusesRepository"): + mock_statuses_repository = MockStatusesRepository() + yield mock_statuses_repository + + +@pytest.fixture(scope="module") +def tasks_service_with_mock(mock_tasks_repository: TasksRepository, mock_statuses_repository: StatusesRepository): + statuses_service = StatusesService(mock_statuses_repository) + tasks_service = TasksService(statuses_service, mock_tasks_repository) + return tasks_service + + +def test_get_tasks(tasks_service_with_mock: TasksService, mock_tasks_repository: TasksRepository): + assert len(tasks_service_with_mock.get_tasks(1)) == 3 + + +def test_assign_task(tasks_service_with_mock: TasksService, mock_tasks_repository: TasksRepository): + task1: Task = mock_tasks_repository.find_by_id(1) + user1: User = User(id=1, name="User 1", avatar="none.jpg") + tasks_service_with_mock.assign_task(task1, user1) + assert task1.user_id == 1 + + +def test_move_task(tasks_service_with_mock: TasksService, mock_tasks_repository: MockTasksRepository): + # test changing order + mock_tasks_repository.reset() + assert mock_tasks_repository.find_by_id(1).sort_order == 10 + tasks_service_with_mock.move_task(1, 1, 2, 3) + assert mock_tasks_repository.find_by_id(1).sort_order == 25 + + # test changing order + mock_tasks_repository.reset() + tasks_service_with_mock.move_task(1, 1, 3, None) + assert mock_tasks_repository.find_by_id(1).sort_order == 40 + + # test moving to in progress + mock_tasks_repository.reset() + mock_tasks_repository.find_by_id(1).sort_order = 0 + tasks_service_with_mock.move_task(1, 2, 0, 0) + assert mock_tasks_repository.find_by_id(1).sort_order == 10 + assert mock_tasks_repository.find_by_id(1).user_id == 1 + + # test moving to todo + mock_tasks_repository.reset() + mock_tasks_repository.find_by_id(1).sort_order = 0 + tasks_service_with_mock.move_task(1, 4, 0, 0) + assert mock_tasks_repository.find_by_id(1).sort_order == 10 + + # test moving move under other card + mock_tasks_repository.reset() + mock_tasks_repository.find_by_id(2).sort_order = 10 + tasks_service_with_mock.move_task(2, 1, 0, 1) + assert mock_tasks_repository.find_by_id(2).sort_order == 5