react-dnd#DndProvider TypeScript Examples

The following examples show how to use react-dnd#DndProvider. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: page-container.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
RenderMainContent = React.memo(
  ({
    noWrapper,
    customMain,
    route,
    layout,
  }: {
    noWrapper: boolean;
    customMain: Function | JSX.Element | null;
    route: RouteConfig;
    layout: {
      [k: string]: any;
    };
  }) => {
    return (
      <ErrorBoundary>
        <DndProvider backend={HTML5Backend}>
          {noWrapper ? (
            <>
              {typeof customMain === 'function' ? customMain() : customMain}
              {renderRoutes(route.routes)}
            </>
          ) : (
            <Card className={layout && layout.fullHeight ? 'h-full overflow-auto' : ''}>
              {typeof customMain === 'function' ? customMain() : customMain}
              {renderRoutes(route.routes)}
            </Card>
          )}
        </DndProvider>
      </ErrorBoundary>
    );
  },
)
Example #2
Source File: index2.tsx    From jetlinks-ui-antd with MIT License 6 votes vote down vote up
App: React.FC = (props) => {
    return (
        <div>
            <DndProvider backend={HTML5Backend}>
                <Example />
            </DndProvider>
        </div>
    )
}
Example #3
Source File: DragAndDropTreeProvider.tsx    From frontend-sample-showcase with MIT License 6 votes vote down vote up
DragAndDropTreeProvider: React.FC = () => {

  // See documentation on DndProvider backends: https://react-dnd.github.io/react-dnd/docs/overview
  return (
    <DndProvider backend={HTML5Backend}>
      <DragAndDropTreeComponent />
    </DndProvider>
  );
}
Example #4
Source File: ComponentPreview.test.tsx    From openchakra with MIT License 6 votes vote down vote up
function renderWithRedux(
  components: React.ReactNode,
  {
    // @ts-ignore
    initialState,
    // @ts-ignore
    store = init(storeConfig),
  } = {},
) {
  return {
    ...render(
      <ChakraProvider resetCSS theme={theme}>
        <DndProvider backend={Backend}>
          <Provider store={store}>{components}</Provider>
        </DndProvider>
      </ChakraProvider>,
    ),
    // adding `store` to the returned utilities to allow us
    // to reference it in our tests (just try to avoid using
    // this to test implementation details).
    store,
  }
}
Example #5
Source File: index.tsx    From openchakra with MIT License 6 votes vote down vote up
App = () => {
  useShortcuts()

  return (
    <>
      <Global
        styles={() => ({
          html: { minWidth: '860px', backgroundColor: '#1a202c' },
        })}
      />
      <Metadata />
      <Header />
      <DndProvider backend={Backend}>
        <Flex h="calc(100vh - 3rem)">
          <Sidebar />
          <EditorErrorBoundary>
            <Box bg="white" flex={1} position="relative">
              <Editor />
            </Box>
          </EditorErrorBoundary>

          <Box
            maxH="calc(100vh - 3rem)"
            flex="0 0 15rem"
            bg="#f7fafc"
            overflowY="auto"
            overflowX="visible"
            borderLeft="1px solid #cad5de"
          >
            <InspectorProvider>
              <Inspector />
            </InspectorProvider>
          </Box>
        </Flex>
      </DndProvider>
    </>
  )
}
Example #6
Source File: index.tsx    From gio-design with Apache License 2.0 6 votes vote down vote up
public render() {
    const { collection, getId, template, container } = this.props;
    const { collections, SortableItemClass } = this.state;
    const SortableItem = SortableItemClass;

    const children = collections.map((props: ItemWithId, i: number) => {
      const originalPosition = collection.indexOf(props);
      const key = getId ? getId(props, i) : props.value;
      const canDrag = props.canDrag === false ? props.canDrag : true;
      return (
        <SortableItem
          sortData={props}
          canDrag={canDrag}
          index={i}
          key={key}
          position={originalPosition}
          onHover={this._handleHover}
          onDrop={this._handleDrop}
          onCancel={this._handleCancel}
          template={template}
        />
      );
    });

    return (
      <DndProvider backend={HTML5Backend as any}>
        {React.createElement(
          container,
          _.omit(this.props, ['collection', 'container', 'onSorted', 'template']),
          children
        )}
      </DndProvider>
    );
  }
Example #7
Source File: Programs.tsx    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
Programs: VFC = () => {
  const isUploadedProgramsPage = useMatch(routes.uploadedPrograms);
  const isAllProgramsPage = useMatch(routes.allPrograms);
  const isAllMessagesPage = useMatch(routes.messages);
  let currentPage = SWITCH_PAGE_TYPES.UPLOAD_PROGRAM;

  if (isUploadedProgramsPage) {
    currentPage = SWITCH_PAGE_TYPES.UPLOADED_PROGRAMS;
  } else if (isAllProgramsPage) {
    currentPage = SWITCH_PAGE_TYPES.ALL_PROGRAMS;
  } else if (isAllMessagesPage) {
    currentPage = SWITCH_PAGE_TYPES.ALL_MESSAGES;
  }

  return (
    <div className="main-content-wrapper">
      <ProgramSwitch pageType={currentPage} />
      {currentPage === SWITCH_PAGE_TYPES.UPLOAD_PROGRAM && (
        <>
          <DndProvider backend={HTML5Backend}>
            <Upload />
          </DndProvider>
          <BlockList />
        </>
      )}
      {currentPage === SWITCH_PAGE_TYPES.UPLOADED_PROGRAMS && <Recent />}
      {currentPage === SWITCH_PAGE_TYPES.ALL_PROGRAMS && <All />}
      {currentPage === SWITCH_PAGE_TYPES.ALL_MESSAGES && <Messages />}
    </div>
  );
}
Example #8
Source File: Viewer.tsx    From legend-studio with Apache License 2.0 6 votes vote down vote up
Viewer: React.FC = () => (
  <EditorStoreProvider>
    <ViewerStoreProvider>
      <DndProvider backend={HTML5Backend}>
        <ViewerInner />
      </DndProvider>
    </ViewerStoreProvider>
  </EditorStoreProvider>
)
Example #9
Source File: DragSortEditTable.tsx    From datart with Apache License 2.0 6 votes vote down vote up
DragSortEditTable: React.FC<DragEditTableProps> = ({
  components,
  ...restProps
}) => {
  const DragEditComponents = {
    body: {
      row: DraggableAndEditableBodyRow,
      cell: EditableCell,
    },
  };

  const onMoveRow = useCallback((a, b) => {
    // const dragRow = rows[dragIndex];
    // rows.splice(dragIndex, 1);
    // rows.splice(hoverIndex, 0, dragRow);
    // setRows([...rows]);
  }, []);
  return (
    <DndProvider backend={HTML5Backend}>
      <Table
        rowClassName={() => 'editable-row'}
        components={DragEditComponents}
        {...restProps}
      />
    </DndProvider>
  );
}
Example #10
Source File: editor-component.tsx    From utopia with MIT License 6 votes vote down vote up
export function EditorComponent(props: EditorProps) {
  const indexedDBFailed = useEditorState(
    (store) => store.editor.indexedDBFailed,
    'EditorComponent indexedDBFailed',
  )

  return indexedDBFailed ? (
    <FatalIndexedDBErrorComponent />
  ) : (
    <DndProvider backend={HTML5Backend}>
      <EditorComponentInner {...props} />
    </DndProvider>
  )
}
Example #11
Source File: $todoListId.tsx    From remix-hexagonal-architecture with MIT License 6 votes vote down vote up
export default function TodoListPage() {
  const todoListPage = useTodoListPage();

  return (
    <DndProvider backend={HTML5Backend}>
      <TodoList todoListPage={todoListPage} />
    </DndProvider>
  );
}
Example #12
Source File: App.tsx    From ui-schema with MIT License 6 votes vote down vote up
Provider: React.ComponentType<React.PropsWithChildren<{}>> = ({children}) => (
    <ConsentUiProvider locale={'en'} definition={customConsentUi} ownId={'bemit'}>
        <DocsProvider loader={docsLoader}>
            <DocsIndexProvider indexRefs={indexRefs}>
                <DocsSearchProvider localKey={'uis-search-history'} bindKey={'k'}>
                    <HeadlinesProvider>
                        <UIApiProvider loadSchema={loadSchema} noCache>
                            <UIMetaProvider widgets={customWidgets} t={browserT}>
                                <DndProvider backend={MultiBackend} options={HTML5toTouch}>
                                    {children}
                                </DndProvider>
                            </UIMetaProvider>
                        </UIApiProvider>
                    </HeadlinesProvider>
                </DocsSearchProvider>
            </DocsIndexProvider>
        </DocsProvider>
    </ConsentUiProvider>
)
Example #13
Source File: index.tsx    From anew-server with MIT License 6 votes vote down vote up
render() {
    const { order } = this.state;
    const { children } = this.props;

    const tabs: any[] = [];
    React.Children.forEach(children, (c) => {
      tabs.push(c);
    });

    const orderTabs = tabs.slice().sort((a, b) => {
      const orderA = order.indexOf(a.key);
      const orderB = order.indexOf(b.key);

      if (orderA !== -1 && orderB !== -1) {
        return orderA - orderB;
      }
      if (orderA !== -1) {
        return -1;
      }
      if (orderB !== -1) {
        return 1;
      }

      const ia = tabs.indexOf(a);
      const ib = tabs.indexOf(b);

      return ia - ib;
    });
    return (
      <DndProvider backend={HTML5Backend}>
        <Tabs renderTabBar={this.renderTabBar} {...this.props}>
          {orderTabs}
        </Tabs>
      </DndProvider>
    );
  }
Example #14
Source File: index.tsx    From datart with Apache License 2.0 5 votes vote down vote up
DraggableList = props => {
  return (
    <DndProvider backend={HTML5Backend}>
      <DraggableContainer {...props} />
    </DndProvider>
  );
}
Example #15
Source File: App.tsx    From querybook with Apache License 2.0 5 votes vote down vote up
App = () => (
    <DndProvider backend={HTML5Backend}>
        <Provider store={reduxStore}>
            <AppRouter />
        </Provider>
    </DndProvider>
)
Example #16
Source File: ChartOperationPanel.tsx    From datart with Apache License 2.0 5 votes vote down vote up
StyledChartOperationPanel = styled(DndProvider)<{ backend }>``
Example #17
Source File: dnd-plain-grid.tsx    From ui-schema with MIT License 5 votes vote down vote up
KitDndPlainGrid = () => {
    const [list, setList] = React.useState<List<string>>(List(['caaa-1', 'cbbb-2', 'cccc-3', 'cddd-4', 'ceee-5']))
    const dataKeys = React.useMemo(() => List([]), [])
    const {onIntent} = useOnIntent<HTMLDivElement>()

    const onMove: KitDndProviderContextType<HTMLDivElement>['onMove'] = React.useMemo(() => {
        // important, or more one way-to-do-it: using `useMemo` instead of `useCallback`, as the return on `onIntent` is compatible with `onMove`
        // just a bit cleaner to write then when using `useCallback`, not even possible to accidentally using the wrong `details` var
        return onIntent(({fromItem, toItem}, intent, _intentKeys, done) => {
            if (!intent) {
                return
            }
            if (
                intent.y && intent.x &&
                (intent.y !== 'same' || intent.x !== 'same') &&
                !intent.edgeX && !intent.edgeY
            ) {
                const {index: fromIndex, id: fromId} = fromItem
                const {id: toId} = toItem
                setList((list) => {
                    const toIndex = list.findIndex(i => i === toId)
                    if (toIndex !== -1) {
                        list = list.splice(fromIndex, 1)
                            .splice(toIndex, 0, fromId)
                    }
                    return list
                })
                done()
                return
            }
            return
        })
    }, [setList, onIntent])

    return <>
        <h2>Plain Grid Draggable</h2>
        <div style={{display: 'flex', flexWrap: 'wrap'}}>
            <DndProvider backend={MultiBackend} options={HTML5toTouch}>
                <KitDndProvider<HTMLDivElement> onMove={onMove} scope={'a3'}>
                    {list.map((i, j) =>
                        <DraggableBlock
                            key={i}
                            id={i}
                            index={j}
                            isLast={j >= (list?.size - 1)}
                            isFirst={j === 0}
                            dataKeys={dataKeys}
                            cols={6}
                        />
                    )?.valueSeq()}
                </KitDndProvider>
            </DndProvider>
        </div>
    </>
}
Example #18
Source File: dnd-plain.tsx    From ui-schema with MIT License 5 votes vote down vote up
KitDndPlain = () => {
    const [list, setList] = React.useState<List<string>>(List(['aaaa-1', 'abbb-2', 'accc-3']))
    const dataKeys = React.useMemo(() => List([]), [])
    const {onIntent} = useOnIntent<HTMLDivElement>()

    const onMove: KitDndProviderContextType<HTMLDivElement>['onMove'] = React.useCallback((
        details
    ) => {
        // example using `useCallback` for `onMove`, it is important to not use `details` directly but to pass it to `onIntent`,
        // use the data received by the `cb` instead -> or better use `useMemo`
        onIntent(({fromItem, toItem}, intent, _intentKeys, done) => {
            if (!intent) {
                return
            }
            const {index: toIndex} = toItem
            const {index: fromIndex, id: fromId} = fromItem
            // example: only supporting `y` axis directions within one list, using `colY` to provide some no-drag gutters
            switch (intent.y) {
                case DndIntents.up:
                    if (intent.colY >= 10) {
                        return
                    }
                    setList((list) =>
                        list.splice(fromIndex, 1)
                            .splice(toIndex, 0, fromId)
                    )
                    done()
                    return
                case DndIntents.down:
                    if (intent.colY <= 2 || intent.colY >= 10) {
                        return
                    }
                    setList((list) =>
                        list.splice(fromIndex, 1)
                            .splice(toIndex, 0, fromId)
                    )
                    done()
                    return
            }
            return
        })(details)
    }, [setList, onIntent])

    return <>
        <h2>Plain Draggable</h2>

        <div style={{display: 'flex', flexDirection: 'column'}}>
            <DndProvider backend={MultiBackend} options={HTML5toTouch}>
                <KitDndProvider<HTMLDivElement> onMove={onMove} scope={'a1'}>
                    {list.map((i, j) =>
                        <DraggableBlock
                            key={i}
                            id={i}
                            index={j}
                            isLast={j >= (list?.size - 1)}
                            isFirst={j === 0}
                            dataKeys={dataKeys}
                            fullDrag
                        />
                    )?.valueSeq()}
                </KitDndProvider>
            </DndProvider>
        </div>
    </>
}
Example #19
Source File: material-ui-dnd-grid.tsx    From ui-schema with MIT License 5 votes vote down vote up
SingleEditor = () => {
    const [showValidity, setShowValidity] = React.useState(false)

    const [schema, setSchema] = React.useState<number>(0)
    const [store, setStore] = React.useState<UIStoreType>(() => createStore(OrderedMap()))

    const onChange: onChangeHandler = React.useCallback((actions) => {
        setStore(prevStore => {
            return storeUpdater(actions)(prevStore)
        })
    }, [setStore])

    const {onIntent} = useOnIntent<HTMLDivElement, DragDropSpec>({edgeSize: 12})
    const {onMove} = useOnDirectedMove<HTMLDivElement, DragDropSpec>(
        onIntent, onChange,
    )

    return <React.Fragment>
        <Box mb={2}>
            <FormControl>
                <Label>Select Schema</Label>
                <Select
                    value={schema}
                    // @ts-ignore
                    onChange={e => {
                        // @ts-ignore
                        const s = e.target.value as number
                        setSchema(s)
                        setStore(createEmptyStore(schemas[s][0].get('type') as SchemaTypesType))
                    }}
                    displayEmpty
                >
                    {schemas.map((schema, i) => (
                        <MenuItem key={i} value={i} disabled={!schema[1]}>{schema[0].get('title')}</MenuItem>
                    ))}
                </Select>
            </FormControl>
        </Box>

        <KitDndProvider<HTMLDivElement, DragDropSpec> onMove={onMove}>
            <DragDropBlockProvider blocks={blocks}>
                <DndProvider backend={MultiBackend} options={HTML5toTouch}>
                    <UIStoreProvider
                        store={store}
                        onChange={onChange}
                        showValidity={showValidity}
                    >
                        <GridStack isRoot schema={schemas[schema][0]}/>
                        <MuiSchemaDebug schema={schemas[schema][0]}/>
                    </UIStoreProvider>
                </DndProvider>
            </DragDropBlockProvider>
        </KitDndProvider>

        <div style={{width: '100%'}}>
            <Button onClick={() => setShowValidity(!showValidity)}>validity</Button>
            <div>
                {isInvalid(store.getValidity()) ? 'invalid' : 'valid'}
            </div>
        </div>
    </React.Fragment>
}
Example #20
Source File: material-ui-dnd.tsx    From ui-schema with MIT License 5 votes vote down vote up
SingleEditor = () => {
    const [showValidity, setShowValidity] = React.useState(false)

    const [schema, setSchema] = React.useState<number>(0)
    const [store, setStore] = React.useState<UIStoreType>(() => createStore(List()))

    const onChange = React.useCallback((actions) => {
        setStore(prevStore => {
            return storeUpdater(actions)(prevStore)
        })
    }, [setStore])

    const {onIntent} = useOnIntent<HTMLDivElement, DragDropSpec>({edgeSize: 12})
    const {onMove} = useOnDirectedMove<HTMLDivElement, DragDropSpec>(onIntent, onChange)

    return <React.Fragment>
        <Box mb={2}>
            <FormControl>
                <Label>Select Schema</Label>
                <Select
                    value={schema}
                    // @ts-ignore
                    onChange={e => {
                        // @ts-ignore
                        const s = e.target.value as number
                        setSchema(s)
                        setStore(createEmptyStore(schemas[s][0].get('type') as SchemaTypesType))
                    }}
                    displayEmpty
                >
                    {schemas.map((schema, i) => (
                        <MenuItem key={i} value={i} disabled={!schema[1]}>{schema[0].get('title')}</MenuItem>
                    ))}
                </Select>
            </FormControl>
        </Box>

        <KitDndProvider<HTMLDivElement, DragDropSpec> onMove={onMove}>
            <DndProvider backend={MultiBackend} options={HTML5toTouch}>
                <UIStoreProvider
                    store={store}
                    onChange={onChange}
                    showValidity={showValidity}
                >
                    <GridStack isRoot schema={schemas[schema][0]}/>
                    <MuiSchemaDebug schema={schemas[schema][0]}/>
                </UIStoreProvider>
            </DndProvider>
        </KitDndProvider>

        <div style={{width: '100%'}}>
            <Button onClick={() => setShowValidity(!showValidity)}>validity</Button>
            <div>
                {isInvalid(store.getValidity()) ? 'invalid' : 'valid'}
            </div>
        </div>
    </React.Fragment>
}
Example #21
Source File: Page.tsx    From freedeck-configurator with GNU General Public License v3.0 5 votes vote down vote up
PageComponent: React.FC<IProps> = ({
  brightness,
  pageIndex,
  deleteImage,
  makeDefaultBackImage,
  originalImages,
  width,
  height,
  convertedImages,
  setOriginalImage,
  buttonSettingsPages,
  displaySettingsPages,
  deletePage,
  addPage,
  setButtonSettings,
  setDisplaySettings,
  pageCount,
  switchDisplays,
}) => {
  return (
    <Wrapper id={`page_${pageIndex}`}>
      <Header>
        <PageIndicator>{pageIndex}</PageIndicator>
        <DeletePage
          onClick={() => {
            const deleteConfirmed = window.confirm(
              "Do you really want to delete this page forever?"
            );
            if (deleteConfirmed) deletePage(pageIndex);
          }}
        >
          <FaTrashAlt size={18} color="white" />
        </DeletePage>
      </Header>
      <Grid height={height} width={width}>
        <DndProvider backend={Backend}>
          {displaySettingsPages.map((imageDisplay, displayIndex) => (
            <Display
              brightness={brightness}
              deleteImage={() => deleteImage(displayIndex)}
              makeDefaultBackImage={() => makeDefaultBackImage(displayIndex)}
              convertedImage={
                convertedImages?.[displayIndex] ?? getEmptyConvertedImage()
              }
              setButtonSettings={(displayAction) =>
                setButtonSettings(displayIndex, displayAction)
              }
              setDisplaySettings={(displayImage) =>
                setDisplaySettings(displayIndex, displayImage)
              }
              actionDisplay={buttonSettingsPages[displayIndex]}
              imageDisplay={displaySettingsPages[displayIndex]}
              key={displayIndex}
              displayIndex={displayIndex}
              pageIndex={pageIndex}
              setOriginalImage={(image) =>
                setOriginalImage(displayIndex, image)
              }
              pages={[...Array(pageCount).keys()].filter(
                (pageNumber) => pageNumber !== pageIndex
              )}
              addPage={(primary: boolean) => addPage(displayIndex, primary)}
              originalImage={originalImages[displayIndex]}
              switchDisplays={switchDisplays}
            />
          ))}
        </DndProvider>
      </Grid>
    </Wrapper>
  );
}
Example #22
Source File: index.tsx    From redux-with-domain with MIT License 5 votes vote down vote up
Workbook: FC<Props> = props => {
  const dispatch = useDispatch()
  const id: string = _.get(props, 'match.params.id')
  // 触发初使化
  useEffect(() => {
    dispatch(PageModule.actions.init(id))
  }, [id])

  // 获取工作簿名称
  const name = useSelector((state: object) => {
    return PageModule.selectors.getWorkbookName(state)
  })

  // 当前选中的报表
  const reportId = useSelector(state => {
    return PageModule.selectors.getSelectedReportId(state)
  })

  // 打开预览
  const onPreview = useCallback(() => {
    window.open(`${window.location.origin}/report/${reportId}`)
  }, [reportId])

  return (
    <DndProvider backend={Backend}>
      <div className="workbook">
        <div className="header">
          <span>{`KOP Demo:${name}`}</span>
          <button onClick={onPreview}>预览</button>
        </div>
        <div className="content">
          <div className="sidebar">
            <div className="sidebar-header">数据</div>
            <div className="sidebar-main">
              <div className="left">
                <DatasetList />
                <DatasetFields />
              </div>
              <div className="right">
                <Attribute />
              </div>
            </div>
          </div>
          <div className="main-container">
            <ReportCanvas reportId={reportId} />
            <ReportList />
          </div>
        </div>
      </div>
    </DndProvider>
  )
}
Example #23
Source File: Drag.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
Drag: React.FC<DragListProps> & {
  Item: React.FC<DragItemProps>;
} = (props) => {
  const { onChange, className, style, options: propsOptions, disabled, ...rest } = props;

  const [options, setOptions] = useState(propsOptions);
  useEffect(() => {
    setOptions(propsOptions);
  }, [propsOptions]);
  const prefixCls = `${usePrefixCls(PREFIX)}`;

  const onMoved = (dragIndex: number, hoverIndex: number) => {
    const dragCard = options[dragIndex];
    const updateOptions = update(options, {
      $splice: [
        [dragIndex, 1],
        [hoverIndex, 0, dragCard],
      ],
    });
    setOptions(updateOptions);
    onChange?.(updateOptions);
  };

  return (
    <DndProvider backend={HTML5Backend}>
      <List className={classNames(`${prefixCls}--drag`, className)} style={style}>
        {options?.map((option: OptionProps, index: number) => (
          <DragItem
            {...option}
            {...rest}
            index={index}
            onMoved={onMoved}
            disabled={option?.disabled ?? disabled}
            key={option?.value}
          />
        ))}
      </List>
    </DndProvider>
  );
}
Example #24
Source File: Editor.tsx    From legend-studio with Apache License 2.0 5 votes vote down vote up
Editor: React.FC = () => (
  <EditorStoreProvider>
    <DndProvider backend={HTML5Backend}>
      <EditorInner />
    </DndProvider>
  </EditorStoreProvider>
)
Example #25
Source File: QueryEditor.tsx    From legend-studio with Apache License 2.0 5 votes vote down vote up
QueryEditor: React.FC = () => (
  <DndProvider backend={HTML5Backend}>
    <QueryEditorInner />
  </DndProvider>
)
Example #26
Source File: EditorElementFactory.tsx    From next-core with GNU General Public License v3.0 5 votes vote down vote up
export function EditorElementFactory(
  EditorComponent: EditorComponentType,
  options?: EditorElementOptions
): EditorBrickElementConstructor {
  class NewEditorElement extends UpdatingElement {
    static get selfLayout(): EditorSelfLayout {
      return options?.selfLayout;
    }

    @property({ type: Number })
    nodeUid: number;

    @property({ attribute: false })
    editorProps: StoryDoc["editorProps"];

    connectedCallback(): void {
      // Don't override user's style settings.
      // istanbul ignore else
      if (!this.style.display) {
        this.style.display = "block";
      }
      if (options?.brickStyle) {
        for (const [key, value] of Object.entries(options.brickStyle)) {
          (this.style as unknown as Record<string, string>)[key] = value;
        }
      }
      this._render();
    }

    disconnectedCallback(): void {
      ReactDOM.unmountComponentAtNode(this);
    }

    protected _render(): void {
      // istanbul ignore else
      if (this.isConnected && this.nodeUid) {
        ReactDOM.render(
          <BrickWrapper>
            <BuilderProvider>
              <DndProvider backend={HTML5Backend}>
                <EditorComponent
                  nodeUid={this.nodeUid}
                  editorProps={this.editorProps}
                />
              </DndProvider>
            </BuilderProvider>
          </BrickWrapper>,
          this
        );
      }
    }
  }
  return NewEditorElement;
}
Example #27
Source File: index.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
protected _render(): void {
    // istanbul ignore else
    if (this.isConnected) {
      ReactDOM.render(
        <BrickWrapper>
          <BuilderProvider>
            <DndProvider backend={HTML5Backend}>
              <BuilderContainer
                ref={this._managerRef}
                appId={this.appId}
                dataSource={this.dataSource}
                brickList={this.brickList}
                editorList={this.editorList}
                providerList={this.providerList}
                routeList={this.routeList}
                templateList={this.templateList}
                snippetList={this.snippetList}
                templateSources={this.templateSources}
                storyList={this.storyList}
                processing={this.processing}
                highlightTokens={this.highlightTokens}
                containerForContextModal={this.containerForContextModal}
                migrateClipboard={this.migrateClipboard}
                clipboardData={this.clipboardData}
                showDataView={this.showDataView}
                initialFullscreen={this.fullscreen}
                initialToolboxTab={this.toolboxTab}
                initialHiddenWrapper={this.hiddenWrapper}
                initialEventStreamNodeId={this.eventStreamNodeId}
                initialClipboardType={this.clipboardType}
                initialClipboardSource={this.clipboardSource}
                initialClipboardNodeType={this.clipboardNodeType}
                initialCanvasIndex={this.canvasIndex}
                initialStoryboardQuery={this.storyboardQuery}
                onNodeAdd={this._handleNodeAdd}
                onSnippetApply={this._handleSnippetApply}
                onNodeReorder={this._handleNodeReorder}
                onNodeMove={this._handleNodeMove}
                onNodeClick={this._handleNodeClick}
                onAskForDeletingNode={this._handleAskForDeletingNode}
                onToggleFullscreen={this._handleToggleFullscreen}
                onSwitchToolboxTab={this._handleSwitchToolboxTab}
                onSwitchHiddenWrapper={this._handleSwitchHiddenWrapper}
                onSelectEventStreamNode={this._handleSelectEventsViewNode}
                onClipboardChange={this._handleClipboardChange}
                onNodeCopy={this._handleNodeCopy}
                onNodeCut={this._handleNodeCut}
                onNodeCopyPaste={this._handleNodeCopyPaste}
                onNodeCutPaste={this._handleNodeCutPaste}
                onClipboardClear={this._handleClipboardClear}
                onContextUpdate={this._handleContextUpdate}
                onRouteSelect={this._handleRouteSelect}
                onTemplateSelect={this._handleTemplateSelect}
                onSnippetSelect={this._handleSnippetSelect}
                onCurrentRouteClick={this._handleCurrentRouteClick}
                onCurrentTemplateClick={this._handleCurrentTemplateClick}
                onCurrentSnippetClick={this._handleCurrentSnippetClick}
                onBuildAndPush={this._handleBuildAndPush}
                onPreview={this._handlePreview}
                onAskForAppendingBrick={this._handleAskForAppendingBrick}
                onAskForAppendingRoute={this._handleAskForAppendingRoute}
                onEventNodeClick={this._handleEventNodeClick}
                onConvertToTemplate={this._handleConvertToTemplate}
                onWorkbenchClose={this._handleWorkbenchClose}
                onSwitchCanvasIndex={this._handleSwitchCanvasIndex}
                onStoryboardQueryUpdate={this._handleStoryboardQueryUpdate}
                onClickHighlightToken={this._handleHighlightTokenClick}
              />
            </DndProvider>
          </BuilderProvider>
        </BrickWrapper>,
        this
      );
    }
  }
Example #28
Source File: StoryPlayerForShare.tsx    From datart with Apache License 2.0 4 votes vote down vote up
StoryPlayerForShare: React.FC<{
  storyBoard: StoryBoard;
  shareToken: string;
}> = memo(({ storyBoard, shareToken }) => {
  const { id: storyId } = storyBoard;
  const domId = useMemo(() => uuidv4(), []);
  const revealRef = useRef<any>();
  const dispatch = useDispatch();
  const [currentPageIndex, setCurrentPageIndex] = useState(0);
  const fullRef: RefObject<HTMLDivElement> = useRef(null);
  const pageMap = useSelector((state: { storyBoard: StoryBoardState }) =>
    makeSelectStoryPagesById(state, storyId),
  );
  const subVizTokenMap = useSelector(selectSubVizTokenMap);

  const sortedPages = useMemo(() => {
    const sortedPages = Object.values(pageMap).sort(
      (a, b) => a.config.index - b.config.index,
    );
    return sortedPages;
  }, [pageMap]);

  const changePage = useCallback(
    e => {
      const { indexh: slideIdx } = e;
      setCurrentPageIndex(slideIdx);
      const pageId = sortedPages[slideIdx].id;
      dispatch(
        storyActions.changePageSelected({
          storyId,
          pageId,
          multiple: false,
        }),
      );
    },
    [dispatch, sortedPages, storyId],
  );

  useEffect(() => {
    if (sortedPages.length === 0) {
      return;
    }
    const pageId = sortedPages[0].id;
    dispatch(
      storyActions.changePageSelected({
        storyId,
        pageId,
        multiple: false,
      }),
    );
  }, [dispatch, sortedPages, storyId]);
  const autoSlide = useMemo(() => {
    if (storyBoard?.config?.autoPlay?.auto) {
      return storyBoard?.config?.autoPlay?.delay * 1000;
    }
    return null;
  }, [storyBoard?.config?.autoPlay?.auto, storyBoard?.config?.autoPlay?.delay]);
  useEffect(() => {
    if (sortedPages.length > 0) {
      revealRef.current = new Reveal(document.getElementById(domId), {
        hash: false,
        history: false,
        controls: true,
        controlsLayout: 'none',
        slideNumber: 'c/t',
        controlsTutorial: false,
        progress: false,
        loop: true,
        width: '100%',
        height: '100%',
        margin: 0,
        minScale: 1,
        maxScale: 1,
        autoSlide: autoSlide,
        transition: 'convex',
        // backgroundTransition: 'fade',
        transitionSpeed: 'slow',
        viewDistance: 100,
        plugins: [RevealZoom],
        keyboard: {
          27: () => {
            // disabled esc
          }, // do something custom when ESC is pressed
        },
      });
      revealRef.current?.initialize();
      if (revealRef.current) {
        revealRef.current.addEventListener('slidechanged', changePage);
      }
      return () => {
        revealRef.current.removeEventListener('slidechanged', changePage);
      };
    }
  }, [domId, changePage, sortedPages.length, autoSlide, dispatch]);

  useEffect(() => {
    const curPage = sortedPages[currentPageIndex];
    if (!curPage || !curPage.relId || !curPage.relType) {
      return;
    }
    const { relId, relType, id } = curPage;
    const vizToken = subVizTokenMap?.[id];
    if (!vizToken) {
      return;
    }
    dispatch(
      getPageContentDetail({
        shareToken,
        relId,
        relType,
        vizToken: vizToken,
      }),
    );
  }, [
    currentPageIndex,
    dispatch,
    sortedPages,
    pageMap,
    subVizTokenMap,
    shareToken,
  ]);

  return (
    <DndProvider backend={HTML5Backend}>
      <Wrapper ref={fullRef}>
        <Content>
          <div id={domId} className="reveal">
            <div className="slides">
              {sortedPages.map(page => (
                <StoryPageItem key={page.id} page={page} />
              ))}
            </div>
          </div>
        </Content>
      </Wrapper>
    </DndProvider>
  );
})
Example #29
Source File: new-canvas-controls.tsx    From utopia with MIT License 4 votes vote down vote up
NewCanvasControls = React.memo((props: NewCanvasControlsProps) => {
  const canvasControlProps = useEditorState(
    (store) => ({
      dispatch: store.dispatch,
      editor: store.editor,
      derived: store.derived,
      canvasOffset: store.editor.canvas.roundedCanvasOffset,
      controls: store.derived.controls,
      scale: store.editor.canvas.scale,
      focusedPanel: store.editor.focusedPanel,
      transientCanvasState: store.derived.transientState,
    }),
    'NewCanvasControls',
  )

  const { localSelectedViews, localHighlightedViews, setSelectedViewsLocally } =
    useLocalSelectedHighlightedViews(
      canvasControlProps.editor.selectedViews,
      canvasControlProps.editor.highlightedViews,
      canvasControlProps.transientCanvasState,
    )

  const canvasScrollAnimation = useEditorState(
    (store) => store.editor.canvas.scrollAnimation,
    'NewCanvasControls scrollAnimation',
  )

  // Somehow this being setup and hooked into the div makes the `onDrop` call
  // work properly in `editor-canvas.ts`. I blame React DnD for this.
  const dropSpec: DropTargetHookSpec<FileBrowserItemProps, 'CANVAS', unknown> = {
    accept: 'filebrowser',
    canDrop: () => true,
  }

  const [_, drop] = useDrop(dropSpec)

  const forwardedRef = React.useCallback(
    (node: ConnectableElement) => {
      return drop(node)
    },
    [drop],
  )

  if (isLiveMode(canvasControlProps.editor.mode) && !canvasControlProps.editor.keysPressed.cmd) {
    return null
  } else {
    return (
      <DndProvider backend={HTML5Backend}>
        <div
          key='canvas-controls'
          ref={forwardedRef}
          className={
            canvasControlProps.focusedPanel === 'canvas'
              ? '  canvas-controls focused '
              : ' canvas-controls '
          }
          id='canvas-controls'
          style={{
            pointerEvents: 'initial',
            position: 'absolute',
            top: 0,
            left: 0,
            transform: 'translate3d(0, 0, 0)',
            width: `100%`,
            height: `100%`,
            zoom: canvasControlProps.scale >= 1 ? `${canvasControlProps.scale * 100}%` : 1,
            cursor: props.cursor,
            visibility: canvasScrollAnimation ? 'hidden' : 'initial',
          }}
        >
          <div
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: `${canvasControlProps.scale < 1 ? 100 / canvasControlProps.scale : 100}%`,
              height: `${canvasControlProps.scale < 1 ? 100 / canvasControlProps.scale : 100}%`,
              transformOrigin: 'top left',
              transform: canvasControlProps.scale < 1 ? `scale(${canvasControlProps.scale}) ` : '',
            }}
          >
            <NewCanvasControlsInner
              windowToCanvasPosition={props.windowToCanvasPosition}
              localSelectedViews={localSelectedViews}
              localHighlightedViews={localHighlightedViews}
              setLocalSelectedViews={setSelectedViewsLocally}
              editor={canvasControlProps.editor}
              transientState={canvasControlProps.transientCanvasState}
              dispatch={canvasControlProps.dispatch}
              canvasOffset={canvasControlProps.canvasOffset}
            />
          </div>
          <ElementContextMenu contextMenuInstance='context-menu-canvas' />
        </div>
      </DndProvider>
    )
  }
})