Skip to content

Commit

Permalink
Implement block action for copying and cutting a single block
Browse files Browse the repository at this point in the history
  • Loading branch information
niklasnatter committed Jun 8, 2022
1 parent 4ce8480 commit 5bcc782
Show file tree
Hide file tree
Showing 16 changed files with 213 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ $actionTextColor: $black;
$actionTextColorActive: $shakespeare;

.icon {
margin-right: 15px;
margin-right: 10px;
}

.action {
min-width: 200px;
min-width: 150px;
display: block;
cursor: pointer;
padding: 5px 20px;
padding: 5px 10px;
color: $actionTextColor;
border: none;
background: transparent;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {action, observable, toJS, reaction, computed} from 'mobx';
import {observer} from 'mobx-react';
import classNames from 'classnames';
import {arrayMove, translate} from '../../utils';
import {clipboardStore} from '../../stores';
import Button from '../Button';
import SortableBlockList from './SortableBlockList';
import blockCollectionStyles from './blockCollection.scss';
Expand All @@ -21,11 +22,14 @@ type Props<T: string, U: {type: T}> = {|
onChange: (value: Array<U>) => void,
onSettingsClick?: (index: number) => void,
onSortEnd?: (oldIndex: number, newIndex: number) => void,
pasteButtonText?: ?string,
renderBlockContent: RenderBlockContentCallback<T, U>,
types?: {[key: T]: string},
value: Array<U>,
|};

const BLOCKS_CLIPBOARD_KEY = 'blocks';

@observer
class BlockCollection<T: string, U: {type: T}> extends React.Component<Props<T, U>> {
static idCounter = 0;
Expand All @@ -37,14 +41,27 @@ class BlockCollection<T: string, U: {type: T}> extends React.Component<Props<T,
value: [],
};

@observable pasteableBlocks: Array<number> = [];
@observable generatedBlockIds: Array<number> = [];
@observable expandedBlocks: Array<boolean> = [];

fillArraysDisposer: ?() => *;
setPasteableBlocksDisposer: ?() => *;

constructor(props: Props<T, U>) {
super(props);

this.fillArrays();
reaction(() => this.props.value.length, this.fillArrays);
this.fillArraysDisposer = reaction(() => this.props.value.length, this.fillArrays, {fireImmediately: true});
this.setPasteableBlocksDisposer = clipboardStore.observe(BLOCKS_CLIPBOARD_KEY, action((blocks) => {
this.pasteableBlocks = (blocks: any) || [];
}));

this.pasteableBlocks = (clipboardStore.get(BLOCKS_CLIPBOARD_KEY): any) || [];
}

componentWillUnmount() {
this.fillArraysDisposer?.();
this.setPasteableBlocksDisposer?.();
}

fillArrays = () => {
Expand Down Expand Up @@ -104,6 +121,31 @@ class BlockCollection<T: string, U: {type: T}> extends React.Component<Props<T,
}
};

@action handlePasteBlocks = (insertionIndex: number) => {
const {onChange, value} = this.props;

if (this.hasMaximumReached) {
throw new Error('The maximum amount of blocks has already been reached!');
}

if (value) {
// TODO: gracefully handle clipboard data this is incompatible with available block types

this.expandedBlocks.splice(
insertionIndex, 0, ...this.pasteableBlocks.map(() => true)
);
this.generatedBlockIds.splice(
insertionIndex, 0, ...this.pasteableBlocks.map(() => ++BlockCollection.idCounter)
);

const elementsBefore = value.slice(0, insertionIndex);
const elementsAfter = value.slice(insertionIndex);
// $FlowFixMe
onChange([...elementsBefore, ...this.pasteableBlocks, ...elementsAfter]);
clipboardStore.set(BLOCKS_CLIPBOARD_KEY, undefined);
}
};

@action handleRemoveBlock = (index: number) => {
const {onChange, value} = this.props;

Expand Down Expand Up @@ -132,10 +174,24 @@ class BlockCollection<T: string, U: {type: T}> extends React.Component<Props<T,
const elementsBefore = value.slice(0, index);
const elementsAfter = value.slice(index);
// $FlowFixMe
onChange([...elementsBefore, {...value[index]}, ...elementsAfter]);
onChange([...elementsBefore, {...toJS(value[index])}, ...elementsAfter]);
}
};

handleCopyBlock = (index: number) => {
const {value} = this.props;

if (value) {
const block = {...toJS(value[index])};
clipboardStore.set(BLOCKS_CLIPBOARD_KEY, [block]);
}
};

handleCutBlock = (index: number) => {
this.handleCopyBlock(index);
this.handleRemoveBlock(index);
};

@action handleSortEnd = ({newIndex, oldIndex}: {newIndex: number, oldIndex: number}) => {
const {onChange, onSortEnd, value} = this.props;

Expand Down Expand Up @@ -186,6 +242,22 @@ class BlockCollection<T: string, U: {type: T}> extends React.Component<Props<T,
@computed get blockActions() {
const blockActions = [];

blockActions.push({
type: 'button',
icon: 'su-copy',
label: translate('sulu_admin.copy'),
onClick: this.handleCopyBlock,
});

if (!this.hasMinimumReached) {
blockActions.push({
type: 'button',
icon: 'su-scissors',
label: translate('sulu_admin.cut'),
onClick: this.handleCutBlock,
});
}

if (!this.hasMaximumReached) {
blockActions.push({
type: 'button',
Expand Down Expand Up @@ -214,7 +286,7 @@ class BlockCollection<T: string, U: {type: T}> extends React.Component<Props<T,
}

renderAddButton = (aboveBlockIndex: number) => {
const {addButtonText, disabled, value} = this.props;
const {addButtonText, pasteButtonText, disabled, value} = this.props;
const isDividerButton = aboveBlockIndex < value.length - 1;

const containerClass = classNames(
Expand All @@ -236,6 +308,21 @@ class BlockCollection<T: string, U: {type: T}> extends React.Component<Props<T,
>
{addButtonText ? addButtonText : translate('sulu_admin.add_block')}
</Button>
{this.pasteableBlocks.length > 0 && (
<Button
className={blockCollectionStyles.addButton}
disabled={disabled || this.hasMaximumReached}
icon="su-copy"
onClick={this.handlePasteBlocks}
skin="secondary"
value={aboveBlockIndex + 1}
>
{pasteButtonText
? pasteButtonText
: translate('sulu_admin.paste_blocks', {count: this.pasteableBlocks.length})
}
</Button>
)}
</div>
);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
text-align: center;
}

.addButton {
margin: 0 5px;
}

.addButtonDivider {
/* replace margin of block above with container to display button if space between blocks is hovered */
margin-top: -$blockMarginBottom;
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Binary file not shown.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
@font-face {
font-family: 'sulu';
src:
url('fonts/sulu.ttf?tj3m4m') format('truetype'),
url('fonts/sulu.woff?tj3m4m') format('woff'),
url('fonts/sulu.svg?tj3m4m#sulu') format('svg');
url('fonts/sulu.ttf?uud37h') format('truetype'),
url('fonts/sulu.woff?uud37h') format('woff'),
url('fonts/sulu.svg?uud37h#sulu') format('svg');
font-weight: normal;
font-style: normal;
font-display: block;
Expand All @@ -24,6 +24,9 @@
-moz-osx-font-smoothing: grayscale;
}

.su-scissors:before {
content: "\e9c0";
}
.su-duplicate:before {
content: "\e9bf";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,22 @@ class FieldBlocks extends React.Component<FieldTypeProps<Array<BlockEntry>>> {
return addButtonText;
}

@computed get pasteButtonText() {
const {
schemaOptions: {
paste_button_text: {
title: pasteButtonText,
} = {},
},
} = this.props;

if (pasteButtonText !== undefined && typeof pasteButtonText !== 'string') {
throw new Error('The "block" field types only accepts strings as "paste_button_text" schema option!');
}

return pasteButtonText;
}

@computed get collapsable() {
const {
schemaOptions: {
Expand Down Expand Up @@ -476,6 +492,7 @@ class FieldBlocks extends React.Component<FieldTypeProps<Array<BlockEntry>>> {
onChange={this.handleBlocksChange}
onSettingsClick={this.settingsFormKey ? this.handleSettingsClick : undefined}
onSortEnd={this.handleSortEnd}
pasteButtonText={this.pasteButtonText}
renderBlockContent={this.renderBlockContent}
types={blockTypes}
value={value}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// @flow
import type {Observer} from './types';

class ClipboardStore {
observers: {[key: string]: Array<Observer>} = {};
storageEventListener: ?(event: StorageEvent) => void;

updateStorageEventListener(): void {
const activeObservers = Object.values(this.observers).flat().length;

// listen for "storage" events to notify observers if something is copied in another browser window
if (activeObservers > 0 && !this.storageEventListener) {
this.storageEventListener = (event: StorageEvent) => {
if (event.key) {
this.notifyObservers(event.key, event.newValue ? JSON.parse(event.newValue) : undefined);
}
};
window.addEventListener('storage', this.storageEventListener);
} else if (activeObservers === 0 && this.storageEventListener) {
window.removeEventListener('storage', this.storageEventListener);
}
}

notifyObservers(key: string, value: mixed): void {
const observers = this.observers[key] || [];

for (const observer of observers) {
observer(value);
}
}

get(key: string): mixed {
const serializedValue = window.localStorage.getItem(key);

return serializedValue ? JSON.parse(serializedValue) : undefined;
}

set(key: string, value: mixed) {
if (value) {
window.localStorage.setItem(key, JSON.stringify(value));
} else {
window.localStorage.removeItem(key);
}

this.notifyObservers(key, value);
}

observe(key: string, observer: Observer) {
if (!this.observers[key]) {
this.observers[key] = [];
}
this.observers[key].push(observer);
this.updateStorageEventListener();

// return disposer function that allows to remove the registered observer
return () => {
const index = this.observers[key]?.indexOf(observer);
if (index > -1) {
this.observers[key].splice(index, 1);
}
this.updateStorageEventListener();
};
}
}

export default new ClipboardStore();
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// @flow
import clipboardStore from './clipboardStore';

export default clipboardStore;
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// @flow
import clipboardStore from '../clipboardStore';

test('Load item from localStorage', () => {
const item = {key1: 'value1', key2: 1234};
const getItemSpy = jest.fn().mockReturnValue(JSON.stringify(item));
window.localStorage = {getItem: getItemSpy};

const result = clipboardStore.get('test-key');
expect(result).toEqual(item);
expect(getItemSpy).toBeCalledWith('test-key');
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// @flow
export type Observer = (value: mixed) => void;
2 changes: 2 additions & 0 deletions src/Sulu/Bundle/AdminBundle/Resources/js/stores/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// @flow
import localizationStore from './localizationStore';
import clipboardStore from './clipboardStore';
import MultiSelectionStore from './MultiSelectionStore';
import ResourceListStore from './ResourceListStore';
import ResourceStore from './ResourceStore';
Expand All @@ -13,6 +14,7 @@ export {
ResourceStore,
SingleSelectionStore,
localizationStore,
clipboardStore,
userStore,
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
{
"sulu_admin.add": "Hinzufügen",
"sulu_admin.add_block": "Block hinzufügen",
"sulu_admin.paste_blocks": "{count} {count, plural, =1 {Block} other {Blocks} einfügen}",
"sulu_admin.delete": "Löschen",
"sulu_admin.delete_selected": "Ausgewählte löschen",
"sulu_admin.delete_locale": "Aktuelle Sprache löschen",
"sulu_admin.move": "Verschieben",
"sulu_admin.move_items": "Datensätze verschieben",
"sulu_admin.copy": "Kopieren",
"sulu_admin.cut": "Ausschneiden",
"sulu_admin.duplicate": "Duplizieren",
"sulu_admin.order": "Sortieren",
"sulu_admin.of": "von",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
{
"sulu_admin.add": "Add",
"sulu_admin.add_block": "Add block",
"sulu_admin.paste_blocks": "Paste {count} {count, plural, =1 {block} other {blocks}}",
"sulu_admin.delete": "Delete",
"sulu_admin.delete_selected": "Delete selected",
"sulu_admin.delete_locale": "Delete current localization",
"sulu_admin.move": "Move",
"sulu_admin.move_items": "Move items",
"sulu_admin.copy": "Copy",
"sulu_admin.cut": "Cut",
"sulu_admin.duplicate": "Duplicate",
"sulu_admin.order": "Order",
"sulu_admin.of": "of",
Expand Down

0 comments on commit 5bcc782

Please sign in to comment.