3.0.1 • Published 5 months ago

@cwrc/leafwriter-storage-service v3.0.1

Weekly downloads
-
License
GPL-2.0
Repository
gitlab
Last release
5 months ago

LEAF-Writer Storage Service

NPM version npm type definitions

Table of Contents

Overview

This is React File Storage component for listing, loading, and saving files from and to the local computer and Git hosting (GitHub and Gitlab). It was built to be used in conjunction with LEAF-Writer-Commons, but it is general enough to be freely used anywhere.

The Load Dialog supports pasting from the clipboard, selecting files from the local computer, dragging & drop a file directly to the UI, and load from an URL or Git provider (GitHub | Gitlab). On the git provider, users can access their own repositories, shared repositories, repositories owned by organizations/groups, and search public repositories. Git repositories are limited to the default branch (usually 'master' or 'main'). There are also search functionalities by file name and within files' content.

The Save Dialog supports downloading to the local computer and saving to Git hosting. On the git hoster, users can create new repositories and new folders and create and overwrite files. Optionally, users can make Pull Requests, saving the file into a different branch. If the user does not have written permission to a repository, they can Fork the repository and make a Pull Request to the original repository.

Extra features:

  • Bypass the dialog UI with a streamlined function to save/load resources.
  • Pass validation function before load.
  • Define a commit message.
  • Show/hide invisible files.
  • Restrict files by MIME type.
  • Responsive: Adapts to large displays and mobile devices.
  • Dark mode: light and dark themes.
  • Localized: English and French.

  • Fully typed with Typescript.

Demo

The LEAF-Writer Commons is running an instance of LEAF-Writer that uses the NPM package published from this repository.

Use

Install

npm i @cwrc/leafwriter-storage-service

Basic Examples

Load Dialog

import { useState } from  'react';
import { StorageDialog } from '@cwrc/leafwriter-storage-service/dialog';

export  const  MyFStorageDialog  = () => {
 const [open, setOpen] =  useState(true);

 const  handleClose  = () =>  setOpen(false);
 const  handleLoad  = () =>  setOpen(false);

 return (
    <StorageDialog
      onCancel={close}
      onLoad={handleLoad}
      open={open}
      type="load"
    />
  );
};

If the property type is not defined, the component displays the Load Dialog. Property open controls the component visibility; onCancel is triggered by the cancel button; onLoad is triggered by the load button.

Save Dialog

import { useState } from 'react';
import { StorageDialog } from '@cwrc/leafwriter-storage-service/dialog';

export const MyFStorageDialog = () => {
  const [open, setOpen] = useState(true);

  const handleClose = () => setOpen(false);
  const handleSave = () => setOpen(false);

  return (
    <StorageDialog
      onCancel={close}
      onSave={handleSave}
      open={open}
      type="save"
    />
  );
};

Property open controls the component visibility; onCancel is triggered by the cancel button; onSave is triggered by the load button.

Full Feature Examples

Load Dialog

import { useState } from 'react';
import { StorageDialog, type Resource } from '@cwrc/leafwriter-storage-service/dialog';

export const MyFStorageDialog = () => {
  const [open, setOpen] = useState(true);

  const handleBackdropClick = () => {
    //do something
    setOpen(false);
  }

  const handleClose = () => {
    //do something
    setOpen(false);
  }

  const handleChange = (resource?: Resource) => {
    //do something with the resource currrent state (e.g., update URL)
  };

  const handleLoad = (resource: Resource) => {
    //do something with the resource loaded
    setOpen(false);
  }

  const handleValidation = (content: string):boolean => {
    //validate content and return true or false.
  };

  return (
    <StorageDialog
      config={{
        allowedMimeTypes: ['application/xml'],
        allowLocalFiles: true,
        allowUrl: true,
        allowPaste: true,
        language: 'en-CA',
        preferProvider: 'github',
        providers: [
          { name: 'github', access_token: '{github_token}' },
          { name: 'gitlab', access_token: '{github_token}' }
        ],
        showInvisibleFiles: true,
        validate: handleValidation,
      }}
      headerLabel="Custom header"
      onBackdropClick={clickAway}
      onCancel={close}
      onChange={handleOnChange}
      onLoad={handleLoad}
      resource={
        storageSource: 'cloud | url | local | paste'
        provider: 'github | gitlab',
        owner: 'username | userid',
        ownerType: 'user',
        repo: 'repository-name| repository-id',
        path: 'path/to/documents',
        writePermission: true,
      }
      open={open}
      source="cloud"
    />
  );
};

See the API section for more details.

Save Dialog

import { useState } from 'react';
import { StorageDialog, type Resource } from '@cwrc/leafwriter-storage-service/dialog';

export const MyFStorageDialog = () => {
  const [open, setOpen] = useState(true);

  const handleClose = () => {
    //do something
    setOpen(false);
  }

  const handleSave = (Resource: Resource) => {
    //do something
    setOpen(false);
  }

  return (
    <StorageDialog
      config={{
        allowedMimeTypes: ['application/xml'],
        defaultCommitMessage: 'Updated via leaf-writer',
        language: 'en-CA',
        preferProvider: 'github_or_gitlab',
        providers: [
          { name: 'github', access_token: '{github_token}' },
          { name: 'gitlab', access_token: '{github_token}' }
        ],
        showInvisibleFiles: true,
      }}
      headerLabel="Custom header"
      onCancel={close}
      onSave={handleSave}
      resource={
        storageSource: 'cloud | local'
        provider: 'github | gitlab',
        owner: 'username | userid',
        ownerType: 'user',
        repo: 'repository-name | repository-id',
        path: 'path/to/documents';
        filename: 'filename',
        content: 'the content of the decument',
        hash: 'sha',
      }
      open={open}
      source="cloud"
    />
  );
};

See the API section for more details.

React Suspense

You can use React suspense to optimize your code. The module will only be loaded when the Dialog is triggered for the first time.

Example:

import { Suspense lazy, useState } from  'react';
const { StorageDialog } = lazy(() => import('@cwrc/leafwriter-storage-service/dialog'));

export  const  MyFStorageDialog = () => {
 const [open, setOpen] = useState(true);

 const handleClose = () =>  setOpen(false);
 const handleLoad = () =>  setOpen(false);

 return (
    <>
      { open === true && (
        <Suspense fallback={<Progress />}>
          <StorageDialog
            onCancel={close}
            onLoad={handleLoad}
            open={open}
            type="load"
          />
        </Suspense>
      )}
    </>
  );
};

Bypass the Dialog with handy functions

loadDocument

Use this function to load a document from a git provider without opening the dialog. You must pass the provider authorization and the resource location.

The function returns the resource with the content and its hash.

import { loadDocument, type Resource } from '@cwrc/leafwriter-storage-service/headless';

const providerAuth = {
  name: 'github',
  access_token: 'token'
}

const resource: Resource = {
  provider: 'github',
  owner: 'username',
  ownerType: 'user',
  repo: 'repository-name',
  path: 'path/to/documents';
  filename: 'filename'
}

const document: Resource = await loadDocument(providerAuth, resource);

saveDocument

Use this function to save a document to a git provider without opening the dialog. You must pass the provider authorization and the resource object, including the location, filename, and content.

By default, the function will not overwrite any file. To overwrite, you must pass a third argument, true and provide the hash for the file in the resource object.

The function returns the resource with the content and a new hash.

import { saveDocument, type Resource } from '@cwrc/leafwriter-storage-service/headless';

const providerAuth = {
  name: 'github',
  access_token: 'token'
}

const document: Resource = {
  provider: 'github',
  owner: 'username',
  ownerType: 'user',
  repo: 'repository-name',
  path: 'path/to/documents';
  filename: 'filename',
  content: 'the content of the decument',
}

//creates a new document
const savedDocument: Resource = await saveDocument(providerAuth, resource);

//updates the same document
const overwrittenDocument: Resource = await saveDocument(providerAuth, savedDocument, true);

API

Since Leaf writer Storage Service is written in Typescript, you will get suggestions through IntelliSense.

Dialog props

NameTypeDefaultDescription
open*booleanfalseDisplay / hide dialog
configStorageDialogConfigA collection of configuration (see bellow).
headerLabelstringDialog's custom header. Ex: instead of load you can pass any string, such as load document.
onBackdropClickfunctionCallback fired when the backdrop is clicked.Save dialog ignores this property since it does not allow for onBackdropClick.
onCancelfunctionCallback fired when the Cancel button is clicked.
onChangefunctionLoad dialog: Callback fired when there is any change on the resource source (cloud, local, paste, url), on the resource url when the source is url, or on the resource path (owner, repository, folder path) when the source is cloud. Save dialog ignores this property. Signature: function(resource?: Resource) => void See more about Resource below.
onLoadfunctionLoad dialog: Callback fired when the Load button is clicked. Save dialog ignores this property. Signature: function(resource: Resource) => void. See more about Resource below.
onSavefunctionSave dialog: Callback fired when the Save button is clicked. Load dialog ignore this property. Signature: function(resource: Resource) => void. See more about Resource below.
resourceResource | stringThe resource information, which might include the document's content to be saved. Load Dialog navigates directly to a specific location. If it is a string, displays paste source panel when open. Save Dialog navigates directly to a specific location, transport the document's content. See more about Resource type bellow.
source'cloud' | 'local' | 'paste''local'The storage source panel to be display when dialog opens. If providers is defined in the configurations, the dialog opens with the cloud source panel.
type'load' | 'save''load'The dialog type to be open.

StorageDialogConfig

NameTypeDefaultDescription
allowedMimeTypesArray MIMEType[]Restrict the file types allowed. Empty array means no restriction. MIME type suported: 'application/json', 'application/pdf', 'application/xml', 'text/csv', 'text/html', 'text/plain'.
allowLocalFilesbooleantrueLoad dialog: Allows loading files from local device.
allowPastebooleantrueLoad dialog: Allows paste from clipboard.
allowUrlbooleantrueLoad dialog: Allows load from URL.
defaultCommitMessagestring'update'Save Dialog: Defines the default commit message.
languagestringLocalize the UI and the messages. Must be valid and supported language code. E.g., en-CA
providersArray ProviderAuth[]Setup Github / Gitlab providers. ProviderAuth: {name: 'github' | 'gitlab', access_token: 'string}
preferProviderstringThe preferred git host provider: 'github' | 'gitlab'
showInvisibleFilesbooleanfalseShow/hide invisible files (files starting with '.')
validatefunctionFunction fired after the content is fetched but before passed to onLoad funcion. Signature: function(content: string) => { valid: boolean; error?: string };

Resource

NameTypeDefaultDescription
storageSourcecloud | local | paste | urlThe resource's source.
urlstringThe resource's url. Only for sourceStorage url or cloud.
providerstring'github', 'gitlab', or empty if not from the git repository. Only for sourceStorage cloud.
ownerstringGithub username or Gitlab: user id. Only for sourceStorage cloud.
ownerTypestring'user' or 'org'. Gitlab groups are used here as 'org' notation. Only for sourceStorage cloud.
repostringGithub repository name. Gitlab repository id. Only for sourceStorage cloud.
branchstringThe repository's brach. It uses the repository's default branch, usually main or master. Only for sourceStorage cloud.
pathstringFolder structure. e.g., 'path/to/file'. Only for sourceStorage cloud.
filenamestringThe file name.
contentstringThe document content. Only for sourceStorage cloud.
hashstringThe Commit hash. On Github, it is the SHA value. On Gitlab, it is the lastCommitId. If present, the dialog alerts the user that the content will be overwritten. Only for sourceStorage cloud.
writePermissionbooleanIndicates if the loged user has write permission for the repository. Default: undefined for owned repositories. Only for sourceStorage cloud.

Development

This component is part of a leaf writer monorepo. Refer to LEAF-Writer Dev Docs for the project's bigger picture.

We use Material UI (@mui/material) to build the visual elements, @octokit/rest and axios to fetch data from and to Github and Gitlab, overmind to control react state, and i18next for localization.

This component is written in Typescript and bundled with Webpack.

We use Jest for testing.

3.0.1

5 months ago

2.2.1

6 months ago

2.1.2

10 months ago

2.2.0

6 months ago

3.0.0-alpha.1

6 months ago

2.2.2

6 months ago

2.1.3

9 months ago

3.0.0-alpha.3

6 months ago

3.0.0-alpha.2

6 months ago

3.0.0-alpha.5

6 months ago

3.0.0-alpha.4

6 months ago

2.2.0-alpha.1

6 months ago

3.0.0

6 months ago

2.1.1

1 year ago

2.1.0

1 year ago

2.0.0

1 year ago

1.4.0

1 year ago

1.3.9

1 year ago

1.3.8

1 year ago

1.3.7

1 year ago

1.3.6

1 year ago

1.3.5

1 year ago

1.3.4

1 year ago

1.3.3

1 year ago

1.3.2

1 year ago

1.3.1

2 years ago

1.3.0

2 years ago

1.2.0

2 years ago

1.1.1

2 years ago

1.1.2

2 years ago

1.1.0

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

0.3.2

2 years ago

0.3.0

2 years ago

0.3.1

2 years ago

0.2.9

2 years ago

0.2.7

2 years ago

0.2.6

2 years ago

0.2.8

2 years ago

0.2.3

2 years ago

0.2.2

2 years ago

0.2.5

2 years ago

0.2.4

2 years ago

0.2.1

2 years ago

0.2.0

2 years ago

0.1.2

2 years ago