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

Wysiwyg editor does not have target settings for link #182

Closed
BramEsposito opened this issue Sep 18, 2019 · 3 comments
Closed

Wysiwyg editor does not have target settings for link #182

BramEsposito opened this issue Sep 18, 2019 · 3 comments

Comments

@BramEsposito
Copy link
Contributor

When adding a link in the Wysiwyg editor, my client wants to add a target="_blank" option for external links.

Trix editor does not have this feature: basecamp/trix#55

Any suggestions for this?

@dvlpp
Copy link
Member

dvlpp commented Sep 18, 2019

There is no real content solution for this, in my opinion — I maybe that's a good thing: it shouldn't be a content rule, but rather a display rule (maybe you could have a different rule if the content was displayed in a mobile app, for instance).

So it has to be a parsing job, before displaying the content, in your application code: maybe a function that parses the HTML, and add the required attributes to <a> tags. I've done this before, but for Markdown data.

@BramEsposito
Copy link
Contributor Author

Hmm, I see what you mean.

In the meantime I have written this method on my SharpForm class and I call it from the update() method. Maybe I'll move it to my view controller.

    /**
     * Add target="_blank" to external links
     *
     * @param string $snippet
     * @return string
     */
    public function addBlankTarget($snippet) {
        $domainparts = parse_url(env('APP_URL'));

        $domain = $domainparts['host'];

        $dom = new \DOMDocument();

        @$dom->loadHTML(
            mb_convert_encoding($snippet, 'HTML-ENTITIES', 'UTF-8'),
            LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD
        );
        $x = new \DOMXPath($dom);

        foreach($x->query("//a") as $node)
        {
            $parts = parse_url($node->getAttribute("href"));

            if (
                array_key_exists("host", $parts) &&
                $parts['host'] != $domain
            ) {
                $node->setAttribute("target","_blank");
            }

        }

        return $dom->saveHtml($dom->documentElement);
    }

@dvlpp
Copy link
Member

dvlpp commented Sep 18, 2019

Yes; if you want to use this in sharp, a clean way may be to can refactor this method to a CustomTransformer and to apply it at save:

// in Form's update()
$this->setCustomTransformer("my_text_field", AddBlankTargetToLinks::class)->save()

@dvlpp dvlpp closed this as completed Sep 18, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants