I'm working on a custom draft.js plugin that inserts an Atomic Block with a GIF in it. I started by copying the Draft.js Image Plugin as it's almost identical. I've got my plugin working but there's one issue I'm not sure best how to solve.
To insert a GIF I'm following the example addImage Modifier in the Image Plugin. However, this always creates a new Atomic Block after the current selection. If the current block is empty, I want to place the GIF there instead.
Here's what my modifier function looks like:
const addGiphy = (editorState, giphyId) => {
const contentState = editorState.getCurrentContent();
// This creates the new Giphy entity
const contentStateWithEntity = contentState.createEntity("GIPHY", "IMMUTABLE", {
giphyId
});
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
// Work out where the selection is
const currentSelection = editorState.getSelection();
const currentKey = currentSelection.getStartKey();
const currentBlock = editorState.getCurrentContent().getBlockForKey(currentKey);
let newEditorState;
if (currentBlock.getType() === "unstyled" && currentBlock.getText() === "") {
// Current line is empty, we should convert to a gif atomic block
// <INSERT MAGIC HERE>
} else {
// There's stuff here, lets create a new block
newEditorState = AtomicBlockUtils.insertAtomicBlock(editorState, entityKey, " ");
}
return EditorState.forceSelection(
newEditorState,
newEditorState.getCurrentContent().getSelectionAfter()
);
};
I'm not sure how to handle the condition of converting the current block to an Atomic Block. Is this Draft.js best practice? Alternatively, am I better to always insert a new block and then remove the empty block?
For clarity, this same issue also exists in the Image Plugin, it's not something I've introduced.
you can use https://draftjs.org/docs/api-reference-modifier/#setblocktype
const content = Modifier.setBlockType(content, editorState.getSelection(), 'atomic');
const newState = EditorState.push(editorState, content, 'change-block-type');
Related
I'm developing a VS Code extension that jump to a specific file:num, but I'm stuck at the step of moving the cursor to a specific line after opening a file.
How can I achieve this :
export const openAndMoveToLine = async (file_line: string) => {
// /home/user/some/path.php:10
let [filename, line_number] = file_line.split(":")
// opening the file => OK
let setting: vscode.Uri = vscode.Uri.parse(filename)
let doc = await vscode.workspace.openTextDocument(setting)
vscode.window.showTextDocument(doc, 1, false);
// FIXME: After being opened, now move to the line X => NOK **/
await vscode.commands.executeCommand("cursorMove", {
to: "down", by:'wrappedLine',
value: parseInt(line_number)
});
}
Thank you
It can be done with the TextDocumentShowOptions easily:
const showDocOptions = {
preserveFocus: false,
preview: false,
viewColumn: 1,
// replace with your line_number's
selection: new vscode.Range(314, 0, 314, 0)
};
let doc = await vscode.window.showTextDocument(setting, showDocOptions);
You will first need to get access to the active editor. This is done by adding a .then to the showTextDocument call (which is a Thenable function) that returns a text editor object. You will then be able to use the textEditor variable (as in the example) to set the position of the cursor using the selection property as follows:
vscode.window.showTextDocument(doc, 1, false).then((textEditor: TextEditor) => {
const lineNumber = 1;
const characterNumberOnLine = 1;
const position = new vscode.Position(lineNumber, characterNumberOnLine);
const newSelection = new vscode.Selection(position, position);
textEditor.selection = newSelection;
});
Reference to selection API can be found here.
The usecase that you are exploring has been discussed in GitHub issue that can be found here.
I have a project which is responsible for managing the rendering of elements, but I'm running into a performance issue replacing elements and then focusing on whatever had focus before.
Below is a minimal example that replicates the performance issue:
const renderPage = () => {
// get the old section element
const oldSection = document.querySelector('section')
// create a new section element (we'll replaceWith later)
const newSection = document.createElement('section')
// create the render button
const newButton = document.createElement('button')
newButton.innerHTML = 'Render Page'
newButton.onclick = renderPage
newSection.appendChild(newButton)
// create a bunch of elements
const dummyDivs = [...new Array(100000)].forEach(() => {
const dummy = document.createElement('div')
dummy.innerHTML = 'dummy'
newSection.appendChild(dummy)
})
// replace the old page with the new one (causes forced reflow)
oldSection.replaceWith(newSection)
// reattach focus on the button (causes forced reflow)
newButton.focus()
}
window.renderPage = renderPage
<section>
<button onclick="renderPage()">Render</button>
</section>
When running this locally, I see the following in the performance report in Chrome/Edge
Both replaceWith and focus are triggering forced reflow. Is there a way to batch or group these actions so that only a single reflow occurs? I realize that there's no way to really get around this happening at all, but if I can batch them, I think that might improve my performance.
Indeed, focus always causes a reflow: What forces layout / reflow
So what you may do, is to reduce the reflowtime by inserting the new button standalone, initiate focus and after that you can append other childs:
Working example: Example
const renderPage = () => {
// get the old section element
const oldSection = document.querySelector('section')
// create a new section element (we'll replaceWith later)
const newSection = document.createElement('section')
// create the render button
const newButton = document.createElement('button')
newButton.innerHTML = 'Render Page'
newButton.onclick = renderPage
newSection.appendChild(newButton)
// create a bunch of elements
const dummies = []; // store in seperate array
const dummyDivs = [...new Array(100000)].forEach(() => {
const dummy = document.createElement('div')
dummy.innerHTML = 'dummy';
dummies.push(dummy)
})
// insert new section only with new button
oldSection.replaceWith(newSection)
newButton.focus(); // always causes reflow; but fast because it's only one element
// store all other nodes after focus
newSection.append(...dummies)
}
window.renderPage = renderPage
i'm working on a simple note-taking app for my portfolio using JS and Firebase. Before i tell you what's happening i feel like i need to show you how my code works, if you have any tips and concerns please tell me as it would be GREATLY appreciated. That being said, let's have a look "together". I'm using this class to create the notes:
const htmlElements = [document.querySelector('.notes'), document.querySelector('.note')];
const [notesDiv, noteDiv] = htmlElements;
class CreateNote {
constructor(title, body) {
this.title = title;
this.body = body;
this.render = () => {
const div1 = document.createElement('div');
div1.className = 'notes-prev-container';
div1.addEventListener('click', () => { this.clickHandler(this) });
const div2 = document.createElement('div');
div2.className = 'notes-prev';
const hr = document.createElement('hr');
hr.className = 'notes__line';
// Nest 'div2' inside 'div1'
div1.appendChild(div2);
div1.appendChild(hr);
/*
Create Paragraph 1 & 2 and give them the same
class name and some text
*/
const p1 = document.createElement('p');
p1.className = 'notes-prev__title';
p1.innerText = this.title;
const p2 = document.createElement('p');
p2.className = 'notes-prev__body';
p2.innerText = this.body;
// Nest p 1 & 2 inside 'div2'
div2.appendChild(p1);
div2.appendChild(p2);
// Finally, render the div to its root tag
notesDiv.appendChild(div1);
}
}
/*
Every time this method is called, it creates 2 textareas,
one for the note title and the other for its body then it
appends it to the DOM.
*/
renderNoteContent () {
const title = document.createElement('textarea');
title.placeholder = 'Title';
title.value = this.title;
title.className = 'note__title';
const body = document.createElement('textarea');
body.placeholder = 'Body';
body.value = this.body;
body.className = 'note__body';
noteDiv.appendChild(title);
noteDiv.appendChild(body);
}
/*
When this method is called, it checks to see if there's a
note rendered already (childElementCount === 1 because there's a
button, so if there's only this button it means there's no
textareas rendered).
If yes, then merely call the renderNoteContent method. Else
get the tags with the classes 'note__title' and 'note__body'
and remove them from the DOM, then call renderNoteContent to
create the textareas with the clicked notes values.
This function gets mentioned at line 19.
*/
clickHandler(thisClass) {
if (noteDiv.childElementCount === 1) {
thisClass.renderNoteContent();
} else {
document.querySelector('.note__title').remove();
document.querySelector('.note__body').remove();
thisClass.renderNoteContent();
}
}
}
Now i need 2 buttons, createNotesButton and saveNotesButton respectively. These 2 buttons must be inside a function that will be called inside .onAuthStateChanged (why? because they will be needing access to the currentUser on firebase auth).
I want the createNotesButton to create a note prototype, render it to the DOM and create a new document on firestore, where this note contents will be stored. Here's how i did it:
PS: I feel like i'm not using this class correctly, so again if you have any tips i appreciate it.
import {db} from '../../firebase_variables/firebase-variables.js';
import {CreateNote} from '../create_notes_class/create_notes_class.js';
const htmlElements = [
document.querySelector('.createNotes-button'),
document.querySelector('.saveNotes-button')
];
const [createNotesButton, saveNotesButton] = htmlElements;
function clickHandler(user) {
/*
1. Creates a class.
2. Creates a new document on firebase with the class's empty value.
3. Renders the empty class to the DOM.
*/
createNotesButton.addEventListener('click', () => {
const note = new CreateNote('', '');
note.render();
// Each user has it's own note collection, said collection has their `uid` as name.
db.collection(`${user.uid}`).doc().set({
title: `${note.title}`,
body: `${note.body}`
})
})
}
Now i need a saveNotesButton, he's the one i'm having issues with. He needs to save the displayed note's content on firestore. Here's what i tried doing:
import {db} from '../../firebase_variables/firebase-variables.js';
import {CreateNote} from '../create_notes_class/create_notes_class.js';
const htmlElements = [
document.querySelector('.createNotes-button'),
document.querySelector('.saveNotes-button')
];
const [createNotesButton, saveNotesButton] = htmlElements;
function clickHandler(user) {
createNotesButton.addEventListener('click', () => {...})
/*
1. Creates 2 variables, `title` and `body, if there's not a note being displayed
their values will be null, which is why the rest of the code is inside an if
statement
2. If statement to check if there's a note being displayed, if yes then:
1. Call the user's note collection. Any document who has the title field equal to the
displayed note's value gets returned as a promise.
2. Then call an specific user document and update the fields `title` and `body` with
the displayed note's values.
3. If no then do nothing.
*/
saveNotesButton.addEventListener('click', () => {
const title = document.querySelector('.note__title');
const body = document.querySelector('.note__body');
db.collection(`${user.uid}`).where('title', '==', `${title.value}`)
.get()
.then(userCollection => {
db.collection(`${user.uid}`).doc(`${userCollection.docs[0].id}`).update({
title: `${title.value}`,
body: `${body.value}`
})
})
.catch(error => {
console.log('Error getting documents: ', error);
});
});
}
This didn't work because i'm using title.value as a query, so if i change it's value it will also change the queries direction to a path that doesn't exist.
So here's the question: how can i make it so the saveNotesButton does its job? I was thinking of adding another field to each note, something that won't change so i can easily identify and edit each note. Again, if there's something in my code that you think can or should be formatted please let me know, i'm using this project as a way to solidify my native JS knowledge so please be patient. I feel like if i had used React i would've finished this sometime ago but definitely wouldn't have learned as much, anyway thanks for your help in advance.
I was thinking of adding another field to each note, something that won't change so i can easily identify and edit each note.
Yes, you absolutely need an immutable identifier for each note document in the firestore so you can unambiguously reference it. You almost always want this whenever you're storing a data object, in any application with any database.
But, the firestore already does this for you: after calling db.collection(user.uid).doc() you should get a doc with an ID. That's the ID you want to use when updating the note.
The part of your code that interacts with the DOM will need to keep track of this. I suggest moving the code the creates the firestore document into the constructor of CreateNote and storing it on this. You'll need the user id there as well.
constructor(title, body, userId) {
this.title = title;
this.body = body;
const docRef = db.collection(userId).doc();
this.docId = docRef.id;
/* etc. */
Then any time you have an instance of CreateNote, you'll know the right user and document to reference.
Other suggestions (since you asked)
Use JsPrettier. It's worth the setup, you'll never go back.
Use HTML semantics correctly. Divs shouldn't be appended as children of hrs, because they're for "a thematic break between paragraph-level elements: for example, a change of scene in a story, or a shift of topic within a section." MDN
For your next project, use a framework. Essentially no one hand-codes event listeners and appends children to get things done. I see the value for basic understanding, but there's a rich and beautiful world of frameworks out there; don't limit yourself by avoiding them :-)
Intended Goal - User selects different colors from various color inputs and creates their own theme. Once the colors are chosen, the user clicks the download button and gets the generated CSS file with the colors he/she chose.
Issue - I'm able to download the CSS file, but I'm getting the original values despite changing the inputs to different colors.
What I've Done
The CSS file that's being downloaded already exists and all of the colors that correspond to different elements are done via CSS variables.
I'm updating the changes live by doing the following.
import { colors } from './colorHelper'
const inputs = [].slice.call(document.querySelectorAll('input[type="color"]'));
const handleThemeUpdate = (colors) => {
const root = document.querySelector(':root');
const keys = Object.keys(colors);
keys.forEach(key => {
root.style.setProperty(key, colors[key]);
});
}
inputs.forEach((input) => {
input.addEventListener('change', (e) => {
e.preventDefault();
const cssPropName = `--${e.target.id}`;
document.styleSheets[2].cssRules[3].style.setProperty(cssPropName, e.target.value);
handleThemeUpdate({
[cssPropName]: e.target.value
});
console.log(`${cssPropName} is now ${e.target.value}`)
});
});
Then, I fetched the stylesheet from the server, grabbed all the CSS Variables and replaced them with their actual value (hex color value).
After that, I got the return value (new stylesheet without variables) and set it for the data URI.
async function updatedStylesheet() {
const res = await fetch("./prism.css");
const orig_css = await res.text();
let updated_css = orig_css;
const regexp = /(?:var\(--)[a-zA-z\-]*(?:\))/g;
let cssVars = orig_css.matchAll(regexp);
cssVars = Array.from(cssVars).flat();
for (const v of cssVars) {
updated_css = updated_css.replace(v, colors[v.slice(6, -1)]);
};
return updated_css;
}
const newStylesheet = updatedStylesheet().then(css => {
downloadBtn.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(css));
downloadBtn.setAttribute('download', 'prism-theme.css');
})
I already have a download button setup in my HTML and I grabbed it earlier in my script so that it was available anywhere for me to use. downloadBtn
I set up the button to fire and grabbed the new sheet.
downloadBtn.addEventListener('click', () => {
newStylesheet();
});
The Result
I get the initial color values of the stylesheet despite changing the colors within the color inputs on the page. So the CSS file isn't being updated with the new colors before I download the file.
You could use PHP to pass the values to a new page. Let's say you chose the colors you want then click a button that says "Generate" that takes you to the "Generate Page".
The values would be passed directly into the HTML and you would download from the Generate Page instead.
This is if you know PHP of course, just a suggestion on how you might solve it.
(would comment, but can't due to reputation)
I have a Draft.js editor with some HTML in it. How can I insert a new piece of HTML at a current selection position, preserving both stylings and entity/block mappings?
I know how to insert raw text via Modifier.insertText:
const contentState = Modifier.insertText(
editorState.getCurrentContent(),
editorState.getSelection(),
insertionText,
editorState.getCurrentInlineStyle(),
);
but it will strip all the HTML which is not ok.
// Original HTML piece
const { contentBlocks, entityMap } = htmlToDraft(originalHTML);
const contentState = ContentState.createFromBlockArray(
contentBlocks,
entityMap,
);
const editorState = EditorState.createWithContent(contentState);
// Additional HTML piece, which I want to insert at the selection (cursor) position of
// previous editor state
const { contentBlocks, entityMap } = htmlToDraft(newHTML);
const newContentState = ContentState.createFromBlockArray(
contentBlocks,
entityMap,
);
You should probably use Modifier.replaceWithFragment for this:
A "fragment" is a section of a block map, effectively just an OrderedMap much the same as the full block map of a ContentState object.
This method will replace the "target" range with the fragment.
This will work identically to insertText, except that you need to give it a block map as a parameter. It’s not entirely clear from your example what the return value of htmlToDraft is but it should be possible for you to either:
Use contentBlocks directly from the return value
Or create a contentState as in your example, then use its .getBlockMap() method to get the block map to insert into the editor’s content.
const newContentState = ContentState.createFromBlockArray(
contentBlocks,
entityMap,
);
// Use newContentState.getBlockMap()
I could not post it in the comment section (too long of a snippet) but as mentioned earlier Modifier.replaceWithFragment is the way to go, so I made it work like in the snippet below.
*** Make sure you have all other infrastructure in place like blockRendererFn, blockRenderMap, compositeDecorator, etc to actually render all those blocks, inline styles for links, images, etc
import {
Modifier,
ContentState,
convertFromHTML,
} from 'draft-js'
onPaste = (text, html, state) => {
if (html) {
const blocks = convertFromHTML(html)
Modifier.replaceWithFragment(
this.state.editorState.getCurrentContent(),
this.state.editorState.getSelection(),
ContentState.createFromBlockArray(blocks, blocks.entityMap).getBlockMap(),
)
}
return false
}