Tldraw/apps/dotcom/src/utils/useFileSystem.tsx

142 wiersze
3.8 KiB
TypeScript
Czysty Zwykły widok Historia

import { fileOpen, fileSave } from 'browser-fs-access'
import { useMemo } from 'react'
import {
Editor,
TLDRAW_FILE_EXTENSION,
TLStore,
TLUiActionItem,
TLUiEventHandler,
TLUiOverrides,
parseAndLoadDocument,
serializeTldrawJsonBlob,
transact,
} from 'tldraw'
import { shouldClearDocument } from './shouldClearDocument'
import { shouldOverrideDocument } from './shouldOverrideDocument'
import { useHandleUiEvents } from './useHandleUiEvent'
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
export const SAVE_FILE_COPY_ACTION = 'save-file-copy'
export const OPEN_FILE_ACTION = 'open-file'
export const NEW_PROJECT_ACTION = 'new-file'
const saveFileNames = new WeakMap<TLStore, string>()
export function useFileSystem({ isMultiplayer }: { isMultiplayer: boolean }): TLUiOverrides {
const handleUiEvent = useHandleUiEvents()
return useMemo((): TLUiOverrides => {
return {
actions(editor, actions, { addToast, msg, addDialog }) {
Allow users to set document name and use it for exporting / saving (#2685) Adds the ability to change document names in the top center part of the UI. This mostly brings back the functionality we already had in the past. This is basically a port of what @SomeHats did a while back. I changed the dropdown options and removed some of the things (we are not dealing with network requests directly so some of that logic did not apply any longer). We did have autosave back then, not sure if we want to bring that back? Changes the `exportAs` api, thus braking. ### Change Type - [ ] `patch` — Bug fix - [ ] `minor` — New feature - [x] `major` — Breaking change - [ ] `dependencies` — Changes to package dependencies[^1] - [ ] `documentation` — Changes to the documentation only[^2] - [ ] `tests` — Changes to any test code only[^2] - [ ] `internal` — Any other changes that don't affect the published package[^2] - [ ] I don't know [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Top center should now show a new UI element. It has a dropdown with a few actions. 2. Double clicking the name should also start editing it. 3. The name should also be respected when exporting things. Not if you select some shapes or a frame. In that case we still use the old names. But if you don't have anything selected and then export / save a project it should have the document name. - [ ] Unit Tests - [ ] End to end tests ### Release Notes - Allow users to name their documents.
2024-02-19 12:30:26 +00:00
actions[SAVE_FILE_COPY_ACTION] = getSaveFileCopyAction(
editor,
handleUiEvent,
msg('document.default-name')
)
actions[OPEN_FILE_ACTION] = {
id: OPEN_FILE_ACTION,
label: 'action.open-file',
readonlyOk: true,
kbd: '$o',
async onSelect(source) {
handleUiEvent('open-file', { source })
// open in multiplayer is not currently supported
if (isMultiplayer) {
addToast({
title: msg('file-system.shared-document-file-open-error.title'),
description: msg('file-system.shared-document-file-open-error.description'),
severity: 'error',
})
return
}
const shouldOverride = await shouldOverrideDocument(addDialog)
if (!shouldOverride) return
let file
try {
file = await fileOpen({
extensions: [TLDRAW_FILE_EXTENSION],
multiple: false,
description: 'tldraw project',
})
} catch (e) {
// user cancelled
return
}
await parseAndLoadDocument(editor, await file.text(), msg, addToast)
},
}
actions[NEW_PROJECT_ACTION] = {
id: NEW_PROJECT_ACTION,
label: 'action.new-project',
readonlyOk: true,
async onSelect(source) {
handleUiEvent('create-new-project', { source })
const shouldOverride = await shouldClearDocument(addDialog)
if (!shouldOverride) return
transact(() => {
const isFocused = editor.getInstanceState().isFocused
const bounds = editor.getViewportScreenBounds().clone()
editor.store.clear()
editor.store.ensureStoreIsUsable()
editor.history.clear()
// Put the old bounds back in place
editor.updateViewportScreenBounds(bounds)
editor.updateRenderingBounds()
editor.updateInstanceState({ isFocused })
})
},
}
return actions
},
}
}, [isMultiplayer, handleUiEvent])
}
export function getSaveFileCopyAction(
editor: Editor,
Allow users to set document name and use it for exporting / saving (#2685) Adds the ability to change document names in the top center part of the UI. This mostly brings back the functionality we already had in the past. This is basically a port of what @SomeHats did a while back. I changed the dropdown options and removed some of the things (we are not dealing with network requests directly so some of that logic did not apply any longer). We did have autosave back then, not sure if we want to bring that back? Changes the `exportAs` api, thus braking. ### Change Type - [ ] `patch` — Bug fix - [ ] `minor` — New feature - [x] `major` — Breaking change - [ ] `dependencies` — Changes to package dependencies[^1] - [ ] `documentation` — Changes to the documentation only[^2] - [ ] `tests` — Changes to any test code only[^2] - [ ] `internal` — Any other changes that don't affect the published package[^2] - [ ] I don't know [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Top center should now show a new UI element. It has a dropdown with a few actions. 2. Double clicking the name should also start editing it. 3. The name should also be respected when exporting things. Not if you select some shapes or a frame. In that case we still use the old names. But if you don't have anything selected and then export / save a project it should have the document name. - [ ] Unit Tests - [ ] End to end tests ### Release Notes - Allow users to name their documents.
2024-02-19 12:30:26 +00:00
handleUiEvent: TLUiEventHandler,
defaultDocumentName: string
): TLUiActionItem {
return {
id: SAVE_FILE_COPY_ACTION,
label: 'action.save-copy',
readonlyOk: true,
kbd: '$s',
async onSelect(source) {
handleUiEvent('save-project-to-file', { source })
Allow users to set document name and use it for exporting / saving (#2685) Adds the ability to change document names in the top center part of the UI. This mostly brings back the functionality we already had in the past. This is basically a port of what @SomeHats did a while back. I changed the dropdown options and removed some of the things (we are not dealing with network requests directly so some of that logic did not apply any longer). We did have autosave back then, not sure if we want to bring that back? Changes the `exportAs` api, thus braking. ### Change Type - [ ] `patch` — Bug fix - [ ] `minor` — New feature - [x] `major` — Breaking change - [ ] `dependencies` — Changes to package dependencies[^1] - [ ] `documentation` — Changes to the documentation only[^2] - [ ] `tests` — Changes to any test code only[^2] - [ ] `internal` — Any other changes that don't affect the published package[^2] - [ ] I don't know [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Top center should now show a new UI element. It has a dropdown with a few actions. 2. Double clicking the name should also start editing it. 3. The name should also be respected when exporting things. Not if you select some shapes or a frame. In that case we still use the old names. But if you don't have anything selected and then export / save a project it should have the document name. - [ ] Unit Tests - [ ] End to end tests ### Release Notes - Allow users to name their documents.
2024-02-19 12:30:26 +00:00
const documentName =
editor.getDocumentSettings().name === ''
? defaultDocumentName
: editor.getDocumentSettings().name
const defaultName =
saveFileNames.get(editor.store) || `${documentName}${TLDRAW_FILE_EXTENSION}`
const blobToSave = serializeTldrawJsonBlob(editor.store)
let handle
try {
handle = await fileSave(blobToSave, {
fileName: defaultName,
extensions: [TLDRAW_FILE_EXTENSION],
description: 'tldraw project',
})
} catch (e) {
// user cancelled
return
}
if (handle) {
// we deliberately don't store the handle for re-use
// next time. we always want to save a copy, but to
// help the user out we'll remember the last name
// they used
saveFileNames.set(editor.store, handle.name)
}
},
}
}