Code Monkey home page Code Monkey logo

react-tile-pane's Introduction

React Tile Pane

A React tiling pane manager

preview

An online demo is available at https://xcfox.github.io/react-tile-pane/demo/

install

npm install @use-gesture/react react-use-measure react-tile-pane

or use yarn

yarn add @use-gesture/react react-use-measure react-tile-pane

react-tile-pane use @use-gesture/react, react-use-measure as peerDependencies, you need to install them at the same time.

Quick Start

Create Tile Panes

First you need to create the Tile Panes List:

const [paneList, names] = createTilePanes({
  arbutus: <Arbutus />,
  cherry: <div style={paneStyle}>cherry</div>,
  apple: <Apple />,
  banana: <div style={paneStyle}>banana🍌</div>,
  lemon: <div style={paneStyle}>lemon</div>,
  mango: <div style={paneStyle}>mango</div>,
  pomelo: <div style={paneStyle}>pomelo</div>,
})

As above, createTilePanes accepts a dictionary containing ReactNode, and return a paneList and a names dictionary. The structure of the output dictionary is consistent with the input, each item in the dictionary is essentially a string.

Describe Layout

const rootPane: TileBranchSubstance = {
  children: [
    { children: [names.apple, names.cherry] },
    {
      isRow: true,
      grow: 2,
      children: [
        { children: names.arbutus },
        { children: names.lemon },
        {
          children: [
            { children: names.mango, grow: 3 },
            { children: names.pomelo },
          ],
        },
      ],
    },
  ],
}

As above, we place items in the same level into the same children's array.
grow is same as flex-grow, This property specifies how much of the remaining space in the TileBranch should be assigned to the item. Its default value is 1.
isRow is used to declare whether the panes is displayed as a row or a column.
If the item of names dictionary in children's array, it displayed as a Multi-Tag Pane.

Note: Each name can only appear in the layout at most once.

Container

const App: React.FC = () => {
  return (
    <TileProvider tilePanes={paneList} rootNode={rootPane}>
      <div className="App">
        <div style={{ height: 30 }} />
        <div style={{ border: '#afafaf solid 2px', width: 1000, height: 600 }}>
          <TileContainer />
        </div>
      </div>
      <DraggableTitle name={names.banana}>Drag this banana🍌</DraggableTitle>
    </TileProvider>
  )
}

As above, we input paneList and rootNode into TileProvider as prop tilePanes and prop rootNode.
Then, we put TileContainer in TileProvider. DraggableTitle can also be put in TileProvider.

Full Example File

App.tsc

import React, { useState } from 'react'
import {
  createTilePanes,
  DraggableTitle,
  TileBranchSubstance,
  TileContainer,
  TileProvider,
} from 'react-tile-pane'
import './App.css'

const paneStyle: React.CSSProperties = {
  width: '100%',
  height: ' 100%',
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'center',
}

function Arbutus() {
  const [number, count] = useState(1)
  return (
    <div onClick={() => count((n) => n + 1)} style={paneStyle}>
      {number} catties of arbutus
    </div>
  )
}

function Apple() {
  return <div style={paneStyle}>apple</div>
}

const [paneList, names] = createTilePanes({
  arbutus: <Arbutus />,
  cherry: <div style={paneStyle}>cherry</div>,
  apple: <Apple />,
  banana: <div style={paneStyle}>banana</div>,
  lemon: <div style={paneStyle}>lemon</div>,
  mango: <div style={paneStyle}>mango</div>,
  pomelo: <div style={paneStyle}>pomelo</div>,
})

const rootPane: TileBranchSubstance = {
  children: [
    { children: [names.apple, names.cherry] },
    {
      isRow: true,
      grow: 2,
      children: [
        { children: names.arbutus },
        { children: names.lemon },
        {
          children: [
            { children: names.mango, grow: 3 },
            { children: names.pomelo },
          ],
        },
      ],
    },
  ],
}

const App: React.FC = () => {
  return (
    <TileProvider tilePanes={paneList} rootNode={rootPane}>
      <div className="App">
        <div style={{ height: 30 }} />
        <div style={{ border: '#afafaf solid 2px', width: 1000, height: 600 }}>
          <TileContainer />
        </div>
      </div>
      <DraggableTitle name={names.banana}>Drag this banana🍌</DraggableTitle>
    </TileProvider>
  )
}

export default App

Custom Styles

React Tile Pane does not focus on styles. It is recommended to use custom styles.

A complete example is available at https://github.com/xcfox/react-tile-pane/tree/main/src/App/demo/left-tab
To customize the style, the TileProvider accepts the following properties:

pane

pane is the basic unit of layout.
It accepts style and className attributes.

preBox

When you drag the title, a box will appear inside the container to help you determine the position of the pane after releasing the mouse, this box is called preBox.
It accepts style, className, child attributes.

stretchBar

The stretchBar is in between the pane and is used to resize the pane.
It accepts style, className, child attributes.

tabBar

TabBar for managing overlapping panes.
It accepts render, thickness, position attributes.

  • render: To customize how the TabsBar is rendered
  • thickness: Accepts a CSS length attribute, which defaults to px if number is passed in
  • position: Where to position the TabsBar in the pane

Hooks and Components

Hooks and components help you do more complex operations.

Note: Hooks and Components only work inside the TileContainer

Examples can be viewed at https://github.com/xcfox/react-tile-pane/blob/main/src/App/demo/left-tab/index.tsx

DraggableTitle

DraggableTitle used to open a new pane from outside the container. It accepts style, className, children attributes.

  • name: Associate a pane from the paneList by the name

  • dragConfig: Drag behavior, see more information in use-gesture doc

  • onDrag: Actions triggered when dragging, see more information in use-gesture doc

  • onDragEnd: Actions triggered when drag ends

  • onDragStart: Actions triggered when drag starts

Example

function PaneIcon({ name }: { name: keyof typeof icons }) {
  const getLeaf = useGetLeaf()
  const move = useMovePane()
  const leaf = getLeaf(name)
  const isShowing = !!leaf
  return (
    <div>
      <div style={{ width: 40, height: 40, cursor: 'move' }}>
        <DraggableTitle name={name}>{icons[name]}</DraggableTitle>
      </div>
      <div onClick={() => move(name, isShowing ? null : [0.99, 0.5])} />
    </div>
  )
}

useGetLeaf

Get a function to get pane by name.

// Used in a React Function Components
const getLeaf = useGetLeaf()
// get a leaf by its name, when the pane is not displayed, it will return undefined
const leaf = getLeaf(names.apple)

useMove

Get a function to move the pane.

// Used in a React Function Components
const move = useMovePane()
return (
  <div>
    <div
      // When an array of length 2 is passed in, the pane will be moved to that position in the container.
      // When null is passed in, the pane will be closed.
      onClick={() => move(name, isShowing ? null : [0.99, 0.5])}
      style={{
        cursor: 'pointer',
        background: isShowing ? color.primary : color.secondary,
        width: 14,
        height: 14,
        borderRadius: 99,
      }}
    />
  </div>
)

useGetRootNode

Get a function to get RootNode, used to persist the current layout.

const localStorageKey = 'react-tile-pane-left-tab-layout'

function AutoSaveLayout() {
  const getRootNode = useGetRootNode()
  localStorage.setItem(localStorageKey, JSON.stringify(getRootNode()))
  return <></>
}

export const LeftTabDemo: React.FC = () => {
  const localRoot = localStorage.getItem(localStorageKey)
  const root = localRoot
    ? (JSON.parse(localRoot) as TileBranchSubstance)
    : rootPane
  return (
    <TileProvider tilePanes={nodeList} rootNode={root} tabBar={tabBarConfig}>
      <TileContainer style={styles.container} />
      <AutoSaveLayout />
    </TileProvider>
  )
}

useReset

Get a function to reset layout.

const reset = useReset()
const handleClick = useCallback(() => reset(rootPane), [])

Some similar projects

react-tile-pane's People

Contributors

xcfox avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

react-tile-pane's Issues

How do pass through props to the individual panes?

I didn't see anything in the samples showing how to get data to the panes.

I tried to workaround this by associating data by name in a context, then each pane can get that data by its name from the context. That works, the data makes it down to the component, but, the panes don't re-render when the parent renders.

In other words, I effectively have

<App>
    <TileProvider>
        <TileContainer>
           // these exist indirectly via TileProvider paneList
           <Arbutus />
           <Apple />
        <TileContainer/>
    </TileProvider>
</App>

But if do something that makes <App> re-render I see react call TileProvider and TileContainer but it never calls Arbutus nor Apple

How did you imagine in working? In your examples it appears the components in the panes are static (created just once at init time).

move() destroys component from DOM

This is a very important use case for a declarative framework like React.
We want to prevent multiple rerenders as much as possible and manage states easily.

Calling the useMovePane() hook to either remove or add a pane is okay, but how about hiding a pane without removing it from the DOM?
move(name, isShowing ? null : [0.99, 0.5])

A pane that is removed and added in a toggle manner gets rerendered all the time and the previous state is lost. Ref to previous elements are also missing and it creates a buggy experience.

Is there a way currently to achieve hiding a pane in addition to adding and removing?
Or is it something we can add in the next update?

Pane stretchBar limit

How can I limit the stretchbar from adjusting the width of surrounding panes beyond a set limit?

For instance, we could have a limit config object set in StrretchBarConfig, as a result, the user cannot adjust the stretchbar and limit the bordered panes beyond 100px in width or height.

const stretchBar: StretchBarConfig = {
	className: 'vertical-stretch-bar',
	style: (isRow) => ({ cursor: isRow ? 'ew-resize' : 'ns-resize' }),
        limit: '100px'
}

Reacting to DraggableTitle being dragged and adding a pane

I have a component like this

<DraggableTitle name={names[nextFreePaneId]}>
   <div onClick={() => setMostRecentlyUsedEditorWindowToFile(filename)}>{filename}</div>
</DraggableTitle>

You can see an example of this in VSCode. Imagine all the filenames on the left are made with the component above

Screen.Recording.2022-10-31.at.1.03.53.AM.mp4

When a component is clicked one thing happens. When a component is dragged, a different thing happens.

I'm trying to dupilicate this behavior. Is it possible?

At the moment I just pre-create 50 panes (pane0, pane1, pane2, ....). But they are not in the rootPane tree. I have an array of free pane names. All of the elements using the component above get the same nextFreePaneId. This seems okay because only one of those elements will be dragged to make a new pane, at which point they'd all get a differetn nextFreePAneId

This almost works, when I click the component one thing happens, when I drag the component, a new pane is created.

I have 2 issues though:

  1. After dragging, the component's onClick event fires. I need to prevent that click.

    Is there some props or context state I can look at to see that I'm being dragged?

  2. Have no way to tell the new pane that was just added which file to use

  3. I have no way to tell a pane was even added

    So I can't update my list of free pane ids.

Am I approaching this the right way? Any idea how I would solve this?

Maybe I could solve it by wrapping that component in another component that some how checks if it's being dragged and passs that as a prop to this component so it can stop setting onClick? That would solve but not 2 or 3.

Trying to understand the demo

This library looks amazing! Thank you for making it

I'm trying to understand the demo. In particular I'd like to make pane manager that functions like say VSCode where you can drag panes around, doc them, etc. that seems like what your library does.

One thing I don't get is how I disassocaite the name used to identify a pane from the name displayed. I need multiple panes with the same name. I guess I can try to create my own tabbar like the left-bar example but I see it's reaching pretty deep into the src of the library.

import {
  createTilePanes,
  DraggableTitle,
  TileBranchSubstance,
  TileContainer,
  TileProvider,
  useGetRootNode,
} from '../../../components'

Is that the direction I should go or is there a simpler way to show a tab name different from its id?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.