Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement block action for copying and cutting a single block #6630

Merged
merged 4 commits into from
Jun 9, 2022
Merged
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
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 @@ -3,7 +3,7 @@ import React from 'react';
import {action, observable, toJS, reaction, computed} from 'mobx';
import {observer} from 'mobx-react';
import classNames from 'classnames';
import {arrayMove, translate} from '../../utils';
import {arrayMove, translate, clipboard} from '../../utils';
import Button from '../Button';
import SortableBlockList from './SortableBlockList';
import blockCollectionStyles from './blockCollection.scss';
Expand All @@ -21,11 +21,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 +40,25 @@ class BlockCollection<T: string, U: {type: T}> extends React.Component<Props<T,
value: [],
};

@observable pasteableBlocks: Array<U>= [];
@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 = clipboard.observe(BLOCKS_CLIPBOARD_KEY, action((blocks) => {
this.pasteableBlocks = blocks || [];
}), true);
}

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

fillArrays = () => {
Expand Down Expand Up @@ -104,6 +118,38 @@ 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) {
this.expandedBlocks.splice(
insertionIndex, 0, ...this.pasteableBlocks.map(() => true)
);
this.generatedBlockIds.splice(
insertionIndex, 0, ...this.pasteableBlocks.map(() => ++BlockCollection.idCounter)
);

const newElements = this.pasteableBlocks.map((block) => {
// paste block with default type if type of block in clipboard is not known
if (!this.props.types?.[block.type]) {
return {...block, type: this.props.defaultType};
}

return block;
});
const elementsBefore = value.slice(0, insertionIndex);
const elementsAfter = value.slice(insertionIndex);

// $FlowFixMe
onChange([...elementsBefore, ...newElements, ...elementsAfter]);
clipboard.set(BLOCKS_CLIPBOARD_KEY, undefined);
}
};

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

Expand Down Expand Up @@ -132,10 +178,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])};
clipboard.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 +246,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 +290,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 +312,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,65 @@
// @flow
import type {Observer} from './types';

class Clipboard {
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);
}
}

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, invokeImmediately?: boolean) {
if (!this.observers[key]) {
this.observers[key] = [];
}
this.observers[key].push(observer);
this.updateStorageEventListener();

if (invokeImmediately) {
const currentValue = window.localStorage.getItem(key);
observer(currentValue ? JSON.parse(currentValue) : undefined);
}

// 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 Clipboard();
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// @flow
import clipboard from './clipboard';

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

test('Set item and observe item', () => {
clipboard.set('test-key', 'test-value');

let item = null;

clipboard.observe('test-key', (value) => {
item = value;
}, true);

expect(item).toEqual('test-value');
});
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/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import {createAjv} from './Ajv';
import {transformBytesToReadableString} from './Bytes';
import {transformDateForUrl} from './Date';
import {translate} from './Translator';
import clipboard from './clipboard';

export {
arrayMove,
buildQueryString,
clipboard,
createAjv,
transformBytesToReadableString,
transformDateForUrl,
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