Full Code of dreamRs/datamods for AI

master 4178781ad4ac cached
126 files
502.5 KB
140.5k tokens
4 symbols
1 requests
Download .txt
Showing preview only (546K chars total). Download the full file or copy to clipboard to get everything.
Repository: dreamRs/datamods
Branch: master
Commit: 4178781ad4ac
Files: 126
Total size: 502.5 KB

Directory structure:
gitextract_a77i5218/

├── .Rbuildignore
├── .github/
│   ├── .gitignore
│   └── workflows/
│       ├── R-CMD-check.yaml
│       ├── pkgdown.yaml
│       └── test-coverage.yaml
├── .gitignore
├── DESCRIPTION
├── LICENSE.md
├── NAMESPACE
├── NEWS.md
├── R/
│   ├── create-column.R
│   ├── cut-variable.R
│   ├── data.R
│   ├── datagrid-infos.R
│   ├── edit-data-utils.R
│   ├── edit-data.R
│   ├── filter-data.R
│   ├── i18n.R
│   ├── import-copypaste.R
│   ├── import-file.R
│   ├── import-globalenv.R
│   ├── import-googlesheets.R
│   ├── import-modal.R
│   ├── import-url.R
│   ├── onLoad.R
│   ├── sample-data.R
│   ├── select-group.R
│   ├── show_data.R
│   ├── update-factor.R
│   ├── update-variables.R
│   ├── utils-shiny.R
│   ├── utils.R
│   ├── validation.R
│   └── zzz.R
├── README.Rmd
├── README.md
├── _pkgdown.yml
├── cran-comments.md
├── data/
│   └── demo_edit.rda
├── data-raw/
│   └── demo_edit.R
├── examples/
│   ├── create_column.R
│   ├── cut_variable.R
│   ├── edit_data-callback.R
│   ├── edit_data-callback_add.R
│   ├── edit_data-callback_delete.R
│   ├── edit_data-callback_update-row_style.R
│   ├── edit_data-callback_update.R
│   ├── edit_data.R
│   ├── filter_data-basic.R
│   ├── filter_data.R
│   ├── from-copypaste.R
│   ├── from-file.R
│   ├── from-globalenv.R
│   ├── from-googlesheets.R
│   ├── from-url.R
│   ├── i18n.R
│   ├── modal-validation.R
│   ├── modal.R
│   ├── sample.R
│   ├── select-group-default.R
│   ├── select-group-selected.R
│   ├── select-group-subset.R
│   ├── select-group-vars.R
│   ├── show_data.R
│   ├── update_factor.R
│   ├── validation.R
│   └── variables.R
├── inst/
│   ├── assets/
│   │   ├── css/
│   │   │   └── datamods.css
│   │   └── js/
│   │       └── datamods.js
│   ├── extdata/
│   │   ├── mtcars.csv
│   │   ├── mtcars.json
│   │   ├── mtcars_fr.csv
│   │   ├── pop-fra-dep.txt
│   │   ├── pop-fra-reg-dep.xls
│   │   └── rules.yaml
│   └── i18n/
│       ├── al.csv
│       ├── cn.csv
│       ├── de.csv
│       ├── es.csv
│       ├── extract_labels.R
│       ├── fr.csv
│       ├── it.csv
│       ├── ja.csv
│       ├── kr.csv
│       ├── maj_csv.R
│       ├── mk.csv
│       ├── pl.csv
│       ├── pt.csv
│       └── tr.csv
├── man/
│   ├── create-column.Rd
│   ├── cut-variable.Rd
│   ├── demo_edit.Rd
│   ├── edit-data.Rd
│   ├── filter-data.Rd
│   ├── get_data_packages.Rd
│   ├── i18n.Rd
│   ├── import-copypaste.Rd
│   ├── import-file.Rd
│   ├── import-globalenv.Rd
│   ├── import-googlesheets.Rd
│   ├── import-modal.Rd
│   ├── import-url.Rd
│   ├── list_pkg_data.Rd
│   ├── module-sample.Rd
│   ├── select-group.Rd
│   ├── show_data.Rd
│   ├── update-factor.Rd
│   ├── update-variables.Rd
│   └── validation.Rd
├── man-roxygen/
│   └── module-import.R
├── tests/
│   ├── testthat/
│   │   ├── test-edit-data.R
│   │   ├── test-filter-data.R
│   │   ├── test-i18n.R
│   │   ├── test-import-copypaste.R
│   │   ├── test-import-file.R
│   │   ├── test-import-globalenv.R
│   │   ├── test-import-googlesheets.R
│   │   ├── test-import-modal.R
│   │   ├── test-import-url.R
│   │   ├── test-onLoad.R
│   │   ├── test-update-variables.R
│   │   └── test-validation.R
│   └── testthat.R
└── vignettes/
    ├── .gitignore
    ├── datamods.Rmd
    └── i18n.Rmd

================================================
FILE CONTENTS
================================================

================================================
FILE: .Rbuildignore
================================================
^datamods\.Rproj$
^\.Rproj\.user$
^LICENSE\.md$
^examples$
^doc$
^Meta$
^\.github$
^dev$
^cran-comments\.md$
^CRAN-RELEASE$
^_pkgdown\.yml$
^docs$
^pkgdown$
^man-roxygen$
^README\.Rmd$
^CRAN-SUBMISSION$
^data-raw$


================================================
FILE: .github/.gitignore
================================================
*.html


================================================
FILE: .github/workflows/R-CMD-check.yaml
================================================
# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples
# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help
on:
  push:
    branches: [main, master]
  pull_request:
    branches: [main, master]

name: R-CMD-check

jobs:
  R-CMD-check:
    runs-on: ${{ matrix.config.os }}

    name: ${{ matrix.config.os }} (${{ matrix.config.r }})

    strategy:
      fail-fast: false
      matrix:
        config:
          - {os: macos-latest,   r: 'release'}
          - {os: windows-latest, r: 'release'}
          - {os: ubuntu-latest,   r: 'devel', http-user-agent: 'release'}
          - {os: ubuntu-latest,   r: 'release'}
          - {os: ubuntu-latest,   r: 'oldrel-1'}

    env:
      GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}
      R_KEEP_PKG_SOURCE: yes

    steps:
      - uses: actions/checkout@v3

      - uses: r-lib/actions/setup-pandoc@v2

      - uses: r-lib/actions/setup-r@v2
        with:
          r-version: ${{ matrix.config.r }}
          http-user-agent: ${{ matrix.config.http-user-agent }}
          use-public-rspm: true

      - uses: r-lib/actions/setup-r-dependencies@v2
        with:
          extra-packages: any::rcmdcheck
          needs: check

      - uses: r-lib/actions/check-r-package@v2
        with:
          upload-snapshots: true


================================================
FILE: .github/workflows/pkgdown.yaml
================================================
# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples
# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help
on:
  push:
    branches: [main, master]
  pull_request:
    branches: [main, master]
  release:
    types: [published]
  workflow_dispatch:

name: pkgdown

jobs:
  pkgdown:
    runs-on: ubuntu-latest
    # Only restrict concurrency for non-PR jobs
    concurrency:
      group: pkgdown-${{ github.event_name != 'pull_request' || github.run_id }}
    env:
      GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}
    steps:
      - uses: actions/checkout@v3

      - uses: r-lib/actions/setup-pandoc@v2

      - uses: r-lib/actions/setup-r@v2
        with:
          use-public-rspm: true

      - uses: r-lib/actions/setup-r-dependencies@v2
        with:
          extra-packages: any::pkgdown, local::.
          needs: website

      - name: Build site
        run: pkgdown::build_site_github_pages(new_process = FALSE, install = FALSE)
        shell: Rscript {0}

      - name: Deploy to GitHub pages 🚀
        if: github.event_name != 'pull_request'
        uses: JamesIves/github-pages-deploy-action@v4.4.1
        with:
          clean: false
          branch: gh-pages
          folder: docs


================================================
FILE: .github/workflows/test-coverage.yaml
================================================
# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples
# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help
on:
  push:
    branches: [main, master]
  pull_request:

name: test-coverage.yaml

permissions: read-all

jobs:
  test-coverage:
    runs-on: ubuntu-latest
    env:
      GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}

    steps:
      - uses: actions/checkout@v4

      - uses: r-lib/actions/setup-r@v2
        with:
          use-public-rspm: true

      - uses: r-lib/actions/setup-r-dependencies@v2
        with:
          extra-packages: any::covr, any::xml2
          needs: coverage

      - name: Test coverage
        run: |
          cov <- covr::package_coverage(
            quiet = FALSE,
            clean = FALSE,
            install_path = file.path(normalizePath(Sys.getenv("RUNNER_TEMP"), winslash = "/"), "package")
          )
          covr::to_cobertura(cov)
        shell: Rscript {0}

      - uses: codecov/codecov-action@v4
        with:
          # Fail if error if not on PR, or if on PR and token is given
          fail_ci_if_error: ${{ github.event_name != 'pull_request' || secrets.CODECOV_TOKEN }}
          file: ./cobertura.xml
          plugin: noop
          disable_search: true
          token: ${{ secrets.CODECOV_TOKEN }}

      - name: Show testthat output
        if: always()
        run: |
          ## --------------------------------------------------------------------
          find '${{ runner.temp }}/package' -name 'testthat.Rout*' -exec cat '{}' \; || true
        shell: bash

      - name: Upload test results
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: coverage-test-failures
          path: ${{ runner.temp }}/package


================================================
FILE: .gitignore
================================================
.Rproj.user
.Rhistory
.RData
.Ruserdata
*.Rproj
inst/doc
doc
Meta
dev/
docs
CRAN-SUBMISSION


================================================
FILE: DESCRIPTION
================================================
Package: datamods
Title: Modules to Import and Manipulate Data in 'Shiny'
Version: 1.5.3.9200
Authors@R: 
    c(person(given = "Victor",
             family = "Perrier",
             role = c("aut", "cre", "cph"),
             email = "victor.perrier@dreamrs.fr"),
      person(given = "Fanny",
             family = "Meyer",
             role = "aut"),
      person(given = "Samra",
             family = "Goumri",
             role = "aut"),
      person(given = "Zauad Shahreer",
             family = "Abeer",
             role = "aut",
             email = "shahreyar.abeer@gmail.com"),
      person(given = "Eduard",
             family = "Szöcs",
             role = "ctb",
             email = "eduardszoecs@gmail.com")
      )
Description: 'Shiny' modules to import data into an application or 'addin'
    from various sources, and to manipulate them after that.
License: GPL-3
URL: https://github.com/dreamRs/datamods, https://dreamrs.github.io/datamods/
BugReports: https://github.com/dreamRs/datamods/issues
Encoding: UTF-8
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.3.2
Imports: 
    bslib,
    classInt,
    data.table,
    htmltools,
    phosphoricons,
    reactable,
    readxl,
    rio,
    rlang,
    shiny (>= 1.5.0),
    shinyWidgets (>= 0.8.4),
    tibble,
    toastui (>= 0.3.3),
    tools,
    shinybusy,
    writexl
Suggests: 
    ggplot2,
    htmlwidgets,
    jsonlite,
    knitr,
    MASS,
    rmarkdown,
    testthat,
    validate
VignetteBuilder: knitr
Depends: 
    R (>= 2.10)
LazyData: true


================================================
FILE: LICENSE.md
================================================
GNU General Public License
==========================

_Version 3, 29 June 2007_  
_Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_

Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.

## Preamble

The GNU General Public License is a free, copyleft license for software and other
kinds of works.

The licenses for most software and other practical works are designed to take away
your freedom to share and change the works. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change all versions of a
program--to make sure it remains free software for all its users. We, the Free
Software Foundation, use the GNU General Public License for most of our software; it
applies also to any other work released this way by its authors. You can apply it to
your programs, too.

When we speak of free software, we are referring to freedom, not price. Our General
Public Licenses are designed to make sure that you have the freedom to distribute
copies of free software (and charge for them if you wish), that you receive source
code or can get it if you want it, that you can change the software or use pieces of
it in new free programs, and that you know you can do these things.

To protect your rights, we need to prevent others from denying you these rights or
asking you to surrender the rights. Therefore, you have certain responsibilities if
you distribute copies of the software, or if you modify it: responsibilities to
respect the freedom of others.

For example, if you distribute copies of such a program, whether gratis or for a fee,
you must pass on to the recipients the same freedoms that you received. You must make
sure that they, too, receive or can get the source code. And you must show them these
terms so they know their rights.

Developers that use the GNU GPL protect your rights with two steps: **(1)** assert
copyright on the software, and **(2)** offer you this License giving you legal permission
to copy, distribute and/or modify it.

For the developers' and authors' protection, the GPL clearly explains that there is
no warranty for this free software. For both users' and authors' sake, the GPL
requires that modified versions be marked as changed, so that their problems will not
be attributed erroneously to authors of previous versions.

Some devices are designed to deny users access to install or run modified versions of
the software inside them, although the manufacturer can do so. This is fundamentally
incompatible with the aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we have designed
this version of the GPL to prohibit the practice for those products. If such problems
arise substantially in other domains, we stand ready to extend this provision to
those domains in future versions of the GPL, as needed to protect the freedom of
users.

Finally, every program is threatened constantly by software patents. States should
not allow patents to restrict development and use of software on general-purpose
computers, but in those that do, we wish to avoid the special danger that patents
applied to a free program could make it effectively proprietary. To prevent this, the
GPL assures that patents cannot be used to render the program non-free.

The precise terms and conditions for copying, distribution and modification follow.

## TERMS AND CONDITIONS

### 0. Definitions

“This License” refers to version 3 of the GNU General Public License.

“Copyright” also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

“The Program” refers to any copyrightable work licensed under this
License. Each licensee is addressed as “you”. “Licensees” and
“recipients” may be individuals or organizations.

To “modify” a work means to copy from or adapt all or part of the work in
a fashion requiring copyright permission, other than the making of an exact copy. The
resulting work is called a “modified version” of the earlier work or a
work “based on” the earlier work.

A “covered work” means either the unmodified Program or a work based on
the Program.

To “propagate” a work means to do anything with it that, without
permission, would make you directly or secondarily liable for infringement under
applicable copyright law, except executing it on a computer or modifying a private
copy. Propagation includes copying, distribution (with or without modification),
making available to the public, and in some countries other activities as well.

To “convey” a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through a computer
network, with no transfer of a copy, is not conveying.

An interactive user interface displays “Appropriate Legal Notices” to the
extent that it includes a convenient and prominently visible feature that **(1)**
displays an appropriate copyright notice, and **(2)** tells the user that there is no
warranty for the work (except to the extent that warranties are provided), that
licensees may convey the work under this License, and how to view a copy of this
License. If the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

### 1. Source Code

The “source code” for a work means the preferred form of the work for
making modifications to it. “Object code” means any non-source form of a
work.

A “Standard Interface” means an interface that either is an official
standard defined by a recognized standards body, or, in the case of interfaces
specified for a particular programming language, one that is widely used among
developers working in that language.

The “System Libraries” of an executable work include anything, other than
the work as a whole, that **(a)** is included in the normal form of packaging a Major
Component, but which is not part of that Major Component, and **(b)** serves only to
enable use of the work with that Major Component, or to implement a Standard
Interface for which an implementation is available to the public in source code form.
A “Major Component”, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system (if any) on which
the executable work runs, or a compiler used to produce the work, or an object code
interpreter used to run it.

The “Corresponding Source” for a work in object code form means all the
source code needed to generate, install, and (for an executable work) run the object
code and to modify the work, including scripts to control those activities. However,
it does not include the work's System Libraries, or general-purpose tools or
generally available free programs which are used unmodified in performing those
activities but which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for the work, and
the source code for shared libraries and dynamically linked subprograms that the work
is specifically designed to require, such as by intimate data communication or
control flow between those subprograms and other parts of the work.

The Corresponding Source need not include anything that users can regenerate
automatically from other parts of the Corresponding Source.

The Corresponding Source for a work in source code form is that same work.

### 2. Basic Permissions

All rights granted under this License are granted for the term of copyright on the
Program, and are irrevocable provided the stated conditions are met. This License
explicitly affirms your unlimited permission to run the unmodified Program. The
output from running a covered work is covered by this License only if the output,
given its content, constitutes a covered work. This License acknowledges your rights
of fair use or other equivalent, as provided by copyright law.

You may make, run and propagate covered works that you do not convey, without
conditions so long as your license otherwise remains in force. You may convey covered
works to others for the sole purpose of having them make modifications exclusively
for you, or provide you with facilities for running those works, provided that you
comply with the terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for you must do so
exclusively on your behalf, under your direction and control, on terms that prohibit
them from making any copies of your copyrighted material outside their relationship
with you.

Conveying under any other circumstances is permitted solely under the conditions
stated below. Sublicensing is not allowed; section 10 makes it unnecessary.

### 3. Protecting Users' Legal Rights From Anti-Circumvention Law

No covered work shall be deemed part of an effective technological measure under any
applicable law fulfilling obligations under article 11 of the WIPO copyright treaty
adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention
of such measures.

When you convey a covered work, you waive any legal power to forbid circumvention of
technological measures to the extent such circumvention is effected by exercising
rights under this License with respect to the covered work, and you disclaim any
intention to limit operation or modification of the work as a means of enforcing,
against the work's users, your or third parties' legal rights to forbid circumvention
of technological measures.

### 4. Conveying Verbatim Copies

You may convey verbatim copies of the Program's source code as you receive it, in any
medium, provided that you conspicuously and appropriately publish on each copy an
appropriate copyright notice; keep intact all notices stating that this License and
any non-permissive terms added in accord with section 7 apply to the code; keep
intact all notices of the absence of any warranty; and give all recipients a copy of
this License along with the Program.

You may charge any price or no price for each copy that you convey, and you may offer
support or warranty protection for a fee.

### 5. Conveying Modified Source Versions

You may convey a work based on the Program, or the modifications to produce it from
the Program, in the form of source code under the terms of section 4, provided that
you also meet all of these conditions:

* **a)** The work must carry prominent notices stating that you modified it, and giving a
relevant date.
* **b)** The work must carry prominent notices stating that it is released under this
License and any conditions added under section 7. This requirement modifies the
requirement in section 4 to “keep intact all notices”.
* **c)** You must license the entire work, as a whole, under this License to anyone who
comes into possession of a copy. This License will therefore apply, along with any
applicable section 7 additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no permission to license the
work in any other way, but it does not invalidate such permission if you have
separately received it.
* **d)** If the work has interactive user interfaces, each must display Appropriate Legal
Notices; however, if the Program has interactive interfaces that do not display
Appropriate Legal Notices, your work need not make them do so.

A compilation of a covered work with other separate and independent works, which are
not by their nature extensions of the covered work, and which are not combined with
it such as to form a larger program, in or on a volume of a storage or distribution
medium, is called an “aggregate” if the compilation and its resulting
copyright are not used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work in an aggregate
does not cause this License to apply to the other parts of the aggregate.

### 6. Conveying Non-Source Forms

You may convey a covered work in object code form under the terms of sections 4 and
5, provided that you also convey the machine-readable Corresponding Source under the
terms of this License, in one of these ways:

* **a)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by the Corresponding Source fixed on a
durable physical medium customarily used for software interchange.
* **b)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by a written offer, valid for at least
three years and valid for as long as you offer spare parts or customer support for
that product model, to give anyone who possesses the object code either **(1)** a copy of
the Corresponding Source for all the software in the product that is covered by this
License, on a durable physical medium customarily used for software interchange, for
a price no more than your reasonable cost of physically performing this conveying of
source, or **(2)** access to copy the Corresponding Source from a network server at no
charge.
* **c)** Convey individual copies of the object code with a copy of the written offer to
provide the Corresponding Source. This alternative is allowed only occasionally and
noncommercially, and only if you received the object code with such an offer, in
accord with subsection 6b.
* **d)** Convey the object code by offering access from a designated place (gratis or for
a charge), and offer equivalent access to the Corresponding Source in the same way
through the same place at no further charge. You need not require recipients to copy
the Corresponding Source along with the object code. If the place to copy the object
code is a network server, the Corresponding Source may be on a different server
(operated by you or a third party) that supports equivalent copying facilities,
provided you maintain clear directions next to the object code saying where to find
the Corresponding Source. Regardless of what server hosts the Corresponding Source,
you remain obligated to ensure that it is available for as long as needed to satisfy
these requirements.
* **e)** Convey the object code using peer-to-peer transmission, provided you inform
other peers where the object code and Corresponding Source of the work are being
offered to the general public at no charge under subsection 6d.

A separable portion of the object code, whose source code is excluded from the
Corresponding Source as a System Library, need not be included in conveying the
object code work.

A “User Product” is either **(1)** a “consumer product”, which
means any tangible personal property which is normally used for personal, family, or
household purposes, or **(2)** anything designed or sold for incorporation into a
dwelling. In determining whether a product is a consumer product, doubtful cases
shall be resolved in favor of coverage. For a particular product received by a
particular user, “normally used” refers to a typical or common use of
that class of product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected to use, the
product. A product is a consumer product regardless of whether the product has
substantial commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

“Installation Information” for a User Product means any methods,
procedures, authorization keys, or other information required to install and execute
modified versions of a covered work in that User Product from a modified version of
its Corresponding Source. The information must suffice to ensure that the continued
functioning of the modified object code is in no case prevented or interfered with
solely because modification has been made.

If you convey an object code work under this section in, or with, or specifically for
use in, a User Product, and the conveying occurs as part of a transaction in which
the right of possession and use of the User Product is transferred to the recipient
in perpetuity or for a fixed term (regardless of how the transaction is
characterized), the Corresponding Source conveyed under this section must be
accompanied by the Installation Information. But this requirement does not apply if
neither you nor any third party retains the ability to install modified object code
on the User Product (for example, the work has been installed in ROM).

The requirement to provide Installation Information does not include a requirement to
continue to provide support service, warranty, or updates for a work that has been
modified or installed by the recipient, or for the User Product in which it has been
modified or installed. Access to a network may be denied when the modification itself
materially and adversely affects the operation of the network or violates the rules
and protocols for communication across the network.

Corresponding Source conveyed, and Installation Information provided, in accord with
this section must be in a format that is publicly documented (and with an
implementation available to the public in source code form), and must require no
special password or key for unpacking, reading or copying.

### 7. Additional Terms

“Additional permissions” are terms that supplement the terms of this
License by making exceptions from one or more of its conditions. Additional
permissions that are applicable to the entire Program shall be treated as though they
were included in this License, to the extent that they are valid under applicable
law. If additional permissions apply only to part of the Program, that part may be
used separately under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

When you convey a copy of a covered work, you may at your option remove any
additional permissions from that copy, or from any part of it. (Additional
permissions may be written to require their own removal in certain cases when you
modify the work.) You may place additional permissions on material, added by you to a
covered work, for which you have or can give appropriate copyright permission.

Notwithstanding any other provision of this License, for material you add to a
covered work, you may (if authorized by the copyright holders of that material)
supplement the terms of this License with terms:

* **a)** Disclaiming warranty or limiting liability differently from the terms of
sections 15 and 16 of this License; or
* **b)** Requiring preservation of specified reasonable legal notices or author
attributions in that material or in the Appropriate Legal Notices displayed by works
containing it; or
* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that
modified versions of such material be marked in reasonable ways as different from the
original version; or
* **d)** Limiting the use for publicity purposes of names of licensors or authors of the
material; or
* **e)** Declining to grant rights under trademark law for use of some trade names,
trademarks, or service marks; or
* **f)** Requiring indemnification of licensors and authors of that material by anyone
who conveys the material (or modified versions of it) with contractual assumptions of
liability to the recipient, for any liability that these contractual assumptions
directly impose on those licensors and authors.

All other non-permissive additional terms are considered “further
restrictions” within the meaning of section 10. If the Program as you received
it, or any part of it, contains a notice stating that it is governed by this License
along with a term that is a further restriction, you may remove that term. If a
license document contains a further restriction but permits relicensing or conveying
under this License, you may add to a covered work material governed by the terms of
that license document, provided that the further restriction does not survive such
relicensing or conveying.

If you add terms to a covered work in accord with this section, you must place, in
the relevant source files, a statement of the additional terms that apply to those
files, or a notice indicating where to find the applicable terms.

Additional terms, permissive or non-permissive, may be stated in the form of a
separately written license, or stated as exceptions; the above requirements apply
either way.

### 8. Termination

You may not propagate or modify a covered work except as expressly provided under
this License. Any attempt otherwise to propagate or modify it is void, and will
automatically terminate your rights under this License (including any patent licenses
granted under the third paragraph of section 11).

However, if you cease all violation of this License, then your license from a
particular copyright holder is reinstated **(a)** provisionally, unless and until the
copyright holder explicitly and finally terminates your license, and **(b)** permanently,
if the copyright holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

Moreover, your license from a particular copyright holder is reinstated permanently
if the copyright holder notifies you of the violation by some reasonable means, this
is the first time you have received notice of violation of this License (for any
work) from that copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

Termination of your rights under this section does not terminate the licenses of
parties who have received copies or rights from you under this License. If your
rights have been terminated and not permanently reinstated, you do not qualify to
receive new licenses for the same material under section 10.

### 9. Acceptance Not Required for Having Copies

You are not required to accept this License in order to receive or run a copy of the
Program. Ancillary propagation of a covered work occurring solely as a consequence of
using peer-to-peer transmission to receive a copy likewise does not require
acceptance. However, nothing other than this License grants you permission to
propagate or modify any covered work. These actions infringe copyright if you do not
accept this License. Therefore, by modifying or propagating a covered work, you
indicate your acceptance of this License to do so.

### 10. Automatic Licensing of Downstream Recipients

Each time you convey a covered work, the recipient automatically receives a license
from the original licensors, to run, modify and propagate that work, subject to this
License. You are not responsible for enforcing compliance by third parties with this
License.

An “entity transaction” is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an organization, or
merging organizations. If propagation of a covered work results from an entity
transaction, each party to that transaction who receives a copy of the work also
receives whatever licenses to the work the party's predecessor in interest had or
could give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if the predecessor
has it or can get it with reasonable efforts.

You may not impose any further restrictions on the exercise of the rights granted or
affirmed under this License. For example, you may not impose a license fee, royalty,
or other charge for exercise of rights granted under this License, and you may not
initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging
that any patent claim is infringed by making, using, selling, offering for sale, or
importing the Program or any portion of it.

### 11. Patents

A “contributor” is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The work thus
licensed is called the contributor's “contributor version”.

A contributor's “essential patent claims” are all patent claims owned or
controlled by the contributor, whether already acquired or hereafter acquired, that
would be infringed by some manner, permitted by this License, of making, using, or
selling its contributor version, but do not include claims that would be infringed
only as a consequence of further modification of the contributor version. For
purposes of this definition, “control” includes the right to grant patent
sublicenses in a manner consistent with the requirements of this License.

Each contributor grants you a non-exclusive, worldwide, royalty-free patent license
under the contributor's essential patent claims, to make, use, sell, offer for sale,
import and otherwise run, modify and propagate the contents of its contributor
version.

In the following three paragraphs, a “patent license” is any express
agreement or commitment, however denominated, not to enforce a patent (such as an
express permission to practice a patent or covenant not to sue for patent
infringement). To “grant” such a patent license to a party means to make
such an agreement or commitment not to enforce a patent against the party.

If you convey a covered work, knowingly relying on a patent license, and the
Corresponding Source of the work is not available for anyone to copy, free of charge
and under the terms of this License, through a publicly available network server or
other readily accessible means, then you must either **(1)** cause the Corresponding
Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the
patent license for this particular work, or **(3)** arrange, in a manner consistent with
the requirements of this License, to extend the patent license to downstream
recipients. “Knowingly relying” means you have actual knowledge that, but
for the patent license, your conveying the covered work in a country, or your
recipient's use of the covered work in a country, would infringe one or more
identifiable patents in that country that you have reason to believe are valid.

If, pursuant to or in connection with a single transaction or arrangement, you
convey, or propagate by procuring conveyance of, a covered work, and grant a patent
license to some of the parties receiving the covered work authorizing them to use,
propagate, modify or convey a specific copy of the covered work, then the patent
license you grant is automatically extended to all recipients of the covered work and
works based on it.

A patent license is “discriminatory” if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on the
non-exercise of one or more of the rights that are specifically granted under this
License. You may not convey a covered work if you are a party to an arrangement with
a third party that is in the business of distributing software, under which you make
payment to the third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties who would receive
the covered work from you, a discriminatory patent license **(a)** in connection with
copies of the covered work conveyed by you (or copies made from those copies), or **(b)**
primarily for and in connection with specific products or compilations that contain
the covered work, unless you entered into that arrangement, or that patent license
was granted, prior to 28 March 2007.

Nothing in this License shall be construed as excluding or limiting any implied
license or other defenses to infringement that may otherwise be available to you
under applicable patent law.

### 12. No Surrender of Others' Freedom

If conditions are imposed on you (whether by court order, agreement or otherwise)
that contradict the conditions of this License, they do not excuse you from the
conditions of this License. If you cannot convey a covered work so as to satisfy
simultaneously your obligations under this License and any other pertinent
obligations, then as a consequence you may not convey it at all. For example, if you
agree to terms that obligate you to collect a royalty for further conveying from
those to whom you convey the Program, the only way you could satisfy both those terms
and this License would be to refrain entirely from conveying the Program.

### 13. Use with the GNU Affero General Public License

Notwithstanding any other provision of this License, you have permission to link or
combine any covered work with a work licensed under version 3 of the GNU Affero
General Public License into a single combined work, and to convey the resulting work.
The terms of this License will continue to apply to the part which is the covered
work, but the special requirements of the GNU Affero General Public License, section
13, concerning interaction through a network will apply to the combination as such.

### 14. Revised Versions of this License

The Free Software Foundation may publish revised and/or new versions of the GNU
General Public License from time to time. Such new versions will be similar in spirit
to the present version, but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the Program specifies that
a certain numbered version of the GNU General Public License “or any later
version” applies to it, you have the option of following the terms and
conditions either of that numbered version or of any later version published by the
Free Software Foundation. If the Program does not specify a version number of the GNU
General Public License, you may choose any version ever published by the Free
Software Foundation.

If the Program specifies that a proxy can decide which future versions of the GNU
General Public License can be used, that proxy's public statement of acceptance of a
version permanently authorizes you to choose that version for the Program.

Later license versions may give you additional or different permissions. However, no
additional obligations are imposed on any author or copyright holder as a result of
your choosing to follow a later version.

### 15. Disclaimer of Warranty

THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

### 16. Limitation of Liability

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS
PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE
OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE
WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

### 17. Interpretation of Sections 15 and 16

If the disclaimer of warranty and limitation of liability provided above cannot be
given local legal effect according to their terms, reviewing courts shall apply local
law that most closely approximates an absolute waiver of all civil liability in
connection with the Program, unless a warranty or assumption of liability accompanies
a copy of the Program in return for a fee.

_END OF TERMS AND CONDITIONS_

## How to Apply These Terms to Your New Programs

If you develop a new program, and you want it to be of the greatest possible use to
the public, the best way to achieve this is to make it free software which everyone
can redistribute and change under these terms.

To do so, attach the following notices to the program. It is safest to attach them
to the start of each source file to most effectively state the exclusion of warranty;
and each file should have at least the “copyright” line and a pointer to
where the full notice is found.

    datamods: Modules to Import and Manipulate Data in 'Shiny' Applications
    Copyright (C) 2020 Victor PERRIER

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

If the program does terminal interaction, make it output a short notice like this
when it starts in an interactive mode:

    datamods Copyright (C) 2020 Victor PERRIER
    This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type 'show c' for details.

The hypothetical commands `show w` and `show c` should show the appropriate parts of
the General Public License. Of course, your program's commands might be different;
for a GUI interface, you would use an “about box”.

You should also get your employer (if you work as a programmer) or school, if any, to
sign a “copyright disclaimer” for the program, if necessary. For more
information on this, and how to apply and follow the GNU GPL, see
&lt;<http://www.gnu.org/licenses/>&gt;.

The GNU General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may consider it
more useful to permit linking proprietary applications with the library. If this is
what you want to do, use the GNU Lesser General Public License instead of this
License. But first, please read
&lt;<http://www.gnu.org/philosophy/why-not-lgpl.html>&gt;.


================================================
FILE: NAMESPACE
================================================
# Generated by roxygen2: do not edit by hand

export(create_column_server)
export(create_column_ui)
export(cut_variable_server)
export(cut_variable_ui)
export(edit_data_server)
export(edit_data_ui)
export(filter_data_server)
export(filter_data_ui)
export(get_data_packages)
export(i18n)
export(i18n_translations)
export(import_copypaste_server)
export(import_copypaste_ui)
export(import_file_server)
export(import_file_ui)
export(import_globalenv_server)
export(import_globalenv_ui)
export(import_googlesheets_server)
export(import_googlesheets_ui)
export(import_modal)
export(import_server)
export(import_ui)
export(import_url_server)
export(import_url_ui)
export(list_allowed_operations)
export(list_pkg_data)
export(modal_create_column)
export(modal_cut_variable)
export(modal_update_factor)
export(sample_server)
export(sample_ui)
export(select_group_server)
export(select_group_ui)
export(set_i18n)
export(show_data)
export(update_factor_server)
export(update_factor_ui)
export(update_variables_server)
export(update_variables_ui)
export(validation_server)
export(validation_ui)
export(winbox_create_column)
export(winbox_cut_variable)
export(winbox_update_factor)
importFrom(bslib,bs_current_theme)
importFrom(bslib,bs_get_variables)
importFrom(bslib,is_bs_theme)
importFrom(classInt,classIntervals)
importFrom(data.table,":=")
importFrom(data.table,.N)
importFrom(data.table,.SD)
importFrom(data.table,as.data.table)
importFrom(data.table,copy)
importFrom(data.table,data.table)
importFrom(data.table,fread)
importFrom(data.table,setattr)
importFrom(data.table,setnames)
importFrom(data.table,setorderv)
importFrom(data.table,uniqueN)
importFrom(graphics,abline)
importFrom(graphics,axis)
importFrom(graphics,hist)
importFrom(graphics,par)
importFrom(graphics,plot.new)
importFrom(graphics,plot.window)
importFrom(htmltools,HTML)
importFrom(htmltools,css)
importFrom(htmltools,div)
importFrom(htmltools,doRenderTags)
importFrom(htmltools,htmlDependency)
importFrom(htmltools,singleton)
importFrom(htmltools,tagAppendAttributes)
importFrom(htmltools,tagAppendChild)
importFrom(htmltools,tagList)
importFrom(htmltools,tags)
importFrom(htmltools,validateCssUnit)
importFrom(phosphoricons,ph)
importFrom(reactable,colDef)
importFrom(reactable,getReactableState)
importFrom(reactable,reactable)
importFrom(reactable,reactableOutput)
importFrom(reactable,renderReactable)
importFrom(reactable,updateReactable)
importFrom(readxl,excel_sheets)
importFrom(rio,import)
importFrom(rlang,"%||%")
importFrom(rlang,as_function)
importFrom(rlang,as_label)
importFrom(rlang,call2)
importFrom(rlang,enquo)
importFrom(rlang,eval_tidy)
importFrom(rlang,exec)
importFrom(rlang,expr)
importFrom(rlang,fn_fmls_names)
importFrom(rlang,is_double)
importFrom(rlang,is_function)
importFrom(rlang,is_list)
importFrom(rlang,is_named)
importFrom(rlang,is_null)
importFrom(rlang,is_vector)
importFrom(rlang,parse_expr)
importFrom(rlang,set_names)
importFrom(rlang,sym)
importFrom(rlang,syms)
importFrom(shiny,NS)
importFrom(shiny,actionButton)
importFrom(shiny,actionLink)
importFrom(shiny,addResourcePath)
importFrom(shiny,bindEvent)
importFrom(shiny,checkboxInput)
importFrom(shiny,column)
importFrom(shiny,conditionalPanel)
importFrom(shiny,dateRangeInput)
importFrom(shiny,downloadButton)
importFrom(shiny,downloadHandler)
importFrom(shiny,eventReactive)
importFrom(shiny,fileInput)
importFrom(shiny,fluidRow)
importFrom(shiny,getDefaultReactiveDomain)
importFrom(shiny,hideTab)
importFrom(shiny,icon)
importFrom(shiny,insertUI)
importFrom(shiny,is.reactive)
importFrom(shiny,isTruthy)
importFrom(shiny,isolate)
importFrom(shiny,modalDialog)
importFrom(shiny,moduleServer)
importFrom(shiny,need)
importFrom(shiny,numericInput)
importFrom(shiny,observe)
importFrom(shiny,observeEvent)
importFrom(shiny,outputOptions)
importFrom(shiny,plotOutput)
importFrom(shiny,reactive)
importFrom(shiny,reactiveVal)
importFrom(shiny,reactiveValues)
importFrom(shiny,reactiveValuesToList)
importFrom(shiny,removeModal)
importFrom(shiny,removeUI)
importFrom(shiny,renderPlot)
importFrom(shiny,renderUI)
importFrom(shiny,req)
importFrom(shiny,selectizeInput)
importFrom(shiny,showModal)
importFrom(shiny,singleton)
importFrom(shiny,sliderInput)
importFrom(shiny,tabPanel)
importFrom(shiny,tabPanelBody)
importFrom(shiny,tabsetPanel)
importFrom(shiny,tagList)
importFrom(shiny,tags)
importFrom(shiny,textAreaInput)
importFrom(shiny,textInput)
importFrom(shiny,uiOutput)
importFrom(shiny,updateActionButton)
importFrom(shiny,updateSliderInput)
importFrom(shiny,updateTabsetPanel)
importFrom(shiny,updateTextAreaInput)
importFrom(shiny,validate)
importFrom(shinyWidgets,WinBox)
importFrom(shinyWidgets,airDatepickerInput)
importFrom(shinyWidgets,alert)
importFrom(shinyWidgets,dropMenu)
importFrom(shinyWidgets,html_dependency_pretty)
importFrom(shinyWidgets,noUiSliderInput)
importFrom(shinyWidgets,numericInputIcon)
importFrom(shinyWidgets,numericRangeInput)
importFrom(shinyWidgets,pickerInput)
importFrom(shinyWidgets,pickerOptions)
importFrom(shinyWidgets,prettyCheckbox)
importFrom(shinyWidgets,prettySwitch)
importFrom(shinyWidgets,radioGroupButtons)
importFrom(shinyWidgets,show_alert)
importFrom(shinyWidgets,textInputIcon)
importFrom(shinyWidgets,updatePickerInput)
importFrom(shinyWidgets,updateVirtualSelect)
importFrom(shinyWidgets,virtualSelectInput)
importFrom(shinyWidgets,wbControls)
importFrom(shinyWidgets,wbOptions)
importFrom(shinybusy,notify_failure)
importFrom(shinybusy,notify_info)
importFrom(shinybusy,notify_success)
importFrom(shinybusy,notify_warning)
importFrom(stats,setNames)
importFrom(tibble,as_tibble)
importFrom(toastui,datagrid)
importFrom(toastui,datagridOutput)
importFrom(toastui,datagridOutput2)
importFrom(toastui,grid_colorbar)
importFrom(toastui,grid_columns)
importFrom(toastui,grid_editor)
importFrom(toastui,grid_editor_opts)
importFrom(toastui,grid_format)
importFrom(toastui,grid_selection_row)
importFrom(toastui,grid_style_column)
importFrom(toastui,renderDatagrid)
importFrom(toastui,renderDatagrid2)
importFrom(tools,file_ext)
importFrom(utils,data)
importFrom(utils,getFromNamespace)
importFrom(utils,hasName)
importFrom(utils,head)
importFrom(utils,modifyList)
importFrom(utils,packageName)
importFrom(utils,packageVersion)
importFrom(utils,type.convert)
importFrom(utils,write.csv)
importFrom(writexl,write_xlsx)


================================================
FILE: NEWS.md
================================================
# datamods 1.5.4

* Rename CSS class `show` to `show-block` (used internally).
* `select_group_server()`: added argument `selected_r =` to set selected values.


# datamods 1.5.3

* `update_variables_server`: change of data update management after clicking on the validate button, fixed a problem when input data are the same as output data.


# datamods 1.5.2

* `import_file_ui`: back to old parameters layout inside a dropdown button and new argument to switch to inline layout. 
* `edit_data_server`: allow to use reactive function for reactable_options.
* cut variable module (`cut_variable_ui`/`cut_variable_server`): allow to select fixed breaks.


# datamods 1.5.1

* New module `update_factor_ui()` / `update_factor_server()` to reorder levels of a factor.
* i18n: Updated translations files with new labels, which are automatically translated, if you see incorrect translations, please open an issue or PR : https://github.com/dreamRs/datamods


# datamods 1.5.0

* New module `create_column_ui()` / `create_column_server()` to add new column based on an expression to a `data.frame`.
* New module `cut_variable_ui()` / `cut_variable_server()` to cut a numeric factor into several interval.


# datamods 1.4.5

* `edit_data_server()` : fixed default variable labels when `var_labels = NULL`.


# datamods 1.4.4

* `edit_data_server()` : added argument `add_default_values = list(...)` to specify default value for input widget when adding a new entry in the table.


# datamods 1.4.3

* `edit_data_server()` : added the ability to specify callbacks functions to be executed before performing an action on the table (add, update or delete).
* `edit_data_server()` : pass reactable option + selection to the table [#82](https://github.com/dreamRs/datamods/pull/82)
* `edit-data` module : use factor levels and sort theme in edit input form for factors (sorting also applies for characters), thanks to [@Felixmil](https://github.com/Felixmil).
* `import-file` module : allow to specify string used to identify `NA`, thanks to [@DrFabach](https://github.com/DrFabach).
* `filter_data_server()` : argument `drop_ids` can now be set via option `datamods.filter.drop_ids` and can be a list like `list(p = 0.9, n = 50)` to specify threshold values to remove IDs columns.


# datamods 1.4.2

* i18n: japanese translations added, thanks to [@nissinbo](https://github.com/nissinbo).
* `select_group_server()` : output value now have an `inputs` attribute with a named list of selected inputs values.


# datamods 1.4.1

* i18n: polish translations added, thanks to [@jakub-jedrusiak](https://github.com/jakub-jedrusiak).

### Bug fixes
* Fixed displaying variable class in View tab (fix [#64](https://github.com/dreamRs/datamods/issues/64)).
* `select_group_server()` : fix update inputs when `multiple = FALSE`.
* `filter_data_server()` : sorting choices in select menus (select, picker and virtual) (fix [#66](https://github.com/dreamRs/datamods/issues/64))).
* `filter_data_server()` : don't use `<`/`>` for empty field to not confuse to an HTML tag (fix [#65](https://github.com/dreamRs/datamods/issues/65))).


# datamods 1.4.0

* New module : `edit_data_ui()` / `edit_data_server()` to interactively edit a `data.frame`, thanks to [@ggsamra](https://github.com/ggsamra).
* New module : `sample_ui()` / `sample_server()` to take a sample from a table, thanks to [@ggsamra](https://github.com/ggsamra).



# datamods 1.3.4

* i18n: korean translations added, thanks to [@ChangwooLim](https://github.com/ChangwooLim) (migrated from esquisse package).
* `import_ui()` / `import_modal()`: added `file_extensions` argument passed to `import_file_ui()` (fix [#51](https://github.com/dreamRs/datamods/issues/51)).



# datamods 1.3.3

* i18n: turkish translations added, thanks to [@sbalci](https://github.com/sbalci).
* `filter_data` module now support getting and setting filter values, thanks to [@bellma-lilly](https://github.com/bellma-lilly).



# datamods 1.3.2

* Fix bad link in NEWS.



# datamods 1.3.1

* Fixed a bug in `update_variables` module.



# datamods 1.3.0

* New module to read flat data from URLs `import_url_*()`.
* Error messages displayed to the user are more informative on the actual error.
* `filter_data_server()`: new argument `value_na` to set default value for NA's filters widgets.
* `import_copypaste_ui()`: new argument `name_field` to show or not name field.
* `import_copypaste_server()`: new argument `fread_args` to pass arguments to `data.table::fread`.
* i18n: chinese translations added, thanks to [@xmusphlkg](https://github.com/xmusphlkg).
* i18n: spanish translations added, thanks to [@dnldelarosa](https://github.com/dnldelarosa).
* i18n: german translations added, thanks to [@SteEcker](https://github.com/SteEcker) and joerghenkebuero.



# datamods 1.2.0

* Switch to [{phosphoricons}](https://github.com/dreamRs/phosphoricons) for icons.
* `import_file_ui()` has a new argument `file_extensions` to select the files that the user can import.
* `import_file_server()` has a new argument `read_fns` to define custom function(s) to read data.

### Translations
* i18n: :macedonia: macedonian translations added, thanks to [@novica](https://github.com/novica).
* i18n: :albania: albanian translations added, thanks to [@novica](https://github.com/novica).
* i18n: :portugal: :brazil: brazilian portuguese translations added, thanks to [@gabrielteotonio](https://github.com/gabrielteotonio).



# datamods 1.1.5

* `import_*_server()` added reset argument to clear the data.
* `import_copypaste_server()` also return a `reactive` function "name" like the others.
* New function `i18n()` to add internationalization in shiny apps.



# datamods 1.1.4

* `filter_data_server`: convert data to `data.frame` (fix [esquisse #149](https://github.com/dreamRs/esquisse/issues/149)).
* `filter_data_server`: fixed bug with timezone if POSIXct.
* Import data from package: use `pkg::data` notation for data's name.



# datamods 1.1.3

* Preserve class `sf` in output.



# datamods 1.1.2

* Fixed a bug when retrieving data from package with parenthesis in name.
* Fixed test on R-oldrel



# datamods 1.1.0

* Added internationalization to translate labels used in modules, see corresponding vignette.



# datamods 1.0.1

* First release on CRAN: Shiny modules import, to update, validate and filter data in interactive applications
* Added a `NEWS.md` file to track changes to the package.


================================================
FILE: R/create-column.R
================================================

#' @title Create new column
#'
#' @description
#' This module allow to enter an expression to create a new column in a `data.frame`.
#'
#'
#' @param id Module's ID.
#'
#' @return A [shiny::reactive()] function returning the data.
#'
#' @note User can only use a subset of function: `r paste(list_allowed_operations(), collapse=", ")`.
#'  You can add more operations using the `allowed_operations` argument, for  example if you want to allow to use package lubridate, you can do:
#'  ```r
#'  c(list_allowed_operations(), getNamespaceExports("lubridate"))
#'  ```
#'
#' @export
#'
#' @importFrom htmltools tagList tags css
#' @importFrom shiny NS textInput textAreaInput uiOutput actionButton
#' @importFrom phosphoricons ph
#' @importFrom shinyWidgets virtualSelectInput
#'
#' @name create-column
#'
#' @example examples/create_column.R
create_column_ui <- function(id) {
  ns <- NS(id)
  tagList(
    html_dependency_datamods(),
    fluidRow(
      column(
        width = 6,
        textInput(
          inputId = ns("new_column"),
          label = i18n("New column name:"),
          value = "new_column1",
          width = "100%"
        )
      ),
      column(
        width = 6,
        virtualSelectInput(
          inputId = ns("group_by"),
          label = i18n("Group calculation by:"),
          choices = NULL,
          multiple = TRUE,
          disableSelectAll = TRUE,
          hasOptionDescription = TRUE,
          width = "100%"
        )
      )
    ),
    textAreaInput(
      inputId = ns("expression"),
      label = i18n("Enter an expression to define new column:"),
      value = "",
      width = "100%",
      rows = 6
    ),
    tags$i(
      class = "d-block",
      ph("info"),
      i18n("Click on a column name to add it to the expression:")
    ),
    uiOutput(outputId = ns("columns")),
    uiOutput(outputId = ns("feedback")),
    tags$div(
      style = css(
        display = "grid",
        gridTemplateColumns = "3fr 1fr",
        columnGap = "10px",
        margin = "10px 0"
      ),
      actionButton(
        inputId = ns("compute"),
        label = tagList(
          ph("gear"), i18n("Create column")
        ),
        class = "btn-outline-primary",
        width = "100%"
      ),
      actionButton(
        inputId = ns("remove"),
        label = tagList(
          ph("trash")
        ),
        class = "btn-outline-danger",
        width = "100%"
      )
    )
  )
}

#' @param data_r A [shiny::reactive()] function returning a `data.frame`.
#' @param allowed_operations A `list` of allowed operations, see below for details.
#'
#' @export
#'
#' @rdname create-column
#'
#' @importFrom shiny moduleServer reactiveValues observeEvent renderUI req
#'  updateTextAreaInput reactive bindEvent observe
#' @importFrom shinyWidgets alert updateVirtualSelect
create_column_server <- function(id,
                                 data_r = reactive(NULL),
                                 allowed_operations = list_allowed_operations()) {
  moduleServer(
    id,
    function(input, output, session) {

      ns <- session$ns

      info_alert <- alert(
        status = "info",
        ph("question"),
        i18n("Choose a name for the column to be created or modified,"),
        i18n("then enter an expression before clicking on the button above to validate or on "),
        ph("trash"), i18n("to delete it.")
      )

      rv <- reactiveValues(
        data = NULL,
        feedback =info_alert
      )

      observeEvent(input$hidden, rv$feedback <- info_alert)

      bindEvent(observe({
        data <- data_r()
        updateVirtualSelect(
          inputId = "group_by",
          choices = make_choices_with_infos(data)
        )
      }), data_r(), input$hidden)

      observeEvent(data_r(), rv$data <- data_r())

      output$feedback <- renderUI(rv$feedback)

      output$columns <- renderUI({
        data <- req(rv$data)
        col_type <- getFromNamespace("col_type", "esquisse")
        mapply(
          label = names(data),
          type = col_type(data),
          FUN = btn_column,
          MoreArgs = list(inputId = ns("add_column")),
          SIMPLIFY = FALSE
        )
      })

      observeEvent(input$add_column, {
        updateTextAreaInput(
          session = session,
          inputId = "expression",
          value = paste0(input$expression, input$add_column)
        )
      })

      observeEvent(input$new_column, {
        if (input$new_column == "") {
          rv$feedback <- alert(
            status = "warning",
            ph("warning"), i18n("New column name cannot be empty")
          )
        }
      })

      observeEvent(input$remove, {
        rv$data[[input$new_column]] <- NULL
      })
      observeEvent(input$compute, {
        rv$feedback <- try_compute_column(
          expression = input$expression,
          name = input$new_column,
          rv = rv,
          allowed_operations = allowed_operations,
          by = input$group_by
        )
      })

      return(reactive(rv$data))
    }
  )
}

#' @export
#'
#' @rdname create-column
# @importFrom methods getGroupMembers
list_allowed_operations <- function() {
  c(
    "(", "c",
    # getGroupMembers("Arith"),
    c("+", "-", "*", "^", "%%", "%/%", "/"),
    # getGroupMembers("Compare"),
    c("==", ">", "<", "!=", "<=", ">="),
    # getGroupMembers("Logic"),
    c("&", "|"),
    # getGroupMembers("Math"),
    c("abs", "sign", "sqrt", "ceiling", "floor", "trunc", "cummax",
      "cummin", "cumprod", "cumsum", "exp", "expm1", "log", "log10",
      "log2", "log1p", "cos", "cosh", "sin", "sinh", "tan", "tanh",
      "acos", "acosh", "asin", "asinh", "atan", "atanh", "cospi", "sinpi",
      "tanpi", "gamma", "lgamma", "digamma", "trigamma"),
    # getGroupMembers("Math2"),
    c("round", "signif"),
    # getGroupMembers("Summary"),
    c("max", "min", "range", "prod", "sum", "any", "all"),
    "pmin", "pmax", "mean",
    "paste", "paste0", "substr", "nchar", "trimws",
    "gsub", "sub", "grepl", "ifelse", "length",
    "as.numeric", "as.character", "as.integer", "as.Date", "as.POSIXct",
    "as.factor", "factor"
  )
}


#' @inheritParams shiny::modalDialog
#' @export
#'
#' @importFrom shiny showModal modalDialog textInput
#' @importFrom htmltools tagList
#'
#' @rdname create-column
modal_create_column <- function(id,
                                title = i18n("Create a new column"),
                                easyClose = TRUE,
                                size = "l",
                                footer = NULL) {
  ns <- NS(id)
  showModal(modalDialog(
    title = tagList(title, button_close_modal()),
    create_column_ui(id),
    tags$div(
      style = "display: none;",
      textInput(inputId = ns("hidden"), label = NULL, value = genId())
    ),
    easyClose = easyClose,
    size = size,
    footer = footer
  ))
}

#' @inheritParams shinyWidgets::WinBox
#' @export
#'
#' @importFrom shinyWidgets WinBox wbOptions wbControls
#' @importFrom htmltools tagList
#' @rdname create-column
winbox_create_column <- function(id,
                                 title = i18n("Create a new column"),
                                 options = shinyWidgets::wbOptions(),
                                 controls = shinyWidgets::wbControls()) {
  ns <- NS(id)
  WinBox(
    title = title,
    ui = tagList(
      create_column_ui(id),
      tags$div(
        style = "display: none;",
        textInput(inputId = ns("hidden"), label = NULL, value = genId())
      )
    ),
    options = modifyList(
      shinyWidgets::wbOptions(height = "550px", modal = TRUE),
      options
    ),
    controls = controls,
    auto_height = FALSE
  )
}


#' @importFrom rlang parse_expr eval_tidy call2 set_names syms
#' @importFrom data.table as.data.table :=
try_compute_column <- function(expression,
                               name,
                               rv,
                               allowed_operations,
                               by = NULL) {
  parsed <- try(parse(text = expression, keep.source = FALSE), silent = TRUE)
  if (inherits(parsed, "try-error")) {
    return(alert_error(attr(parsed, "condition")$message))
  }
  funs <- unlist(c(extract_calls(parsed), lapply(parsed, extract_calls)), recursive = TRUE)
  if (!are_allowed_operations(funs, allowed_operations)) {
    return(alert_error(i18n("Some operations are not allowed")))
  }
  if (!isTruthy(by)) {
    result <- try(
      eval_tidy(parse_expr(expression), data = rv$data),
      silent = TRUE
    )
  } else {
    result <- try(
      {
        dt <- as.data.table(rv$data)
        new_col <- NULL
        dt[, new_col := eval_tidy(parse_expr(expression), data = .SD), by = by]
        dt$new_col
      },
      silent = TRUE
    )
  }
  if (inherits(result, "try-error")) {
    return(alert_error(attr(result, "condition")$message))
  }
  adding_col <- try(rv$data[[name]] <- result, silent = TRUE)
  if (inherits(adding_col, "try-error")) {
    return(alert_error(attr(adding_col, "condition")$message))
  }
  code <- if (!isTruthy(by)) {
    call2("mutate", !!!set_names(list(parse_expr(expression)), name))
  } else {
    call2(
      "mutate",
      !!!set_names(list(parse_expr(expression)), name),
      !!!list(.by = expr(c(!!!syms(by))))
    )
  }
  attr(rv$data, "code") <- Reduce(
    f = function(x, y) expr(!!x %>% !!y),
    x = c(attr(rv$data, "code"),  code)
  )
  alert(
    status = "success",
    ph("check"), i18n("Column added!")
  )
}

are_allowed_operations <- function(x, allowed_operations) {
  all(
    x %in% allowed_operations
  )
}


extract_calls <- function(exp) {
  if (is.call(exp))
    return(list(
      as.character(exp[[1L]]),
      lapply(exp[-1L], extract_calls)
    ))
}

alert_error <- function(text) {
  alert(
    status = "danger",
    ph("bug"), text
  )
}


btn_column <- function(label, type, inputId) {
  icon <- switch (
    type,
    discrete = "text-aa",
    time = "calendar",
    continuous = "hash",
    NULL
  )
  tags$button(
    type = "button",
    class = paste0("btn btn-column-", type),
    style = css(
      "--bs-btn-padding-y" = ".25rem",
      "--bs-btn-padding-x" = ".5rem",
      "--bs-btn-font-size" = ".75rem",
      "margin-bottom" = "5px"
    ),
    if (!is.null(icon)) ph(icon, weight = "regular"),
    label,
    onclick = sprintf(
      "Shiny.setInputValue('%s', '%s', {priority: 'event'})",
      inputId, label
    )
  )
}


#' @importFrom data.table uniqueN
#' @importFrom htmltools doRenderTags
make_choices_with_infos <- function(data) {
  lapply(
    X = seq_along(data),
    FUN = function(i) {
      nm <- names(data)[i]
      values <- data[[nm]]
      icon <- if (inherits(values, "character")) {
        phosphoricons::ph("text-aa")
      } else if (inherits(values, "factor")) {
        phosphoricons::ph("list-bullets")
      } else if (inherits(values, c("numeric", "integer"))) {
        phosphoricons::ph("hash")
      } else if (inherits(values, c("Date"))) {
        phosphoricons::ph("calendar")
      } else if (inherits(values, c("POSIXt"))) {
        phosphoricons::ph("clock")
      } else {
        NULL
      }
      description <- if (is.atomic(values)) {
        paste(i18n("Unique values:"), data.table::uniqueN(values))
      } else {
        ""
      }
      list(
        label = htmltools::doRenderTags(tagList(
          icon, nm
        )),
        value = nm,
        description = description
      )
    }
  )
}



================================================
FILE: R/cut-variable.R
================================================

#' @title Module to Convert Numeric to Factor
#'
#' @description
#' This module contain an interface to cut a numeric into several intervals.
#'
#'
#' @param id Module ID.
#'
#' @return A [shiny::reactive()] function returning the data.
#' @export
#'
#' @importFrom shiny NS fluidRow column numericInput checkboxInput checkboxInput plotOutput uiOutput
#' @importFrom shinyWidgets virtualSelectInput
#' @importFrom toastui datagridOutput2
#'
#' @name cut-variable
#'
#' @example examples/cut_variable.R
cut_variable_ui <- function(id) {
  ns <- NS(id)
  tagList(
    fluidRow(
      column(
        width = 3,
        virtualSelectInput(
          inputId = ns("variable"),
          label = i18n("Variable to cut:"),
          choices = NULL,
          width = "100%"
        )
      ),
      column(
        width = 3,
        virtualSelectInput(
          inputId = ns("method"),
          label = i18n("Method:"),
          choices = c(
            "fixed",
            "sd",
            "equal",
            "pretty",
            "quantile",
            # "kmeans",
            # "hclust",
            # "bclust",
            # "fisher",
            # "jenks",
            "headtails",
            "maximum",
            "box"
          ),
          selected = "quantile",
          width = "100%"
        )
      ),
      column(
        width = 3,
        numericInput(
          inputId = ns("n_breaks"),
          label = i18n("Number of breaks:"),
          value = 5,
          min = 2,
          max = 12,
          width = "100%"
        )
      ),
      column(
        width = 3,
        checkboxInput(
          inputId = ns("right"),
          label = i18n("Close intervals on the right"),
          value = TRUE
        ),
        checkboxInput(
          inputId = ns("include_lowest"),
          label = i18n("Include lowest value"),
          value = FALSE
        )
      )
    ),
    conditionalPanel(
      condition = "input.method == 'fixed'",
      ns = ns,
      uiOutput(outputId = ns("slider_fixed"))
    ),
    plotOutput(outputId = ns("plot"), width = "100%", height = "270px"),
    datagridOutput2(outputId = ns("count")),
    actionButton(
      inputId = ns("create"),
      label = tagList(ph("scissors"), i18n("Create factor variable")),
      class = "btn-outline-primary float-end"
    ),
    tags$div(class = "clearfix")
  )
}

#' @param data_r A [shiny::reactive()] function returning a `data.frame`.
#'
#' @export
#'
#' @importFrom shiny moduleServer observeEvent reactive req bindEvent renderPlot
#' @importFrom shinyWidgets updateVirtualSelect noUiSliderInput
#' @importFrom toastui renderDatagrid2 datagrid grid_colorbar
#' @importFrom rlang %||% call2 set_names expr syms
#' @importFrom classInt classIntervals
#'
#' @rdname cut-variable
cut_variable_server <- function(id, data_r = reactive(NULL)) {
  moduleServer(
    id,
    function(input, output, session) {

      rv <- reactiveValues(data = NULL)

      bindEvent(observe({
        data <- data_r()
        rv$data <- data
        vars_num <- vapply(data, is.numeric, logical(1))
        vars_num <- names(vars_num)[vars_num]
        updateVirtualSelect(
          inputId = "variable",
          choices = vars_num,
          selected = if (isTruthy(input$variable)) input$variable else vars_num[1]
        )
      }), data_r(), input$hidden)

      output$slider_fixed <- renderUI({
        data <- req(data_r())
        variable <- req(input$variable)
        req(hasName(data, variable))
        noUiSliderInput(
          inputId = session$ns("fixed_brks"),
          label = i18n("Fixed breaks:"),
          min = floor(min(data[[variable]], na.rm = TRUE)),
          max = ceiling(max(data[[variable]], na.rm = TRUE)),
          value = classInt::classIntervals(
            var = data[[variable]],
            n = input$n_breaks,
            style = "quantile"
          )$brks,
          color = get_primary_color(),
          width = "100%"
        )
      })

      breaks_r <- reactive({
        data <- req(data_r())
        variable <- req(input$variable)
        req(hasName(data, variable))
        req(input$n_breaks, input$method)
        if (input$method == "fixed") {
          req(input$fixed_brks)
          classInt::classIntervals(
            var = data[[variable]],
            n = input$n_breaks,
            style = "fixed",
            fixedBreaks = input$fixed_brks
          )
        } else {
          classInt::classIntervals(
            var = data[[variable]],
            n = input$n_breaks,
            style = input$method
          )
        }
      })

      output$plot <- renderPlot({
        data <- req(data_r())
        variable <- req(input$variable)
        plot_histogram(data, variable, breaks = breaks_r()$brks, color = get_primary_color())
      })


      data_cutted_r <- reactive({
        data <- req(data_r())
        variable <- req(input$variable)
        data[[paste0(variable, "_cut")]] <- cut(
          x = data[[variable]],
          breaks = breaks_r()$brks,
          include.lowest = input$include_lowest,
          right = input$right
        )
        code <- call2(
          "mutate",
          !!!set_names(
            list(
              expr(cut(
                !!!syms(list(x = variable)),
                !!!list(breaks = breaks_r()$brks, include.lowest = input$include_lowest, right = input$right)
              ))
            ),
            paste0(variable, "_cut")
          )
        )
        attr(data, "code") <- Reduce(
          f = function(x, y) expr(!!x %>% !!y),
          x = c(attr(data, "code"),  code)
        )
        data
      })

      output$count <- renderDatagrid2({
        data <- req(data_cutted_r())
        variable <- req(input$variable)
        count_data <- as.data.frame(
          table(
            breaks = data[[paste0(variable, "_cut")]],
            useNA = "ifany"
          ),
          responseName = "count"
        )
        gridTheme <- getOption("datagrid.theme")
        if (length(gridTheme) < 1) {
          apply_grid_theme()
        }
        on.exit(toastui::reset_grid_theme())
        grid <- datagrid(
          data = count_data,
          colwidths = "guess",
          theme = "default",
          bodyHeight = "auto"
        )
        grid <- toastui::grid_columns(grid, className = "font-monospace")
        grid_colorbar(
          grid,
          column = "count",
          label_outside = TRUE,
          label_width = "40px",
          bar_bg = get_primary_color(),
          from = c(0, max(count_data$count) + 1)
        )
      })

      data_returned_r <- observeEvent(input$create, {
        rv$data <- data_cutted_r()
      })
      return(reactive(rv$data))
    }
  )
}



#' @inheritParams shiny::modalDialog
#' @export
#'
#' @importFrom shiny showModal modalDialog textInput
#' @importFrom htmltools tagList
#'
#' @rdname cut-variable
modal_cut_variable <- function(id,
                               title = i18n("Convert Numeric to Factor"),
                               easyClose = TRUE,
                               size = "l",
                               footer = NULL) {
  ns <- NS(id)
  showModal(modalDialog(
    title = tagList(title, button_close_modal()),
    cut_variable_ui(id),
    tags$div(
      style = "display: none;",
      textInput(inputId = ns("hidden"), label = NULL, value = genId())
    ),
    easyClose = easyClose,
    size = size,
    footer = footer
  ))
}


#' @inheritParams shinyWidgets::WinBox
#' @export
#'
#' @importFrom shinyWidgets WinBox wbOptions wbControls
#' @importFrom htmltools tagList
#' @rdname cut-variable
winbox_cut_variable <- function(id,
                                title = i18n("Convert Numeric to Factor"),
                                options = shinyWidgets::wbOptions(),
                                controls = shinyWidgets::wbControls()) {
  ns <- NS(id)
  WinBox(
    title = title,
    ui = tagList(
      cut_variable_ui(id),
      tags$div(
        style = "display: none;",
        textInput(inputId = ns("hidden"), label = NULL, value = genId())
      )
    ),
    options = modifyList(
      shinyWidgets::wbOptions(height = "750px", modal = TRUE),
      options
    ),
    controls = controls,
    auto_height = FALSE
  )
}


#' @importFrom graphics abline axis hist par plot.new plot.window
plot_histogram <- function(data, column, bins = 30, breaks = NULL, color = "#112466") {
  x <- data[[column]]
  op <- par(mar = rep(1.5, 4)); on.exit(par(op))
  plot.new()
  plot.window(xlim = range(pretty(x)), ylim =  range(pretty(hist(x, breaks = bins, plot = FALSE)$counts)))
  abline(v = pretty(x), col = "#D8D8D8")
  abline(h = pretty(hist(x, breaks = bins, plot = FALSE)$counts), col = "#D8D8D8")
  hist(x, breaks = bins, xlim = range(pretty(x)), xaxs = "i", yaxs = "i", col = color, add = TRUE)
  axis(side = 1, at = pretty(x), pos = 0)
  axis(side = 2, at = pretty(hist(x, breaks = bins, plot = FALSE)$counts), pos = min(pretty(x)))
  abline(v = breaks, col = "#FFFFFF", lty = 1, lwd = 1.5)
  abline(v = breaks, col = "#2E2E2E", lty = 2, lwd = 1.5)
}




================================================
FILE: R/data.R
================================================
#' Customer Credit Card Information
#'
#' A subset of fake customer credit card information inspired by the `{charlatan}` package.
#'
#' @format ## `demo_edit`
#' A data frame with 20 rows and 6 columns:
#' \describe{
#'   \item{name}{Customer name}
#'   \item{job}{Customer job}
#'   \item{credit_card_provider}{Credit card provider}
#'   \item{credit_card_security_code}{Credit card security code}
#'   \item{date_obtained}{Date of obtaining the credit card}
#'   \item{contactless_card}{Contactless card}
#' }
#' @source <https://CRAN.R-project.org/package=charlatan>
"demo_edit"


================================================
FILE: R/datagrid-infos.R
================================================

#' @importFrom htmltools tagList tags css
describe_col_char <- function(x, with_summary = TRUE) {
  tags$div(
    style = css(padding = "3px 0", fontSize = "x-small"),
    tags$div(
      style = css(fontStyle = "italic"),
      phosphoricons::ph("text-aa"),
      "character"
    ),
    if (with_summary) {
      tagList(
        tags$hr(style = css(margin = "3px 0")),
        tags$div(
          i18n("Unique:"), length(unique(x))
        ),
        tags$div(
          i18n("Missing:"), sum(is.na(x))
        ),
        tags$div(
          style = css(whiteSpace = "normal", wordBreak = "break-all"),
          i18n("Most Common:"), gsub(
            pattern = "'",
            replacement = "\u07F4",
            x = names(sort(table(x), decreasing = TRUE))[1]
          )
        ),
        tags$div(
          "\u00A0"
        )
      )
    }
  )
}

fmt_p <- function(val, tot) {
  paste0(round(val / tot * 100, 1), "%")
}

describe_col_factor <- function(x, with_summary = TRUE) {
  count <- sort(table(x, useNA = "always"), decreasing = TRUE)
  total <- sum(count)
  one <- count[!is.na(names(count))][1]
  two <- count[!is.na(names(count))][2]
  missing <- count[is.na(names(count))]
  tags$div(
    style = css(padding = "3px 0", fontSize = "x-small"),
    tags$div(
      style = css(fontStyle = "italic"),
      phosphoricons::ph("list-bullets"),
      "factor"
    ),
    if (with_summary) {
      tagList(
        tags$hr(style = css(margin = "3px 0")),
        tags$div(
          names(one), ":", fmt_p(one, total)
        ),
        tags$div(
          names(two), ":", fmt_p(two, total)
        ),
        tags$div(
          "Missing", ":", fmt_p(missing, total)
        ),
        tags$div(
          "\u00A0"
        )
      )
    }
  )
}

describe_col_num <- function(x, with_summary = TRUE) {
  tags$div(
    style = css(padding = "3px 0", fontSize = "x-small"),
    tags$div(
      style = css(fontStyle = "italic"),
      phosphoricons::ph("hash"),
      "numeric"
    ),
    if (with_summary) {
      tagList(
        tags$hr(style = css(margin = "3px 0")),
        tags$div(
          i18n("Min:"), round(min(x, na.rm = TRUE), 2)
        ),
        tags$div(
          i18n("Mean:"), round(mean(x, na.rm = TRUE), 2)
        ),
        tags$div(
          i18n("Max:"), round(max(x, na.rm = TRUE), 2)
        ),
        tags$div(
          i18n("Missing:"), sum(is.na(x))
        )
      )
    }
  )
}


describe_col_date <- function(x, with_summary = TRUE) {
  tags$div(
    style = css(padding = "3px 0", fontSize = "x-small"),
    tags$div(
      style = css(fontStyle = "italic"),
      phosphoricons::ph("calendar"),
      "date"
    ),
    if (with_summary) {
      tagList(
        tags$hr(style = css(margin = "3px 0")),
        tags$div(
          i18n("Min:"), min(x, na.rm = TRUE)
        ),
        tags$div(
          i18n("Max:"), max(x, na.rm = TRUE)
        ),
        tags$div(
          i18n("Missing:"), sum(is.na(x))
        ),
        tags$div(
          "\u00A0"
        )
      )
    }
  )
}

describe_col_datetime <- function(x, with_summary = TRUE) {
  tags$div(
    style = css(padding = "3px 0", fontSize = "x-small"),
    tags$div(
      style = css(fontStyle = "italic"),
      phosphoricons::ph("clock"),
      "datetime"
    ),
    if (with_summary) {
      tagList(
        tags$hr(style = css(margin = "3px 0")),
        tags$div(
          i18n("Min:"), min(x, na.rm = TRUE)
        ),
        tags$div(
          i18n("Max:"), max(x, na.rm = TRUE)
        ),
        tags$div(
          i18n("Missing:"), sum(is.na(x))
        ),
        tags$div(
          "\u00A0"
        )
      )
    }
  )
}


describe_col_other <- function(x, with_summary = TRUE) {
  tags$div(
    style = css(padding = "3px 0", fontSize = "x-small"),
    tags$div(
      style = css(fontStyle = "italic"),
      # phosphoricons::ph("clock"),
      paste(class(x), collapse = ", ")
    ),
    if (with_summary) {
      tagList(
        tags$hr(style = css(margin = "3px 0")),
        tags$div(
          i18n("Unique:"), length(unique(x))
        ),
        tags$div(
          i18n("Missing:"), sum(is.na(x))
        ),
        tags$div(
          "\u00A0"
        ),
        tags$div(
          "\u00A0"
        )
      )
    }
  )
}

#' @importFrom htmltools doRenderTags
construct_col_summary <- function(data) {
  list(
    position = "top",
    height = 90,
    columnContent = lapply(
      X = setNames(names(data), names(data)),
      FUN = function(col) {
        values <- data[[col]]
        content <- if (inherits(values, "character")) {
          describe_col_char(values)
        } else if (inherits(values, "factor")) {
          describe_col_factor(values)
        } else if (inherits(values, c("numeric", "integer"))) {
          describe_col_num(values)
        } else if (inherits(values, c("Date"))) {
          describe_col_date(values)
        } else if (inherits(values, c("POSIXt"))) {
          describe_col_datetime(values)
        } else {
          describe_col_other(values)
        }
        list(
          template = toastui::JS(
            "function(value) {",
            sprintf(
              "return '%s';",
              gsub(replacement = "", pattern = "\n", x = doRenderTags(content))
            ),
            "}"
          )
        )
      }
    )
  )
}


================================================
FILE: R/edit-data-utils.R
================================================


#' @title Edit modal
#'
#' @description The `edit_modal` function generates a modal window with the variables to edit
#'
#' @return a modal window with the variables to edit
#'
#' @param default row on which to operate a modification or a deletion, otherwise empty list for an addition
#' @param id_validate inputId of the actionButton()
#' @param title title of the modalDialog()
#' @param data `data.frame` to use
#' @param colnames `data.frame` column names
#' @param var_edit vector of `character` which allows to choose the editable columns
#' @param var_mandatory vector of `character` which allows to choose obligatory fields to fill
#' @param modal_size `character` which allows to choose the size of the modalDialog. One of "s" for small, "m" (the default) for medium, "l" for large, or "xl" for extra large.
#' @param modal_easy_close `boolean` If TRUE, modalDialog can be dismissed by clicking outside the dialog box, or be pressing the Escape key. If FALSE (the default), modalDialog can't be dismissed in those ways; instead it must be dismissed by clicking on a modalButton(), or from a call to removeModal() on the server.
#' @param session The `session` object passed to function given to shinyServer
#'
#' @importFrom shiny showModal modalDialog actionButton
#' @importFrom phosphoricons ph
#' @importFrom htmltools tagList tags css
#'
#' @noRd
#'
edit_modal <- function(default = list(),
                       id_validate = "add_row",
                       title = i18n("Add a row"),
                       data,
                       var_edit = NULL,
                       var_mandatory = NULL,
                       var_labels = colnames(data),
                       modal_size = "m",
                       modal_easy_close = FALSE,
                       n_column = 1,
                       session = getDefaultReactiveDomain()) {
  ns <- session$ns

  if (length(var_edit) > 0) {
    data <- data[, ..var_edit]
  }

  showModal(modalDialog(
    title = tagList(
      title,
      tags$button(
        phosphoricons::ph("x", title = i18n("Close"), height = "2em"),
        class = "btn btn-link",
        style = css(border = "0 none", position = "absolute", top = "5px", right = "5px"),
        `data-bs-dismiss` = "modal",
        `data-dismiss` = "modal",
        `aria-label` = "Close"
      )
    ),
    footer = NULL,
    size = modal_size,
    easyClose = modal_easy_close,
    edit_input_form(
      default = default,
      data = data,
      var_mandatory = var_mandatory,
      var_labels = var_labels,
      n_column = n_column,
      session = session
    ),
    actionButton(
      inputId = ns(id_validate),
      label = tagList(
        ph("floppy-disk"), i18n("Save")
      ),
      class = "btn-outline-primary float-end"
    )
  ))
}


#' @title Edit input form
#'
#' @description The `edit_input_form` function allows to correctly generate the variables to be edited in the modal window according to their respective class
#'
#' @param default default row on which to operate a modification or a deletion, otherwise empty list for an addition
#' @param data `data.frame` to use
#' @param colnames `data.frame` column names
#' @param var_mandatory vector of `character` which allows to choose obligatory fields to fill
#' @param position_var_edit position of editable columns in order to retrieve their name
#' @param session The `session` object passed to function given to shinyServer
#'
#' @importFrom shiny numericInput textInput
#' @importFrom shinyWidgets virtualSelectInput prettyCheckbox airDatepickerInput
#' @importFrom htmltools tagList tags
#' @importFrom rlang is_vector is_named
#'
#' @return different shiny widgets with edited columns according to their respective class
#' @noRd
#'
edit_input_form <- function(default = list(),
                            data,
                            var_mandatory = NULL,
                            var_labels = colnames(data),
                            n_column = 1,
                            session = getDefaultReactiveDomain()) {

  ns <- session$ns

  if (is_vector(var_labels) & !is_named(var_labels)) {
    var_labels <- setNames(var_labels, unlist(var_labels))
  }

  widgets <- lapply(
    X = seq_len(ncol(data)),
    FUN = function(i) {
      variable_id <- colnames(data)[i]
      variable_label <- var_labels[which(names(var_labels) == variable_id)]
      if (length(variable_label) < 1)
        variable_label <- variable_id
      variable <- data[[i]]

      suffix <- if (isTRUE((inherits(variable, "logical")))) "" else " : "
      if (variable_id %in% var_mandatory) {
        label <- tagList(
          variable_label,
          tags$span(HTML("&#42;"), class = "asterisk", style = "color: red;"), suffix
        )
      } else {
        label <- paste0(variable_label, suffix)
      }

      if (isTRUE(inherits(variable, c("numeric", "integer")))) {
        opts <- getOption("datamods.edit.input.numeric", list())
        opts <- modifyList(
          x = opts,
          val = list(
            inputId = ns(variable_id),
            label = label,
            value = default[[variable_id]] %||% NA_real_,
            width = "100%"
          )
        )
        do.call(numericInput, opts)
      } else if (inherits(variable, "factor")) {
        opts <- getOption("datamods.edit.input.factor", list())
        opts <- modifyList(
          x = opts,
          val = list(
            inputId = ns(variable_id),
            label = label,
            choices = sort(unique(c(as.character(variable), levels(variable)))),
            selected = default[[variable_id]] %||% "",
            width = "100%",
            allowNewOption = TRUE,
            autoSelectFirstOption = FALSE,
            placeholder = i18n("Select"),
            zIndex = 999
          )
        )
        do.call(virtualSelectInput, opts)
      } else if (inherits(variable, "character")) {
        opts <- getOption("datamods.edit.input.character", list())
        opts <- modifyList(
          x = opts,
          val = list(
            inputId = ns(variable_id),
            label = label,
            value = default[[variable_id]] %||% "",
            width = "100%"
          )
        )
        do.call(textInput, opts)
      } else if (inherits(variable, "logical")) {
        opts <- getOption("datamods.edit.input.logical", list())
        opts <- modifyList(
          x = opts,
          val = list(
            inputId = ns(variable_id),
            label = label,
            value = default[[variable_id]] %||% FALSE,
            icon = icon("check"),
            status = "primary",
            width = "100%"
          )
        )
        do.call(prettyCheckbox, opts)
      } else if (inherits(variable, "Date")) {
        opts <- getOption("datamods.edit.input.Date", list())
        opts <- modifyList(
          x = opts,
          val = list(
            inputId = ns(variable_id),
            label = label,
            value = default[[variable_id]] %||% Sys.Date(),
            width = "100%"
          )
        )
        do.call(airDatepickerInput, opts)
      } else if (inherits(variable, c("POSIXct", "POSIXt"))) {
        opts <- getOption("datamods.edit.input.POSIXt", list())
        opts <- modifyList(
          x = opts,
          val = list(
            inputId = ns(variable_id),
            label = label,
            value = default[[variable_id]] %||% Sys.time(),
            timepicker = TRUE,
            width = "100%"
          )
        )
        do.call(airDatepickerInput, opts)
      } else {
        return(NULL)
      }
    }
  )
  fluidRow(
    lapply(
      X = split(
        x = seq_along(widgets),
        f = rep(seq_len(n_column), each = ceiling(length(widgets)/n_column))[seq_along(widgets)]
      ),
      FUN = function(i) {
        column(
          width = 12 / n_column,
          widgets[i]
        )
      }
    )
  )
}


#' @title Table display
#'
#' @description The `table_display` function allows you to display the table in reactable format with columns to edit and delete rows
#'
#' @param data `data.frame` to use
#' @param colnames `data.frame` column names
#' @param reactable_options `list` allowing you to add reactable options
#'
#' @return the `data.frame` in reactable format
#' @noRd
#'
#' @importFrom reactable reactable colDef
#' @importFrom data.table copy setnames
table_display <- function(data, colnames = NULL, reactable_options = NULL) {

  data <- copy(data)
  if (!is.null(colnames)) {
    setnames(data, old = seq_along(colnames), new = colnames)
  }

  cols <- reactable_options$columns %||% list()
  if (all(is.na(data$.datamods_edit_update))) {
    cols$.datamods_edit_update <- colDef(show = FALSE)
  } else {
    cols$.datamods_edit_update <- col_def_update()
  }

  if (all(is.na(data$.datamods_edit_delete))) {
    cols$.datamods_edit_delete <- colDef(show = FALSE)
  } else {
    cols$.datamods_edit_delete <- col_def_delete()
  }

  cols$.datamods_id <- colDef(show = FALSE)

  if (is.null(reactable_options))
    reactable_options <- list()
  reactable_options <- reactable_options
  reactable_options$data <- data
  reactable_options$columns <- cols

  rlang::exec(reactable::reactable, !!!reactable_options)
}

#' @importFrom reactable updateReactable getReactableState
#' @importFrom data.table copy setnames
update_table <- function(data, colnames) {
  data <- copy(data)
  setnames(data, old = seq_along(colnames), new = colnames)
  page <- getReactableState(outputId = "table", name = "page")
  updateReactable("table", data = data, page = page)
  return(data)
}

format_edit_data <- function(data, colnames, internal_colnames = NULL) {
  data <- as.data.table(data)
  vars_datamods_edit <- intersect(c(".datamods_id", ".datamods_edit_update", ".datamods_edit_delete"), names(data))
  data <- data[, -..vars_datamods_edit]
  if (is.null(internal_colnames))
    internal_colnames <- seq_along(colnames)
  setnames(data, old = internal_colnames, new = colnames, skip_absent = TRUE)
  data[]
}

rename_edit <- function(data, var_labels) {
  for(i in seq_along(names(var_labels))) {
    names(data)[names(data) == names(var_labels)[i]] <- var_labels[[i]]
  }
  data
}


#' @importFrom rlang set_names is_null is_list is_named
get_variables_labels <- function(labels, column_names, internal_names) {
  if (is_null(labels)) {
    labels <- column_names
  } else {
    if (!is_list(labels)) {
      stopifnot(
        "If `var_labels` is an unnamed vector, it must have same length as `colnames(data)`" = length(labels) == length(column_names)
      )
      labels <- set_names(as.list(labels), column_names)
    }
    stopifnot(
      "`var_labels` must be a named list" = is_named(labels)
    )
    names(labels) <- internal_names[match(names(labels), column_names)]
    labels <- modifyList(
      x = set_names(as.list(column_names), internal_names),
      val = labels
    )
  }
  return(labels)
}

get_variables_default <- function(default, column_names, internal_names) {
  default <- default[column_names]
  idx <- match(names(default), column_names, nomatch = 0L)
  names(default)[idx > 0] <- internal_names[idx]
  default
}


#' @title The update column definition
#'
#' @return A column definition object that can be used to customize the update column in reactable().
#' @noRd
#'
#' @importFrom reactable colDef
#'
col_def_update <- function() {
  colDef(
    name = i18n("Update"),
    width = 82,
    sortable = FALSE,
    html = TRUE,
    filterable = FALSE
  )
}

#' The update button
#'
#' @param inputId ID
#'
#' @return the update button
#' @noRd
#'
#' @importFrom htmltools tags css doRenderTags
#' @importFrom phosphoricons ph
#'
btn_update <- function(inputId) {
  function(value) {
    htmltools::doRenderTags(
      tags$button(
        class = "btn btn-outline-primary rounded-circle",
        style = htmltools::css(
          height = "40px",
          width = "40px",
          padding = 0
        ),
        onClick = sprintf(
          "Shiny.setInputValue(\'%s\', %s,  {priority: \'event\'})",
          inputId,
          value
        ),
        title = i18n("Click to edit"),
        ph("pencil-simple-line", height = "1.2em")
      )
    )

  }
}


#' @title The delete column definition
#'
#' @return A column definition object that can be used to customize the delete column in reactable().
#' @noRd
#' @importFrom reactable colDef
#'
col_def_delete <- function() {
  reactable::colDef(
    name = i18n("Delete"),
    width = 96,
    sortable = FALSE,
    html = TRUE,
    filterable = FALSE
  )
}

#' The delete button
#'
#' @param inputId ID
#'
#' @return the delete button
#' @noRd
#'
#' @importFrom htmltools tags css doRenderTags
#' @importFrom phosphoricons ph
#'
btn_delete <- function(inputId) {
  function(value) {
    htmltools::doRenderTags(
      tags$button(
        class = "btn btn-outline-danger rounded-circle",
        style = htmltools::css(
          height = "40px",
          width = "40px",
          padding = 0
        ),
        onClick = sprintf(
          "Shiny.setInputValue(\'%s\', %s,  {priority: \'event\'})",
          inputId,
          value
        ),
        title = i18n("Click to delete"),
        ph("x", height = "1.2em")
      )
    )
  }
}


#' Confirmation window
#'
#' @param inputId ID
#' @param ... optional additional elements to add in the ui
#' @param title title of the confirmation window
#'
#' @return a confirmation window
#' @noRd
#'
#' @importFrom shiny modalDialog actionButton
#' @importFrom htmltools tagList tags css
#' @importFrom phosphoricons ph
#'
confirmation_window <- function(inputId, ..., title = NULL) {
  modalDialog(
    title = tagList(
      tags$button(
        phosphoricons::ph("x", title = i18n("Close"), height = "2em"),
        class = "btn btn-link",
        style = css(border = "0 none", position = "absolute", top = "5px", right = "5px"),
        `data-bs-dismiss` = "modal",
        `aria-label` = "Fermer"
      ),
      title
    ),
    ...,
    size = "m",
    footer = tagList(
      tags$button(
        i18n("Cancel"),
        class = "btn btn-outline-secondary",
        `data-bs-dismiss` = "modal"
      ),
      actionButton(
        inputId = paste0(inputId, "_no"),
        label = i18n("No"),
        class = "btn-outline-danger",
        `data-bs-dismiss` = "modal"
      ),
      actionButton(
        inputId = paste0(inputId, "_yes"),
        label = i18n("Yes"),
        class = "btn-outline-primary"
      )
    )
  )
}


#' @importFrom shinybusy notify_failure notify_success notify_info notify_warning
notification_failure <- function(title, text, use_notify = TRUE) {
  if (isTRUE(use_notify)) {
    shinybusy::notify_failure(
      title = title,
      text = text,
      position = "center-top",
      clickToClose = TRUE
    )
  }
}
notification_warning <- function(title, text, use_notify = TRUE) {
  if (isTRUE(use_notify)) {
    shinybusy::notify_warning(
      title = title,
      text = text,
      position = "center-top",
      clickToClose = TRUE
    )
  }
}
notification_success <- function(title, text, use_notify = TRUE) {
  if (isTRUE(use_notify)) {
    shinybusy::notify_success(
      title = title,
      text = text,
      position = "center-top",
      clickToClose = TRUE
    )
  }
}
notification_info <- function(title, text, use_notify = TRUE) {
  if (isTRUE(use_notify)) {
    shinybusy::notify_info(
      title = title,
      text = text,
      position = "center-top",
      clickToClose = TRUE
    )
  }
}



================================================
FILE: R/edit-data.R
================================================


#' @title Shiny module to interactively edit a `data.frame`
#'
#' @description The module generates different options to edit a `data.frame`: adding, deleting and modifying rows, exporting data (csv and excel), choosing editable columns, choosing mandatory columns.
#' This module returns the edited table with the user modifications.
#'
#' @param id Module ID
#'
#' @importFrom shiny uiOutput
#' @importFrom htmltools tagList tags
#' @importFrom reactable reactableOutput
#' @importFrom utils getFromNamespace
#'
#' @export
#'
#' @name edit-data
#'
#' @example examples/edit_data.R
edit_data_ui <- function(id) {
  ns <- NS(id)

  notify_dep <- getFromNamespace("html_dependency_notify", "shinybusy")

  tagList(

    notify_dep(),

    # Download data in Excel format --
    uiOutput(outputId = ns("download_excel"), style = "display: inline;"),

    # Download data in csv format --
    uiOutput(outputId = ns("download_csv"), style = "display: inline;"),

    # Add a row --
    uiOutput(outputId = ns("add_button"), style = "display: inline;"),

    tags$div(class = "clearfix mb-2"),

    # Table --
    reactableOutput(outputId = ns("table"))
  )
}

#' @title Shiny module to interactively edit a `data.frame`
#'
#' @param id Module ID
#' @param data_r data_r `reactive` function containing a `data.frame` to use in the module.
#' @param add `boolean`, if `TRUE`, allows you to add a row in the table via a button at the top right.
#' @param update `boolean`, if `TRUE`, allows you to modify a row of the table via a button located in the table on the row you want to edit.
#' @param delete `boolean`, if `TRUE`, allows a row to be deleted from the table via a button in the table.
#' @param download_csv if `TRUE`, allows to export the table in csv format via a download button.
#' @param download_excel if `TRUE`, allows to export the table in excel format via a download button.
#' @param file_name_export `character` that allows you to choose the export name of the downloaded file.
#' @param var_edit vector of `character` which allows to choose the names of the editable columns.
#' @param var_mandatory vector of `character` which allows to choose obligatory fields to fill.
#' @param var_labels named list, where names are colnames and values are labels to be used in edit modal.
#' @param add_default_values Default values to use for input control when adding new data, e.g. `list(my_var_text = "Default text to display")`.
#' @param n_column Number of column in the edit modal window, must be a number that divide 12 since it use Bootstrap grid system with [shiny::column()].
#' @param return_class Class of returned data: `data.frame`, `data.table`, `tbl_df` (tibble) or `raw`.
#' @param reactable_options Options passed to [reactable::reactable()].
#' @param modal_size `character` which allows to choose the size of the modalDialog. One of "s" for small, "m" (the default) for medium, "l" for large, or "xl" for extra large.
#' @param modal_easy_close `boolean` If TRUE, modalDialog can be dismissed by clicking outside the dialog box, or be pressing the Escape key. If FALSE (the default), modalDialog can't be dismissed in those ways; instead it must be dismissed by clicking on a modalButton(), or from a call to removeModal() on the server.
#' @param callback_add,callback_update,callback_delete Functions to be executed just before an action (add, update or delete) is performed on the data.
#'  Functions used must be like `function(data, row) {...}` where :
#'    * `data` will be the data in the table at the moment the function is called
#'    * `row` will contain either a new row of data (add), an updated row (update) or the row that will be deleted (delete).
#'
#'  If the return value of a callback function is not truthy (see [shiny::isTruthy()]) then the action is cancelled.
#' @param only_callback Only use callbacks, don't alter data within the module.
#' @param use_notify Display information or not to user through [shinybusy::notify()].
#'
#'
#'
#' @return the edited `data.frame` in reactable format with the user modifications
#'
#' @name edit-data
#'
#' @importFrom shiny moduleServer eventReactive reactiveValues is.reactive reactive renderUI actionButton observeEvent isTruthy showModal removeModal downloadButton downloadHandler
#' @importFrom data.table copy as.data.table := copy setnames as.data.table setattr
#' @importFrom reactable renderReactable reactableOutput getReactableState
#' @importFrom phosphoricons ph
#' @importFrom writexl write_xlsx
#' @importFrom utils write.csv
#' @importFrom htmltools tagList
#' @importFrom rlang is_function is_list
#'
#' @export
#'
edit_data_server <- function(id,
                             data_r = reactive(NULL),
                             add = TRUE,
                             update = TRUE,
                             delete = TRUE,
                             download_csv = TRUE,
                             download_excel = TRUE,
                             file_name_export = "data",
                             var_edit = NULL,
                             var_mandatory = NULL,
                             var_labels = NULL,
                             add_default_values = list(),
                             n_column = 1,
                             return_class = c("data.frame", "data.table", "tbl_df", "raw"),
                             reactable_options = NULL,
                             modal_size = c("m", "s", "l", "xl"),
                             modal_easy_close = TRUE,
                             callback_add = NULL,
                             callback_update = NULL,
                             callback_delete = NULL,
                             only_callback = FALSE,
                             use_notify = TRUE) {
  return_class <- match.arg(return_class)
  modal_size <- match.arg(modal_size)
  callback_default <- function(...) return(TRUE)
  if (!is_function(callback_add))
    callback_add <- callback_default
  if (!is_function(callback_update))
    callback_update <- callback_default
  if (!is_function(callback_delete))
    callback_delete <- callback_default
  moduleServer(
    id,
    function(input, output, session) {

      ns <- session$ns

      data_rv <- reactiveValues(data = NULL, colnames = NULL, mandatory = NULL, edit = NULL)

      # Data data_r() with added columns ".datamods_edit_update" et ".datamods_edit_delete" ---
      data_init_r <- eventReactive(data_r(), {
        req(data_r())
        data <- data_r()
        if (is.reactive(var_mandatory))
          var_mandatory <- var_mandatory()
        if (is.reactive(var_labels))
          var_labels <- var_labels()
        if (is.null(var_labels))
          var_labels <- setNames(as.list(names(data)), names(data))
        if (is.reactive(var_edit))
          var_edit <- var_edit()
        if (is.null(var_edit))
          var_edit <- names(data)
        data <- as.data.table(data)
        data_rv$colnames <- copy(colnames(data))
        if (ncol(data) > 0) {
          setnames(data, paste0("col_", seq_along(data)))
          data_rv$internal_colnames <- copy(colnames(data))
        }
        data_rv$mandatory <- data_rv$internal_colnames[data_rv$colnames %in% var_mandatory]
        data_rv$edit <- data_rv$internal_colnames[data_rv$colnames %in% var_edit]
        data_rv$labels <- get_variables_labels(var_labels, data_rv$colnames, data_rv$internal_colnames)

        data[, .datamods_id := seq_len(.N)]

        if (is.reactive(update)) {
          update <- update()
        }

        if (isTRUE(update)) {
          data[, .datamods_edit_update := as.character(seq_len(.N))]
          data[, .datamods_edit_update := list(
            lapply(.datamods_edit_update, btn_update(ns("update")))
          )]
        } else {
          data[, .datamods_edit_update := NA]
        }

        if (is.reactive(delete)) {
          delete <- delete()
        }

        if (isTRUE(delete)) {
        data[, .datamods_edit_delete := as.character(seq_len(.N))]
        data[, .datamods_edit_delete := list(
          lapply(.datamods_edit_delete, btn_delete(ns("delete")))
        )]
        } else {
          data[, .datamods_edit_delete := NA]
        }

        data_rv$data <- data
        return(data)
      })


      # Table ---
      output$table <- renderReactable({
        data <- req(data_init_r())
        if (is.reactive(reactable_options))
          reactable_options <- reactable_options()
        table_display(
          data = data,
          colnames = data_rv$colnames,
          reactable_options = reactable_options
        )
      })

      # Retrieve selected row(s)
      selected_r <- reactive({
        getReactableState("table", "selected")
      })


      # Add a row ---
      output$add_button <- renderUI({
        if (is.reactive(add)) {
          add <- add()
        }
        if (isTRUE(add)) {
          actionButton(
            inputId = ns("add"),
            label = tagList(ph("plus"), i18n("Add a row")),
            class = "btn-outline-primary float-end"
          )
        }
      })

      observeEvent(input$add, {
        req(data_r())
        edit_modal(
          default = get_variables_default(
            add_default_values,
            data_rv$colnames,
            data_rv$internal_colnames
          ),
          id_validate = "add_row",
          data = data_rv$data,
          var_edit = data_rv$edit,
          var_mandatory = data_rv$mandatory,
          var_labels = data_rv$labels,
          modal_size = modal_size,
          modal_easy_close = modal_easy_close,
          n_column = n_column
        )
      })

      observeEvent(input$add_row, {
        req(data_r())
        data <- copy(data_rv$data)
        data <- as.data.table(data)

        for (var in data_rv$mandatory) {
          if (!isTruthy(input[[var]])) {
            notification_warning(
              title = i18n("Required field"),
              text = i18n("Please fill in the required fields"),
              use_notify = use_notify
            )
            return(NULL)
          }
        }

        results_add <- try({
          results_inputs <- lapply(
            X = setNames(data_rv$edit, data_rv$edit),
            FUN = function(x) {
              input[[x]] %||% NA
            }
          )
          id <- max(data$.datamods_id) + 1
          results_inputs[[".datamods_id"]] <- id
          results_inputs[[".datamods_edit_update"]] <- if (update) list(btn_update(ns("update"))(id)) else NA
          results_inputs[[".datamods_edit_delete"]] <- if (delete) list(btn_delete(ns("delete"))(id)) else NA

          new <- as.data.table(results_inputs)

          res_callback <- callback_add(
            format_edit_data(data, data_rv$colnames),
            format_edit_data(new, data_rv$colnames, data_rv$internal_colnames)
          )

          if (isTruthy(res_callback) & !isTRUE(only_callback)) {
            data <- rbind(data, new[, .SD, .SDcols = !anyNA], use.names = TRUE, fill = TRUE)
            data_rv$data <- data
            removeModal()
            update_table(data, data_rv$colnames)
          } else {
            NULL
          }
        })

        if (is.null(results_add)) {
          notification_warning(
            title = i18n("Warning"),
            text = i18n("The row wasn't added to the data"),
            use_notify = use_notify
          )
        } else if (inherits(results_add, "try-error")) {
          notification_failure(
            title = i18n("Error"),
            text = i18n("Unable to add the row, contact the platform administrator"),
            use_notify = use_notify
          )
        } else {
          notification_success(
            title = i18n("Registered"),
            text = i18n("Row has been saved"),
            use_notify = use_notify
          )
        }
      })


      # Update a row ---
      observeEvent(input$update, {
        data <- copy(data_rv$data)
        data <- as.data.table(data)
        row <- data[.datamods_id == input$update]
        edit_modal(
          default = row,
          title = i18n("Update row"),
          id_validate = "update_row",
          data = data,
          var_edit = data_rv$edit,
          var_mandatory = data_rv$mandatory,
          var_labels = data_rv$labels,
          modal_size = modal_size,
          modal_easy_close = modal_easy_close,
          n_column = n_column
        )
      })

      observeEvent(input$update_row, {
        req(data_r())
        data <- copy(data_rv$data)
        data <- as.data.table(data)

        for (var in data_rv$mandatory) {
          if (!isTruthy(input[[var]])) {
            notification_failure(
              title = i18n("Required field"),
              text = i18n("Please fill in the required fields"),
              use_notify = use_notify
            )
            return(NULL)
          }
        }

        results_update <- try({
          id <- input$update

          data_updated <- copy(data)
          data_updated[.datamods_id == id, (data_rv$edit) := lapply(data_rv$edit, function(x) {
            input[[x]] %||% NA
          })]

          res_callback <- callback_update(
            format_edit_data(data, data_rv$colnames),
            format_edit_data(
              data_updated[.datamods_id == id],
              data_rv$colnames,
              data_rv$internal_colnames
            )
          )
          if (isTruthy(res_callback) & !isTRUE(only_callback)) {
            data_updated <- data_updated[order(.datamods_id)]
            data_rv$data <- copy(data_updated)
            removeModal()
            update_table(data_updated, data_rv$colnames)
          } else {
            NULL
          }
        })
        if (is.null(results_update)) {
          notification_warning(
            title = i18n("Warning"),
            text = i18n("Data wasn't updated"),
            use_notify = use_notify
          )
        } else if (inherits(results_update, "try-error")) {
          notification_failure(
            title = i18n("Error"),
            text = i18n("Unable to modify the item, contact the platform administrator"),
            use_notify = use_notify
          )
        } else {
          notification_success(
            title = i18n("Registered"),
            text = i18n("Item has been modified"),
            use_notify = use_notify
          )
        }
      })


      # Delete a row ---
      observeEvent(input$delete, {
        req(data_r())
        data <- copy(data_rv$data)
        data <- as.data.table(data)
        row <- data[.datamods_id == input$delete]
        removeModal()
        showModal(confirmation_window(
          inputId = ns("confirmation_delete_row"),
          title = i18n("Delete"),
          i18n("Do you want to delete the selected row ?")
        ))
      })
      observeEvent(input$confirmation_delete_row_yes, {
        req(data_r())
        data <- copy(data_rv$data)
        data <- as.data.table(data)

        results_delete <- try({

          res_callback <- callback_delete(
            format_edit_data(data, data_rv$colnames),
            format_edit_data(
              data[.datamods_id == input$delete],
              data_rv$colnames,
              data_rv$internal_colnames
            )
          )

          if (isTruthy(res_callback) & !isTRUE(only_callback)) {
            data <- data[.datamods_id != input$delete]
            data <- data[order(.datamods_id)]
            data_rv$data <- data
            removeModal()
            update_table(data, data_rv$colnames)
          } else {
            NULL
          }
        })
        if (is.null(results_delete)) {
          notification_warning(
            title = i18n("Warning"),
            text = i18n("Data wasn't deleted"),
            use_notify = use_notify
          )
        } else if (inherits(results_delete, "try-error")) {
          notification_failure(
            title = i18n("Error"),
            text = i18n("Unable to delete the row, contact platform administrator"),
            use_notify = use_notify
          )
        } else {
          notification_success(
            title = i18n("Registered"),
            text = i18n("The row has been deleted"),
            use_notify = use_notify
          )
        }
      })
      observeEvent(input$confirmation_delete_row_no, {
        notification_info(
          title = i18n("Information"),
          text = i18n("Row was not deleted"),
          use_notify = use_notify
        )
        removeModal()
      })


      # Download data in Excel format ---
      output$download_excel <- renderUI({
        if (is.reactive(download_excel)) {
          download_excel <- download_excel()
        }
        if (isTRUE(download_excel)) {
          downloadButton(
            outputId = ns("export_excel"),
            label = tagList(ph("download"), "Excel"),
            icon = NULL,
            class = "btn-datamods-export"
          )
        }
      })

      output$export_excel <- downloadHandler(
        filename = function() {
          file_name <- file_name_export
          paste0(file_name, ".xlsx")
        },
        content = function(file) {
          data <- format_edit_data(data_rv$data, data_rv$colnames)
          write_xlsx(
            x = list(data = data),
            path = file
          )
        }
      )

      # Download data in csv format ---
      output$download_csv <- renderUI({
        if (is.reactive(download_csv)) {
          download_csv <- download_csv()
        }
        if (isTRUE(download_csv)) {
          downloadButton(
            outputId = ns("export_csv"),
            label = tagList(ph("download"), "CSV"),
            icon = NULL,
            class = "btn-datamods-export"
          )
        }
      })
      output$export_csv <- downloadHandler(
        filename = function() {
          file_name <- file_name_export
          paste0(file_name, ".csv")
        },
        content = function(file) {
          data <- format_edit_data(data_rv$data, data_rv$colnames)
          write.csv(
            x = data,
            file = file
          )
        }
      )


      return(
        reactive({
          req(data_rv$data)
          data <- format_edit_data(data_rv$data, data_rv$colnames)
          setattr(data, "selected", selected_r())
          as_out(data, return_class)
        })
      )

    }
  )
}



================================================
FILE: R/filter-data.R
================================================

#' @title Shiny module to interactively filter a `data.frame`
#'
#' @description Module generate inputs to filter `data.frame` according column's type.
#'  Code to reproduce the filter is returned as an expression with filtered data.
#'
#' @param id Module id. See [shiny::moduleServer()].
#' @param show_nrow Show number of filtered rows and total.
#' @param max_height Maximum height for filters panel, useful
#'  if you have many variables to filter and limited space.
#'
#' @return
#' * UI: HTML tags that can be included in shiny's UI
#' * Server: a `list` with four slots:
#'   + **filtered**: a `reactive` function returning the data filtered.
#'   + **code**: a `reactive` function returning the dplyr pipeline to filter data.
#'   + **expr**: a `reactive` function returning an expression to filter data.
#'   + **values**: a `reactive` function returning a named list of variables and filter values.
#'
#' @export
#'
#' @name filter-data
#'
#' @importFrom htmltools tagList singleton tags validateCssUnit
#' @importFrom shiny NS uiOutput
#'
#' @example examples/filter_data.R
filter_data_ui <- function(id,
                           show_nrow = TRUE,
                           max_height = NULL) {
  ns <- NS(id)
  max_height <- if (!is.null(max_height)) {
    paste0("overflow-y: auto; overflow-x: hidden; max-height:", validateCssUnit(max_height), ";")
  }
  tagList(
    singleton(
      tags$style(
        ".selectize-big .selectize-input {height: 72px; overflow-y: scroll;}"
      )
    ),
    if (isTRUE(show_nrow)) {
      tags$span(i18n("Number of rows:"), uiOutput(outputId = ns("nrow"), inline = TRUE))
    },
    uiOutput(outputId = ns("placeholder_filters"), style = max_height)
  )
}

#' @param data [shiny::reactive()] function returning a
#'  \code{data.frame} to filter.
#' @param vars [shiny::reactive()] function returning a
#'  `character` vector of variables for which to add a filter.
#'  If a named `list`, names are used as labels.
#' @param name [shiny::reactive()] function returning a
#'  `character` string representing `data` name, only used for code generated.
#' @param defaults [shiny::reactive()] function returning a
#'  named `list` of variable:value pairs which will be used to set the filters.
#' @param drop_ids Drop columns containing more than 90% of unique values, or than 50 distinct values.
#' Use `FALSE` to disable or use `list(p = 0.9, n = 50)` to customize threshold values.
#' @param widget_char Widget to use for `character` variables: [shinyWidgets::pickerInput()]
#'  or [shiny::selectInput()] (default).
#' @param widget_num Widget to use for `numeric` variables: [shinyWidgets::numericRangeInput()]
#'  or [shiny::sliderInput()] (default).
#' @param widget_date Widget to use for `date/time` variables: [shiny::dateRangeInput()]
#'  or [shiny::sliderInput()] (default).
#' @param label_na Label for missing value widget.
#' @param value_na Default value for all NA's filters.
#'
#'
#' @rdname filter-data
#' @export
#'
#' @importFrom rlang eval_tidy %||%
#' @importFrom shiny observeEvent reactiveValues removeUI
#'  insertUI reactive req isolate reactive renderUI tags outputOptions
filter_data_server <- function(id,
                               data = reactive(NULL),
                               vars = reactive(NULL),
                               name = reactive("data"),
                               defaults = reactive(NULL),
                               drop_ids = getOption("datamods.filter.drop_ids", default = TRUE),
                               widget_char = c("virtualSelect", "select", "picker"),
                               widget_num = c("slider", "range"),
                               widget_date = c("slider", "range"),
                               label_na = "NA",
                               value_na = TRUE) {
  widget_char <- match.arg(widget_char)
  widget_num <- match.arg(widget_num)
  widget_date <- match.arg(widget_date)
  moduleServer(
    id,
    function(input, output, session) {
      ns <- session$ns
      jns <- function(x) paste0("#", ns(x))

      output$nrow <- renderUI({
        tags$b(nrow(data_filtered()) , "/", nrow(data()))
      })

      rv_filters <- reactiveValues(mapping = NULL, mapping_na = NULL)
      rv_code <- reactiveValues(expr = NULL, dplyr = NULL)

      output$placeholder_filters <- renderUI({
        data <- data()
        req(data)
        vars <- vars()
        defaults <- defaults()
        filters <- create_filters(
          data = data,
          vars = vars,
          defaults = defaults,
          drop_ids = drop_ids,
          widget_char = widget_char,
          widget_num = widget_num,
          widget_date = widget_date,
          label_na = label_na,
          value_na = value_na
        )
        rv_filters$mapping <- filters$filters_id
        rv_filters$mapping_na <- filters$filters_na_id
        return(filters$ui)
      })

      filter_values <- reactive({
        data <- data()
        req(data)
        req(all(names(rv_filters$mapping) %in% names(data)))
        filter_inputs <- lapply(
          X = rv_filters$mapping,
          FUN = function(x) {
            input[[x]]
          }
        )
        filter_inputs
      })

      data_filtered <- reactive({
        data <- data()
        req(data)
        req(all(names(rv_filters$mapping) %in% names(data)))
        filter_inputs <- lapply(
          X = rv_filters$mapping,
          FUN = function(x) {
            # req(input[[x]])
            input[[x]]
          }
        )
        filter_nas <- lapply(
          X = rv_filters$mapping_na,
          FUN = function(x) {
            input[[x]]
          }
        )
        filters <- make_expr_filter(
          filters = filter_inputs,
          filters_na = filter_nas,
          data = data,
          data_name = isolate(name()) %||% "data"
        )
        rv_code$expr <- filters$expr
        rv_code$dplyr <- filters$expr_dplyr
        if (length(rv_code$expr) > 0) {
          result <- eval_tidy(expr = rv_code$expr, data = data)
          data[result, , drop = FALSE]
        } else {
          data
        }
      })
      outputOptions(x = output, name = "placeholder_filters", suspendWhenHidden = FALSE)

      return(list(
        filtered = data_filtered,
        values = filter_values,
        code = reactive(rv_code$dplyr),
        expr = reactive(rv_code$expr)
      ))
    }
  )
}



# Utils -------------------------------------------------------------------




#' @importFrom htmltools HTML tagList tags
#' @importFrom shiny selectizeInput sliderInput dateRangeInput
#' @importFrom stats setNames
#' @importFrom shinyWidgets pickerInput pickerOptions numericRangeInput virtualSelectInput
#' @importFrom rlang is_list
create_filters <- function(data,
                           vars = NULL,
                           defaults = NULL,
                           drop_ids = TRUE,
                           widget_char = c("virtualSelect", "select", "picker"),
                           widget_num = c("slider", "range"),
                           widget_date = c("slider", "range"),
                           label_na = "NA",
                           value_na = TRUE,
                           width = "100%",
                           session = getDefaultReactiveDomain()) {
  data <- as.data.frame(data)
  if (ncol(data) < 1)
    return(NULL)
  widget_char <- match.arg(widget_char)
  widget_num <- match.arg(widget_num)
  widget_date <- match.arg(widget_date)
  ns <- session$ns
  data <- drop_na(data)
  if (isTRUE(drop_ids)) {
    data <- drop_id(data)
  }
  if (is_list(drop_ids)) {
    data <- drop_id(data, n = drop_ids$n, p = drop_ids$p)
  }
  data <- dropListColumns(data)
  if (is.null(vars)) {
    vars <- names(data)
    labels <- vars
  } else {
    if (rlang::is_named(vars)) {
      labels <- names(vars)
      vars <- unname(unlist(vars))
    } else {
      labels <- vars
    }
    vars_display <- intersect(vars, names(data))
    labels <- labels[vars %in% vars_display]
    vars <- vars_display
  }
  # filters_id <- paste0("filter_", sample.int(1e9, length(vars)))
  filters_id <- paste0("filter_", makeId(vars))
  filters_id <- setNames(as.list(filters_id), vars)
  filters_na_id <- setNames(as.list(paste0("na_", filters_id)), vars)
  ui <- lapply(
    X = vars,
    FUN = function(variable) {
      var <- data[[variable]]
      any_na <- anyNA(var)
      var <- var[!is.na(var)]
      id <- filters_id[[variable]]
      label <- labels[variable == vars]

      tag_label <- tags$span(
        tags$label(
          label,
          class = "control-label",
          `for` = id
        ),
        HTML("&nbsp;&nbsp;"),
        if (any_na) na_filter(id = ns(paste0("na_", id)), label = label_na, value = value_na)
      )

      if (inherits(x = var, what = c("numeric", "integer"))) {
        params <- find_range_step(var)
        if(!is.null(defaults) && label %in% names(defaults)){
          params$range = defaults[[label]]
        }
        if (identical(widget_num, "slider")) {
          tags$div(
            style = "position: relative;",
            tag_label,
            set_slider_attr(sliderInput(
              inputId = ns(id),
              min = params$min,
              max = params$max,
              value = params$range,
              step = params$step,
              label = NULL,
              width = width
            ))
          )
        } else {
          tags$div(
            style = "position: relative;",
            tag_label,
            numericRangeInput(
              inputId = ns(id),
              value = params$range,
              label = NULL,
              width = width
            )
          )
        }
      } else if (inherits(x = var, what = c("Date", "POSIXct"))) {
        # browser()
        var <- pretty(var)
        range_var <- range(var)
        if(!is.null(defaults) && label %in% names(defaults)) {
          range_var <- defaults[[label]]
        }
        if (identical(widget_date, "slider")) {
          tags$div(
            style = "position: relative;",
            tag_label,
            set_slider_attr(sliderInput(
              inputId = ns(id),
              min = range_var[1],
              max = range_var[2],
              value = range_var,
              label = NULL,
              width = width,
              timezone = if (inherits(var, "POSIXct")) format(var[1], format = "%z")
            ))
          )
        } else {
          range_var <- format(range_var, format = "%Y-%m-%d")
          tags$div(
            style = "position: relative;",
            tag_label,
            dateRangeInput(
              inputId = ns(id),
              min = range_var[1],
              max = range_var[2],
              start = range_var[1],
              end = range_var[2],
              label = NULL,
              width = width
            )
          )
        }
      } else {
        choices <- unique(as.character(sort(var)))
        if ("" %in% choices)
          choices <- append(choices, .empty_field_char)
        choices <- tryCatch(choices[trimws(choices) != ""], error = function(e) {
          Encoding(choices[!validEnc(choices)]) <- "unknown"
          choices
        })
        selected <- choices
        if(!is.null(defaults) && label %in% names(defaults)){
          selected = defaults[[label]]
        }
        if (identical(widget_char, "picker")) {
          tags$div(
            style = "position: relative;",
            tag_label,
            pickerInput(
              inputId = ns(id),
              choices = choices,
              selected = selected,
              label = NULL,
              multiple = TRUE,
              width = width,
              options = pickerOptions(
                container = "body",
                actionsBox = TRUE,
                selectedTextFormat = "count",
                liveSearch = TRUE
              )
            )
          )
        } else if (identical(widget_char, "virtualSelect")) {
          tags$div(
            style = "position: relative;",
            tag_label,
            virtualSelectInput(
              inputId = ns(id),
              choices = choices,
              selected = selected,
              label = NULL,
              multiple = TRUE,
              width = width,
              showValueAsTags = TRUE,
              zIndex = 9999,
              dropboxWrapper = paste0("#", ns("placeholder_filters"), " .datamods-filters-container"),
              html = TRUE
            )
          )
        } else {
          tags$div(
            style = "position: relative;",
            class = if (length(choices) > 15) "selectize-big",
            tag_label,
            selectizeInput(
              inputId = ns(id),
              choices = choices,
              selected = selected,
              label = NULL,
              multiple = TRUE,
              width = width,
              options = list(plugins = list("remove_button"))
            )
          )
        }
      }
    }
  )
  list(
    ui = tags$div(
      class = "datamods-filters-container",
      ui
    ),
    filters_id = filters_id,
    filters_na_id = filters_na_id
  )
}

tagSetAttributes <- function(tag, ...) {
  tag$attribs[names(list(...))] <- NULL
  tag$attribs <- c(tag$attribs, list(...))
  tag
}

set_slider_attr <- function(slider) {
  slider$children[[2]] <- tagSetAttributes(
    tag = slider$children[[2]],
    `data-force-edges` = "true",
    `data-grid-num` = "4"
  )
  slider
}

#' @importFrom htmltools tags
#' @importFrom shinyWidgets prettySwitch
na_filter <- function(id, label = "NA", value = TRUE) {
  tags$span(
    style = "position: absolute; right: 0px; margin-right: -20px;",
    prettySwitch(
      inputId = id,
      label = label,
      value = value,
      slim = TRUE,
      status = "primary",
      inline = TRUE
    )
  )
}


#' @importFrom rlang expr sym
make_expr_filter <- function(filters, filters_na, data, data_name) {
  expressions <- lapply(
    X = names(filters),
    FUN = function(var) {
      values <- filters[[var]]
      nas <- filters_na[[var]]
      data_values <- data[[var]]
      if (!is.null(values) & !match_class(values, data_values))
        return(NULL)
      values_expr <- NULL
      if (inherits(x = values, what = c("numeric", "integer"))) {
        data_range <- find_range_step(data_values)$range
        if (!isTRUE(all.equal(values, data_range))) {
          if (isTRUE(nas)) {
            if (anyNA(data_values)) {
              values_expr <- expr(!!sym(var) >= !!values[1] & !!sym(var) <= !!values[2] | is.na(!!sym(var)))
            } else {
              values_expr <- expr(!!sym(var) >= !!values[1] & !!sym(var) <= !!values[2])
            }
          } else {
            if (anyNA(data_values)) {
              values_expr <- expr(!!sym(var) >= !!values[1] & !!sym(var) <= !!values[2] & !is.na(!!sym(var)))
            } else {
              values_expr <- expr(!!sym(var) >= !!values[1] & !!sym(var) <= !!values[2])
            }
          }
        }
      } else if (inherits(x = values, what = c("Date", "POSIXct"))) {
        date_fmt <- if (inherits(values, "Date")) {
          "%Y-%m-%d"
        } else {
          "%Y-%m-%d %H:%M:%S"
        }
        data_values <- pretty(data_values)
        data_range <- range(data_values, na.rm = TRUE)
        data_range <- format(data_range, format = date_fmt, tz = "UTC")
        if (!identical(format(values, format = date_fmt, tz = "UTC"), data_range)) {
          values <- format(values, format = date_fmt)
          if (isTRUE(nas)) {
            if (anyNA(data_values)) {
              values_expr <- expr(!!sym(var) >= !!values[1] & !!sym(var) <= !!values[2] | is.na(!!sym(var)))
            } else {
              values_expr <- expr(!!sym(var) >= !!values[1] & !!sym(var) <= !!values[2])
            }
          } else {
            if (anyNA(data_values)) {
              values_expr <- expr(!!sym(var) >= !!values[1] & !!sym(var) <= !!values[2] & !is.na(!!sym(var)))
            } else {
              values_expr <- expr(!!sym(var) >= !!values[1] & !!sym(var) <= !!values[2])
            }
          }
        }
      } else {
        data_values <- unique(as.character(data_values))
        if (.empty_field_char %in% values)
          values[which(values == .empty_field_char)] <- ""
        if (!identical(sort(values), sort(data_values))) {
          if (length(values) == 0) {
            if (isTRUE(nas)) {
              values_expr <- expr(is.na(!!sym(var)))
            } else {
              values_expr <- expr(!(!!sym(var) %in% !!data_values[!is.na(data_values)]) & !is.na(!!sym(var)))
            }
          } else {
            if (length(values) <= length(data_values)/2) {
              if (isTRUE(nas)) {
                if (anyNA(data_values)) {
                  values_expr <- expr(!!sym(var) %in% !!values | is.na(!!sym(var)))
                } else {
                  values_expr <- expr(!!sym(var) %in% !!values)
                }
              } else {
                values_expr <- expr(!!sym(var) %in% !!values)
              }
            } else {
              if (isTRUE(nas)) {
                if (anyNA(data_values)) {
                  values_expr <- expr(!(!!sym(var) %in% !!setdiff(data_values[!is.na(data_values)], values)) | is.na(!!sym(var)))
                } else {
                  values_expr <- expr(!(!!sym(var) %in% !!setdiff(data_values[!is.na(data_values)], values)))
                }
              } else {
                if (anyNA(data_values)) {
                  values_expr <- expr(!(!!sym(var) %in% !!setdiff(data_values[!is.na(data_values)], values)) & !is.na(!!sym(var)))
                } else {
                  values_expr <- expr(!(!!sym(var) %in% !!setdiff(data_values[!is.na(data_values)], values)))
                }
              }
            }
          }
        }
      }
      if (is.null(values_expr) & !isTRUE(nas) & anyNA(data_values)) {
        expr(!is.na(!!sym(var)))
      } else {
        values_expr
      }
    }
  )
  expressions <- lapply(
    X = expressions,
    FUN = function(expr) {
      res_expr <- try(eval_tidy(expr = expr, data = data), silent = TRUE)
      if (inherits(res_expr, "try-error"))
        return(expr)
      if (isTRUE(all(res_expr)))
        return(NULL)
      expr
    }
  )
  expressions <- dropNullsOrEmpty(expressions)
  data_name <- as.character(data_name)
  if (grepl("::", data_name)) {
    data_name <- str2lang(data_name)
  } else {
    data_name <- sym(data_name)
  }
  expr_dplyr <- Reduce(
    f = function(x, y) expr(!!x %>% filter(!!y)),
    x = expressions,
    init = expr(!!data_name)
  )
  expression <- Reduce(
    f = function(x, y) expr(!!x & !!y),
    x = expressions
  )
  return(list(
    expr_dplyr = expr_dplyr,
    expr = expression
  ))
}

#' @importFrom rlang is_double
drop_id <- function(data, p = 0.9, n = 50) {
  p <- as.numeric(p)
  if (!is_double(p, n = 1))
    p <- 0.9
  n <- as.numeric(n)
  if (!is_double(n, n = 1))
    n <- 50
  data[] <- lapply(
    X = data,
    FUN = function(x) {
      if (inherits(x, c("factor", "character"))) {
        values <- unique(as.character(x))
        values <- tryCatch(
          values[trimws(values) != ""],
          error = function(e) {
            Encoding(values[!validEnc(values)]) <- "unknown"
            values
          }
        )
        if (length(values) <= 1)
          return(NULL)
        if (isTRUE(length(values) >= (length(x) * p)))
          return(NULL)
        if (isTRUE(length(values) >= n))
          return(NULL)
      }
      x
    }
  )
  data
}

drop_na <- function(data) {
  data[] <- lapply(
    X = data,
    FUN = function(x) {
      if (all(is.na(x)))
        return(NULL)
      x
    }
  )
  data
}


# borrowed from shiny
hasDecimals <- function (value) {
  truncatedValue <- round(value)
  return(!identical(value, truncatedValue))
}

find_range_step <- function(x) {
  max <- max(x, na.rm = TRUE)
  min <- min(x, na.rm = TRUE)
  range <- max - min
  if (range < 2 || hasDecimals(min) || hasDecimals(max)) {
    pretty_steps <- pretty(c(min, max), n = 100, high.u.bias = 1)
    n_steps <- length(pretty_steps) - 1
    list(
      range = range(pretty_steps),
      min = min(pretty_steps),
      max = max(pretty_steps),
      step = signif(digits = 10, (max(pretty_steps) - min(pretty_steps))/n_steps)
    )
  }
  else {
    list(
      range = range(x, na.rm = TRUE),
      min = min,
      max = max,
      step = 1
    )
  }
}

match_class <- function(x, y) {
  char <- c("character", "factor")
  num <- c("numeric", "integer")
  date <- c("Date", "POSIXt")
  if (inherits(x, num) & inherits(y, num))
    return(TRUE)
  if (inherits(x, char) & inherits(y, char))
    return(TRUE)
  if (inherits(x, date) & inherits(y, date))
    return(TRUE)
  return(FALSE)
}


.empty_field_char <- "\u3008 \U0001d626\U0001d62e\U0001d631\U0001d635\U0001d63a \U0001d627\U0001d62a\U0001d626\U0001d62d\U0001d625 \u3009"


================================================
FILE: R/i18n.R
================================================

#' @title Internationalization
#'
#' @description Simple mechanism to translate labels in a Shiny application.
#'
#' @param x Label to translate.
#' @param translations Either a `list` or a `data.frame` with translations.
#'
#' @return `i18n()` returns a `character`, `i18n_translations()` returns a `list` or a `data.frame`.
#' @export
#'
#' @name i18n
#'
#' @importFrom data.table as.data.table :=
#'
#' @example examples/i18n.R
i18n <- function(x, translations = i18n_translations()) {
  if (is.null(translations))
    return(x)
  if (is.list(translations) & !is.data.frame(translations)) {
    if (!x %in% names(translations)) {
      warning("i18n: translation for '", x, "' not found!", call. = FALSE)
      return(x)
    }
    return(translations[[x]])
  }
  if (is.data.frame(translations)) {
    translations <- as.data.table(translations)
    translations[, label := as.character(label)]
    translations <- unique(translations, by = "label")
    translations[, translation := as.character(translation)]
    if (!x %in% translations$label) {
      warning("i18n: translation for '", x, "' not found!", call. = FALSE)
      return(x)
    }
    return(translations[label == x, c(translation)])
  }
  stop("i18n option must be either: a list, a data.frame, or a path to a valid file.", call. = FALSE)
}

#' @param package Name of the package where the function is called, use `NULL` outside a package.
#'  It will retrieve option `"i18n.<PACKAGE>"` (or `"i18n"` if no package) to returns appropriate labels.
#'
#' @export
#'
#' @rdname i18n
#'
#' @importFrom utils packageName
#' @importFrom data.table fread
i18n_translations <- function(package = packageName(parent.frame(2))) {
  if (is.null(package)) {
    opts <- "i18n"
  } else {
    opts <- paste(package, "i18n", sep = ".")
  }
  language <- getOption(x = opts)
  if (is.null(language))
    return(NULL)
  if (is.character(language) && i18n_exist(language, package = package)) {
    language <- fread(file = i18n_file(language, package = package), encoding = "UTF-8", fill = TRUE)
  } else if (is.character(language) && file.exists(language)) {
    language <- fread(file = language, encoding = "UTF-8", fill = TRUE)
  } else if (is.character(language)) {
    warning(
      "i18n translations not found for : ", language,
      call. = FALSE
    )
    language <- NULL
  }
  return(language)
}

#' @param value Value to set for translation. Can be:
#'   * single `character` to use a supported language (`"fr"`, `"mk"`, `"al"`, `"pt"` for esquisse and datamods packages).
#'   * a `list` with labels as names and translations as values.
#'   * a `data.frame` with 2 column: `label` & `translation`.
#'   * path to a CSV file with same structure as for `data.frame` above.
#' @param packages Name of packages for which to set i18n, default to esquisse and datamods
#'
#' @export
#'
#' @rdname i18n
#'
#' @importFrom stats setNames
set_i18n <- function(value, packages = c("datamods", "esquisse")) {
  if (is.null(packages)) {
    options("i18n" = value)
  } else {
    i18n.opts <- setNames(
      lapply(seq_along(packages), function(...) value),
      paste(packages, "i18n", sep = ".")
    )
    options(i18n.opts)
  }
}


i18n_file <- function(x, package) {
  if (is.null(package))
    return(character(0))
  system.file("i18n", paste0(x, ".csv"), package = package)
}
i18n_exist <- function(x, package) {
  isTRUE(file.exists(i18n_file(x, package)))
}

i18n_test <- function(x) {
  i18n(x)
}


================================================
FILE: R/import-copypaste.R
================================================

#' @title Import data with copy & paste
#'
#' @description Let the user copy data from Excel or text file then paste it into a text area to import it.
#'
#' @inheritParams import-globalenv
#' @param name_field Show or not a field to add a name to data (that is returned server-side).
#'
#' @template module-import
#'
#' @export
#'
#' @name import-copypaste
#'
#' @importFrom shiny NS icon textAreaInput actionButton textInput
#' @importFrom htmltools tags tagAppendAttributes
#'
#' @example examples/from-copypaste.R
import_copypaste_ui <- function(id, title = TRUE, name_field = TRUE) {

  ns <- NS(id)

  if (isTRUE(title)) {
    title <- tags$h4(
      i18n("Copy & paste data"),
      class = "datamods-title"
    )
  }

  tags$div(
    class = "datamods-import",
    html_dependency_datamods(),
    title,
    tagAppendAttributes(
      textAreaInput(
        inputId = ns("data_pasted"),
        label = i18n("Paste data here:"),
        height = "300px",
        width = "100%",
        resize = "none"
      ),
      class = "shiny-input-container-inline"
    ),
   if (isTRUE(name_field)) {
     textInput(
       inputId = ns("name"),
       label = NULL,
       placeholder = i18n("Add a label to data"),
       width = "100%"
     )
   },
    tags$div(
      id = ns("import-placeholder"),
      alert(
        id = ns("import-result"),
        status = "info",
        tags$b(i18n("Nothing pasted yet!")),
        i18n("Please copy and paste some data in the dialog box above."),
        dismissible = TRUE
      )
    ),
    uiOutput(
      outputId = ns("container_valid_btn"),
      style = "margin-top: 20px;"
    )
  )
}


#' @inheritParams import_globalenv_server
#' @param fread_args `list` of additional arguments to pass to [data.table::fread()] when reading data.
#'
#' @export
#'
#' @importFrom shiny moduleServer
#' @importFrom data.table fread
#' @importFrom shiny reactiveValues observeEvent removeUI reactive
#' @importFrom htmltools tags tagList
#' @importFrom rlang %||%
#'
#' @rdname import-copypaste
import_copypaste_server <- function(id,
                                    btn_show_data = TRUE,
                                    show_data_in = c("popup", "modal"),
                                    trigger_return = c("button", "change"),
                                    return_class = c("data.frame", "data.table", "tbl_df", "raw"),
                                    reset = reactive(NULL),
                                    fread_args = list()) {

  trigger_return <- match.arg(trigger_return)
  return_class <- match.arg(return_class)

  module <- function(input, output, session) {

    ns <- session$ns
    imported_rv <- reactiveValues(data = NULL, name = NULL)
    temporary_rv <- reactiveValues(data = NULL, name = NULL, status = NULL)

    observeEvent(reset(), {
      temporary_rv$data <- NULL
      temporary_rv$name <- NULL
      temporary_rv$status <- NULL
    })

    output$container_valid_btn <- renderUI({
      if (identical(trigger_return, "button")) {
        button_import()
      }
    })

    observeEvent(input$data_pasted, {
      req(input$data_pasted)
      fread_args$tex <- input$data_pasted
      imported <- try(rlang::exec(data.table::fread, !!!fread_args), silent = TRUE)

      if (inherits(imported, "try-error") || NROW(imported) < 1) {
        toggle_widget(inputId = "confirm", enable = FALSE)
        insert_error(mssg = i18n(attr(imported, "condition")$message))
        temporary_rv$status <- "error"
        temporary_rv$data <- NULL
        temporary_rv$name <- NULL
      } else {
        toggle_widget(inputId = "confirm", enable = TRUE)
        insert_alert(
          selector = ns("import"),
          status = "success",
          make_success_alert(
            imported,
            trigger_return = trigger_return,
            btn_show_data = btn_show_data
          )
        )
        temporary_rv$status <- "success"
        temporary_rv$data <- imported
      }
    }, ignoreInit = TRUE)

    observeEvent(input$name, {
      temporary_rv$name <- if (isTruthy(input$name)) {
        input$name
      } else {
        "clipboard_data"
      }
    })

    observeEvent(input$see_data, {
      show_data(temporary_rv$data, title = i18n("Imported data"), type = show_data_in)
    })

    observeEvent(input$confirm, {
      imported_rv$data <- temporary_rv$data
      imported_rv$name <- temporary_rv$name
    })


    if (identical(trigger_return, "button")) {
      return(list(
        status = reactive(temporary_rv$status),
        name = reactive(imported_rv$name),
        data = reactive(as_out(imported_rv$data, return_class))
      ))
    } else {
      return(list(
        status = reactive(temporary_rv$status),
        name = reactive(temporary_rv$name),
        data = reactive(as_out(temporary_rv$data, return_class))
      ))
    }
  }

  moduleServer(
    id = id,
    module = module
  )
}





================================================
FILE: R/import-file.R
================================================

#' @title Import data from a file
#'
#' @description Let user upload a file and import data
#'
#' @inheritParams import-globalenv
#' @param preview_data Show or not a preview of the data under the file input.
#' @param file_extensions File extensions accepted by [shiny::fileInput()], can also be MIME type.
#' @param layout_params How to display import parameters : in a dropdown button or inline below file input.
#'
#' @template module-import
#'
#' @export
#'
#' @name import-file
#'
#' @importFrom shiny NS fileInput actionButton icon
#' @importFrom htmltools tags tagAppendAttributes css tagAppendChild
#' @importFrom shinyWidgets pickerInput numericInputIcon textInputIcon dropMenu
#' @importFrom phosphoricons ph
#' @importFrom toastui datagridOutput2
#'
#' @example examples/from-file.R
import_file_ui <- function(id,
                           title = TRUE,
                           preview_data = TRUE,
                           file_extensions = c(".csv", ".txt", ".xls", ".xlsx", ".rds", ".fst", ".sas7bdat", ".sav"),
                           layout_params = c("dropdown", "inline")) {

  ns <- NS(id)

  if (!is.null(layout_params)) {
    layout_params <- match.arg(layout_params)
  }

  if (isTRUE(title)) {
    title <- tags$h4(
      i18n("Import a file"),
      class = "datamods-title"
    )
  }


  params_ui <- fluidRow(
    column(
      width = 6,
      numericInputIcon(
        inputId = ns("skip_rows"),
        label = i18n("Rows to skip before reading data:"),
        value = 0,
        min = 0,
        icon = list("n ="),
        size = "sm",
        width = "100%"
      ),
      tagAppendChild(
        textInputIcon(
          inputId = ns("na_label"),
          label = i18n("Missing values character(s):"),
          value = ",NA",
          icon = list("NA"),
          size = "sm",
          width = "100%"
        ),
        shiny::helpText(ph("info"), i18n("if several use a comma (',') to separate them"))
      )
    ),
    column(
      width = 6,
      textInputIcon(
        inputId = ns("dec"),
        label = i18n("Decimal separator:"),
        value = ".",
        icon = list("0.00"),
        size = "sm",
        width = "100%"
      ),
      textInputIcon(
        inputId = ns("encoding"),
        label = i18n("Encoding:"),
        value = "UTF-8",
        icon = phosphoricons::ph("text-aa"),
        size = "sm",
        width = "100%"
      )
    )
  )

  file_ui <- tagAppendAttributes(
    fileInput(
      inputId = ns("file"),
      label = i18n("Upload a file:"),
      buttonLabel = i18n("Browse..."),
      placeholder = i18n("No file selected"),
      accept = file_extensions,
      width = "100%"
    ),
    class = "mb-0"
  )
  if (identical(layout_params, "dropdown")) {
    file_ui <- tags$div(
      style = css(
        display = "grid",
        gridTemplateColumns = "1fr 50px",
        gridColumnGap = "10px"
      ),
      file_ui,
      tags$div(
        class = "shiny-input-container",
        tags$label(
          class = "control-label",
          `for` = ns("dropdown_params"),
          "...",
          style = css(visibility = "hidden")
        ),
        shinyWidgets::dropMenu(
          actionButton(
            inputId = ns("dropdown_params"),
            label = ph("gear", title = "Parameters"),
            width = "50px",
            class = "px-1"
          ),
          params_ui
        )
      )
    )
  }
  tags$div(
    class = "datamods-import",
    html_dependency_datamods(),
    shinyWidgets::html_dependency_winbox(),
    title,
    file_ui,
    if (identical(layout_params, "inline")) params_ui,
    tags$div(
      class = "hidden",
      id = ns("sheet-container"),
      pickerInput(
        inputId = ns("sheet"),
        label = i18n("Select sheet to import:"),
        choices = NULL,
        width = "100%"
      )
    ),
    tags$div(
      id = ns("import-placeholder"),
      alert(
        id = ns("import-result"),
        status = "info",
        tags$b(i18n("No file selected:")),
        sprintf(i18n("You can import %s files"), paste(file_extensions, collapse = ", ")),
        dismissible = TRUE
      )
    ),
    if (isTRUE(preview_data)) {
      datagridOutput2(outputId = ns("table"))
    },
    uiOutput(
      outputId = ns("container_confirm_btn"),
      style = "margin-top: 20px;"
    ),
    tags$div(
      style = css(display = "none"),
      checkboxInput(
        inputId = ns("preview_data"),
        label = NULL,
        value = isTRUE(preview_data)
      )
    )
  )
}


#' @inheritParams import_globalenv_server
#' @param read_fns Named list with custom function(s) to read data:
#'  * the name must be the extension of the files to which the function will be applied
#'  * the value must be a function that can have 5 arguments (you can ignore some of them, but you have to use the same names),
#'    passed by user through the interface:
#'    + `file`: path to the file
#'    + `sheet`: for Excel files, sheet to read
#'    + `skip`: number of row to skip
#'    + `dec`: decimal separator
#'    + `encoding`: file encoding
#'    + `na.strings`: character(s) to interpret as missing values.
#'
#' @export
#'
#' @importFrom shiny moduleServer
#' @importFrom htmltools tags tagList
#' @importFrom shiny reactiveValues reactive observeEvent removeUI req
#' @importFrom shinyWidgets updatePickerInput
#' @importFrom readxl excel_sheets
#' @importFrom rio import
#' @importFrom rlang exec fn_fmls_names is_named is_function
#' @importFrom tools file_ext
#' @importFrom utils head
#' @importFrom toastui renderDatagrid2 datagrid
#'
#' @rdname import-file
import_file_server <- function(id,
                               btn_show_data = TRUE,
                               show_data_in = "winbox",
                               trigger_return = c("button", "change"),
                               return_class = c("data.frame", "data.table", "tbl_df", "raw"),
                               reset = reactive(NULL),
                               read_fns = list()) {

  if (length(read_fns) > 0) {
    if (!is_named(read_fns))
      stop("import_file_server: `read_fns` must be a named list.", call. = FALSE)
    if (!all(vapply(read_fns, is_function, logical(1))))
      stop("import_file_server: `read_fns` must be list of function(s).", call. = FALSE)
  }

  trigger_return <- match.arg(trigger_return)
  return_class <- match.arg(return_class)

  module <- function(input, output, session) {

    ns <- session$ns
    imported_rv <- reactiveValues(data = NULL, name = NULL)
    temporary_rv <- reactiveValues(data = NULL, name = NULL, status = NULL)

    observeEvent(reset(), {
      temporary_rv$data <- NULL
      temporary_rv$name <- NULL
      temporary_rv$status <- NULL
    })

    output$container_confirm_btn <- renderUI({
      if (identical(trigger_return, "button")) {
        button_import()
      }
    })

    observeEvent(input$file, {
      if (isTRUE(is_excel(input$file$datapath))) {
        updatePickerInput(
          session = session,
          inputId = "sheet",
          choices = readxl::excel_sheets(input$file$datapath)
        )
        showUI(paste0("#", ns("sheet-container")))
      } else {
        hideUI(paste0("#", ns("sheet-container")))
      }
    })

    observeEvent(list(
      input$file,
      input$sheet,
      input$skip_rows,
      input$dec,
      input$encoding,
      input$na_label
    ), {
      req(input$file)
      # req(input$skip_rows)
      extension <- tools::file_ext(input$file$datapath)
      if (isTRUE(extension %in% names(read_fns))) {
        parameters <- list(
          file = input$file$datapath,
          sheet = input$sheet,
          skip = input$skip_rows,
          dec = input$dec,
          encoding = input$encoding,
          na.strings = split_char(input$na_label)
        )
        parameters <- parameters[which(names(parameters) %in% fn_fmls_names(read_fns[[extension]]))]
        imported <- try(rlang::exec(read_fns[[extension]], !!!parameters), silent = TRUE)
        code <- call2(read_fns[[extension]], !!!modifyList(parameters, list(file = input$file$name)))
      } else {
        if (is_excel(input$file$datapath)) {
          req(input$sheet)
          parameters <- list(
            file = input$file$datapath,
            which = input$sheet,
            skip = input$skip_rows,
            na = split_char(input$na_label)
          )
        } else if (is_sas(input$file$datapath)) {
          parameters <- list(
            file = input$file$datapath,
            skip = input$skip_rows,
            encoding = input$encoding
          )
        } else {
          parameters <- list(
            file = input$file$datapath,
            skip = input$skip_rows,
            dec = input$dec,
            encoding = input$encoding,
            na.strings = split_char(input$na_label)
          )
        }
        imported <- try(rlang::exec(rio::import, !!!parameters), silent = TRUE)
        code <- call2("import", !!!modifyList(parameters, list(file = input$file$name)), .ns = "rio")
      }

      if (inherits(imported, "try-error")) {
        imported <- try(rlang::exec(rio::import, !!!parameters[1]), silent = TRUE)
        code <- call2("import", !!!list(file = input$file$name), .ns = "rio")
      }

      if (inherits(imported, "try-error") || NROW(imported) < 1) {

        toggle_widget(inputId = "confirm", enable = FALSE)
        insert_error(mssg = i18n(attr(imported, "condition")$message))
        temporary_rv$status <- "error"
        temporary_rv$data <- NULL
        temporary_rv$name <- NULL
        temporary_rv$code <- NULL

      } else {

        toggle_widget(inputId = "confirm", enable = TRUE)

        insert_alert(
          selector = ns("import"),
          status = "success",
          make_success_alert(
            imported,
            trigger_return = trigger_return,
            btn_show_data = btn_show_data,
            extra = if (isTRUE(input$preview_data)) i18n("First five rows are shown below:")
          )
        )
        temporary_rv$status <- "success"
        temporary_rv$data <- imported
        temporary_rv$name <- input$file$name
        temporary_rv$code <- code
      }
    }, ignoreInit = TRUE)

    observeEvent(input$see_data, {
      show_data(temporary_rv$data, title = i18n("Imported data"), type = show_data_in)
    })

    output$table <- renderDatagrid2({
      req(temporary_rv$data)
      datagrid(
        data = head(temporary_rv$data, 5),
        theme = "striped",
        colwidths = "guess",
        minBodyHeight = 250
      )
    })

    observeEvent(input$confirm, {
      imported_rv$data <- temporary_rv$data
      imported_rv$name <- temporary_rv$name
      imported_rv$code <- temporary_rv$code
    })

    if (identical(trigger_return, "button")) {
      return(list(
        status = reactive(temporary_rv$status),
        name = reactive(imported_rv$name),
        code = reactive(imported_rv$code),
        data = reactive(as_out(imported_rv$data, return_class))
      ))
    } else {
      return(list(
        status = reactive(temporary_rv$status),
        name = reactive(temporary_rv$name),
        code = reactive(temporary_rv$code),
        data = reactive(as_out(temporary_rv$data, return_class))
      ))
    }
  }

  moduleServer(
    id = id,
    module = module
  )
}

# utils -------------------------------------------------------------------

is_excel <- function(path) {
  isTRUE(tools::file_ext(path) %in% c("xls", "xlsx"))
}

is_sas <- function(path) {
  isTRUE(tools::file_ext(path) %in% c("sas7bdat"))
}



================================================
FILE: R/import-globalenv.R
================================================

#' @title Import data from an Environment
#'
#' @description Let the user select a dataset from its own environment or from a package's environment.
#'
#' @param id Module's ID.
#' @param globalenv Search for data in Global environment.
#' @param packages Name of packages in which to search data.
#' @param title Module's title, if `TRUE` use the default title,
#'  use `NULL` for no title or a `shiny.tag` for a custom one.
#'
#' @template module-import
#'
#' @export
#'
#' @name import-globalenv
#'
#' @importFrom htmltools tags
#' @importFrom shiny NS actionButton icon textInput
#' @importFrom shinyWidgets pickerInput alert
#'
#' @example examples/from-globalenv.R
import_globalenv_ui <- function(id,
                                globalenv = TRUE,
                                packages = get_data_packages(),
                                title = TRUE) {

  ns <- NS(id)

  choices <- list()
  if (isTRUE(globalenv)) {
    choices <- append(choices, "Global Environment")
  }
  if (!is.null(packages)) {
    choices <- append(choices, list(Packages = as.character(packages)))
  }

  if (isTRUE(globalenv)) {
    selected <- "Global Environment"
  } else {
    selected <- packages[1]
  }

  if (isTRUE(title)) {
    title <- tags$h4(
      i18n("Import a dataset from an environment"),
      class = "datamods-title"
    )
  }

  tags$div(
    class = "datamods-import",
    html_dependency_datamods(),
    title,
    pickerInput(
      inputId = ns("data"),
      label = i18n("Select a data.frame:"),
      choices = NULL,
      options = list(title = i18n("List of data.frame...")),
      width = "100%"
    ),
    pickerInput(
      inputId = ns("env"),
      label = i18n("Select an environment in which to search:"),
      choices = choices,
      selected = selected,
      width = "100%",
      options = list(
        "title" = i18n("Select environment"),
        "live-search" = TRUE,
        "size" = 10
      )
    ),

    tags$div(
      id = ns("import-placeholder"),
      alert(
        id = ns("import-result"),
        status = "info",
        tags$b(i18n("No data selected!")),
        i18n("Use a data.frame from your environment or from the environment of a package."),
        dismissible = TRUE
      )
    ),
    uiOutput(
      outputId = ns("container_valid_btn"),
      style = "margin-top: 20px;"
    )
  )
}



#' @param btn_show_data Display or not a button to display data in a modal window if import is successful.
#' @param show_data_in Where to display data: in a `"popup"` or in a `"modal"` window.
#' @param trigger_return When to update selected data:
#'  `"button"` (when user click on button) or
#'  `"change"` (each time user select a dataset in the list).
#' @param return_class Class of returned data: `data.frame`, `data.table`, `tbl_df` (tibble) or `raw`.
#' @param reset A `reactive` function that when triggered resets the data.
#'
#' @export
#'
#' @importFrom shiny moduleServer reactiveValues observeEvent reactive removeUI is.reactive icon actionLink isTruthy
#' @importFrom htmltools tags tagList
#' @importFrom shinyWidgets updatePickerInput
#'
#' @rdname import-globalenv
import_globalenv_server <- function(id,
                                    btn_show_data = TRUE,
                                    show_data_in = c("popup", "modal"),
                                    trigger_return = c("button", "change"),
                                    return_class = c("data.frame", "data.table", "tbl_df", "raw"),
                                    reset = reactive(NULL)) {

  trigger_return <- match.arg(trigger_return)
  return_class <- match.arg(return_class)

  module <- function(input, output, session) {

    ns <- session$ns
    imported_rv <- reactiveValues(data = NULL, name = NULL)
    temporary_rv <- reactiveValues(data = NULL, name = NULL, status = NULL)

    observeEvent(reset(), {
      temporary_rv$data <- NULL
      temporary_rv$name <- NULL
      temporary_rv$status <- NULL
    })

    output$container_valid_btn <- renderUI({
      if (identical(trigger_return, "button")) {
        button_import()
      }
    })

    observeEvent(input$env, {
      if (identical(input$env, "Global Environment")) {
        choices <- search_obj("data.frame")
      } else {
        choices <- list_pkg_data(input$env)
      }
      if (is.null(choices)) {
        choices <- i18n("No data.frame here...")
        choicesOpt <- list(disabled = TRUE)
      } else {
        choicesOpt <- list(
          subtext = get_dimensions(choices)
        )
      }
      temporary_rv$package <- attr(choices, "package")
      updatePickerInput(
        session = session,
        inputId = "data",
        choices = choices,
        choicesOpt = choicesOpt
      )
    })


    observeEvent(input$trigger, {
      if (identical(trigger_return, "change")) {
        hideUI(selector = paste0("#", ns("container_valid_btn")))
      }
    })


    observeEvent(input$data, {
      if (!isTruthy(input$data)) {
        toggle_widget(inputId = "confirm", enable = FALSE)
        insert_alert(
          selector = ns("import"),
          status = "info",
          tags$b(i18n("No data selected!")),
          i18n("Use a data.frame from your environment or from the environment of a package.")
        )
      } else {
        name_df <- input$data

        if (!is.null(temporary_rv$package)) {
          attr(name_df, "package") <- temporary_rv$package
        }

        imported <- try(get_env_data(name_df), silent = TRUE)

        if (inherits(imported, "try-error") || NROW(imported) < 1) {
          toggle_widget(inputId = "confirm", enable = FALSE)
          insert_error(mssg = i18n(attr(imported, "condition")$message))
          temporary_rv$status <- "error"
          temporary_rv$data <- NULL
          temporary_rv$name <- NULL
        } else {
          toggle_widget(inputId = "confirm", enable = TRUE)
          insert_alert(
            selector = ns("import"),
            status = "success",
            make_success_alert(
              imported,
              trigger_return = trigger_return,
              btn_show_data = btn_show_data
            )
          )
          pkg <- attr(name_df, "package")
          if (!is.null(pkg)) {
            name <- paste(pkg, input$data, sep = "::")
          } else {
            name <- input$data
          }
          name <- trimws(sub("\\(([^\\)]+)\\)", "", name))
          temporary_rv$status <- "success"
          temporary_rv$data <- imported
          temporary_rv$name <- name
        }
      }
    }, ignoreInit = TRUE, ignoreNULL = FALSE)


    observeEvent(input$see_data, {
      show_data(temporary_rv$data, title = i18n("Imported data"), type = show_data_in)
    })

    observeEvent(input$confirm, {
      imported_rv$data <- temporary_rv$data
      imported_rv$name <- temporary_rv$name
    })


    if (identical(trigger_return, "button")) {
      return(list(
        status = reactive(temporary_rv$status),
        name = reactive(imported_rv$name),
        data = reactive(as_out(imported_rv$data, return_class))
      ))
    } else {
      return(list(
        status = reactive(temporary_rv$status),
        name = reactive(temporary_rv$name),
        data = reactive(as_out(temporary_rv$data, return_class))
      ))
    }
  }

  moduleServer(
    id = id,
    module = module
  )
}







# utils -------------------------------------------------------------------


#' Get packages containing datasets
#'
#' @return a character vector of packages names
#' @export
#'
#' @importFrom utils data
#'
#' @examples
#' if (interactive()) {
#'
#'   get_data_packages()
#'
#' }
get_data_packages <- function() {
  suppressWarnings({
    pkgs <- data(package = .packages(all.available = TRUE))
  })
  unique(pkgs$results[, 1])
}


#' List dataset contained in a package
#'
#' @param pkg Name of the package, must be installed.
#'
#' @return a \code{character} vector or \code{NULL}.
#' @export
#'
#' @importFrom utils data
#'
#' @examples
#'
#' list_pkg_data("ggplot2")
list_pkg_data <- function(pkg) {
  if (isTRUE(requireNamespace(pkg, quietly = TRUE))) {
    list_data <- data(package = pkg, envir = environment())$results[, "Item"]
    list_data <- sort(list_data)
    attr(list_data, "package") <- pkg
    if (length(list_data) < 1) {
      NULL
    } else {
      unname(list_data)
    }
  } else {
    NULL
  }
}

#' @importFrom utils data
get_env_data <- function(obj, env = globalenv()) {
  pkg <- attr(obj, "package")
  re <- regexpr(pattern = "\\(([^\\)]+)\\)", text = obj)
  obj_ <- substr(x = obj, start = re + 1, stop = re + attr(re, "match.length") - 2)
  obj <- gsub(pattern = "\\s.*", replacement = "", x = obj)
  if (obj %in% ls(name = env)) {
    get(x = obj, envir = env)
  } else if (!is.null(pkg) && !identical(pkg, "")) {
    res <- suppressWarnings(try(
      get(utils::data(list = obj, package = pkg, envir = environment())), silent = TRUE
    ))
    if (!inherits(res, "try-error"))
      return(res)
    data(list = obj_, package = pkg, envir = environment())
    get(obj, envir = environment())
  } else {
    NULL
  }
}


get_dimensions <- function(objs) {
  if (is.null(objs))
    return(NULL)
  dataframes_dims <- Map(
    f = function(name, pkg) {
      attr(name, "package") <- pkg
      tmp <- suppressWarnings(get_env_data(name))
      if (is.data.frame(tmp)) {
        sprintf("%d obs. of  %d variables", nrow(tmp), ncol(tmp))
      } else {
        i18n("Not a data.frame")
      }
    },
    name = objs,
    pkg = if (!is.null(attr(objs, "package"))) {
      attr(objs, "package")
    } else {
      character(1)
    }
  )
  unlist(dataframes_dims)
}


================================================
FILE: R/import-googlesheets.R
================================================

#' @title Import data from Googlesheet
#'
#' @description Let user paste link to a Google sheet then import the data.
#'
#' @inheritParams import-globalenv
#'
#' @template module-import
#'
#' @export
#' @name import-googlesheets
#'
#' @importFrom shiny NS actionLink
#' @importFrom shinyWidgets textInputIcon
#' @importFrom htmltools tags tagList
#'
#' @example examples/from-googlesheets.R
import_googlesheets_ui <- function(id, title = TRUE) {

  ns <- NS(id)

  if (isTRUE(title)) {
    title <- tags$h4(
      i18n("Import Google Spreadsheet"),
      class = "datamods-title"
    )
  }

  tags$div(
    class = "datamods-import",
    html_dependency_datamods(),
    title,
    tags$div(
      class = "pull-right float-right",
      help_popup(tagList(
        i18n("You can either use:"),
        tags$ul(
          tags$li(
            i18n("A shareable link, in that case first sheet will be read")
          ),
          tags$li(
            i18n("The URL that appear in your browser, in that case the current sheet will be read")
          )
        )
      ))
    ),
    textInputIcon(
      inputId = ns("link"),
      label = i18n("Enter a shareable link to a GoogleSheet:"),
      icon = phosphoricons::ph("link"),
      width = "100%"
    ),
    tags$div(
      id = ns("import-placeholder"),
      alert(
        id = ns("import-result"),
        status = "info",
        tags$b(i18n("Nothing pasted yet!")),
        i18n("Please paste a valid GoogleSheet link in the dialog box above."),
        dismissible = TRUE
      )
    ),
    uiOutput(
      outputId = ns("container_confirm_btn"),
      style = "margin-top: 20px;"
    )
  )
}


#' @inheritParams import_globalenv_server
#'
#' @export
#'
#' @importFrom shiny moduleServer
#' @importFrom shiny reactiveValues observeEvent removeUI reactive req
#' @importFrom htmltools tags tagList
#'
#' @rdname import-googlesheets
import_googlesheets_server <- function(id,
                                       btn_show_data = TRUE,
                                       show_data_in = c("popup", "modal"),
                                       trigger_return = c("button", "change"),
                                       return_class = c("data.frame", "data.table", "tbl_df", "raw"),
                                       reset = reactive(NULL)) {

  trigger_return <- match.arg(trigger_return)
  return_class <- match.arg(return_class)

  module <- function(input, output, session) {

    ns <- session$ns
    imported_rv <- reactiveValues(data = NULL, name = NULL)
    temporary_rv <- reactiveValues(data = NULL, name = NULL, status = NULL)

    observeEvent(reset(), {
      temporary_rv$data <- NULL
      temporary_rv$name <- NULL
      temporary_rv$status <- NULL
    })

    output$container_confirm_btn <- renderUI({
      if (identical(trigger_return, "button")) {
        button_import()
      }
    })

    observeEvent(input$trigger, {
      if (identical(trigger_return, "change")) {
        hideUI(selector = paste0("#", ns("confirm-button")))
      }
    })

    observeEvent(input$link, {
      req(input$link)
      imported <- try(read_gsheet(input$link), silent = TRUE)
      if (inherits(imported, "try-error") || NROW(imported) < 1) {
        toggle_widget(inputId = "confirm", enable = FALSE)
        insert_error(mssg = i18n(attr(imported, "condition")$message))
        temporary_rv$status <- "error"
        temporary_rv$data <- NULL
      } else {
        toggle_widget(inputId = "confirm", enable = TRUE)
        insert_alert(
          selector = ns("import"),
          status = "success",
          make_success_alert(
            imported,
            trigger_return = trigger_return,
            btn_show_data = btn_show_data
          )
        )
        temporary_rv$status <- "success"
        temporary_rv$data <- imported
      }
    }, ignoreInit = TRUE)

    observeEvent(input$see_data, {
      show_data(temporary_rv$data, title = i18n("Imported data"), type = show_data_in)
    })

    observeEvent(input$confirm, {
      imported_rv$data <- temporary_rv$data
    })

    if (identical(trigger_return, "button")) {
      return(list(
        status = reactive(temporary_rv$status),
        name = reactive(imported_rv$name),
        data = reactive(as_out(imported_rv$data, return_class))
      ))
    } else {
      return(list(
        status = reactive(temporary_rv$status),
        name = reactive(temporary_rv$name),
        data = reactive(as_out(temporary_rv$data, return_class))
      ))
    }
  }

  moduleServer(
    id = id,
    module = module
  )
}



# Utils -------------------------------------------------------------------

get_id <- function(x) {
  if (grepl("/d/", x)) {
    x <- strsplit(x = x, split = "/")
    x <- unlist(x)
    x[which(x == "d") + 1]
  } else if (grepl("id=", x)) {
    x <- regmatches(x, gregexpr("id=[[:alnum:]_-]+", x))
    gsub("^id=", "", x[[1]])
  } else {
    stop("Failed to retrieve Googlesheet ID")
  }
}

#' @importFrom data.table fread .SD
#' @importFrom utils type.convert
read_gsheet <- function(url, dec = NULL) {
  url_ <- sprintf(
    "https://docs.google.com/spreadsheets/export?id=%s&format=csv",
    get_id(url)
  )
  if (grepl("gid=", url)) {
    gid <- regmatches(url, gregexpr("gid=[0-9]+", url))
    url_ <- paste0(url_, "&", gid[[1]])
  }
  dt <- fread(input = url_)
  if (!is.null(dec)) {
    dt <- dt[, lapply(.SD, type.convert, dec = dec)]
  }
  return(dt)
}



================================================
FILE: R/import-modal.R
================================================

#' @title Import from all sources
#'
#' @description Wrap all import modules into one, can be displayed inline or in a modal window..
#'
#' @param id Module's id
#' @param from The import_ui & server to use, i.e. the method.
#'   There are 5 options to choose from. ("env", "file", "copypaste", "googlesheets", "url")
#' @inheritParams import-file
#'
#' @template module-import
#'
#' @export
#' @name import-modal
#'
#' @importFrom shiny NS tabsetPanel tabPanel tabPanelBody icon fluidRow column
#' @importFrom htmltools tags HTML
#' @importFrom shinyWidgets radioGroupButtons
#'
#' @example examples/modal.R
#'
import_ui <- function(id,
                      from = c("env", "file", "copypaste", "googlesheets", "url"),
                      file_extensions = c(".csv", ".txt", ".xls", ".xlsx", ".rds", ".fst", ".sas7bdat", ".sav")) {
  ns <- NS(id)
  from <- match.arg(from, several.ok = TRUE)

  env <- if ("env" %in% from) {
    tabPanelBody(
      value = "env",
      tags$br(),
      import_globalenv_ui(id = ns("env"), title = NULL)
    )
  }

  file <- if ("file" %in% from) {
    tabPanelBody(
      value = "file",
      tags$br(),
      import_file_ui(id = ns("file"), title = NULL, file_extensions = file_extensions)
    )
  }

  copypaste <- if ("copypaste" %in% from) {
    tabPanelBody(
      value = "copypaste",
      tags$br(),
      import_copypaste_ui(id = ns("copypaste"), title = NULL)
    )
  }

  googlesheets <- if ("googlesheets" %in% from) {
    tabPanelBody(
      value = "googlesheets",
      tags$br(),
      import_googlesheets_ui(id = ns("googlesheets"), title = NULL)
    )
  }

  url <- if ("url" %in% from) {
    tabPanelBody(
      value = "url",
      tags$br(),
      import_url_ui(id = ns("url"), title = NULL)
    )
  }

  #database <- if("database" %in% from) tabPanel("Database", import_database_ui(ns("database")))

  labsImport <- list(
    "env" = i18n("Environment"),
    "file" = i18n("External file"),
    "copypaste" = i18n("Copy / Paste"),
    "googlesheets" = i18n("Googlesheets"),
    "url" = i18n("URL")
  )
  iconsImport <- list(
    "env" = phosphoricons::ph("code", title = labsImport$env),
    "file" = phosphoricons::ph("file-arrow-down", title = labsImport$file),
    "copypaste" = phosphoricons::ph("clipboard-text", title = labsImport$copypaste),
    "googlesheets" = phosphoricons::ph("cloud-arrow-down", title = labsImport$googlesheets),
    "url" = phosphoricons::ph("link", title = labsImport$url)
  )


  if (identical(length(from), 1L)) {
    importTab <- switch(
      from,
      "env" = import_globalenv_ui(id = ns("env")),
      "file" = import_file_ui(id = ns("file"), file_extensions = file_extensions),
      "copypaste" = import_copypaste_ui(id = ns("copypaste")),
      "googlesheets" = import_googlesheets_ui(id = ns("googlesheets")),
      "url" = import_url_ui(id = ns("url")),
    )
  } else {
    tabsetPanelArgs <- dropNulls(list(
      env, file, copypaste, googlesheets, url,
      id = ns("tabs-import"),
      type = "hidden"
    ))
    importTab <- do.call(
      what = tabsetPanel,
      args = tabsetPanelArgs
    )
    importTab <- fluidRow(
      column(
        width = 3,
        tags$br(),
        tags$style(
          HTML(sprintf("#%s>.btn-group-vertical {width: 100%%;}", ns("from"))),
          HTML(sprintf(".btn-group-vertical>.btn-group>.btn {text-align: left;}"))
        ),
        radioGroupButtons(
          inputId = ns("from"),
          label = i18n("How to import data?"),
          choiceValues = from,
          choiceNames = lapply(
            X = from,
            FUN = function(x) {
              tagList(iconsImport[[x]], labsImport[[x]])
            }
          ),
          direction = "vertical",
          width = "100%"
        )
      ),
      column(
        width = 9, importTab
      )
    )
  }

  tags$div(
    class = "datamods-imports",
    html_dependency_datamods(),
    tags$style(".tui-grid-cell-summary {vertical-align: baseline;}"),
    bslib::navset_underline(
      id = ns("tabs-mode"),
      bslib::nav_panel(
        title = tagList(
          phosphoricons::ph("download-simple", title = i18n("Import")),
          i18n("Import")
        ),
        value = "import",
        importTab
      ),
      bslib::nav_panel(
        title = tagList(
          phosphoricons::ph("table", title = i18n("View")),
          i18n("View")
        ),
        value = "view",
        tags$br(),
        tags$div(
          style = css(minHeight = "600px"),
          toastui::datagridOutput(outputId = ns("view"), height = "auto")
        )
      ),
      bslib::nav_panel(
        title = tagList(
          phosphoricons::ph("gear-six", title = i18n("Update")),
          i18n("Update")
        ),
        value = "update",
        tags$br(),
        update_variables_ui(id = ns("update"), title = NULL)
      ),
      bslib::nav_panel(
        title = tagList(
          phosphoricons::ph("shield-check", title = i18n("Validate")),
          i18n("Validate")
        ),
        value = "validate",
        tags$br(),
        validation_ui(
          id = ns("validation"),
          display = "inline",
          max_height = "400px"
        )
      )
    ),
    tags$div(
      id = ns("confirm-button"),
      style = "margin-top: 20px;",
      button_import(list(ns = ns))
    ),
    tags$div(
      style = "display: none;",
      textInput(inputId = ns("hidden"), label = NULL, value = genId())
    ),
    tags$script(
      sprintf("$('#%s').addClass('nav-justified');", ns("tabs-mode")),
      sprintf("fadeTab({id: '%s'});", ns("tabs-mode")),
      sprintf("disableTab({id: '%s', value: '%s'});", ns("tabs-mode"), "view"),
      sprintf("disableTab({id: '%s', value: '%s'});", ns("tabs-mode"), "update"),
      sprintf("disableTab({id: '%s', value: '%s'});", ns("tabs-mode"), "validate")
    )
  )
}


#' @param validation_opts `list` of arguments passed to [validation_server().
#' @param allowed_status Vector of statuses allowed to confirm dataset imported,
#'  if you want that all validation rules are successful before importing data use `allowed_status = "OK"`.
#' @param return_class Class of returned data: `data.frame`, `data.table`, `tbl_df` (tibble) or `raw`.
#'
#' @export
#' @rdname import-modal
#' @importFrom shiny moduleServer reactiveValues observeEvent
#'  reactive removeModal updateTabsetPanel hideTab observe
#' @importFrom rlang %||%
import_server <- function(id,
                          validation_opts = NULL,
                          allowed_status = c("OK", "Failed", "Error"),
                          return_class = c("data.frame", "data.table", "tbl_df", "raw"),
                          read_fns = list()) {
  allowed_status <- match.arg(allowed_status, several.ok = TRUE)
  return_class <- match.arg(return_class)
  if (length(read_fns) > 0) {
    if (!is_named(read_fns))
      stop("import_file_server: `read_fns` must be a named list.", call. = FALSE)
    if (!all(vapply(read_fns, is_function, logical(1))))
      stop("import_file_server: `read_fns` must be list of function(s).", call. = FALSE)
  }

  moduleServer(
    id,
    function(input, output, session) {

      ns <- session$ns

      data_rv <- reactiveValues(data = NULL)
      imported_rv <- reactiveValues(data = NULL)

      observeEvent(input$hidden, {
        data_rv$data <- NULL
        data_rv$name <- NULL
        if (length(validation_opts) < 1) {
          hideTab(inputId = "tabs-mode", target = "validate")
        }
      })

      observeEvent(input$from, {
        updateTabsetPanel(
          session = session,
          inputId = "tabs-import",
          selected = input$from
        )
      })

      from_env <- import_globalenv_server(
        id = "env",
        trigger_return = "change",
        btn_show_data = FALSE,
        reset = reactive(input$hidden)
      )
      from_file <- import_file_server(
        id = "file",
        trigger_return = "change",
        btn_show_data = FALSE,
        reset = reactive(input$hidden),
        read_fns = read_fns
      )
      from_copypaste <- import_copypaste_server(
        id = "copypaste",
        trigger_return = "change",
        btn_show_data = FALSE,
        reset = reactive(input$hidden)
      )
      from_googlesheets <- import_googlesheets_server(
        id = "googlesheets",
        trigger_return = "change",
        btn_show_data = FALSE,
        reset = reactive(input$hidden)
      )
      from_url <- import_url_server(
        id = "url",
        trigger_return = "change",
        btn_show_data = FALSE,
        reset = reactive(input$hidden)
      )
      #from_database <- import_database_server("database")

      observeEvent(from_env$data(), {
        data_rv$data <- from_env$data()
        data_rv$name <- from_env$name()
      })
      observeEvent(from_file$data(), {
        data_rv$data <- from_file$data()
        data_rv$name <- from_file$name()
      })
      observeEvent(from_copypaste$data(), {
        data_rv$data <- from_copypaste$data()
        data_rv$name <- from_copypaste$name()
      })
      observeEvent(from_googlesheets$data(), {
        data_rv$data <- from_googlesheets$data()
        data_rv$name <- from_googlesheets$name()
      })
      observeEvent(from_url$data(), {
        data_rv$data <- from_url$data()
        data_rv$name <- from_url$name()
      })
      # observeEvent(from_database$data(), {
      #   data_rv$data <- from_database$data()
      # })

      observeEvent(data_rv$data, {
        req(data_rv$data)
        if (is.data.frame(data_rv$data)) {
          if (length(validation_opts) < 1) {
            toggle_widget(inputId = "confirm", enable = TRUE)
          } else {
            status <- validation_results$status()
            if (isTRUE(status %in% allowed_status)) {
              toggle_widget(inputId = "confirm", enable = TRUE)
            } else {
              toggle_widget(inputId = "confirm", enable = FALSE)
            }
          }
          enable_tab("tabs-mode", "view")
          enable_tab("tabs-mode", "update")
          enable_tab("tabs-mode", "validate")
        } else {
          toggle_widget(inputId = "confirm", enable = FALSE)
        }
      })

      output$view <- toastui::renderDatagrid({
        data <- req(data_rv$data)
        session <- shiny::getDefaultReactiveDomain()
        gridTheme <- getOption("datagrid.theme")
        if (length(gridTheme) < 1) {
          apply_grid_theme()
        }
        on.exit(toastui::reset_grid_theme())
        grid <- toastui::datagrid(
          data = data,
          summary = construct_col_summary(data),
          colwidths = "guess",
          minBodyHeight = 500
        )
        toastui::grid_columns(grid, className = "font-monospace")
      })

      updated_data <- update_variables_server(
        id = "update",
        data = reactive(data_rv$data),
        height = "300px"
      )

      validation_results <- validation_server(
        id = "validation",
        data = reactive({
          data_rv$data
        }),
        n_row = validation_opts$n_row,
        n_col = validation_opts$n_col,
        n_row_label = validation_opts$n_row_label %||% "Valid number of rows",
        n_col_label = validation_opts$n_col_label %||% "Valid number of columns",
        btn_label = validation_opts$btn_label,
        rules = validation_opts$rules
      )

      observeEvent(validation_results$status(), {
        status <- validation_results$status()
        req(status)
        if (status %in% c("Error", "Failed")) {
          update_tab_label("tabs-mode", "validate", tagList(
            phosphoricons::ph("warning-circle", weight = "fill", fill = "firebrick"), i18n("Validate")
          ))
        } else {
          update_tab_label("tabs-mode", "validate", i18n("Validate"))
        }
        if (status %in% allowed_status) {
          toggle_widget(inputId = "confirm", enable = TRUE)
        } else {
          toggle_widget(inputId = "confirm", enable = FALSE)
        }
      })

      observeEvent(updated_data(), {
        data_rv$data <- updated_data()
      })

      observeEvent(input$confirm, {
        removeModal()
        imported_rv$data <- data_rv$data
        imported_rv$name <- data_rv$name %||% "imported_data"
      })

      return(list(
        data = reactive(as_out(imported_rv$data, return_class)),
        name = reactive(imported_rv$name)
      ))
    }
  )
}


#' @param title Modal window title.
#' @param size Modal window size, default to \code{"l"} (large).
#'
#' @export
#' @rdname import-modal
#' @importFrom shiny modalDialog showModal
#' @importFrom htmltools tags css
import_modal <- function(id,
                         from,
                         title = i18n("Import data"),
                         size = "l",
                         file_extensions = c(".csv", ".txt", ".xls", ".xlsx", ".rds", ".fst", ".sas7bdat", ".sav")) {
  showModal(modalDialog(
    title = tagList(
      button_close_modal(),
      title
    ),
    import_ui(id, from, file_extensions = file_extensions),
    size = size,
    footer = NULL
  ))
}




================================================
FILE: R/import-url.R
================================================
#' @title Import data from a URL
#'
#' @description Let user paste link to a JSON then import the data.
#'
#' @inheritParams import-globalenv
#'
#' @template module-import
#'
#' @export
#' @name import-url
#'
#' @importFrom htmltools tags
#'
#' @example examples/from-url.R
import_url_ui <- function(id, title = TRUE) {

  ns <- shiny::NS(id)

  if (isTRUE(title)) {
    title <- tags$h4(
      i18n("Import Url"),
      class = "datamods-title"
    )
  }

  tags$div(
    class = "datamods-import",
    html_dependency_datamods(),
    title,
    shinyWidgets::textInputIcon(
      inputId = ns("link"),
      label = i18n("Enter URL to data:"),
      icon = phosphoricons::ph("link"),
      width = "100%"
    ),
    tags$div(
      id = ns("import-placeholder"),
      alert(
        id = ns("import-result"),
        status = "info",
        tags$b(i18n("Nothing pasted yet!")),
        i18n("Please paste a valid link in the dialog box above."),
        i18n("You can import from flat table format supported by"),
        tags$a(
          href = "https://CRAN.R-project.org/package=rio/vignettes/rio.html#Supported_file_formats",
          "package rio"
        ),
        dismissible = TRUE
      )
    ),
    shiny::uiOutput(
      outputId = ns("container_confirm_btn"),
      style = "margin-top: 20px;"
    )
  )
}

#' @inheritParams import_globalenv_server
#'
#' @export
#'
#' @importFrom shiny moduleServer
#' @importFrom shiny reactiveValues observeEvent removeUI reactive req
#' @importFrom htmltools tags tagList
#'
#' @rdname import-url
import_url_server <- function(id,
                              btn_show_data = TRUE,
                              show_data_in = c("popup", "modal"),
                              trigger_return = c("button", "change"),
                              return_class = c("data.frame", "data.table", "tbl_df", "raw"),
                              reset = reactive(NULL)) {

  trigger_return <- match.arg(trigger_return)
  return_class <- match.arg(return_class)

  module <- function(input, output, session) {

    ns <- session$ns
    imported_rv <- reactiveValues(data = NULL, name = NULL)
    temporary_rv <- reactiveValues(data = NULL, name = NULL, status = NULL)

    observeEvent(reset(), {
      temporary_rv$data <- NULL
      temporary_rv$name <- NULL
      temporary_rv$status <- NULL
    })

    output$container_confirm_btn <- renderUI({
      if (identical(trigger_return, "button")) {
        button_import()
      }
    })

    observeEvent(input$trigger, {
      if (identical(trigger_return, "change")) {
        hideUI(selector = paste0("#", ns("confirm-button")))
      }
    })

    observeEvent(input$link, {
      req(input$link)

      imported <- try(rio::import(input$link), silent = TRUE)
      if (inherits(imported, "try-error")) # retry with explicit json format
        imported <- try(rio::import(input$link, format = "json"), silent = TRUE)

      if (inherits(imported, "try-error") || NROW(imported) < 1) {
        toggle_widget(inputId = "confirm", enable = FALSE)
        # pass error message to UI
        insert_error(mssg = i18n(attr(imported, "condition")$message))
        temporary_rv$status <- "error"
        temporary_rv$data <- NULL
        temporary_rv$name <- NULL
      } else {
        toggle_widget(inputId = "confirm", enable = TRUE)
        insert_alert(
          selector = ns("import"),
          status = "success",
          make_success_alert(
            imported,
            trigger_return = trigger_return,
            btn_show_data = btn_show_data
          )
        )
        temporary_rv$status <- "success"
        temporary_rv$data <- imported
        temporary_rv$name <- basename(input$link)
      }
    }, ignoreInit = TRUE)

    observeEvent(input$see_data, {
      show_data(temporary_rv$data, title = i18n("Imported data"), type = show_data_in)
    })

    observeEvent(input$confirm, {
      imported_rv$data <- temporary_rv$data
      imported_rv$name <- temporary_rv$name
    })

    if (identical(trigger_return, "button")) {
      return(list(
        status = reactive(temporary_rv$status),
        name = reactive(imported_rv$name),
        data = reactive(as_out(imported_rv$data, return_class))
      ))
    } else {
      return(list(
        status = reactive(temporary_rv$status),
        name = reactive(temporary_rv$name),
        data = reactive(as_out(temporary_rv$data, return_class))
      ))
    }
  }

  moduleServer(
    id = id,
    module = module
  )
}



================================================
FILE: R/onLoad.R
================================================
#' Shiny resource
#'
#' @importFrom shiny addResourcePath
#'
#' @noRd
.onLoad <- function(...) {
  shiny::addResourcePath("datamods", system.file("assets", package = "datamods"))
}


================================================
FILE: R/sample-data.R
================================================
## Function sample_n()

#' @title Sample rows
#'
#' @description The `sample_n` function returns the sample of a dataset from a number of rows chosen by the user.
#'
#' @param data `data.frame`
#' @param n vector of type `numeric`
#'
#' @return the sample of a dataset in the form of `data.table`
#'
#' @noRd
#'
#' @importFrom data.table as.data.table .N
#'
#' @examples
#' sample_n(iris, 25)
sample_n <- function(data, n) {
  as.data.table(data)[sample(x = .N, size = n)]
}


## Function sample_prop()

#' @title Sample percentage
#'
#' @description The `sample_prop` function returns the sample of a dataset from a percentage chosen by the user.
#'
#' @param data `data.frame`
#' @param percentage vector of type `numeric`
#'
#' @return the sample of a dataset in the form of `data.table`
#'
#' @noRd
#'
#' @importFrom data.table as.data.table .N
#'
sample_prop <- function(data, prop) {
  as.data.table(data)[sample(x = .N, size = nrow(data) * (prop/100))]
}


## Function sample_ui()

#' @title Shiny module to interactively sample a `data.frame`
#'
#' @description Allow to take a sample of `data.frame` for a given number or proportion of rows to keep.
#'
#' @param id Module id. See [shiny::moduleServer()].
#'
#' @return
#' * UI: HTML tags that can be included in shiny's UI
#' * Server: a `reactive` fgunction with the sampled data.
#'
#' @export
#'
#' @name module-sample
#'
#' @importFrom htmltools tagList
#' @importFrom shinyWidgets radioGroupButtons
#' @importFrom shiny NS conditionalPanel sliderInput uiOutput
#'
#' @example examples/sample.R
sample_ui <- function(id) {
  ns <- NS(id)

  tagList(
    radioGroupButtons(
      inputId = ns("choice"),
      label = i18n("Sample data by :"),
      choiceNames = c(i18n("number of rows"), i18n("proportion of rows")),
      choiceValues = c("number of rows", "proportion of rows"),
      justified = TRUE,
      size = "xs",
      width = "100%"
    ),

    conditionalPanel(
      condition = "input.choice == `proportion of rows`",
      ns = ns,
      sliderInput(
        inputId = ns("proportion_rows"),
        label = i18n("Choose a percentage :"),
        min = 0,
        max = 100,
        value = 100,
        post = " %",
        width = "100%"
      ),
      uiOutput(outputId = ns("feedback_proportion_rows"))
    ),

    conditionalPanel(
      condition = "input.choice == `number of rows`",
      ns = ns,
      sliderInput(
        inputId = ns("number_rows"),
        label = i18n("Choose a number of rows :"),
        min = 0,
        max = 10,
        value = 10,
        width = "100%"
      ),
      uiOutput(outputId = ns("feedback_number_rows"))
    )
  )
}


## Function sample_server()

#' @param data_r `reactive` containing a `data.frame` to use in the module.
#'
#' @export
#'
#' @rdname module-sample
#'
#' @importFrom shiny moduleServer observeEvent updateSliderInput renderUI reactive
#' @importFrom htmltools tags div
#'
sample_server <- function(id, data_r = reactive(NULL)) {
  moduleServer(
    id,
    function(input, output, session) {

      observeEvent(data_r(), {
        req(data_r())
        updateSliderInput(
          session,
          inputId = "number_rows",
          min = 0,
          max = nrow(data_r()),
          value = nrow(data_r())
        )
      })

      output$feedback_proportion_rows <- renderUI({
        sample <- req(sample_r())
        tags$div(
          paste(input$proportion_rows, i18n("% of the total, i.e."), nrow(sample), i18n("rows"))
        )
      })

      output$feedback_number_rows <- renderUI({
        data <- req(data_r())
        tags$div(
          paste(input$number_rows, i18n("lines, i.e."), round(input$number_rows / nrow(data) * 100, 1), i18n("% of the total"))
        )
      })

      sample_r <- reactive({
        req(data_r())
        if (input$choice == "proportion of rows") {
          table_sample <- sample_prop(data = data_r(), prop = input$proportion_rows)
        } else {
          table_sample <- sample_n(data = data_r(), n = input$number_rows)
        }
        return(table_sample)
      })

      return(sample_r)
    }
  )
}




================================================
FILE: R/select-group.R
================================================
#' @title Select Group Input Module
#'
#' @description Group of mutually dependent select menus for filtering `data.frame`'s columns (like in Excel).
#'
#' @param id Module's id.
#' @param params A list of parameters passed to each [shinyWidgets::virtualSelectInput()],
#'  you can use :
#'   * `inputId`: mandatory, must correspond to variable name.
#'   * `label`: Display label for the control.
#'   * `placeholder`: Text to show when no options selected.
#' @param label Character, global label on top of all labels.
#' @param btn_reset_label Character, reset button label. If `NULL` no button is added.
#' @param inline If `TRUE` (the default),
#'  select menus are horizontally positioned, otherwise vertically.
#' @param vs_args Arguments passed to all [shinyWidgets::virtualSelectInput()] created.
#'
#' @return A [shiny::reactive()] function containing data filtered with an attribute `inputs` containing a named list of selected inputs.
#' @export
#'
#' @name select-group
#'
#' @importFrom utils modifyList
#' @importFrom htmltools tagList tags css
#' @importFrom shiny NS actionLink icon singleton
#' @importFrom shinyWidgets virtualSelectInput
#'
#' @example examples/select-group-default.R
#' @example examples/select-group-selected.R
select_group_ui <- function(
  id,
  params,
  label = NULL,
  btn_reset_label = "Reset filters",
  inline = TRUE,
  vs_args = list()
) {
  ns <- NS(id)

  button_reset <- if (!is.null(btn_reset_label)) {
    actionLink(
      inputId = ns("reset_all"),
      label = tagList(
        phosphoricons::ph("x", title = btn_reset_label),
        btn_reset_label
      ),
      icon = NULL,
      style = "text-align: right;"
    )
  }
  label_tag <- if (!is.null(label)) tags$b(label, class = "select-group-label")

  sel_tag <- lapply(
    X = seq_along(params),
    FUN = function(x) {
      input <- params[[x]]
      vs_args <- modifyList(
        x = vs_args,
        val = list(
          inputId = ns(input$inputId),
          label = input$label,
          placeholder = input$placeholder,
          choices = input$selected,
          selected = input$selected,
          multiple = ifelse(is.null(input$multiple), TRUE, input$multiple),
          width = "100%"
        ),
        keep.null = TRUE
      )
      if (is.null(vs_args$showValueAsTags)) vs_args$showValueAsTags <- TRUE
      if (is.null(vs_args$zIndex)) vs_args$zIndex <- 10
      if (is.null(vs_args$disableSelectAll)) vs_args$disableSelectAll <- TRUE
      tags$div(
        class = "select-group-item",
        id = ns(paste0("container-", input$inputId)),
        do.call(shinyWidgets::virtualSelectInput, vs_args)
      )
    }
  )

  if (isTRUE(inline)) {
    sel_tag <- tags$div(
      class = "select-group-container",
      style = htmltools::css(
        display = "grid",
        gridTemplateColumns = sprintf("repeat(%s, 1fr)", length(params)),
        gridColumnGap = "5px"
      ),
      sel_tag
    )
  }

  tags$div(
    class = "select-group",
    label_tag,
    sel_tag,
    button_reset,
    html_dependency_datamods()
  )
}


#' @param data_r Either a [data.frame()] or a [shiny::reactive()]
#'  function returning a `data.frame` (do not use parentheses).
#' @param vars_r character, columns to use to create filters,
#'  must correspond to variables listed in `params`. Can be a
#'  [shiny::reactive()] function, but values must be included in the initial ones (in `params`).
#' @param selected_r [shiny::reactive()] function returning a named list with selected values to set.
#'
#' @export
#'
#' @rdname select-group
#' @importFrom shiny observeEvent observe reactiveValues reactive is.reactive isolate isTruthy
#' @importFrom shinyWidgets updateVirtualSelect
#' @importFrom rlang %||%
select_group_server <- function(id, data_r, vars_r, selected_r = reactive(list())) {
  moduleServer(
    id = id,
    module = function(input, output, session) {
      # Namespace
      ns <- session$ns
      hideUI(selector = paste0("#", ns("reset_all")))

      # data <- as.data.frame(data)
      rv <- reactiveValues(data = NULL, vars = NULL)
      observe({
        if (is.reactive(data_r)) {
          rv$data <- data_r()
        } else {
          rv$data <- as.data.frame(data_r)
        }
        if (is.reactive(vars_r)) {
          rv$vars <- vars_r()
        } else {
          rv$vars <- vars_r
        }
        for (var in names(rv$data)) {
          if (var %in% rv$vars) {
            showUI(id = paste0("container-", var))
          } else {
            hideUI(id = paste0("container-", var))
          }
        }
      })

      observe({
        selected <- selected_r()
        if (!is.list(selected)) selected <- list()
        lapply(
          X = rv$vars,
          FUN = function(x) {
            vals <- sort(uniqu
Download .txt
gitextract_a77i5218/

├── .Rbuildignore
├── .github/
│   ├── .gitignore
│   └── workflows/
│       ├── R-CMD-check.yaml
│       ├── pkgdown.yaml
│       └── test-coverage.yaml
├── .gitignore
├── DESCRIPTION
├── LICENSE.md
├── NAMESPACE
├── NEWS.md
├── R/
│   ├── create-column.R
│   ├── cut-variable.R
│   ├── data.R
│   ├── datagrid-infos.R
│   ├── edit-data-utils.R
│   ├── edit-data.R
│   ├── filter-data.R
│   ├── i18n.R
│   ├── import-copypaste.R
│   ├── import-file.R
│   ├── import-globalenv.R
│   ├── import-googlesheets.R
│   ├── import-modal.R
│   ├── import-url.R
│   ├── onLoad.R
│   ├── sample-data.R
│   ├── select-group.R
│   ├── show_data.R
│   ├── update-factor.R
│   ├── update-variables.R
│   ├── utils-shiny.R
│   ├── utils.R
│   ├── validation.R
│   └── zzz.R
├── README.Rmd
├── README.md
├── _pkgdown.yml
├── cran-comments.md
├── data/
│   └── demo_edit.rda
├── data-raw/
│   └── demo_edit.R
├── examples/
│   ├── create_column.R
│   ├── cut_variable.R
│   ├── edit_data-callback.R
│   ├── edit_data-callback_add.R
│   ├── edit_data-callback_delete.R
│   ├── edit_data-callback_update-row_style.R
│   ├── edit_data-callback_update.R
│   ├── edit_data.R
│   ├── filter_data-basic.R
│   ├── filter_data.R
│   ├── from-copypaste.R
│   ├── from-file.R
│   ├── from-globalenv.R
│   ├── from-googlesheets.R
│   ├── from-url.R
│   ├── i18n.R
│   ├── modal-validation.R
│   ├── modal.R
│   ├── sample.R
│   ├── select-group-default.R
│   ├── select-group-selected.R
│   ├── select-group-subset.R
│   ├── select-group-vars.R
│   ├── show_data.R
│   ├── update_factor.R
│   ├── validation.R
│   └── variables.R
├── inst/
│   ├── assets/
│   │   ├── css/
│   │   │   └── datamods.css
│   │   └── js/
│   │       └── datamods.js
│   ├── extdata/
│   │   ├── mtcars.csv
│   │   ├── mtcars.json
│   │   ├── mtcars_fr.csv
│   │   ├── pop-fra-dep.txt
│   │   ├── pop-fra-reg-dep.xls
│   │   └── rules.yaml
│   └── i18n/
│       ├── al.csv
│       ├── cn.csv
│       ├── de.csv
│       ├── es.csv
│       ├── extract_labels.R
│       ├── fr.csv
│       ├── it.csv
│       ├── ja.csv
│       ├── kr.csv
│       ├── maj_csv.R
│       ├── mk.csv
│       ├── pl.csv
│       ├── pt.csv
│       └── tr.csv
├── man/
│   ├── create-column.Rd
│   ├── cut-variable.Rd
│   ├── demo_edit.Rd
│   ├── edit-data.Rd
│   ├── filter-data.Rd
│   ├── get_data_packages.Rd
│   ├── i18n.Rd
│   ├── import-copypaste.Rd
│   ├── import-file.Rd
│   ├── import-globalenv.Rd
│   ├── import-googlesheets.Rd
│   ├── import-modal.Rd
│   ├── import-url.Rd
│   ├── list_pkg_data.Rd
│   ├── module-sample.Rd
│   ├── select-group.Rd
│   ├── show_data.Rd
│   ├── update-factor.Rd
│   ├── update-variables.Rd
│   └── validation.Rd
├── man-roxygen/
│   └── module-import.R
├── tests/
│   ├── testthat/
│   │   ├── test-edit-data.R
│   │   ├── test-filter-data.R
│   │   ├── test-i18n.R
│   │   ├── test-import-copypaste.R
│   │   ├── test-import-file.R
│   │   ├── test-import-globalenv.R
│   │   ├── test-import-googlesheets.R
│   │   ├── test-import-modal.R
│   │   ├── test-import-url.R
│   │   ├── test-onLoad.R
│   │   ├── test-update-variables.R
│   │   └── test-validation.R
│   └── testthat.R
└── vignettes/
    ├── .gitignore
    ├── datamods.Rmd
    └── i18n.Rmd
Download .txt
SYMBOL INDEX (4 symbols across 1 files)

FILE: inst/assets/js/datamods.js
  function fadeTab (line 52) | function fadeTab(data) {
  function updateTabLabel (line 67) | function updateTabLabel(data) {
  function disableTab (line 75) | function disableTab(data) {
  function enableTab (line 85) | function enableTab(data) {
Condensed preview — 126 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (567K chars).
[
  {
    "path": ".Rbuildignore",
    "chars": 214,
    "preview": "^datamods\\.Rproj$\n^\\.Rproj\\.user$\n^LICENSE\\.md$\n^examples$\n^doc$\n^Meta$\n^\\.github$\n^dev$\n^cran-comments\\.md$\n^CRAN-RELEA"
  },
  {
    "path": ".github/.gitignore",
    "chars": 7,
    "preview": "*.html\n"
  },
  {
    "path": ".github/workflows/R-CMD-check.yaml",
    "chars": 1326,
    "preview": "# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples\n# Need help debugging build failures? Start at"
  },
  {
    "path": ".github/workflows/pkgdown.yaml",
    "chars": 1262,
    "preview": "# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples\n# Need help debugging build failures? Start at"
  },
  {
    "path": ".github/workflows/test-coverage.yaml",
    "chars": 1790,
    "preview": "# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples\n# Need help debugging build failures? Start at"
  },
  {
    "path": ".gitignore",
    "chars": 92,
    "preview": ".Rproj.user\n.Rhistory\n.RData\n.Ruserdata\n*.Rproj\ninst/doc\ndoc\nMeta\ndev/\ndocs\nCRAN-SUBMISSION\n"
  },
  {
    "path": "DESCRIPTION",
    "chars": 1525,
    "preview": "Package: datamods\nTitle: Modules to Import and Manipulate Data in 'Shiny'\nVersion: 1.5.3.9200\nAuthors@R: \n    c(person(g"
  },
  {
    "path": "LICENSE.md",
    "chars": 34727,
    "preview": "GNU General Public License\n==========================\n\n_Version 3, 29 June 2007_  \n_Copyright © 2007 Free Software Found"
  },
  {
    "path": "NAMESPACE",
    "chars": 6330,
    "preview": "# Generated by roxygen2: do not edit by hand\n\nexport(create_column_server)\nexport(create_column_ui)\nexport(cut_variable_"
  },
  {
    "path": "NEWS.md",
    "chars": 6429,
    "preview": "# datamods 1.5.4\n\n* Rename CSS class `show` to `show-block` (used internally).\n* `select_group_server()`: added argument"
  },
  {
    "path": "R/create-column.R",
    "chars": 11421,
    "preview": "\n#' @title Create new column\n#'\n#' @description\n#' This module allow to enter an expression to create a new column in a "
  },
  {
    "path": "R/cut-variable.R",
    "chars": 9093,
    "preview": "\n#' @title Module to Convert Numeric to Factor\n#'\n#' @description\n#' This module contain an interface to cut a numeric i"
  },
  {
    "path": "R/data.R",
    "chars": 583,
    "preview": "#' Customer Credit Card Information\n#'\n#' A subset of fake customer credit card information inspired by the `{charlatan}"
  },
  {
    "path": "R/datagrid-infos.R",
    "chars": 5338,
    "preview": "\n#' @importFrom htmltools tagList tags css\ndescribe_col_char <- function(x, with_summary = TRUE) {\n  tags$div(\n    style"
  },
  {
    "path": "R/edit-data-utils.R",
    "chars": 15495,
    "preview": "\n\n#' @title Edit modal\n#'\n#' @description The `edit_modal` function generates a modal window with the variables to edit\n"
  },
  {
    "path": "R/edit-data.R",
    "chars": 18382,
    "preview": "\n\n#' @title Shiny module to interactively edit a `data.frame`\n#'\n#' @description The module generates different options "
  },
  {
    "path": "R/filter-data.R",
    "chars": 20991,
    "preview": "\n#' @title Shiny module to interactively filter a `data.frame`\n#'\n#' @description Module generate inputs to filter `data"
  },
  {
    "path": "R/i18n.R",
    "chars": 3464,
    "preview": "\n#' @title Internationalization\n#'\n#' @description Simple mechanism to translate labels in a Shiny application.\n#'\n#' @p"
  },
  {
    "path": "R/import-copypaste.R",
    "chars": 4913,
    "preview": "\n#' @title Import data with copy & paste\n#'\n#' @description Let the user copy data from Excel or text file then paste it"
  },
  {
    "path": "R/import-file.R",
    "chars": 11567,
    "preview": "\n#' @title Import data from a file\n#'\n#' @description Let user upload a file and import data\n#'\n#' @inheritParams import"
  },
  {
    "path": "R/import-globalenv.R",
    "chars": 9642,
    "preview": "\n#' @title Import data from an Environment\n#'\n#' @description Let the user select a dataset from its own environment or "
  },
  {
    "path": "R/import-googlesheets.R",
    "chars": 5439,
    "preview": "\n#' @title Import data from Googlesheet\n#'\n#' @description Let user paste link to a Google sheet then import the data.\n#"
  },
  {
    "path": "R/import-modal.R",
    "chars": 13079,
    "preview": "\n#' @title Import from all sources\n#'\n#' @description Wrap all import modules into one, can be displayed inline or in a "
  },
  {
    "path": "R/import-url.R",
    "chars": 4504,
    "preview": "#' @title Import data from a URL\n#'\n#' @description Let user paste link to a JSON then import the data.\n#'\n#' @inheritPa"
  },
  {
    "path": "R/onLoad.R",
    "chars": 181,
    "preview": "#' Shiny resource\n#'\n#' @importFrom shiny addResourcePath\n#'\n#' @noRd\n.onLoad <- function(...) {\n  shiny::addResourcePat"
  },
  {
    "path": "R/sample-data.R",
    "chars": 4109,
    "preview": "## Function sample_n()\n\n#' @title Sample rows\n#'\n#' @description The `sample_n` function returns the sample of a dataset"
  },
  {
    "path": "R/select-group.R",
    "chars": 7306,
    "preview": "#' @title Select Group Input Module\n#'\n#' @description Group of mutually dependent select menus for filtering `data.fram"
  },
  {
    "path": "R/show_data.R",
    "chars": 3670,
    "preview": "\n#' Display a table in a window\n#'\n#' @param data a data object (either a `matrix` or a `data.frame`).\n#' @param title T"
  },
  {
    "path": "R/update-factor.R",
    "chars": 7419,
    "preview": "\n#' @title Module to Reorder the Levels of a Factor Variable\n#'\n#' @description\n#' This module contain an interface to r"
  },
  {
    "path": "R/update-variables.R",
    "chars": 16806,
    "preview": "\n#' Select, rename and convert variables\n#'\n#' @param id Module id. See [shiny::moduleServer()].\n#' @param title Module'"
  },
  {
    "path": "R/utils-shiny.R",
    "chars": 5920,
    "preview": "\n#' @importFrom htmltools htmlDependency\n#' @importFrom utils packageVersion\nhtml_dependency_datamods <- function() {\n  "
  },
  {
    "path": "R/utils.R",
    "chars": 3479,
    "preview": "`%||%` <- function(x, y) {\n  if (is.null(x))\n    y\n  else x\n}\n\ndropNulls <- function(x) {\n  x[!vapply(x, is.null, FUN.VA"
  },
  {
    "path": "R/validation.R",
    "chars": 9927,
    "preview": "\n#' @title Validation module\n#'\n#' @description Check that a dataset respect some validation expectations.\n#'\n#' @param "
  },
  {
    "path": "R/zzz.R",
    "chars": 242,
    "preview": "\nutils::globalVariables(c(\n  \"%>%\", \"filter\", \"group_by\", \"label\", \"translation\",\n  \".datamods_edit_update\", \".datamods_"
  },
  {
    "path": "README.Rmd",
    "chars": 4884,
    "preview": "---\noutput: github_document\n---\n\n<!-- README.md is generated from README.Rmd. Please edit that file -->\n\n```{r, include "
  },
  {
    "path": "README.md",
    "chars": 4980,
    "preview": "\n<!-- README.md is generated from README.Rmd. Please edit that file -->\n\n# datamods\n\n> Shiny modules to import and manip"
  },
  {
    "path": "_pkgdown.yml",
    "chars": 713,
    "preview": "url: https://dreamrs.github.io/datamods\n\ntemplate:\n  bootstrap: 5\n  bootswatch: zephyr\n  bslib:\n    base_font: {google: "
  },
  {
    "path": "cran-comments.md",
    "chars": 211,
    "preview": "## Test environments\n* local R installation, R 4.4.1\n* ubuntu 22.04, Windows 10, macOS (on GitHub Actions), R 4.4.1\n* wi"
  },
  {
    "path": "data-raw/demo_edit.R",
    "chars": 575,
    "preview": "## code to prepare `demo_edit` dataset goes here\n\n#library(charlatan)\ndemo_edit <- data.frame(\n  \"name\" = ch_name(n = 20"
  },
  {
    "path": "examples/create_column.R",
    "chars": 1654,
    "preview": "\nlibrary(shiny)\nlibrary(datamods)\nlibrary(reactable)\n\nui <- fluidPage(\n  theme = bslib::bs_theme(version = 5L, preset = "
  },
  {
    "path": "examples/cut_variable.R",
    "chars": 1654,
    "preview": "\nlibrary(shiny)\nlibrary(datamods)\nlibrary(reactable)\n\nui <- fluidPage(\n  theme = bslib::bs_theme(version = 5L, preset = "
  },
  {
    "path": "examples/edit_data-callback.R",
    "chars": 3319,
    "preview": "\n# -------------------------------------------------------------------------\n# Edit data only with callbacks -----------"
  },
  {
    "path": "examples/edit_data-callback_add.R",
    "chars": 802,
    "preview": "library(shiny)\nlibrary(datamods)\nlibrary(bslib)\nlibrary(reactable)\n\nui <- fluidPage(\n  theme = bs_theme(\n    version = 5"
  },
  {
    "path": "examples/edit_data-callback_delete.R",
    "chars": 713,
    "preview": "library(shiny)\nlibrary(datamods)\nlibrary(bslib)\nlibrary(reactable)\n\nui <- fluidPage(\n  theme = bs_theme(\n    version = 5"
  },
  {
    "path": "examples/edit_data-callback_update-row_style.R",
    "chars": 1519,
    "preview": "library(shiny)\n# library(datamods)\npkgload::load_all()\nlibrary(bslib)\nlibrary(reactable)\n\nui <- fluidPage(\n  theme = bs_"
  },
  {
    "path": "examples/edit_data-callback_update.R",
    "chars": 799,
    "preview": "library(shiny)\nlibrary(datamods)\nlibrary(bslib)\nlibrary(reactable)\n\nui <- fluidPage(\n  theme = bs_theme(\n    version = 5"
  },
  {
    "path": "examples/edit_data.R",
    "chars": 2675,
    "preview": "library(shiny)\nlibrary(datamods)\nlibrary(bslib)\nlibrary(reactable)\n\nui <- fluidPage(\n  theme = bs_theme(\n    version = 5"
  },
  {
    "path": "examples/filter_data-basic.R",
    "chars": 1275,
    "preview": "library(shiny)\nlibrary(datamods)\n\n\nui <- fluidPage(\n  tags$h2(\"Filter data.frame\"),\n  fluidRow(\n    column(\n      width "
  },
  {
    "path": "examples/filter_data.R",
    "chars": 2783,
    "preview": "library(shiny)\nlibrary(shinyWidgets)\nlibrary(datamods)\nlibrary(MASS)\n\n# Add some NAs to mpg\nmtcars_na <- mtcars\nmtcars_n"
  },
  {
    "path": "examples/from-copypaste.R",
    "chars": 745,
    "preview": "\nlibrary(shiny)\nlibrary(datamods)\n\nui <- fluidPage(\n  tags$h3(\"Import data with copy & paste\"),\n  fluidRow(\n    column(\n"
  },
  {
    "path": "examples/from-file.R",
    "chars": 1431,
    "preview": "\n\nlibrary(shiny)\nlibrary(datamods)\n\nui <- fluidPage(\n  # theme = bslib::bs_theme(version = 5L),\n  # theme = bslib::bs_th"
  },
  {
    "path": "examples/from-globalenv.R",
    "chars": 1077,
    "preview": "if (interactive()) {\n  library(shiny)\n  library(datamods)\n\n  # Create some data.frames\n\n  my_df <- data.frame(\n    varia"
  },
  {
    "path": "examples/from-googlesheets.R",
    "chars": 751,
    "preview": "\nlibrary(shiny)\nlibrary(datamods)\n\nui <- fluidPage(\n  tags$h3(\"Import data from Googlesheets\"),\n  fluidRow(\n    column(\n"
  },
  {
    "path": "examples/from-url.R",
    "chars": 785,
    "preview": "\nlibrary(shiny)\nlibrary(datamods)\n\nui <- fluidPage(\n  tags$h3(\"Import data from URL\"),\n  fluidRow(\n    column(\n      wid"
  },
  {
    "path": "examples/i18n.R",
    "chars": 437,
    "preview": "library(datamods)\n\n# Use with an objet\nmy.translations <- list(\n  \"Hello\" = \"Bonjour\"\n)\ni18n(\"Hello\", my.translations)\n\n"
  },
  {
    "path": "examples/modal-validation.R",
    "chars": 2343,
    "preview": "\nlibrary(shiny)\nlibrary(datamods)\n\nif (requireNamespace(\"validate\")) {\n  library(validate)\n  # Define some rules to be a"
  },
  {
    "path": "examples/modal.R",
    "chars": 1265,
    "preview": "\nlibrary(shiny)\nlibrary(datamods)\n\nui <- fluidPage(\n  # Try with different Bootstrap version\n  theme = bslib::bs_theme(v"
  },
  {
    "path": "examples/sample.R",
    "chars": 659,
    "preview": "library(shiny)\nlibrary(datamods)\nlibrary(reactable)\n\n\nui <- fluidPage(\n\n  tags$h2(\"Sampling\"),\n\n  fluidRow(\n    column(\n"
  },
  {
    "path": "examples/select-group-default.R",
    "chars": 1305,
    "preview": "# Default -----------------------------------------------------------------\n\nlibrary(shiny)\nlibrary(datamods)\nlibrary(sh"
  },
  {
    "path": "examples/select-group-selected.R",
    "chars": 993,
    "preview": "\n\n# Selected value --------------------------------------------------------------------\n\nlibrary(shiny)\nlibrary(datamods"
  },
  {
    "path": "examples/select-group-subset.R",
    "chars": 1364,
    "preview": "\n# Subset data -------------------------------------------------------------\n\nlibrary(shiny)\nlibrary(datamods)\nlibrary(s"
  },
  {
    "path": "examples/select-group-vars.R",
    "chars": 1350,
    "preview": "\n# Select variables --------------------------------------------------------\n\nlibrary(shiny)\nlibrary(datamods)\nlibrary(s"
  },
  {
    "path": "examples/show_data.R",
    "chars": 1277,
    "preview": "\nlibrary(shiny)\nlibrary(datamods)\n\nui <- fluidPage(\n  theme = bslib::bs_theme(version = 5L),\n  shinyWidgets::html_depend"
  },
  {
    "path": "examples/update_factor.R",
    "chars": 1860,
    "preview": "\nlibrary(shiny)\nlibrary(datamods)\nlibrary(ggplot2)\n\nui <- fluidPage(\n  theme = bslib::bs_theme(version = 5L, preset = \"b"
  },
  {
    "path": "examples/validation.R",
    "chars": 2146,
    "preview": "library(datamods)\nlibrary(shiny)\n\nif (requireNamespace(\"validate\")) {\n  library(validate)\n\n  # Define some rules to be a"
  },
  {
    "path": "examples/variables.R",
    "chars": 1396,
    "preview": "\nlibrary(shiny)\nlibrary(datamods)\n\ntestdata <- data.frame(\n  date_as_char = as.character(Sys.Date() + 0:9),\n  date_as_nu"
  },
  {
    "path": "inst/assets/css/datamods.css",
    "chars": 1753,
    "preview": "/*!\n * Copyright (c) 2020 dreamRs\n *\n * datamods, CSS styles\n * https://github.com/dreamRs/datamods\n *\n * @version 0.0.1"
  },
  {
    "path": "inst/assets/js/datamods.js",
    "chars": 2447,
    "preview": "/*!\n * Copyright (c) 2020 dreamRs\n *\n * datamods, JavaScript utilities\n * https://github.com/dreamRs/datamods\n *\n * @ver"
  },
  {
    "path": "inst/extdata/mtcars.csv",
    "chars": 1281,
    "preview": "mpg,cyl,disp,hp,drat,wt,qsec,vs,am,gear,carb\n21,6,160,110,3.9,2.62,16.46,0,1,4,4\n21,6,160,110,3.9,2.875,17.02,0,1,4,4\n22"
  },
  {
    "path": "inst/extdata/mtcars.json",
    "chars": 4147,
    "preview": "[{\"mpg\":21,\"cyl\":6,\"disp\":160,\"hp\":110,\"drat\":3.9,\"wt\":2.62,\"qsec\":16.46,\"vs\":0,\"am\":1,\"gear\":4,\"carb\":4,\"_row\":\"Mazda R"
  },
  {
    "path": "inst/extdata/mtcars_fr.csv",
    "chars": 1375,
    "preview": "mpg;cyl;disp;hp;drat;wt;qsec;vs;am;gear;carb\n21,0;6;160,0;110;3,90;2,620;16,46;0;1;4;4\n21,0;6;160,0;110;3,90;2,875;17,02"
  },
  {
    "path": "inst/extdata/pop-fra-dep.txt",
    "chars": 5948,
    "preview": "Code région\tNom de la région\tCode département\tNom du département\tNombre d'arrondissements\tNombre de cantons\tNombre de co"
  },
  {
    "path": "inst/extdata/rules.yaml",
    "chars": 642,
    "preview": "rules:\n- expr: speed >= 0\n  name: 'speed'\n  label: 'speed positivity'\n  description: |\n    speed can not be negative\n  c"
  },
  {
    "path": "inst/i18n/al.csv",
    "chars": 9643,
    "preview": "\"label\",\"translation\",\"comment\"\n\"% of the total\",\"% e totalit\",\"Automatically translated\"\n\"% of the total, i.e.\",\"% e to"
  },
  {
    "path": "inst/i18n/cn.csv",
    "chars": 6974,
    "preview": "\"label\",\"translation\",\"comment\"\n\"% of the total\",\"鍗犳€绘暟鐨�%\",\"Automatically translated\"\n\"% of the total, i.e.\",\"鍗犳€绘暟鐨�%锛"
  },
  {
    "path": "inst/i18n/de.csv",
    "chars": 9715,
    "preview": "\"label\",\"translation\",\"comment\"\n\"% of the total\",\"% von allen\",\"Automatically translated\"\n\"% of the total, i.e.\",\"% der "
  },
  {
    "path": "inst/i18n/es.csv",
    "chars": 9778,
    "preview": "\"label\",\"translation\",\"comment\"\n\"% of the total\",\"% del total\",\"Automatically translated\"\n\"% of the total, i.e.\",\"% del "
  },
  {
    "path": "inst/i18n/extract_labels.R",
    "chars": 3406,
    "preview": "#' Function to extract labels\n#'\n#' @param folder file directory\n#'\n#' @return an extraction of the labels contained in "
  },
  {
    "path": "inst/i18n/fr.csv",
    "chars": 9691,
    "preview": "\"label\",\"translation\",\"comment\"\n\"% of the total\",\"% du total\",\"Automatically translated\"\n\"% of the total, i.e.\",\"% du to"
  },
  {
    "path": "inst/i18n/it.csv",
    "chars": 9530,
    "preview": "\"label\",\"translation\",\"comment\"\n\"% of the total\",\"% del totale\",\"Automatically translated\"\n\"% of the total, i.e.\",\"% del"
  },
  {
    "path": "inst/i18n/ja.csv",
    "chars": 3596,
    "preview": "label,translation,comment\n\"Import a dataset from an environment\",\"Global environment からデータセットをインポート\"\n\"Select a data.fram"
  },
  {
    "path": "inst/i18n/kr.csv",
    "chars": 7822,
    "preview": "\"label\",\"translation\",\"comment\"\n\"% of the total\",\"�꾩껜�� %\",\"Automatically translated\"\n\"% of the total, i.e.\",\"�꾩껜�� %, 利"
  },
  {
    "path": "inst/i18n/maj_csv.R",
    "chars": 2424,
    "preview": "\nlibrary(data.table)\nlibrary(stringr)\nlibrary(utils)\nlibrary(polyglotr)\n\nsource(\"inst/i18n/extract_labels.R\")\n\n\n# Extrac"
  },
  {
    "path": "inst/i18n/mk.csv",
    "chars": 9520,
    "preview": "\"label\",\"translation\",\"comment\"\n\"% of the total\",\"% од вкупниот број\",\"Automatically translated\"\n\"% of the total, i.e.\","
  },
  {
    "path": "inst/i18n/pl.csv",
    "chars": 9181,
    "preview": "\"label\",\"translation\",\"comment\"\n\"% of the total\",\"% całkowitej\",\"Automatically translated\"\n\"% of the total, i.e.\",\"% cał"
  },
  {
    "path": "inst/i18n/pt.csv",
    "chars": 9453,
    "preview": "\"label\",\"translation\",\"comment\"\n\"% of the total\",\"% do total\",\"Automatically translated\"\n\"% of the total, i.e.\",\"% do to"
  },
  {
    "path": "inst/i18n/tr.csv",
    "chars": 8994,
    "preview": "\"label\",\"translation\",\"comment\"\n\"% of the total\",\"toplamın yüzdesi\",\"Automatically translated\"\n\"% of the total, i.e.\",\"T"
  },
  {
    "path": "man/create-column.Rd",
    "chars": 4928,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/create-column.R, R/update-factor.R\n\\name{c"
  },
  {
    "path": "man/cut-variable.Rd",
    "chars": 3664,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/cut-variable.R\n\\name{cut-variable}\n\\alias{"
  },
  {
    "path": "man/demo_edit.Rd",
    "chars": 746,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/data.R\n\\docType{data}\n\\name{demo_edit}\n\\al"
  },
  {
    "path": "man/edit-data.Rd",
    "chars": 6863,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/edit-data.R\n\\name{edit-data}\n\\alias{edit-d"
  },
  {
    "path": "man/filter-data.Rd",
    "chars": 5980,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/filter-data.R\n\\name{filter-data}\n\\alias{fi"
  },
  {
    "path": "man/get_data_packages.Rd",
    "chars": 375,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/import-globalenv.R\n\\name{get_data_packages"
  },
  {
    "path": "man/i18n.Rd",
    "chars": 1870,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/i18n.R\n\\name{i18n}\n\\alias{i18n}\n\\alias{i18"
  },
  {
    "path": "man/import-copypaste.Rd",
    "chars": 2854,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/import-copypaste.R\n\\name{import-copypaste}"
  },
  {
    "path": "man/import-file.Rd",
    "chars": 4279,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/import-file.R\n\\name{import-file}\n\\alias{im"
  },
  {
    "path": "man/import-globalenv.Rd",
    "chars": 3088,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/import-globalenv.R\n\\name{import-globalenv}"
  },
  {
    "path": "man/import-googlesheets.Rd",
    "chars": 2574,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/import-googlesheets.R\n\\name{import-googles"
  },
  {
    "path": "man/import-modal.Rd",
    "chars": 4017,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/import-modal.R\n\\name{import-modal}\n\\alias{"
  },
  {
    "path": "man/import-url.Rd",
    "chars": 2531,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/import-url.R\n\\name{import-url}\n\\alias{impo"
  },
  {
    "path": "man/list_pkg_data.Rd",
    "chars": 422,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/import-globalenv.R\n\\name{list_pkg_data}\n\\a"
  },
  {
    "path": "man/module-sample.Rd",
    "chars": 1414,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/sample-data.R\n\\name{module-sample}\n\\alias{"
  },
  {
    "path": "man/select-group.Rd",
    "chars": 4361,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/select-group.R\n\\name{select-group}\n\\alias{"
  },
  {
    "path": "man/show_data.Rd",
    "chars": 2724,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/show_data.R\n\\name{show_data}\n\\alias{show_d"
  },
  {
    "path": "man/update-factor.Rd",
    "chars": 3532,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/update-factor.R\n\\name{update-factor}\n\\alia"
  },
  {
    "path": "man/update-variables.Rd",
    "chars": 2429,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/update-variables.R\n\\name{update-variables}"
  },
  {
    "path": "man/validation.Rd",
    "chars": 4153,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/validation.R\n\\name{validation_ui}\n\\alias{v"
  },
  {
    "path": "man-roxygen/module-import.R",
    "chars": 369,
    "preview": "#' @return\n#' * UI: HTML tags that can be included in shiny's UI\n#' * Server: a `list` with three slots:\n#'   + **status"
  },
  {
    "path": "tests/testthat/test-edit-data.R",
    "chars": 1546,
    "preview": "\ntest_that(\"edit_data_ui works\", {\n  expect_is(edit_data_ui(\"ID\"), \"shiny.tag.list\")\n})\n\n\ntest_that(\"table_display works"
  },
  {
    "path": "tests/testthat/test-filter-data.R",
    "chars": 3524,
    "preview": "\ntest_that(\"filter_data_ui works\", {\n  expect_is(filter_data_ui(\"ID\"), \"shiny.tag.list\")\n})\n\n\ntest_that(\"create_filters "
  },
  {
    "path": "tests/testthat/test-i18n.R",
    "chars": 1994,
    "preview": "test_that(\"i18n works if option not set\", {\n  options(\"datamods.i18n\" = NULL)\n  label <- \"something\"\n  expect_identical("
  },
  {
    "path": "tests/testthat/test-import-copypaste.R",
    "chars": 463,
    "preview": "test_that(\"import_copypaste_ui works\", {\n  expect_is(import_copypaste_ui(\"ID\"), \"shiny.tag\")\n})\n\ntest_that(\"import_copyp"
  },
  {
    "path": "tests/testthat/test-import-file.R",
    "chars": 642,
    "preview": "test_that(\"import_file_ui works\", {\n  expect_is(import_file_ui(\"ID\"), \"shiny.tag\")\n})\n\ntest_that(\"import_file_server wor"
  },
  {
    "path": "tests/testthat/test-import-globalenv.R",
    "chars": 1232,
    "preview": "test_that(\"import_globalenv_ui works\", {\n  expect_is(import_globalenv_ui(\"ID\"), \"shiny.tag\")\n})\n\ntest_that(\"import_globa"
  },
  {
    "path": "tests/testthat/test-import-googlesheets.R",
    "chars": 596,
    "preview": "test_that(\"import_googlesheets_ui works\", {\n  expect_is(import_googlesheets_ui(\"ID\"), \"shiny.tag\")\n})\n\ntest_that(\"import"
  },
  {
    "path": "tests/testthat/test-import-modal.R",
    "chars": 446,
    "preview": "test_that(\"import_ui works\", {\n  expect_is(import_ui(\"ID\"), \"shiny.tag\")\n})\n\ntest_that(\"import_server works\", {\n  shiny:"
  },
  {
    "path": "tests/testthat/test-import-url.R",
    "chars": 1443,
    "preview": "test_that(\"import_url_ui works\", {\n  expect_is(import_url_ui(\"ID\"), \"shiny.tag\")\n})\n\ntest_that(\"import_url_server works "
  },
  {
    "path": "tests/testthat/test-onLoad.R",
    "chars": 113,
    "preview": "test_that(\"onLoad works\", {\n  .onLoad()\n  x <- shiny::resourcePaths()\n  expect_true(\"datamods\" %in% names(x))\n})\n"
  },
  {
    "path": "tests/testthat/test-update-variables.R",
    "chars": 3552,
    "preview": "test_that(\"update_variables_ui works\", {\n  expect_is(update_variables_ui(\"ID\"), \"shiny.tag\")\n})\n\n\n# test_that(\"update_va"
  },
  {
    "path": "tests/testthat/test-validation.R",
    "chars": 633,
    "preview": "test_that(\"validation_ui works\", {\n  expect_is(validation_ui(\"ID\"), \"shiny.tag.list\")\n  expect_is(validation_ui(\"ID\", di"
  },
  {
    "path": "tests/testthat.R",
    "chars": 60,
    "preview": "library(testthat)\nlibrary(datamods)\n\ntest_check(\"datamods\")\n"
  },
  {
    "path": "vignettes/.gitignore",
    "chars": 11,
    "preview": "*.html\n*.R\n"
  },
  {
    "path": "vignettes/datamods.Rmd",
    "chars": 7773,
    "preview": "---\ntitle: \"Getting started with datamods\"\noutput: rmarkdown::html_vignette\nvignette: >\n  %\\VignetteIndexEntry{Getting s"
  },
  {
    "path": "vignettes/i18n.Rmd",
    "chars": 3674,
    "preview": "---\ntitle: \"Internationalization\"\noutput: rmarkdown::html_vignette\nvignette: >\n  %\\VignetteIndexEntry{Internationalizati"
  }
]

// ... and 2 more files (download for full content)

About this extraction

This page contains the full source code of the dreamRs/datamods GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 126 files (502.5 KB), approximately 140.5k tokens, and a symbol index with 4 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!