项目作者: nomcopter

项目描述 :
A React tiling window manager
高级语言: TypeScript
项目地址: git://github.com/nomcopter/react-mosaic.git
创建时间: 2017-03-23T15:51:26Z
项目社区:https://github.com/nomcopter/react-mosaic

开源协议:Other

下载


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.

Screencast

screencast demo

Usage

The core of react-mosaic’s operations revolve around the simple binary tree specified by MosaicNode<T>.
T 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
  2. Make sure react-mosaic-component.css is included on your page.
  3. Import the Mosaic component and use it in your app.
  4. (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. html,
  2. body,
  3. #app {
  4. height: 100%;
  5. width: 100%;
  6. margin: 0;
  7. }
App.tsx
  1. import { Mosaic } from 'react-mosaic-component';
  2. import 'react-mosaic-component/react-mosaic-component.css';
  3. import '@blueprintjs/core/lib/css/blueprint.css';
  4. import '@blueprintjs/icons/lib/css/blueprint-icons.css';
  5. import './app.css';
  6. const ELEMENT_MAP: { [viewId: string]: JSX.Element } = {
  7. a: <div>Left Window</div>,
  8. b: <div>Top Right Window</div>,
  9. c: <div>Bottom Right Window</div>,
  10. };
  11. export const app = (
  12. <div id="app">
  13. <Mosaic<string>
  14. renderTile={(id) => ELEMENT_MAP[id]}
  15. initialValue={{
  16. direction: 'row',
  17. first: 'a',
  18. second: {
  19. direction: 'column',
  20. first: 'b',
  21. second: 'c',
  22. },
  23. splitPercentage: 40,
  24. }}
  25. />
  26. </div>
  27. );

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<T>.

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. export type ViewId = 'a' | 'b' | 'c' | 'new';
  2. const TITLE_MAP: Record<ViewId, string> = {
  3. a: 'Left Window',
  4. b: 'Top Right Window',
  5. c: 'Bottom Right Window',
  6. new: 'New Window',
  7. };
  8. export const app = (
  9. <Mosaic<ViewId>
  10. renderTile={(id, path) => (
  11. <MosaicWindow<ViewId> path={path} createNode={() => 'new'} title={TITLE_MAP[id]}>
  12. <h1>{TITLE_MAP[id]}</h1>
  13. </MosaicWindow>
  14. )}
  15. initialValue={{
  16. direction: 'row',
  17. first: 'a',
  18. second: {
  19. direction: 'column',
  20. first: 'b',
  21. second: 'c',
  22. },
  23. }}
  24. />
  25. );

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.

See Controlled Components.

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

MosaicWindow

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

The default controls rendered by MosaicWindow can be accessed from defaultToolbarControls

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. /**
  2. * Valid node types
  3. * @see React.Key
  4. */
  5. export type MosaicKey = string | number;
  6. export type MosaicBranch = 'first' | 'second';
  7. export type MosaicPath = MosaicBranch[];
  8. /**
  9. * Context provided to everything within Mosaic
  10. */
  11. export interface MosaicContext<T extends MosaicKey> {
  12. mosaicActions: MosaicRootActions<T>;
  13. mosaicId: string;
  14. }
  15. export interface MosaicRootActions<T extends MosaicKey> {
  16. /**
  17. * Increases the size of this node and bubbles up the tree
  18. * @param path Path to node to expand
  19. * @param percentage Every node in the path up to root will be expanded to this percentage
  20. */
  21. expand: (path: MosaicPath, percentage?: number) => void;
  22. /**
  23. * Remove the node at `path`
  24. * @param path
  25. */
  26. remove: (path: MosaicPath) => void;
  27. /**
  28. * Hide the node at `path` but keep it in the DOM. Used in Drag and Drop
  29. * @param path
  30. */
  31. hide: (path: MosaicPath) => void;
  32. /**
  33. * Replace currentNode at `path` with `node`
  34. * @param path
  35. * @param node
  36. */
  37. replaceWith: (path: MosaicPath, node: MosaicNode<T>) => void;
  38. /**
  39. * Atomically applies all updates to the current tree
  40. * @param updates
  41. * @param suppressOnRelease (default: false)
  42. */
  43. updateTree: (updates: MosaicUpdate<T>[], suppressOnRelease?: boolean) => void;
  44. /**
  45. * Returns the root of this Mosaic instance
  46. */
  47. getRoot: () => MosaicNode<T> | null;
  48. }

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

  1. export interface MosaicWindowContext<T extends MosaicKey> extends MosaicContext<T> {
  2. mosaicWindowActions: MosaicWindowActions;
  3. }
  4. export interface MosaicWindowActions {
  5. /**
  6. * Fails if no `createNode()` is defined
  7. * Creates a new node and splits the current node.
  8. * The current node becomes the `first` and the new node the `second` of the result.
  9. * `direction` is chosen by querying the DOM and splitting along the longer axis
  10. */
  11. split: () => Promise<void>;
  12. /**
  13. * Fails if no `createNode()` is defined
  14. * Convenience function to call `createNode()` and replace the current node with it.
  15. */
  16. replaceWithNew: () => Promise<void>;
  17. /**
  18. * Sets the open state for the tray that holds additional controls.
  19. * Pass 'toggle' to invert the current state.
  20. */
  21. setAdditionalControlsOpen: (open: boolean | 'toggle') => 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. }

To access the functions simply use the MosaicContext
or MosaicWindowContext context consumers.

Mutating the Tree

Utilities are provided for working with the MosaicNode tree in mosaicUtilities and
mosaicUpdates

MosaicUpdate

MosaicUpdateSpec is an argument meant to be passed to immutability-helper
to modify the state at a path.
mosaicUpdates has examples.

Upgrade Considerations / Changelog

See Releases

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

  1. 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.