Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/features/src/Domain/Component/ComponentAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ export enum ComponentAction {
KeyDown = 'key-down',
KeyUp = 'key-up',
Click = 'click',
ScrollToEnd = 'scroll-to-end',
ScrollState = 'scroll-state',
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export type ComponentScrollState = {
canScroll: boolean
isAtBottom: boolean
/** Space between the scroll container and the bottom of the editor, e.g. a toolbar the host must not cover */
bottomInset?: number
}
5 changes: 5 additions & 0 deletions packages/models/src/Domain/Abstract/Component/MessageData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,9 @@ export type MessageData = Partial<{
metaKey?: boolean
shiftKey?: boolean
altKey?: boolean
moveCaret?: boolean
canScroll?: boolean
isAtBottom?: boolean
bottomInset?: number
handlesScrollToEndShortcut?: boolean
}>
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export const PrefDefaults = {
[PrefKey.DEPRECATED_ActiveThemes]: [],
[PrefKey.ActiveComponents]: [],
[PrefKey.AlwaysShowSuperToolbar]: true,
[PrefKey.ShowScrollToBottomButton]: true,
[PrefKey.AddImportsToTag]: true,
[PrefKey.AlwaysCreateNewTagForImports]: true,
[PrefKey.ExistingTagForImports]: undefined,
Expand Down
2 changes: 2 additions & 0 deletions packages/models/src/Domain/Syncable/UserPrefs/PrefKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export enum PrefKey {
ComponentPreferences = 'componentPreferences',
ActiveComponents = 'activeComponents',
AlwaysShowSuperToolbar = 'alwaysShowSuperToolbar',
ShowScrollToBottomButton = 'showScrollToBottomButton',
AddImportsToTag = 'addImportsToTag',
AlwaysCreateNewTagForImports = 'alwaysCreateNewTagForImports',
ExistingTagForImports = 'existingTagForImports',
Expand Down Expand Up @@ -99,6 +100,7 @@ export type PrefValue = {
[PrefKey.ComponentPreferences]: AllComponentPreferences
[PrefKey.ActiveComponents]: string[]
[PrefKey.AlwaysShowSuperToolbar]: boolean
[PrefKey.ShowScrollToBottomButton]: boolean
[PrefKey.AddImportsToTag]: boolean
[PrefKey.AlwaysCreateNewTagForImports]: boolean
[PrefKey.ExistingTagForImports]: string | undefined
Expand Down
1 change: 1 addition & 0 deletions packages/models/src/Domain/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export * from './Abstract/Component/ComponentViewerEvent'
export * from './Abstract/Component/IncomingComponentItemPayload'
export * from './Abstract/Component/KeyboardModifier'
export * from './Abstract/Component/MessageData'
export * from './Abstract/Component/ComponentScrollState'
export * from './Abstract/Component/OutgoingItemMessagePayload'
export * from './Abstract/Component/PermissionDialog'
export * from './Abstract/Content/ItemContent'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { ActionObserver, ComponentEventObserver, ComponentMessage, UIFeature } from '@standardnotes/models'
import {
ActionObserver,
ComponentEventObserver,
ComponentMessage,
ComponentScrollState,
UIFeature,
} from '@standardnotes/models'
import { FeatureStatus } from '../Feature/FeatureStatus'
import { ComponentViewerError } from './ComponentViewerError'
import { IframeComponentFeatureDescription, NativeFeatureIdentifier } from '@standardnotes/features'
Expand All @@ -22,6 +28,10 @@ export interface ComponentViewerInterface {
setWindow(window: Window): void
addEventObserver(observer: ComponentEventObserver): () => void
addActionObserver(observer: ActionObserver): () => void
addScrollStateObserver(observer: (state: ComponentScrollState) => void): () => void
/** Tells the component that the host scrolls it to the end on the shortcut, so it can cancel its own handling */
setHandlesScrollToEndShortcut(handles: () => boolean): void
requestScrollToEnd(options: { moveCaret: boolean }): void
postActiveThemes(): void
handleMessage(message: ComponentMessage): void
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export enum InternalFeature {
Vaults = 'vaults',
ScrollToBottom = 'scroll-to-bottom',
}
134 changes: 134 additions & 0 deletions packages/snjs/lib/Services/ComponentManager/ComponentViewer.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import { ComponentAction, IframeComponentFeatureDescription } from '@standardnotes/features'
import { ComponentMessage, Environment, Platform, SNNote, UIFeature } from '@standardnotes/models'
import { UuidGenerator } from '@standardnotes/utils'
import { ComponentViewer } from './ComponentViewer'
import { ComponentViewerRequiresComponentManagerProperties } from './ComponentViewerRequiresComponentManagerFunctions'

describe('ComponentViewer scroll to end', () => {
const createViewer = () => {
const services = {
items: { addObserver: jest.fn().mockReturnValue(jest.fn()) },
features: { addEventObserver: jest.fn().mockReturnValue(jest.fn()) },
logger: { info: jest.fn() },
alerts: { alert: jest.fn() },
}

const viewer = new ComponentViewer(
{
displayName: 'Editor',
uniqueIdentifier: { value: 'editor' },
} as unknown as UIFeature<IframeComponentFeatureDescription>,
services as unknown as ConstructorParameters<typeof ComponentViewer>[1],
{ item: { uuid: 'note-uuid' } as unknown as SNNote, url: 'https://editor' },
{
environment: Environment.Web,
platform: Platform.MacWeb,
componentManagerFunctions: {} as ComponentViewerRequiresComponentManagerProperties,
},
)

return { viewer, services }
}

const scrollStateMessage = (data: ComponentMessage['data']): ComponentMessage => ({
action: ComponentAction.ScrollState,
data,
})

it('notifies scroll state observers and replays the latest state to new observers', () => {
const { viewer } = createViewer()
const observer = jest.fn()
viewer.addScrollStateObserver(observer)

viewer.handleMessage(scrollStateMessage({ canScroll: true, isAtBottom: false, bottomInset: 40 }))
expect(observer).toHaveBeenCalledWith({ canScroll: true, isAtBottom: false, bottomInset: 40 })

const lateObserver = jest.fn()
viewer.addScrollStateObserver(lateObserver)
expect(lateObserver).toHaveBeenCalledWith({ canScroll: true, isAtBottom: false, bottomInset: 40 })
})

it('defaults the bottom inset to none for components that do not report it', () => {
const { viewer } = createViewer()
const observer = jest.fn()
viewer.addScrollStateObserver(observer)

viewer.handleMessage(scrollStateMessage({ canScroll: true, isAtBottom: false }))

expect(observer).toHaveBeenCalledWith({ canScroll: true, isAtBottom: false, bottomInset: 0 })
})

it('does not call observers before the component reports a scroll state', () => {
const { viewer } = createViewer()
const observer = jest.fn()

viewer.addScrollStateObserver(observer)

expect(observer).not.toHaveBeenCalled()
})

it('ignores malformed scroll state messages', () => {
const { viewer } = createViewer()
const observer = jest.fn()
viewer.addScrollStateObserver(observer)

viewer.handleMessage(scrollStateMessage({ canScroll: true }))

expect(observer).not.toHaveBeenCalled()
})

it('stops notifying removed observers', () => {
const { viewer } = createViewer()
const observer = jest.fn()
const removeObserver = viewer.addScrollStateObserver(observer)

removeObserver()
viewer.handleMessage(scrollStateMessage({ canScroll: true, isAtBottom: true }))

expect(observer).not.toHaveBeenCalled()
})

it('sends a scroll-to-end message to the component window', () => {
const { viewer } = createViewer()
const postMessage = jest.fn()
;(viewer as unknown as { window: Window }).window = { postMessage } as unknown as Window

viewer.requestScrollToEnd({ moveCaret: true })

expect(postMessage).toHaveBeenCalledWith(
expect.objectContaining({ action: ComponentAction.ScrollToEnd, data: { moveCaret: true } }),
'*',
)
})

it('tells the component on registration whether the host handles the scroll to end shortcut', () => {
UuidGenerator.SetGenerator(() => 'session-key')
const { viewer } = createViewer()
;(viewer as unknown as { config: { componentManagerFunctions: object } }).config.componentManagerFunctions = {
getComponentPreferences: () => undefined,
urlsForActiveThemes: () => [],
}
const postMessage = jest.fn()

let hostHandlesShortcut = false
viewer.setHandlesScrollToEndShortcut(() => hostHandlesShortcut)
hostHandlesShortcut = true
viewer.setWindow({ postMessage } as unknown as Window)

expect(postMessage).toHaveBeenCalledWith(
expect.objectContaining({
action: ComponentAction.ComponentRegistered,
data: expect.objectContaining({ handlesScrollToEndShortcut: true }),
}),
'*',
)
})

it('does not alert when there is no component window yet', () => {
const { viewer, services } = createViewer()

viewer.requestScrollToEnd({ moveCaret: false })

expect(services.alerts.alert).not.toHaveBeenCalled()
})
})
46 changes: 46 additions & 0 deletions packages/snjs/lib/Services/ComponentManager/ComponentViewer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
ComponentPreferencesEntry,
UIFeature,
ComponentInterface,
ComponentScrollState,
} from '@standardnotes/models'
import { environmentToString, platformToString } from '@Lib/Application/Platforms'
import {
Expand Down Expand Up @@ -85,6 +86,9 @@ export class ComponentViewer implements ComponentViewerInterface {
private removeItemObserver: () => void
public identifier = nonSecureRandomIdentifier()
private actionObservers: ActionObserver[] = []
private scrollStateObservers: ((state: ComponentScrollState) => void)[] = []
private scrollState?: ComponentScrollState
private handlesScrollToEndShortcut: () => boolean = () => false

private removeFeaturesObserver: () => void
private eventObservers: ComponentEventObserver[] = []
Expand Down Expand Up @@ -179,6 +183,7 @@ export class ComponentViewer implements ComponentViewerInterface {

this.eventObservers.length = 0
this.actionObservers.length = 0
this.scrollStateObservers.length = 0

this.removeFeaturesObserver()
;(this.removeFeaturesObserver as unknown) = undefined
Expand Down Expand Up @@ -211,6 +216,32 @@ export class ComponentViewer implements ComponentViewerInterface {
}
}

/**
* Only components that support scrolling to the end report their scroll state,
* so observers are not called for components that don't.
*/
public addScrollStateObserver(observer: (state: ComponentScrollState) => void): () => void {
this.scrollStateObservers.push(observer)

if (this.scrollState) {
observer(this.scrollState)
}

const thislessScrollStateObservers = this.scrollStateObservers
return () => {
removeFromArray(thislessScrollStateObservers, observer)
}
}

/** Evaluated when the component registers, so availability changes before then are picked up */
public setHandlesScrollToEndShortcut(handles: () => boolean): void {
this.handlesScrollToEndShortcut = handles
}

public requestScrollToEnd(options: { moveCaret: boolean }): void {
this.sendMessage({ action: ComponentAction.ScrollToEnd, data: { moveCaret: options.moveCaret } }, false)
}

public setReadonly(readonly: boolean): void {
if (this.lockReadonly) {
throw Error('Attempting to set readonly on lockedReadonly component viewer')
Expand Down Expand Up @@ -538,6 +569,7 @@ export class ComponentViewer implements ComponentViewerInterface {
environment: environmentToString(this.config.environment),
platform: platformToString(this.config.platform),
activeThemeUrls: this.config.componentManagerFunctions.urlsForActiveThemes(),
handlesScrollToEndShortcut: this.handlesScrollToEndShortcut(),
},
})

Expand Down Expand Up @@ -590,6 +622,7 @@ export class ComponentViewer implements ComponentViewerInterface {
[ComponentAction.CreateItem]: this.handleCreateItemsMessage.bind(this),
[ComponentAction.SaveItems]: this.handleSaveItemsMessage.bind(this),
[ComponentAction.SetSize]: this.handleSetSizeEvent.bind(this),
[ComponentAction.ScrollState]: this.handleScrollStateMessage.bind(this),
}

const handler = messageHandlers[message.action]
Expand All @@ -600,6 +633,19 @@ export class ComponentViewer implements ComponentViewerInterface {
}
}

private handleScrollStateMessage(message: ComponentMessage): void {
const { canScroll, isAtBottom, bottomInset } = message.data
if (typeof canScroll !== 'boolean' || typeof isAtBottom !== 'boolean') {
return
}

this.scrollState = { canScroll, isAtBottom, bottomInset: typeof bottomInset === 'number' ? bottomInset : 0 }

for (const observer of this.scrollStateObservers) {
observer(this.scrollState)
}
}

private handleStreamItemsMessage(message: ComponentMessage): void {
const data = message.data as StreamItemsMessageData
const types = data.content_types.filter((type) => AllowedBatchContentTypes.includes(type)).sort()
Expand Down
1 change: 1 addition & 0 deletions packages/ui-services/src/Keyboard/KeyboardCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export const OPEN_NOTE_HISTORY_COMMAND = createKeyboardCommand('OPEN_NOTE_HISTOR
export const CAPTURE_SAVE_COMMAND = createKeyboardCommand('CAPTURE_SAVE_COMMAND')
export const STAR_NOTE_COMMAND = createKeyboardCommand('STAR_NOTE_COMMAND')
export const PIN_NOTE_COMMAND = createKeyboardCommand('PIN_NOTE_COMMAND')
export const SCROLL_NOTE_TO_BOTTOM_KEYBOARD_COMMAND = createKeyboardCommand('SCROLL_NOTE_TO_BOTTOM_KEYBOARD_COMMAND')

export const SUPER_TOGGLE_SEARCH = createKeyboardCommand('SUPER_TOGGLE_SEARCH')
export const SUPER_TOGGLE_TOOLBAR = createKeyboardCommand('SUPER_TOGGLE_TOOLBAR')
Expand Down
27 changes: 27 additions & 0 deletions packages/ui-services/src/Keyboard/getKeyboardShortcuts.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* @jest-environment jsdom
*/

import { Environment, Platform } from '@standardnotes/models'
import { getKeyboardShortcuts } from './getKeyboardShortcuts'
import { SCROLL_NOTE_TO_BOTTOM_KEYBOARD_COMMAND } from './KeyboardCommands'
import { KeyboardKey } from './KeyboardKey'
import { KeyboardModifier } from './KeyboardModifier'

describe('scroll note to bottom shortcut', () => {
const getShortcut = (platform: Platform) =>
getKeyboardShortcuts(platform, Environment.Web).find(
(shortcut) => shortcut.command === SCROLL_NOTE_TO_BOTTOM_KEYBOARD_COMMAND,
)

it.each([Platform.MacWeb, Platform.MacDesktop])('is Cmd+Down on %s', (platform) => {
expect(getShortcut(platform)).toMatchObject({ key: KeyboardKey.Down, modifiers: [KeyboardModifier.Meta] })
})

it.each([Platform.WindowsWeb, Platform.WindowsDesktop, Platform.LinuxWeb, Platform.LinuxDesktop])(
'is Ctrl+End on %s',
(platform) => {
expect(getShortcut(platform)).toMatchObject({ key: KeyboardKey.End, modifiers: [KeyboardModifier.Ctrl] })
},
)
})
7 changes: 7 additions & 0 deletions packages/ui-services/src/Keyboard/getKeyboardShortcuts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
CAPTURE_SAVE_COMMAND,
STAR_NOTE_COMMAND,
PIN_NOTE_COMMAND,
SCROLL_NOTE_TO_BOTTOM_KEYBOARD_COMMAND,
SUPER_SHOW_MARKDOWN_PREVIEW,
OPEN_PREFERENCES_COMMAND,
TOGGLE_DARK_MODE_COMMAND,
Expand Down Expand Up @@ -153,6 +154,12 @@ export function getKeyboardShortcuts(platform: Platform, _environment: Environme
modifiers: [primaryModifier, KeyboardModifier.Shift],
preventDefault: true,
},
{
// Keep in sync with `isScrollToEndShortcut` in component-relay, which cancels the native key for component editors
command: SCROLL_NOTE_TO_BOTTOM_KEYBOARD_COMMAND,
key: isMacPlatform(platform) ? KeyboardKey.Down : KeyboardKey.End,
modifiers: [primaryModifier],
},
{
command: SUPER_TOGGLE_TOOLBAR,
key: 'k',
Expand Down
1 change: 1 addition & 0 deletions packages/web/src/javascripts/Application/DevMode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { WebApplicationInterface } from '@standardnotes/ui-services'
export class DevMode {
constructor(private application: WebApplicationInterface) {
InternalFeatureService.get().enableFeature(InternalFeature.Vaults)
InternalFeatureService.get().enableFeature(InternalFeature.ScrollToBottom)
}

/** Valid only when running a mock event publisher on port 3124 */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ describe('NoteView', () => {
notesController,
noteViewController,
vaults,
featuresController: { hasScrollToBottom: false },
} as unknown as jest.Mocked<WebApplication>

application.hasProtectionSources = jest.fn().mockReturnValue(true)
Expand Down
Loading
Loading