Code Monkey home page Code Monkey logo

codeflask's Introduction

npm version Build Status


CodeFlask: A micro code-editor for awesome web pages.

Installation

You can install CodeFlask via npm:

npm install codeflask

Or use it directly in browser via cdn service:

https://unpkg.com/codeflask/build/codeflask.min.js

Usage

import CodeFlask from 'codeflask';

const flask = new CodeFlask('#my-selector', { language: 'js' });

You can also pass a DOM element instead of a selector:

import CodeFlask from 'codeflask';

const editorElem = document.getElementById('editor');
const flask = new CodeFlask(editorElem, { language: 'js' });

Usage with Shadow DOM:

import CodeFlask from 'codeflask';
...
const shadowElem = this.shadowRoot.querySelector('#editor');
const flask = new CodeFlask(shadowElem, { language: 'js', styleParent: this.shadowRoot });

Listening for changes in editor

flask.onUpdate((code) => {
  // do something with code here.
  // this will trigger whenever the code
  // in the editor changes.
});

Updating the editor programatically

// This will also trigger .onUpdate()
flask.updateCode('const my_new_code_here = "Blabla"');

Getting the current code from editor

const code = flask.getCode();

Enabling line numbers

import CodeFlask from 'codeflask';

const flask = new CodeFlask('#my-selector', {
  language: 'js',
  lineNumbers: true
});

Enabling rtl (right to left writing)

import CodeFlask from 'codeflask';

const flask = new CodeFlask('#my-selector', {
  language: 'js',
  rtl: true
});

Enabling read only mode

import CodeFlask from 'codeflask';

const flask = new CodeFlask('#my-selector', {
  language: 'js',
  readonly: true
});

Adding other languages support:

flask.addLanguage('ruby', options)

For Example to add 'Ruby'

import Prism from 'prismjs';
import CodeFlask from 'codeflask';

const flask = new CodeFlask('#my-selector', {
  language: 'ruby',
  readonly: true
});

flask.addLanguage('ruby', Prism.languages['ruby']);

This API is simply a proxy to add a new language to Prism itself (the code highlighter). The options parameter must be the same accepted in Prism. You can read more about it here.

By default, CodeFlask supports the following languages (which are also the default supported in Prism):

  • Markup (HTML/XML);
  • CSS;
  • C-like;
  • JavaScript;

Adding your own theme to CodeFlask

By default, CodeFlask comes with a simple theme made from scratch called CodeNoon.

You can easily override this theme with your own by writting your own CSS and adding it to your project. If that's the case, you should also disable CodeNoon with the defaultTheme option:

import CodeFlask from 'codeflask';

const flask = new CodeFlask('#my-selector', {
  language: 'js',
  defaultTheme: false
});

Credits & Thanks

CodeFlask.js was made possible by awesome open-source projects such as Prism.js and Rollup.

codeflask's People

Contributors

alexcp avatar andreynering avatar aziz512 avatar ecchochan avatar gabrielsimoes avatar holwech avatar jeroenvisser101 avatar johnnyeric avatar joshlgrossman avatar kazzkiq avatar leaverou avatar lehni avatar mujz avatar nayunhwan avatar nexts avatar peterdavehello avatar petersolopov avatar pleasedontbelong avatar shahinsorkh avatar travis-w avatar valpackett avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

codeflask's Issues

How to use the code from the editor?

Hello,

Is this a toy for the user, or something that's just there for aesthetics? Because it seems
impossible to actually use the code inside the editor.

In my use case I have 2 editors that and the code inside needs to be send to the server and processed, how can I achive that with this script, if possible by default.

php constant

define('ADMIN_EMAIL_TEXT', 'Hi %s,' . "\n\n" . 'Your personal information, perhaps including your password, has been changed. If this was done without your knowledge or consent please contact the administrator immediatly!' . "\n\n" . 'Website : %s' . "\n" . 'Username: %s' . "\n" . 'Password: %s' . "\n\n" . 'Thanks!' . "\n" . '%s' . "\n\n" . 'This is an automated response, please do not reply!');

why get such an error?

<script src="/static/js/bower_components/prism/prism.js" async></script> <script src="/static/js/bower_components/codeflask.js/src/codeflask.js" async></script> <title>Title</title>
<script> var flask = new CodeFlask; flask.run('#my-code-wrapper', { language: 'javascript' }) </script> #

Uncaught ReferenceError: CodeFlask is not defined

Disabling the text editor

Is there any API for disabling the text area of the editor, such that the editor serves as a code viewer on different events?

flasks.update()

Hi;

How can i use "update" funtion when i using "runAll" ??

lineNumbers: true has no effect

flask.run(`#code-${this.get('selector')}`, {
        language: "javascript",
        lineNumbers: true
      });

do not add "line-number" class to the corresponding elements.

Update CodeFlask on npm?

Is there a reason why the last update of the codeflask npm package was 11 months ago? I like to use it in my project as a npm package

line numbers

only thing really missing, or not mentioned in the documentation.

Option to disable keyup events

Hi there, thanks for the great library!

I think it would be good if we could pass some options to disable keyup events on the editor. There currently isn't a way to turn off tab indentation or auto closing parentheses via this library and I can't remove the event listener either because it is defined anonymously.

scrolling issue

Scrolling seems to cause the editor to not render code highlights. The code that is scrolled into view is shaded as grey and does not have any highlighting. To be clear, the initial code on page load is highlighted, it's just the code underneath it that does not receive highlighting. I've tested in Firefox, Chrome, and Safari. Upon scrolling, I receive this warning:

This site appears to use a scroll-linked positioning effect. This may not work well with asynchronous panning; see https://developer.mozilla.org/docs/Mozilla/Performance/ScrollLinkedEffects for further details and to join the discussion on related tools and features!

My codeflask.css is slightly modified (I removed the -webkit-text-fill-color: transparent; line from .CodeFlask__textarea because it seems to cause text that is scrolled into view to be transparent):

.CodeFlask{
    position:relative;
    overflow:hidden;
}

.CodeFlask__textarea,
.CodeFlask__pre, 
code[class*="language-"], 
pre[class*="language-"]{
    box-sizing:border-box;
    position:absolute;
    top:0;
    left:0;
    width:100%;
    padding:1rem !important;
    border:none;
    font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
    font-size:13px;
    background:transparent;
    white-space:pre-wrap !important;
    line-height:1.5em;
    word-wrap: break-word;
}

.CodeFlask__textarea{
    border:none;
    background:transparent;
    outline:none;
    resize:none;
    opacity:0.4;
    color:#000;
    margin:0;
    z-index:1;
    height:100%;
    -webkit-overflow-scrolling: touch;
    tab-size: 4;
}

.CodeFlask__pre{
    z-index:2;
    pointer-events:none;
    overflow-y:auto;
    margin:0;
    min-height:100%;
    margin:0 !important;
    background:transparent !important;
}

.CodeFlask__code{
    font-size:inherit;
    font-family:inherit;
    color:inherit;
    display:block;
}

.CodeFlask__is-code {
    white-space: pre;
}

.CodeFlask__textarea_line-numbers {
    width: calc(100% - 3.8em);
    margin-left: 3.8em;
    padding-left: 0px !important;
}

.CodeFlask__pre_line-numbers {
    padding-left: 3.8em !important;
}

HTML API

First off, thanks for making this awesome plugin!

I suggest not requiring JavaScript for basic usage. Lots of people aren't comfortable with it.
Have a codeflask class that when people use it, these elements are automatically made into editors.

Similarly, default language can just be defined on an ancestor, like <body class="language-css">: This is just basic Prism.js functionality, you don't even need to implement it yourself :) Just include it in the docs.

Text in background textarea seen on selection (Chrome 66)

Well, when text is selected - it's actually also selected in background textarea. If you're using only text it's not a big problem (but it don't looks clean anyway!), but you have more problems when you're replacing some characters in prism (emoji, for example) - so you get image in foreground and text in background, which both seen on selection and interfere with each other (at least in Chrome, haven't tested in other browser, but I expected it is reproduced there also). Here is screenshot (for text-only case) https://ibb.co/cRFvFo
I understand that CodeFlask is tiny project, but there is no such problem in CodeMirror, which is also using background textarea, so it would be useful if you clarify this thing in documentation if this can't be fixed for some reason, thank you.

runUpdate / onUpdate callback has wrong scope on initial load

In an older version of CodeFlask, onUpdate would run on the initial update to the textarea. It's still making the call to runUpdate, but the initial function scope is wrong so the callback never runs on page load.

If you log this in runUpdate on page load it points to window...where Codeflask won't find this.updateCallBack later on. Once you type in the textarea, the scope is set to the appropriate object.

This is the part of the code that is wrong: https://github.com/kazzkiq/CodeFlask/blob/master/src/codeflask.js#L295

Fix: Change onUpdate to bind the correct scope

updateCode(newCode) {
    // previous code here
    setTimeout(this.runUpdate.bind(this), 1);
}

Create Bower package

CodeFlask.js have dependency on Prism.js. I don't know how the dependency policy works on Bower, but we would need to import Prism too.

Related to PullRequest #7 .

Feature request: areaId option for labeling textarea

Codeflask generates a textarea without a paired label element, which poses accessibility problems. An easy way to get around it would be to add an areaId option to specify an id value for the textarea. That way a label element can be paired with it for screen reader users.

I'm not sure if this feature previously existed or if someone on my team hacked in their own fix, but it's super easy to add. I've got it working on my local fork and will contribute it back to you as soon as I add it to the tests.

Version 1.0

Ok folks,

So I'm working on a new CodeFlask version, one that is more stable and easier to maintain and use. For this, I've written v1.0 from scratch.

The goal is to make CodeFlask super simple, like a small core which have only one main goal: provide code highlight as you edit your code snippet.

In short, here is the list of features/changes being worked on before releasing v1.0:

  • Use ES6/7+ syntax for CodeFlask source code;
  • Generate production files automatically;
  • Write decent automated tests to prevent things breaking every new release;
  • Improve performance making use of WebWorkers on Prism.js; (Under discussion);
  • Embbed Prism as a CodeFlask dependency, so users don't need to install other things;
  • Create a default theme for CodeFlask independent from default one that comes with Prism.js.
  • Add line numbers support out of the box (without the need of plugins);
  • (If possible) make code even smaller; (Since CodeFlask adds more features, this turns out impraticable);
  • Enable importing of language support on the fly (flask.addLanguage(), etc);
  • Enable hardware acceleration for scroll sync (via translate instead of margin/top/left);
  • Add support for autoclosing basic characters;
  • Drop support for older browsers (did it ever had?);
  • Drop support for Bower;
  • Drop support for .runAll();
  • Drop support for web components (CodeFlask is a library, one can always wrap it around a (web)component, but its not CodeFlask goal to be a component itself);

I'm also considering dropping cdnjs and adopting unpkg. The cool thing here is that unpkg automatically generate cached files from npm releases. As soon as a new release is pushed, you immediately have CDN updated and ready to go. Way easier to work out.

The v1.0 has no release date yet, but I managed to push a lot of code into it in the last few days, and hope to have something ready in the (really) near future.

Keyboard trap upon tabbing into editor

Keyboard-only users get stuck in a keyboard trap when tabbing into the editor. It makes it impossible to exit, a huge blocker for people who can't use a mouse or trackpad. One quick and dirty solution would be to wire up the escape key once you tab into the text editor...maybe it could send focus to the next tab stop, allowing you to keep going through the page?

In an ideal world, editing with the keyboard would only start once you'd pressed an "enable editor" button, where combined with the escape key to exit, the user would thus be making a more conscious choice to toggle edit mode. But that would be a way bigger change, where an escape key + focus management might do the trick in the meantime. I'll try to put a PR together since I have to fix this for our site.

Edit: this must have started occurring in the latest version, because I'm not experiencing a keyboard trap with an older one.

Allow multiple instances of CodeFlask

By now, only one instance of CodeFlask is available per page. With the new APIs being developed each instance should be retrievable later for bindings and function calls. User should be able to do this kind of stuff:

var flask = new CodeFlask;
var multiFlasks = new CodeFlask;


// Init a single editor
flask.run('#my-editor', { language: 'javascript' });

flask.onUpdate(function(code){
    console.log(code);
});


// Init multiple others
multiFlasks.runAll('.all-my-flasks', { language: 'html' });

flask.update('<button>I am a button</button>'); // updates all editors

For this, the architecture of the plugin will have to change a little, possibly breaking how you call CodeFlask.js on your page (yeah, this shouldn't happen).

Wrong main field in package.json

I've been trying to use codeflask from webpack, and I am getting the following error:

Module not found: Error: Can't resolve 'codeflask'

I discovered this is because inside package.json, the main field points to the non-existing index.js:

"main": "index.js",

I've manually changed it to this, and the import works:

"main": "src/codeflask.js",

It's almost too simple a fix for a PR, but I could create one if desired.

CSS.supports prevents Codeflask from working in IE11

The CSS.supports call in editor.js throws an unrecoverable error in IE11. Lots of people still use IE, and it's a pretty easy change to get it working. I wrapped it in a try...catch block but there might be a more graceful way to do it.

let COLOR;
try {
  COLOR = (CSS.supports('caret-color', '#000')) ? BACKGROUND_COLOR : '#fff';
} catch (e) {
  COLOR = '#fff';
}

{add,update}Language aren't static

In the process of updating to 1.0, I realized that I would need to tell CodeFlask how to use all the languages that Prism has, doing something similar to the following:

// load prism.js after codeflask so it doesn't get overwritten
for (var lang of Object.entries(Prism.languages)) {
  flask.addLanguage(lang[0], lang[1]);
}

To do this, I need to have already created an editor, but as someone who frequently will have multiple editors on the page (dynamically added, as well), it doesn't really make sense for this to be a function on an editor instance. My first instinct was to call it as CodeFlask.addLanguage().

Is there a reason that this is an instance function?

Horizontal scrolling on mobile

I have such view:

If page width is small:

Horizontal scrolling to rigth with cursor:

Same code is hidden now!

After selection i see it:

How to fix this?
The problem is most important on mobile devices.

n is undefined

Hi,

I followed the readme to test the editor.
But with the line flask.run('#my-code-wrapper'); I obtain one error of n is undefined

With the line flask.run('#my-code-wrapper', { language: 'sql', lineNumbers: true }), all run normaly.

My testing code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.1/semantic.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.14.0/themes/prism.min.css" async integrity="sha256-N1K43s+8twRa+tzzoF3V8EgssdDiZ6kd9r8Rfgg8kZU=" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.14.0/plugins/line-numbers/prism-line-numbers.min.css" async integrity="sha256-SA3HrKLu4tldegZQVdUx8Cwwo2hQFIu7iW6UOo6OdS4=" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/CodeFlask.js/0.1.1/codeflask.min.css" async integrity="sha256-WrayoNKyvtuOAWLPQkI9vvI/ZG8zfJeOrwHiRlFm2BY=" crossorigin="anonymous" />
    <style>
        .main.container {
            padding-top: 50px;
        }

        #my-code-wrapper {
            width:350px;
            height:250px;
            position:relative; /* Position must be: relative, absolute or fixed */
        }
    </style>
</head>
<body>
    <div class="ui main container">
       <div id="my-code-wrapper" data-language="sql"></div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.14.0/prism.min.js" async integrity="sha256-jTGzLAqOAcOL+ALD2f2tvFY7fs6dwkOeo88xiuVHaRk=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.14.0/plugins/line-numbers/prism-line-numbers.min.js" async integrity="sha256-JfF9MVfGdRUxzT4pecjOZq6B+F5EylLQLwcQNg+6+Qk=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/CodeFlask.js/0.1.1/codeflask.min.js" async integrity="sha256-ERpc+wfArI8UJK0iigJWqNNoZETrxAOF8dMjDSCcOTQ=" crossorigin="anonymous"></script>
    <script>
        var flask = new CodeFlask;
        flask.run('#my-code-wrapper');
        //flask.run('#my-code-wrapper', { language: 'sql', lineNumbers: true })
      </script>
</body>
</html>

Prism being contained in CodeFlask removes plugin abilities

I use the Custom Class plugin to namespace the Prism classes, since some of them conflict with my own CSS.

Before 1.0, CodeFlask used the Prism that I provided, meaning everything worked just fine. Now, however, CodeFlask uses its own version of Prism, meaning that I no longer can use the plugin, which breaks styling.

I see no way to interface with CodeFlask's version of Prism outside of the language functions. (I see Prism is in the global namespace, confusing me even more as to why it's included with CodeFlask) I would love to see a way to disable CodeFlask's version of Prism and be able to use my own, similar to how it was before 1.0. I can only see more issues in the future because of Prism being included in CodeFlask instead of CodeFlask depending on it.


This may change depending on the load order, but I have to load Prism before CodeFlask so I can add languages to it (#65 related). I suppose that I could maybe load Prism before CodeFlask, change its name to Prism2, then set CodeFlask's Prism equal to Prism2, but that seems like a gigantic hack.

Either way, I shouldn't have to (and by extension shouldn't have to force my users to) load Prism twice ๐Ÿ˜ข

Auto-indent on line break

Unsure if there's another issue open for this, but it'd be nice if CodeFlask automatically added the same number of indenting characters (tabs/spaces) based on the previous line when hitting Enter

Steps to reproduce:

  • Enter the following text:
function foo() {
    // cursor is here: โ–ˆ 
  • Hit Enter

Result:

  • New line starts flush against the LHS

Expected result:

  • New line is indented 4 spaces per previous line

Unindent `Shift + Tab`

Add a keyboard shortcut to unindent(remove a level of indent, spaces or tabs).

Shift + Tab works well for this and lots of code editors use this keyboard shortcut.

Exposing code in CodeFlask API

CodeFlask should have a method for exposing the current code inside the editor.

Something like:

const flask = new CodeFlask;
flask.run('#my-editor');

flask.code(); // Retrieve current code in the editor.

Weird text displacement on iOS devices

It seems that iOS Safari renders an "extra" padding on <textarea> elements, preventing <code> element to match text position.

Both have the same computed values for padding, margin and border properties, but Safari is stubborn it seems.

cmp4dreusaatqln

Auto-added closing parentheses behave incorrectly

When writing code, closing parentheses are now added automatically! ๐ŸŽ‰

However, the behavior is not as expected.

fn main(<caret> adds the ending paren: fn main(<caret>), but if you type ) after it's added, you end up with fn main()). This is inconsistent with almost every editor that auto-adds ending marks.

Typing fn main() should result in fn main()<caret>, not fn main()<caret>).

Deprecated or No Longer Supported?

Noticed PRs seem to be multiple months old.
Has the maintainer stopped supporting this plugin?
Has it been deprecated in favor of other plugins?

Missing license

From bower.jsonit seems that the project is under the MIT license, but this isn't made particularly clear.

Add support for auto closing certain characters

Hello, is there a possibility you could add support for autoclosing certain characters like brackets and quotes? e.g. when editing a json you can just type one { and the editor would automatically write a closing }

Thanks for reply and keep up the good work. ;-)

Release new version?

I see that line-numbers support is not available in any release yet. Any plans to make a new release with that feature?

Inline styles

Firstly, looks like you released 1.0! Congrats! :D

Unfortunately, it seems that you have introduced inline styles with this update. As someone enforcing a strict Content Security Policy, the reason I was using CodeFlask is precisely because it didn't do this. Please consider changing this new update to remove the inline styles and be more CSP-friendly!

iOS scroll text displacement

Similar to issue #4, I'm seeing weird text displacement issues on iOS. Particularly, when trying to scroll upwards before the beginning or downwards past the end of code sections (where you might usually see rubber banding).

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.