Skip to content

Latest commit

 

History

History
1313 lines (788 loc) · 37.7 KB

api.md

File metadata and controls

1313 lines (788 loc) · 37.7 KB

Table of Contents

ProjectFile

A project file fetched from TERA

id

A UUID string representing the unique ID of the file

Type: String

name

Relative name path (can contain prefix directories) for the human readable file name

Type: String

icon

CSS class to use as the file icon

Type: String

path

Full path to the file This is also used as the unique identifier within the project

Type: String

url

Fully qualified URL to view / access / download the file from TERA This will usually open an edit UI within the TERA site

Type: String

teraUrl

Rewrite of the URL where the absolute URL has been removed in place of a relative path, assuming the owner project is active This is used to direct to the edit/view/download UI when the files project is active and is usually used in place of URL for TERA related operations

Type: String

parsedName

An object representing meta file parts of a file name

Type: Object

Properties

  • basename String The filename + extention (i.e. everything without directory name)
  • filename String The file portion of the name (basename without the extension)
  • ext String The extension portion of the name (always lower case)
  • dirName String The directory path portion of the name

created

A date representing when the file was created

Type: Date

createdFormatted

A human readable, formatted version of "created"

Type: String

modified

A date representing when the file was created

Type: Date

modifiedFormatted

A human readable, formatted version of "modified"

Type: String

accessed

A date representing when the file was last accessed

Type: Date

accessedFormatted

A human readable, formatted version of "accessed"

Type: String

size

Size, in bytes, of the file

Type: Number

sizeFormatted

A human readable, formatted version of the file size

Type: String

mime

The associated mime type for the file

Type: String

meta

Additional meta information for the file

Type: Object

getContents

  • See: getProjectFile()

Fetch the raw file contents as a Blob

returns {Blob} The eventual raw file contents as a Blob

setContents

  • See: setProjectFile()

Overwrite the contents of a file with new content

Parameters

Returns Promise A promise which resolves when the operation has completed

getRefs

  • See: getProjectLibrary()

Fetch the file contents as an array of Reflib refs

Returns Promise<Array<Ref>> An eventual array of RefLib references

setRefs

  • See: setProjectLibrary()

Overwrite the contents of a file with a new collection of Reflib refs

Parameters

  • refs
  • Collection Array<RefLibRef> of references for the selected library

Returns Promise A promise which resolves when the operation has completed

serialize

Compress a file state down into a serializable entity By default this computes a Structured Clone which can be stringified

Returns Object A Structured Clone compatible representation of this ProjectFile instance

deserialize

Restore an entity created with serialize

Parameters

  • data Object An input object created via ProjectFiles.serialize()

Returns ProjectFile A ProjectFile instance setup against the deserializzed data

TeraFy

Main Tera-Fy Client (class singleton) to be used in a frontend browser

settings

Various settings to configure behaviour

Type: Object

Properties

  • devMode Boolean Operate in devMode - i.e. force outer refresh when encountering an existing TeraFy instance
  • verbosity Number Verbosity level, the higher the more chatty TeraFY will be. Set to zero to disable all debug() call output
  • mode ("detect" | "parent" | "child" | "popup") How to communicate with TERA. 'parent' assumes that the parent of the current document is TERA, 'child' spawns an iFrame and uses TERA there, 'detect' tries parent and switches to modeFallback if communication fails
  • modeFallback String Method to use when all method detection fails
  • modeTimeout Number How long entities have in 'detect' mode to identify themselves
  • siteUrl String The TERA URL to connect to
  • restrictOrigin String URL to restrict communications to
  • List Array<String> of sandbox allowables for the embedded if in embed mode
  • handshakeInterval Number Interval in milliseconds when sanning for a handshake

events

Event emitter subscription endpoint

Type: Mitt

dom

DOMElements for this TeraFy instance

Type: Object

Properties

  • el DOMElement The main tera-fy div wrapper
  • iframe DOMElement The internal iFrame element (if settings.mode == 'child')
  • popup Window The popup window context (if settings.mode == 'popup')
  • stylesheet DOMElement The corresponding stylesheet

methods

List of function stubs mapped from the server to here This array is forms the reference of TeraFy.METHOD() objects to provide locally which will be mapped via TeraFy.rpc(METHOD, ...args)

Type: Array<String>

plugins

Loaded plugins via Use()

Type: Array<TeraFyPlugin>

send

Send a message + wait for a response object

Parameters

  • message Object Message object to send

Returns Promise<any> A promise which resolves when the operation has completed with the remote reply

sendRaw

Send raw message content to the server This function does not return or wait for a reply - use send() for that

Parameters

  • message Object Message object to send

rpc

Call an RPC function in the server instance

Parameters

  • method String The method name to call
  • args ...any

Returns Promise<any> The resolved output of the server function

acceptMessage

Accept an incoming message

Parameters

acceptPostboxes

Listening postboxes, these correspond to outgoing message IDs that expect a response

createProjectStatePatch

Create + transmit a new project state patch base on the current and previous states The transmitted patch follows the JSPatch standard This function accepts an entire projectState instance, computes the delta and transmits that to the server for merging

Parameters

  • newState Object The local projectState to accept
  • oldState Object The previous projectState to examine against

Returns Promise A promise which will resolve when the operation has completed

applyProjectStatePatchLocal

Client function which accepts a patch from the server and applies it to local project state The patch should follow the JSPatch standard This function is expected to be sub-classed by a plugin

Parameters

  • patch Array A JSPatch patch to apply

Returns Promise A promise which will resolve when the operation has completed

init

Initalize the TERA client singleton This function can only be called once and will return the existing init() worker Promise if its called againt

Parameters

  • options Object? Additional options to merge into settings via set

Returns Promise<TeraFy> An eventual promise which will resovle with this terafy instance

detectMode

Populate settings.mode Try to communicate with a parent frame, if none assume we need to fallback to child mode

Returns Promise<String> A promise which will resolve with the detected mode to use

injectComms

Find an existing active TERA server OR initalize one

Returns Promise A promise which will resolve when the loading has completed and we have found a parent TERA instance or initiallized a child

injectStylesheet

Inject a local stylesheet to handle TERA server functionality

Returns Promise A promise which will resolve when the loading has completed and we have found a parent TERA instance or initiallized a child

injectMethods

Inject all server methods defined in methods as local functions wrapped in the rpc function

debug

Debugging output function This function will only act if settings.devMode is truthy

Parameters

  • msg ...any
  • method ("INFO" | "LOG" | "WARN" | "ERROR") Logging method to use (optional, default 'LOG')
  • verboseLevel Number The verbosity level to trigger at. If settings.verbosity is lower than this, the message is ignored (optional, default 1)

set

Set or merge settings This function also routes 'special' keys like devMode to their internal handlers

Parameters

  • key (String | Object) Either a single setting key to set or an object to merge

  • value any The value to set if key is a string

  • options Object? Additional options to mutate behaviour

    • options.ignoreNullish Boolean If falsy, this forces the setting of undefined or null values rather than ignoring them when specifying values by string (optional, default true)

Returns TeraFy This chainable terafy instance

setIfDev

  • See: set()

Set or merge settings - but only in dev mode and only if the value is not undefined

Parameters

  • key (String | Object) Either a single setting key to set or an object to merge
  • value any The value to set if key is a string
  • options Object? Additional options to mutate behaviour

Returns TeraFy This chainable terafy instance

use

Include a TeraFy client plugin

Parameters

  • mod
  • options Object? Additional options to mutate behaviour during construction (pass options to init() to intialize later options)
  • The Object module function to include. Invoked as (teraClient:TeraFy, options:Object)

Returns TeraFy This chainable terafy instance

mixin

Internal function used by use() to merge an external declared singleton against this object

Parameters

  • target Object Initalied class instance to extend
  • source Object Initalized source object to extend from

toggleDevMode

Set or toggle devMode This function also accepts meta values:

'toggle' - Set dev mode to whatever the opposing value of the current mode
'proxy'  - Optimize for using a loopback proxy

Parameters

  • devModeEnabled ("toggle" | "proxy" | Boolean) Optional boolean to force dev mode or specify other behaviour (optional, default 'toggle')

Returns TeraFy This chainable terafy instance

toggleFocus

Fit the nested TERA server to a full-screen This is usually because the server component wants to perform some user activity like calling $prompt

Parameters

  • isFocused (String | Boolean) Whether to fullscreen the embedded component (optional, default 'toggle')

selectProjectFile

Require a user login to TERA If there is no user OR they are not logged in a prompt is shown to go and do so This is an pre-requisite step for requireProject()

Parameters

  • options

Returns Promise A promise which will resolve if the there is a user and they are logged in

getProjectFiles

Fetch the files associated with a given project

Parameters

  • options Object Options which mutate behaviour

    • options.autoRequire Boolean Run requireProject() automatically before continuing (optional, default true)
    • options.lazy Boolean If true, use the fastest method to retrieve the file list such as the cache. If false, force a refresh each time (optional, default true)
    • options.meta Boolean Pull meta information for each file entity (optional, default true)

Returns Promise<Array<ProjectFile>> A collection of project files for the given project

getProjectFile

Fetch a project file by its name

Parameters

  • id

  • name String The name + relative directory path component

  • options (Object | String)? Additional options to mutate behaviour, if a string is given options.subkey is assumed

    • options.subkey String? If specified only the extracted subkey is returned rather than the full object
    • options.cache Boolean Use the existing file cache if possible, set to false to force a refresh of files from the server first (optional, default true)

Returns Promise<ProjectFile> The eventual fetched ProjectFile (or requested subkey)

createProjectFile

Create a new file This creates an empty file which can then be written to

Parameters

  • name String The name + relative directory path component

Returns Promise<ProjectFile> The eventual ProjectFile created

handshake

Return basic server information as a form of validation

Properties

  • date Date Server date

Returns Promise<Object> Basic promise result

setServerVerbosity

RPC callback to set the server verbostiy level

Parameters

  • verbosity Number The desired server verbosity level

User

User / active session within TERA

Properties

  • id String Unique identifier of the user
  • email String The email address of the current user
  • name String The provided full name of the user
  • isSubscribed Boolean Whether the active user has a TERA subscription

getUser

Fetch the current session user

Returns Promise<User> The current logged in user or null if none

requireUser

Require a user login to TERA If there is no user OR they are not logged in a prompt is shown to go and do so This is an pre-requisite step for requireProject()

Parameters

  • options Object? Additional options to mutate behaviour

    • options.forceRetry Boolean Forcabily try to refresh the user state (optional, default false)

Returns Promise<User> The current logged in user or null if none

Project

Project entry within TERA

getProject

Get the currently active project, if any

Returns Promise<(Project | null)> The currently active project, if any

getProjects

Get a list of projects the current session user has access to

Returns Promise<Array<Project>> Collection of projects the user has access to

setActiveProject

Set the currently active project within TERA

Parameters

  • project (Object | String) The project to set as active - either the full Project object or its ID

requireProject

Ask the user to select a project from those available - if one isn't already active Note that this function will percist in asking the uesr even if they try to cancel

Parameters

  • options Object? Additional options to mutate behaviour

    • options.autoSetActiveProject Boolean After selecting a project set that project as active in TERA (optional, default true)
    • options.title String The title of the dialog to display (optional, default "Select a project to work with")
    • options.noSelectTitle String Dialog title when warning the user they need to select something (optional, default 'Select project')
    • options.noSelectBody String Dialog body when warning the user they need to select something (optional, default 'A project needs to be selected to continue')

Returns Promise<Project> The active project

selectProject

Prompt the user to select a project from those available

Parameters

  • options Object? Additional options to mutate behaviour

    • options.title String The title of the dialog to display (optional, default "Select a project to work with")
    • options.allowCancel Boolean Advertise cancelling the operation, the dialog can still be cancelled by closing it (optional, default true)
    • options.setActive Boolean Also set the project as active when selected (optional, default false)

Returns Promise<Project> The active project

getProjectState

Return the current, full snapshot state of the active project

Parameters

  • options Object? Additional options to mutate behaviour

    • options.autoRequire Boolean Run requireProject() automatically before continuing (optional, default true)
  • Paths Array<String> to subscribe to e.g. ['/users/'],

Returns Promise<Object> The current project state snapshot

setProjectState

Set a nested value within the project state Paths can be any valid Lodash.set() value such as:

- Dotted notation - e.g. `foo.bar.1.baz`
- Array path segments e.g. `['foo', 'bar', 1, 'baz']`

Parameters

  • path (String | Array<String>) The sub-path within the project state to set

  • value any The value to set

  • options Object? Additional options to mutate behaviour

    • options.save Boolean Save the changes to the server immediately, disable to queue up multiple writes (optional, default true)

Returns Promise A promise which resolves when the operation has been dispatched to the server

setProjectStateDefaults

  • See: setProjectState()

Set a nested value within the project state - just like setProjectState() - but only if no value for that path exists

Parameters

  • path (String | Array<String>) The sub-path within the project state to set
  • value any The value to set
  • options Object? Additional options to mutate behaviour, see setProjectState() for the full list of supported options

Returns Promise<Boolean> A promise which resolves to whether any changes were made - True if defaults were applied, false otherwise

setProjectStateFlush

Force copying local changes to the server This is only ever needed when saving large quantities of data that need to be immediately available

Returns Promise A promise which resolves when the operation has completed

setProjectStateRefresh

Force refetching the remote project state into local This is only ever needed when saving large quantities of data that need to be immediately available

Returns Promise A promise which resolves when the operation has completed

saveProjectState

Force-Save the currently active project state

Returns Promise A promise which resolves when the operation has completed

replaceProjectState

  • See: setProjectState()

Overwrite the entire project state with a new object You almost never want to use this function directly, see setProjectState(path, value) for a nicer wrapper

Parameters

  • newState Object The new state to replace the current state with

Returns Promise A promise which resolves when the operation has completed

applyProjectStatePatch

Apply a computed just-diff patch to the current project state

Parameters

Returns Promise A promise which resolves when the operation has completed

subscribeProjectState

Subscribe to project state changes This will dispatch an RPC call to the source object applyProjectStatePatchLocal() function with the patch If the above call fails the subscriber is assumed as dead and unsubscribed from the polling list

Returns Promise<Function> A promise which resolves when a subscription has been created, call the resulting function to unsubscribe

FileFilters

Data structure for a file filter

Properties

  • library Boolean? Restrict to library files only
  • filename String? CSV of @momsfriendlydevco/match expressions to filter the filename by (filenames are the basename sans extension)
  • basename String? CSV of @momsfriendlydevco/match expressions to filter the basename by
  • ext String? CSV of @momsfriendlydevco/match expressions to filter the file extension by

selectProjectFile

Prompt the user to select a library to operate on

Parameters

  • options Object? Additional options to mutate behaviour

    • options.title String The title of the dialog to display (optional, default "Select a file")
    • options.hint (String | Array<String>)? Hints to identify the file to select in array order of preference
    • options.save Boolean Set to truthy if saving a new file, UI will adjust to allowing overwrite OR new file name input (optional, default false)
    • options.filters FileFilters? Optional file filters
    • options.allowUpload Boolean Allow uploading new files (optional, default true)
    • options.allowRefresh Boolean Allow the user to manually refresh the file list (optional, default true)
    • options.allowDownloadZip Boolean Allow the user to download a Zip of all files (optional, default true)
    • options.allowCancel Boolean Allow cancelling the operation. Will throw 'CANCEL' as the promise rejection if acationed (optional, default true)
    • options.autoRequire Boolean Run requireProject() automatically before continuing (optional, default true)
    • options.filter FileFilters? Optional file filters

Returns Promise<ProjectFile> The eventually selected file, if in save mode new files are created as stubs

deleteProjectFile

Remove a project file by its ID

Parameters

  • id String The File ID to remove

Returns Promise A promise which resolves when the operation has completed

setProjectFile

Replace a project files contents

Parameters

Returns Promise A promise which will resolve when the write operation has completed

selectProjectLibrary

Prompt the user to select a library to operate on and return a array of references in a given format

Parameters

  • options Object? Additional options to mutate behaviour

    • options.title String The title of the dialog to display (optional, default "Select a citation library")
    • options.hint (String | Array<String>)? Hints to identify the library to select in array order of preference. Generally corresponds to the previous stage - e.g. 'deduped', 'review1', 'review2', 'dedisputed'
    • options.allowUpload Boolean Allow uploading new files (optional, default true)
    • options.allowRefresh Boolean Allow the user to manually refresh the file list (optional, default true)
    • options.allowDownloadZip Boolean Allow the user to download a Zip of all files (optional, default true)
    • options.allowCancel Boolean Allow cancelling the operation. Will throw 'CANCEL' as the promise rejection if acationed (optional, default true)
    • options.autoRequire Boolean Run requireProject() automatically before continuing (optional, default true)
    • options.filters FileFilters? Optional file filters, defaults to citation library selection only

Returns Promise<Array<Ref>> A collection of references from the selected file

getProjectLibrary

Fetch + convert a project file into a library of citations

Parameters

  • id String File ID to read

  • options Object? Additional options to mutate behaviour

    • options.format String Format for the file. ENUM: 'pojo' (return a parsed JS collection), 'blob' (raw JS Blob object), 'file' (named JS File object) (optional, default 'json')
    • options.autoRequire Boolean Run requireProject() automatically before continuing (optional, default true)
    • options.filter Function? Optional async file filter, called each time as (File:ProjectFile)
    • options.find Function? Optional async final stage file filter to reduce all candidates down to one subject file

Returns (Promise<Array<Ref>> | Promise<any>) A collection of references (default bevahiour) or a whatever format was requested

setProjectLibrary

Save back a citation library from some input

Parameters

  • id String? File ID to save back to, if omitted a file will be prompted for

  • refs (Array<RefLibRef> | Blob | File)? Collection of references for the selected library or the raw Blob/File

  • options Object? Additional options to mutate behaviour

    • options.id String? Alternate method to specify the file ID to save as, if omitted one will be prompted for
    • options.refs (Array<RefLibRef> | Blob | File)? Alternate method to specify the refs to save as an array or raw Blob/File
    • options.format String Input format used. ENUM: 'pojo' (return a parsed JS collection), 'blob' (raw JS Blob object), 'file' (named JS File object) (optional, default 'json')
    • options.autoRequire Boolean Run requireProject() automatically before continuing (optional, default true)
    • options.hint String? Hint to store against the library. Generally corresponds to the current operation being performed - e.g. 'deduped'
    • options.filename String? Suggested filename if id is unspecified
    • options.title String Dialog title if id is unspecified and a prompt is necessary (optional, default 'Save citation library')
    • options.overwrite Boolean Allow existing file upsert (optional, default true)
    • options.meta Object? Optional meta data to merge into the file data

Returns Promise A promise which resolves when the save operation has completed

projectLog

Create a log entry for the currently active project

The required log object can be of various forms. See https://tera-tools.com/api/logs.json for the full list

Parameters

  • log Object The log entry to create

Returns Promise A promise which resolves when the operation has completed

setPageUrl

Set an active tools URL so that it survives a refresh This only really makes a difference to tools within the tera-tools.com site where the tool is working as an embed

Parameters

  • url String The URL to restore on next refresh

setPageTitle

Set the active page title This is usually called by a tool nested within the tera-tools.com embed

Parameters

  • title String The current page title

uiAlert

Display simple text within TERA

Parameters

  • text String The text to display

  • options Object? Additional options to mutate behaviour

    • options.title String The title of the alert box (optional, default 'TERA')
    • options.isHtml Boolean If falsy the text is rendered as plain-text otherwise it will be assumed as HTML content (optional, default false)

Returns Promise A promise which resolves when the alert has been dismissed

uiProgress

Display, update or dispose of windows for long running tasks All options are cumulative - i.e. they are merged with other options previously provided

Parameters

  • options (Object | Boolean)? Additional options to mutate behaviour, if boolean false {close: true} is assumed

    • options.title String Window title, can only be set on the initial call (optional, default 'TERA')
    • options.body String Window body text, can only be set on the initial call (optional, default '')
    • options.bodyHtml Boolean Treat body text as HTML (optional, default false)
    • options.close Boolean Close the existing dialog, if true the dialog is disposed and options reset (optional, default false)
    • options.text String? The text of the task being conducted
    • options.progress Number? The current progress of the task being conducted, this is assumed to be a value less than maxProgress
    • options.maxProgress Number? The maximum value that the progress can be

Returns Promise A promise which resolves when the dialog has been updated

uiWindow

Open a popup window containing a new site

Parameters

  • url String The URL to open

  • options Object? Additional options to mutate behaviour

    • options.width Number The desired width of the window (optional, default 500)
    • options.height Number The desired height of the window (optional, default 600)
    • options.center Boolean Attempt to center the window on the screen (optional, default true)
    • options.permissions Object? Additional permissions to set on opening, defaults to a suitable set of permission for popups (see code)

Returns WindowProxy The opened window object (if noopener is not set in permissions)

uiSplat

Display HTML content full-screen within TERA This function is ideally called within a requestFocus() wrapper

Parameters

  • content (DOMElement | String | false) Either a prepared DOM element or string to compile, set to falsy to remove existing content

  • options Object? Additional options to mutate behaviour

    • options.logo (Boolean | String) Add a logo to the output, if boolean true the Tera-tools logo is used otherwise specify a path or URL (optional, default false)