react-mosaic

A React tiling window manager

README

react-mosaic

CircleCI npm

react-mosaic is a full-featured React Tiling Window Manager meant to give a user complete control over their workspace.
It provides a simple and flexible API to tile arbitrarily complex react components across a user's view.
react-mosaic is written in TypeScript and provides typings but can be used in JavaScript as well.

The best way to see it is a simple [Demo](https://nomcopter.github.io/react-mosaic/).

Screencast

screencast demo

Usage


The core of react-mosaic's operations revolve around the simple binary tree [specified by `MosaicNode`](./src/types.ts#L12).
[T](./src/types.ts#L7) is the type of the leaves of the tree and is a string or a number that can be resolved to a JSX.Element for display.

Installation


1.  yarn add react-mosaic-component
1.  Make sure react-mosaic-component.css is included on your page.
1.  Import the Mosaic component and use it in your app.
1.  (Optional) Install Blueprint

Blueprint Theme


Without a theme, Mosaic only loads the styles necessary for it to function -
making it easier for the consumer to style it to match their own app.

By default, Mosaic renders with the mosaic-blueprint-theme class.
This uses the excellent Blueprint React UI Toolkit to provide a good starting state.
It is recommended to at least start developing with this theme.
To use it install Blueprint yarn add @blueprintjs/core @blueprintjs/icons and add their CSS to your page.
Don't forget to set blueprintNamespace in Mosaic to the correct value for the version of Blueprint you are using.

See blueprint-theme.less for an example of creating a theme.

Blueprint Dark Theme


Mosaic supports the Blueprint Dark Theme out of the box when rendered with the mosaic-blueprint-theme bp3-dark class.

Examples


Simple Tiling


app.css

  1. ```css
  2. html,
  3. body,
  4. #app {
  5.   height: 100%;
  6.   width: 100%;
  7.   margin: 0;
  8. }
  9. ```

App.tsx

  1. ```tsx
  2. import { Mosaic } from 'react-mosaic-component';

  3. import 'react-mosaic-component/react-mosaic-component.css';
  4. import '@blueprintjs/core/lib/css/blueprint.css';
  5. import '@blueprintjs/icons/lib/css/blueprint-icons.css';

  6. import './app.css';

  7. const ELEMENT_MAP: { [viewId: string]: JSX.Element } = {
  8.   a: <div>Left Window</div>,
  9.   b: <div>Top Right Window</div>,
  10.   c: <div>Bottom Right Window</div>,
  11. };

  12. export const app = (
  13.   <div id="app">
  14.     <Mosaic<string>
  15.       renderTile={(id) => ELEMENT_MAP[id]}
  16.       initialValue={{
  17.         direction: 'row',
  18.         first: 'a',
  19.         second: {
  20.           direction: 'column',
  21.           first: 'b',
  22.           second: 'c',
  23.         },
  24.         splitPercentage: 40,
  25.       }}
  26.     />
  27.   </div>
  28. );
  29. ```

renderTile is a stateless lookup function to convert T into a displayable JSX.Element.
By default T is string (so to render one element initialValue="ID" works).
Ts must be unique within an instance of Mosaic, they are used as keys for React list management.
`initialValue` is a [`MosaicNode`](./src/types.ts#L12).

The user can resize these panes but there is no other advanced functionality.
This example renders a simple tiled interface with one element on the left half, and two stacked elements on the right half.
The user can resize these panes but there is no other advanced functionality.

Drag, Drop, and other advanced functionality with MosaicWindow


MosaicWindow is a component that renders a toolbar and controls around its children for a tile as well as providing full featured drag and drop functionality.

  1. ```tsx
  2. export type ViewId = 'a' | 'b' | 'c' | 'new';

  3. const TITLE_MAP: Record<ViewId, string> = {
  4.   a: 'Left Window',
  5.   b: 'Top Right Window',
  6.   c: 'Bottom Right Window',
  7.   new: 'New Window',
  8. };

  9. export const app = (
  10.   <Mosaic<ViewId>
  11.     renderTile={(id, path) => (
  12.       <MosaicWindow<ViewId> path={path} createNode={() => 'new'} title={TITLE_MAP[id]}>
  13.         <h1>{TITLE_MAP[id]}</h1>
  14.       </MosaicWindow>
  15.     )}
  16.     initialValue={{
  17.       direction: 'row',
  18.       first: 'a',
  19.       second: {
  20.         direction: 'column',
  21.         first: 'b',
  22.         second: 'c',
  23.       },
  24.     }}
  25.   />
  26. );
  27. ```

Here T is a ViewId that can be used to look elements up in TITLE_MAP.
This allows for easy view state specification and serialization.
This will render a view that looks very similar to the previous examples, but now each of the windows will have a toolbar with buttons.
These toolbars can be dragged around by a user to rearrange their workspace.

MosaicWindow API docs here.

Controlled vs. Uncontrolled


Mosaic views have two modes, similar to React.DOM input elements:

- Controlled, where the consumer manages Mosaic's state through callbacks.
  Using this API, the consumer can perform any operation upon the tree to change the the view as desired.
- Uncontrolled, where Mosaic manages all of its state internally.


All of the previous examples show use of Mosaic in an Uncontrolled fashion.

Example Application


See ExampleApp (the application used in the Demo)
for a more interesting example that shows the usage of Mosaic as a controlled component and modifications of the tree structure.

API


Mosaic Props


  1. ```typescript
  2. export interface MosaicBaseProps<T extends MosaicKey> {
  3.   /**
  4.    * Lookup function to convert `T` to a displayable `JSX.Element`
  5.    */
  6.   renderTile: TileRenderer<T>;
  7.   /**
  8.    * Called when a user initiates any change to the tree (removing, adding, moving, resizing, etc.)
  9.    */
  10.   onChange?: (newNode: MosaicNode<T> | null) => void;
  11.   /**
  12.    * Called when a user completes a change (fires like above except for the interpolation during resizing)
  13.    */
  14.   onRelease?: (newNode: MosaicNode<T> | null) => void;
  15.   /**
  16.    * Additional classes to affix to the root element
  17.    * Default: 'mosaic-blueprint-theme'
  18.    */
  19.   className?: string;
  20.   /**
  21.    * Options that control resizing
  22.    * @see: [[ResizeOptions]]
  23.    */
  24.   resize?: ResizeOptions;
  25.   /**
  26.    * View to display when the current value is `null`
  27.    * default: Simple NonIdealState view
  28.    */
  29.   zeroStateView?: JSX.Element;
  30.   /**
  31.    * Override the mosaicId passed to `react-dnd` to control how drag and drop works with other components
  32.    * Note: does not support updating after instantiation
  33.    * default: Random UUID
  34.    */
  35.   mosaicId?: string;
  36.   /**
  37.    * Make it possible to use different versions of Blueprint with `mosaic-blueprint-theme`
  38.    * Note: does not support updating after instantiation
  39.    * default: 'bp3'
  40.    */
  41.   blueprintNamespace?: string;
  42.   /**
  43.    * Override the react-dnd provider to allow applications to inject an existing drag and drop context
  44.    */
  45.   dragAndDropManager?: DragDropManager | undefined;
  46. }

  47. export interface MosaicControlledProps<T extends MosaicKey> extends MosaicBaseProps<T> {
  48.   /**
  49.    * The tree to render
  50.    */
  51.   value: MosaicNode<T> | null;
  52.   onChange: (newNode: MosaicNode<T> | null) => void;
  53. }

  54. export interface MosaicUncontrolledProps<T extends MosaicKey> extends MosaicBaseProps<T> {
  55.   /**
  56.    * The initial tree to render, can be modified by the user
  57.    */
  58.   initialValue: MosaicNode<T> | null;
  59. }

  60. export type MosaicProps<T extends MosaicKey> = MosaicControlledProps<T> | MosaicUncontrolledProps<T>;
  61. ```

MosaicWindow


  1. ```typescript
  2. export interface MosaicWindowProps<T extends MosaicKey> {
  3.   title: string;
  4.   /**
  5.    * Current path to this window, provided by `renderTile`
  6.    */
  7.   path: MosaicBranch[];
  8.   className?: string;
  9.   /**
  10.    * Controls in the top right of the toolbar
  11.    * default: [Replace, Split, Expand, Remove] if createNode is defined and [Expand, Remove] otherwise
  12.    */
  13.   toolbarControls?: React.ReactNode;
  14.   /**
  15.    * Additional controls that will be hidden in a drawer beneath the toolbar.
  16.    * default: []
  17.    */
  18.   additionalControls?: React.ReactNode;
  19.   /**
  20.    * Label for the button that expands the drawer
  21.    */
  22.   additionalControlButtonText?: string;
  23.   /**
  24.    * A callback that triggers when a user toggles the additional controls
  25.    */
  26.   onAdditionalControlsToggle?: (toggle: boolean) => void;
  27.   /**
  28.    * Whether or not a user should be able to drag windows around
  29.    */
  30.   draggable?: boolean;
  31.   /**
  32.    * Method called when a new node is required (such as the Split or Replace buttons)
  33.    */
  34.   createNode?: CreateNode<T>;
  35.   /**
  36.    * Optional method to override the displayed preview when a user drags a window
  37.    */
  38.   renderPreview?: (props: MosaicWindowProps<T>) => JSX.Element;
  39.   /**
  40.    * Optional method to override the displayed toolbar
  41.    */
  42.   renderToolbar?: ((props: MosaicWindowProps<T>, draggable: boolean | undefined) => JSX.Element) | null;
  43.   /**
  44.    * Optional listener for when the user begins dragging the window
  45.    */
  46.   onDragStart?: () => void;
  47.   /**
  48.    * Optional listener for when the user finishes dragging a window.
  49.    */
  50.   onDragEnd?: (type: 'drop' | 'reset') => void;
  51. }
  52. ```

The default controls rendered by MosaicWindow can be accessed from [defaultToolbarControls](./src/buttons/defaultToolbarControls.tsx)

Advanced API


The above API is good for most consumers, however Mosaic provides functionality on the Context of its children that make it easier to alter the view state.
All leaves rendered by Mosaic will have the following available on React context.
These are used extensively by MosaicWindow.

  1. ```typescript
  2. /**
  3. * Valid node types
  4. * @see React.Key
  5. */
  6. export type MosaicKey = string | number;
  7. export type MosaicBranch = 'first' | 'second';
  8. export type MosaicPath = MosaicBranch[];

  9. /**
  10. * Context provided to everything within Mosaic
  11. */
  12. export interface MosaicContext<T extends MosaicKey> {
  13.   mosaicActions: MosaicRootActions<T>;
  14.   mosaicId: string;
  15. }

  16. export interface MosaicRootActions<T extends MosaicKey> {
  17.   /**
  18.    * Increases the size of this node and bubbles up the tree
  19.    * @param path Path to node to expand
  20.    * @param percentage Every node in the path up to root will be expanded to this percentage
  21.    */
  22.   expand: (path: MosaicPath, percentage?: number) => void;
  23.   /**
  24.    * Remove the node at `path`
  25.    * @param path
  26.    */
  27.   remove: (path: MosaicPath) => void;
  28.   /**
  29.    * Hide the node at `path` but keep it in the DOM. Used in Drag and Drop
  30.    * @param path
  31.    */
  32.   hide: (path: MosaicPath) => void;
  33.   /**
  34.    * Replace currentNode at `path` with `node`
  35.    * @param path
  36.    * @param node
  37.    */
  38.   replaceWith: (path: MosaicPath, node: MosaicNode<T>) => void;
  39.   /**
  40.    * Atomically applies all updates to the current tree
  41.    * @param updates
  42.    * @param suppressOnRelease (default: false)
  43.    */
  44.   updateTree: (updates: MosaicUpdate<T>[], suppressOnRelease?: boolean) => void;
  45.   /**
  46.    * Returns the root of this Mosaic instance
  47.    */
  48.   getRoot: () => MosaicNode<T> | null;
  49. }
  50. ```

Children (and toolbar elements) within MosaicWindow are passed the following additional functions on context.

  1. ```typescript
  2. export interface MosaicWindowContext<T extends MosaicKey> extends MosaicContext<T> {
  3.   mosaicWindowActions: MosaicWindowActions;
  4. }

  5. export interface MosaicWindowActions {
  6.   /**
  7.    * Fails if no `createNode()` is defined
  8.    * Creates a new node and splits the current node.
  9.    * The current node becomes the `first` and the new node the `second` of the result.
  10.    * `direction` is chosen by querying the DOM and splitting along the longer axis
  11.    */
  12.   split: () => Promise<void>;
  13.   /**
  14.    * Fails if no `createNode()` is defined
  15.    * Convenience function to call `createNode()` and replace the current node with it.
  16.    */
  17.   replaceWithNew: () => Promise<void>;
  18.   /**
  19.    * Sets the open state for the tray that holds additional controls
  20.    */
  21.   setAdditionalControlsOpen: (open: boolean) => void;
  22.   /**
  23.    * Returns the path to this window
  24.    */
  25.   getPath: () => MosaicPath;
  26.   /**
  27.    * Enables connecting a different drag source besides the react-mosaic toolbar
  28.    */
  29.   connectDragSource: (connectedElements: React.ReactElement<any>) => React.ReactElement<any>;
  30. }
  31. ```

To access the functions simply use the [MosaicContext](./src/contextTypes.ts#L90)
or [MosaicWindowContext](./src/contextTypes.ts#L91) context consumers.

Mutating the Tree


Utilities are provided for working with the MosaicNode tree in [mosaicUtilities](src/util/mosaicUtilities.ts) and
[mosaicUpdates](src/util/mosaicUpdates.ts)

MosaicUpdate


[MosaicUpdateSpec](./src/types.ts#L33) is an argument meant to be passed to [immutability-helper](https://github.com/kolodny/immutability-helper)
to modify the state at a path.
[mosaicUpdates](src/util/mosaicUpdates.ts) has examples.

Upgrade Considerations / Changelog



License


Copyright 2019 Kevin Verdieck, originally developed at Palantir Technologies, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.