Tldraw/packages/tldraw/src/lib/ui/hooks/menu-hooks.ts

216 wiersze
4.9 KiB
TypeScript
Czysty Zwykły widok Historia

Composable custom UI (#2796) This PR refactors our menu systems and provides an interface to hide or replace individual user interface elements. # Background Previously, we've had two types of overrides: - "schema" overrides that would allow insertion or replacement of items in the different menus - "component" overrides that would replace components in the editor's user interface This PR is an attempt to unify the two and to provide for additional cases where the "schema-based" user interface had begun to break down. # Approach This PR makes no attempt to change the `actions` or `tools` overrides—the current system seems to be correct for those because they are not reactive. The challenge with the other ui schemas is that they _are_ reactive, and thus the overrides both need to a) be fed in from outside of the editor as props, and b) react to changes from the editor, which is an impossible situation. The new approach is to use React to declare menu items. (Surprise!) ```tsx function CustomHelpMenuContent() { return ( <> <DefaultHelpMenuContent /> <TldrawUiMenuGroup id="custom stuff"> <TldrawUiMenuItem id="about" label="Like my posts" icon="external-link" readonlyOk onSelect={() => { window.open('https://x.com/tldraw', '_blank') }} /> </TldrawUiMenuGroup> </> ) } const components: TLComponents = { HelpMenuContent: CustomHelpMenuContent, } export default function CustomHelpMenuContentExample() { return ( <div className="tldraw__editor"> <Tldraw components={components} /> </div> ) } ``` We use a `components` prop with the combined editor and ui components. - [ ] Create a "layout" component? - [ ] Make UI components more isolated? If possible, they shouldn't depend on styles outside of themselves, so that they can be used in other layouts. Maybe we wait on this because I'm feeling a slippery slope toward presumptions about configurability. - [ ] OTOH maybe we go hard and consider these things as separate components, even packages, with their own interfaces for customizability / configurability, just go all the way with it, and see what that looks like. # Pros Top line: you can customize tldraw's user interface in a MUCH more granular / powerful way than before. It solves a case where menu items could not be made stateful from outside of the editor context, and provides the option to do things in the menus that we couldn't allow previously with the "schema-based" approach. It also may (who knows) be more performant because we can locate the state inside of the components for individual buttons and groups, instead of all at the top level above the "schema". Because items / groups decide their own state, we don't have to have big checks on how many items are selected, or whether we have a flippable state. Items and groups themselves are allowed to re-build as part of the regular React lifecycle. Menus aren't constantly being rebuilt, if that were ever an issue. Menu items can be shared between different menu types. We'll are sometimes able to re-use items between, for example, the menu and the context menu and the actions menu. Our overrides no longer mutate anything, so there's less weird searching and finding. # Cons This approach can make customization menu contents significantly more complex, as an end user would need to re-declare most of a menu in order to make any change to it. Luckily a user can add things to the top or bottom of the context menu fairly easily. (And who knows, folks may actually want to do deep customization, and this allows for it.) It's more code. We are shipping more react components, basically one for each menu item / group. Currently this PR does not export the subcomponents, i.e. menu items. If we do want to export these, then heaven help us, it's going to be a _lot_ of exports. # Progress - [x] Context menu - [x] Main menu - [x] Zoom menu - [x] Help menu - [x] Actions menu - [x] Keyboard shortcuts menu - [x] Quick actions in main menu? (new) - [x] Helper buttons? (new) - [x] Debug Menu And potentially - [x] Toolbar - [x] Style menu - [ ] Share zone - [x] Navigation zone - [ ] Other zones ### Change Type - [x] `major` — Breaking change ### Test Plan 1. use the context menu 2. use the custom context menu example 3. use cursor chat in the context menu - [x] Unit Tests - [ ] End to end tests ### Release Notes - Add a brief release note for your PR here.
2024-02-15 12:10:09 +00:00
import {
Editor,
TLArrowShape,
TLDrawShape,
TLGroupShape,
TLLineShape,
TLTextShape,
useEditor,
useValue,
} from '@tldraw/editor'
function shapesWithUnboundArrows(editor: Editor) {
const selectedShapeIds = editor.getSelectedShapeIds()
const selectedShapes = selectedShapeIds.map((id) => {
return editor.getShape(id)
})
return selectedShapes.filter((shape) => {
if (!shape) return false
if (
editor.isShapeOfType<TLArrowShape>(shape, 'arrow') &&
shape.props.start.type === 'binding'
) {
return false
}
if (editor.isShapeOfType<TLArrowShape>(shape, 'arrow') && shape.props.end.type === 'binding') {
return false
}
return true
})
}
/** @internal */
export const useThreeStackableItems = () => {
const editor = useEditor()
return useValue('threeStackableItems', () => shapesWithUnboundArrows(editor).length > 2, [editor])
}
/** @internal */
export const useAllowGroup = () => {
const editor = useEditor()
return useValue(
'allow group',
() => {
// We can't group arrows that are bound to shapes that aren't selected
// if more than one shape has an arrow bound to it, allow group
const selectedShapes = editor.getSelectedShapes()
if (selectedShapes.length < 2) return false
for (const shape of selectedShapes) {
if (editor.isShapeOfType<TLArrowShape>(shape, 'arrow')) {
const { start, end } = shape.props
if (start.type === 'binding') {
// if the other shape is not among the selected shapes...
if (!selectedShapes.some((s) => s.id === start.boundShapeId)) {
return false
}
}
if (end.type === 'binding') {
// if the other shape is not among the selected shapes...
if (!selectedShapes.some((s) => s.id === end.boundShapeId)) {
return false
}
}
}
}
return true
},
[editor]
)
}
/** @internal */
export const useAllowUngroup = () => {
const editor = useEditor()
return useValue(
'allowUngroup',
() => editor.getSelectedShapeIds().some((id) => editor.getShape(id)?.type === 'group'),
[editor]
)
}
export const showMenuPaste =
typeof window !== 'undefined' &&
'navigator' in window &&
Boolean(navigator.clipboard) &&
Boolean(navigator.clipboard.read)
/**
* Returns true if the number of LOCKED OR UNLOCKED selected shapes is at least min or at most max.
*/
export function useAnySelectedShapesCount(min?: number, max?: number) {
const editor = useEditor()
return useValue(
'selectedShapes',
() => {
const len = editor.getSelectedShapes().length
if (min === undefined) {
if (max === undefined) {
// just length
return len
} else {
// max but no min
return len <= max
}
} else {
if (max === undefined) {
// min but no max
return len >= min
} else {
// max and min
return len >= min && len <= max
}
}
},
[editor, min, max]
)
}
/**
* Returns true if the number of UNLOCKED selected shapes is at least min or at most max.
*/
export function useUnlockedSelectedShapesCount(min?: number, max?: number) {
const editor = useEditor()
return useValue(
'selectedShapes',
() => {
const len = editor
.getSelectedShapes()
.filter((s) => !editor.isShapeOrAncestorLocked(s)).length
if (min === undefined) {
if (max === undefined) {
// just length
return len
} else {
// max but no min
return len <= max
}
} else {
if (max === undefined) {
// min but no max
return len >= min
} else {
// max and min
return len >= min && len <= max
}
}
},
[editor]
)
}
export function useShowAutoSizeToggle() {
const editor = useEditor()
return useValue(
'showAutoSizeToggle',
() => {
const selectedShapes = editor.getSelectedShapes()
return (
selectedShapes.length === 1 &&
editor.isShapeOfType<TLTextShape>(selectedShapes[0], 'text') &&
selectedShapes[0].props.autoSize === false
)
},
[editor]
)
}
export function useHasLinkShapeSelected() {
const editor = useEditor()
return useValue(
'hasLinkShapeSelected',
() => {
const onlySelectedShape = editor.getOnlySelectedShape()
return !!(
onlySelectedShape &&
onlySelectedShape.type !== 'embed' &&
'url' in onlySelectedShape.props &&
!onlySelectedShape.isLocked
Composable custom UI (#2796) This PR refactors our menu systems and provides an interface to hide or replace individual user interface elements. # Background Previously, we've had two types of overrides: - "schema" overrides that would allow insertion or replacement of items in the different menus - "component" overrides that would replace components in the editor's user interface This PR is an attempt to unify the two and to provide for additional cases where the "schema-based" user interface had begun to break down. # Approach This PR makes no attempt to change the `actions` or `tools` overrides—the current system seems to be correct for those because they are not reactive. The challenge with the other ui schemas is that they _are_ reactive, and thus the overrides both need to a) be fed in from outside of the editor as props, and b) react to changes from the editor, which is an impossible situation. The new approach is to use React to declare menu items. (Surprise!) ```tsx function CustomHelpMenuContent() { return ( <> <DefaultHelpMenuContent /> <TldrawUiMenuGroup id="custom stuff"> <TldrawUiMenuItem id="about" label="Like my posts" icon="external-link" readonlyOk onSelect={() => { window.open('https://x.com/tldraw', '_blank') }} /> </TldrawUiMenuGroup> </> ) } const components: TLComponents = { HelpMenuContent: CustomHelpMenuContent, } export default function CustomHelpMenuContentExample() { return ( <div className="tldraw__editor"> <Tldraw components={components} /> </div> ) } ``` We use a `components` prop with the combined editor and ui components. - [ ] Create a "layout" component? - [ ] Make UI components more isolated? If possible, they shouldn't depend on styles outside of themselves, so that they can be used in other layouts. Maybe we wait on this because I'm feeling a slippery slope toward presumptions about configurability. - [ ] OTOH maybe we go hard and consider these things as separate components, even packages, with their own interfaces for customizability / configurability, just go all the way with it, and see what that looks like. # Pros Top line: you can customize tldraw's user interface in a MUCH more granular / powerful way than before. It solves a case where menu items could not be made stateful from outside of the editor context, and provides the option to do things in the menus that we couldn't allow previously with the "schema-based" approach. It also may (who knows) be more performant because we can locate the state inside of the components for individual buttons and groups, instead of all at the top level above the "schema". Because items / groups decide their own state, we don't have to have big checks on how many items are selected, or whether we have a flippable state. Items and groups themselves are allowed to re-build as part of the regular React lifecycle. Menus aren't constantly being rebuilt, if that were ever an issue. Menu items can be shared between different menu types. We'll are sometimes able to re-use items between, for example, the menu and the context menu and the actions menu. Our overrides no longer mutate anything, so there's less weird searching and finding. # Cons This approach can make customization menu contents significantly more complex, as an end user would need to re-declare most of a menu in order to make any change to it. Luckily a user can add things to the top or bottom of the context menu fairly easily. (And who knows, folks may actually want to do deep customization, and this allows for it.) It's more code. We are shipping more react components, basically one for each menu item / group. Currently this PR does not export the subcomponents, i.e. menu items. If we do want to export these, then heaven help us, it's going to be a _lot_ of exports. # Progress - [x] Context menu - [x] Main menu - [x] Zoom menu - [x] Help menu - [x] Actions menu - [x] Keyboard shortcuts menu - [x] Quick actions in main menu? (new) - [x] Helper buttons? (new) - [x] Debug Menu And potentially - [x] Toolbar - [x] Style menu - [ ] Share zone - [x] Navigation zone - [ ] Other zones ### Change Type - [x] `major` — Breaking change ### Test Plan 1. use the context menu 2. use the custom context menu example 3. use cursor chat in the context menu - [x] Unit Tests - [ ] End to end tests ### Release Notes - Add a brief release note for your PR here.
2024-02-15 12:10:09 +00:00
)
},
[editor]
)
}
export function useOnlyFlippableShape() {
const editor = useEditor()
return useValue(
'onlyFlippableShape',
() => {
Menu updates / fix flip / add export / remove Shape menu (#3115) This PR: - adds the export all menu items to the main menu - removes the export all menu items from the dotcom menus - removes the shape menu and reverts several changes from https://github.com/tldraw/tldraw/pull/2782. This was not properly reviewed (I thought it was a PR about hiding / showing menu items). - fixes a bug with exporting (exporting JSON was not working when the user had no selected shapes) - fixes a bug that would prevent "flip shapes" from appearing in the menu - prevents export / copy actions from running if there are no shapes on the page - allows export / copy actions to default to all shapes on the page if no shapes are selected These changes have not been released in the dotcom yet. There's will be some thrash in the APIs. # Menu philosophy In the menu, the **edit** submenu relates to undo/redo, plus the user's current selection. Menu items that relate to specific to certain shapes are hidden when not available. Menu items that relate to all shapes are disabled when not available. <img width="640" alt="image" src="https://github.com/tldraw/tldraw/assets/23072548/e467e6bb-d958-4a9a-ac19-1dada52dcfa6"> ### Change Type - [x] `major` — Bug fix ### Test - Select no shapes (arrange / flip should not be visible) - Select one geo shape (arrange / flip should not be visible) - Select two geo shapes (arrange / flip should be visible) - Select one draw shape (arrange / flip should not be visible) ### Release Notes - Revert some changes in the menu.
2024-03-11 18:31:28 +00:00
const shape = editor.getOnlySelectedShape()
Composable custom UI (#2796) This PR refactors our menu systems and provides an interface to hide or replace individual user interface elements. # Background Previously, we've had two types of overrides: - "schema" overrides that would allow insertion or replacement of items in the different menus - "component" overrides that would replace components in the editor's user interface This PR is an attempt to unify the two and to provide for additional cases where the "schema-based" user interface had begun to break down. # Approach This PR makes no attempt to change the `actions` or `tools` overrides—the current system seems to be correct for those because they are not reactive. The challenge with the other ui schemas is that they _are_ reactive, and thus the overrides both need to a) be fed in from outside of the editor as props, and b) react to changes from the editor, which is an impossible situation. The new approach is to use React to declare menu items. (Surprise!) ```tsx function CustomHelpMenuContent() { return ( <> <DefaultHelpMenuContent /> <TldrawUiMenuGroup id="custom stuff"> <TldrawUiMenuItem id="about" label="Like my posts" icon="external-link" readonlyOk onSelect={() => { window.open('https://x.com/tldraw', '_blank') }} /> </TldrawUiMenuGroup> </> ) } const components: TLComponents = { HelpMenuContent: CustomHelpMenuContent, } export default function CustomHelpMenuContentExample() { return ( <div className="tldraw__editor"> <Tldraw components={components} /> </div> ) } ``` We use a `components` prop with the combined editor and ui components. - [ ] Create a "layout" component? - [ ] Make UI components more isolated? If possible, they shouldn't depend on styles outside of themselves, so that they can be used in other layouts. Maybe we wait on this because I'm feeling a slippery slope toward presumptions about configurability. - [ ] OTOH maybe we go hard and consider these things as separate components, even packages, with their own interfaces for customizability / configurability, just go all the way with it, and see what that looks like. # Pros Top line: you can customize tldraw's user interface in a MUCH more granular / powerful way than before. It solves a case where menu items could not be made stateful from outside of the editor context, and provides the option to do things in the menus that we couldn't allow previously with the "schema-based" approach. It also may (who knows) be more performant because we can locate the state inside of the components for individual buttons and groups, instead of all at the top level above the "schema". Because items / groups decide their own state, we don't have to have big checks on how many items are selected, or whether we have a flippable state. Items and groups themselves are allowed to re-build as part of the regular React lifecycle. Menus aren't constantly being rebuilt, if that were ever an issue. Menu items can be shared between different menu types. We'll are sometimes able to re-use items between, for example, the menu and the context menu and the actions menu. Our overrides no longer mutate anything, so there's less weird searching and finding. # Cons This approach can make customization menu contents significantly more complex, as an end user would need to re-declare most of a menu in order to make any change to it. Luckily a user can add things to the top or bottom of the context menu fairly easily. (And who knows, folks may actually want to do deep customization, and this allows for it.) It's more code. We are shipping more react components, basically one for each menu item / group. Currently this PR does not export the subcomponents, i.e. menu items. If we do want to export these, then heaven help us, it's going to be a _lot_ of exports. # Progress - [x] Context menu - [x] Main menu - [x] Zoom menu - [x] Help menu - [x] Actions menu - [x] Keyboard shortcuts menu - [x] Quick actions in main menu? (new) - [x] Helper buttons? (new) - [x] Debug Menu And potentially - [x] Toolbar - [x] Style menu - [ ] Share zone - [x] Navigation zone - [ ] Other zones ### Change Type - [x] `major` — Breaking change ### Test Plan 1. use the context menu 2. use the custom context menu example 3. use cursor chat in the context menu - [x] Unit Tests - [ ] End to end tests ### Release Notes - Add a brief release note for your PR here.
2024-02-15 12:10:09 +00:00
return (
Menu updates / fix flip / add export / remove Shape menu (#3115) This PR: - adds the export all menu items to the main menu - removes the export all menu items from the dotcom menus - removes the shape menu and reverts several changes from https://github.com/tldraw/tldraw/pull/2782. This was not properly reviewed (I thought it was a PR about hiding / showing menu items). - fixes a bug with exporting (exporting JSON was not working when the user had no selected shapes) - fixes a bug that would prevent "flip shapes" from appearing in the menu - prevents export / copy actions from running if there are no shapes on the page - allows export / copy actions to default to all shapes on the page if no shapes are selected These changes have not been released in the dotcom yet. There's will be some thrash in the APIs. # Menu philosophy In the menu, the **edit** submenu relates to undo/redo, plus the user's current selection. Menu items that relate to specific to certain shapes are hidden when not available. Menu items that relate to all shapes are disabled when not available. <img width="640" alt="image" src="https://github.com/tldraw/tldraw/assets/23072548/e467e6bb-d958-4a9a-ac19-1dada52dcfa6"> ### Change Type - [x] `major` — Bug fix ### Test - Select no shapes (arrange / flip should not be visible) - Select one geo shape (arrange / flip should not be visible) - Select two geo shapes (arrange / flip should be visible) - Select one draw shape (arrange / flip should not be visible) ### Release Notes - Revert some changes in the menu.
2024-03-11 18:31:28 +00:00
shape &&
(editor.isShapeOfType<TLGroupShape>(shape, 'group') ||
editor.isShapeOfType<TLArrowShape>(shape, 'arrow') ||
editor.isShapeOfType<TLLineShape>(shape, 'line') ||
editor.isShapeOfType<TLDrawShape>(shape, 'draw'))
Composable custom UI (#2796) This PR refactors our menu systems and provides an interface to hide or replace individual user interface elements. # Background Previously, we've had two types of overrides: - "schema" overrides that would allow insertion or replacement of items in the different menus - "component" overrides that would replace components in the editor's user interface This PR is an attempt to unify the two and to provide for additional cases where the "schema-based" user interface had begun to break down. # Approach This PR makes no attempt to change the `actions` or `tools` overrides—the current system seems to be correct for those because they are not reactive. The challenge with the other ui schemas is that they _are_ reactive, and thus the overrides both need to a) be fed in from outside of the editor as props, and b) react to changes from the editor, which is an impossible situation. The new approach is to use React to declare menu items. (Surprise!) ```tsx function CustomHelpMenuContent() { return ( <> <DefaultHelpMenuContent /> <TldrawUiMenuGroup id="custom stuff"> <TldrawUiMenuItem id="about" label="Like my posts" icon="external-link" readonlyOk onSelect={() => { window.open('https://x.com/tldraw', '_blank') }} /> </TldrawUiMenuGroup> </> ) } const components: TLComponents = { HelpMenuContent: CustomHelpMenuContent, } export default function CustomHelpMenuContentExample() { return ( <div className="tldraw__editor"> <Tldraw components={components} /> </div> ) } ``` We use a `components` prop with the combined editor and ui components. - [ ] Create a "layout" component? - [ ] Make UI components more isolated? If possible, they shouldn't depend on styles outside of themselves, so that they can be used in other layouts. Maybe we wait on this because I'm feeling a slippery slope toward presumptions about configurability. - [ ] OTOH maybe we go hard and consider these things as separate components, even packages, with their own interfaces for customizability / configurability, just go all the way with it, and see what that looks like. # Pros Top line: you can customize tldraw's user interface in a MUCH more granular / powerful way than before. It solves a case where menu items could not be made stateful from outside of the editor context, and provides the option to do things in the menus that we couldn't allow previously with the "schema-based" approach. It also may (who knows) be more performant because we can locate the state inside of the components for individual buttons and groups, instead of all at the top level above the "schema". Because items / groups decide their own state, we don't have to have big checks on how many items are selected, or whether we have a flippable state. Items and groups themselves are allowed to re-build as part of the regular React lifecycle. Menus aren't constantly being rebuilt, if that were ever an issue. Menu items can be shared between different menu types. We'll are sometimes able to re-use items between, for example, the menu and the context menu and the actions menu. Our overrides no longer mutate anything, so there's less weird searching and finding. # Cons This approach can make customization menu contents significantly more complex, as an end user would need to re-declare most of a menu in order to make any change to it. Luckily a user can add things to the top or bottom of the context menu fairly easily. (And who knows, folks may actually want to do deep customization, and this allows for it.) It's more code. We are shipping more react components, basically one for each menu item / group. Currently this PR does not export the subcomponents, i.e. menu items. If we do want to export these, then heaven help us, it's going to be a _lot_ of exports. # Progress - [x] Context menu - [x] Main menu - [x] Zoom menu - [x] Help menu - [x] Actions menu - [x] Keyboard shortcuts menu - [x] Quick actions in main menu? (new) - [x] Helper buttons? (new) - [x] Debug Menu And potentially - [x] Toolbar - [x] Style menu - [ ] Share zone - [x] Navigation zone - [ ] Other zones ### Change Type - [x] `major` — Breaking change ### Test Plan 1. use the context menu 2. use the custom context menu example 3. use cursor chat in the context menu - [x] Unit Tests - [ ] End to end tests ### Release Notes - Add a brief release note for your PR here.
2024-02-15 12:10:09 +00:00
)
},
[editor]
)
}
/** @public */
export function useCanRedo() {
const editor = useEditor()
return useValue('useCanRedo', () => editor.getCanRedo(), [editor])
}
/** @public */
export function useCanUndo() {
const editor = useEditor()
return useValue('useCanUndo', () => editor.getCanUndo(), [editor])
}